From 8c5bd1d586132ecf009731a8c74f893976484499 Mon Sep 17 00:00:00 2001 From: takuaraki Date: Wed, 27 Sep 2017 16:42:14 +0900 Subject: [PATCH 001/417] 2.x: fix incorrect error message at SubscriptionHelper.setOnce (#5623) --- .../io/reactivex/internal/subscriptions/SubscriptionHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java b/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java index d8c8f97cea..071aefb683 100644 --- a/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java +++ b/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java @@ -137,7 +137,7 @@ public static boolean set(AtomicReference field, Subscription s) { * @return true if the operation succeeded, false if the target field was not null. */ public static boolean setOnce(AtomicReference field, Subscription s) { - ObjectHelper.requireNonNull(s, "d is null"); + ObjectHelper.requireNonNull(s, "s is null"); if (!field.compareAndSet(null, s)) { s.cancel(); if (field.get() != CANCELLED) { From ea4d43a7967e0db8425528289a870345ab985f71 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 28 Sep 2017 18:23:32 +0200 Subject: [PATCH 002/417] 2.x: add onTerminateDetach to Single and Completable (#5624) * 2.x: add onTerminateDetach to Single and Completable * Improve coverage, fix lack of nulling out the downstream --- src/main/java/io/reactivex/Completable.java | 18 +++ src/main/java/io/reactivex/Maybe.java | 3 +- src/main/java/io/reactivex/Single.java | 18 +++ .../completable/CompletableDetach.java | 91 +++++++++++ .../internal/operators/maybe/MaybeDetach.java | 3 + .../operators/single/SingleDetach.java | 92 ++++++++++++ .../completable/CompletableDetachTest.java | 141 ++++++++++++++++++ .../operators/maybe/MaybeDetachTest.java | 111 ++++++++++++++ .../operators/single/SingleDetachTest.java | 141 ++++++++++++++++++ 9 files changed, 617 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java create mode 100644 src/main/java/io/reactivex/internal/operators/single/SingleDetach.java create mode 100644 src/test/java/io/reactivex/internal/operators/completable/CompletableDetachTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/single/SingleDetachTest.java diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 2c7f22bb75..fd541b03fe 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1380,6 +1380,24 @@ public final Completable onErrorResumeNext(final Function + *
Scheduler:
+ *
{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.
+ * + * @return a Completable which nulls out references to the upstream producer and downstream CompletableObserver if + * the sequence is terminated or downstream calls dispose() + * @since 2.1.5 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final Completable onTerminateDetach() { + return RxJavaPlugins.onAssembly(new CompletableDetach(this)); + } + /** * Returns a Completable that repeatedly subscribes to this Completable until cancelled. *
diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index daff77cff4..deae7c020c 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3316,6 +3316,7 @@ public final Maybe onExceptionResumeNext(final MaybeSource next) ObjectHelper.requireNonNull(next, "next is null"); return RxJavaPlugins.onAssembly(new MaybeOnErrorNext(this, Functions.justFunction(next), false)); } + /** * Nulls out references to the upstream producer and downstream MaybeObserver if * the sequence is terminated or downstream calls dispose(). @@ -3323,7 +3324,7 @@ public final Maybe onExceptionResumeNext(final MaybeSource next) *
Scheduler:
*
{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.
*
- * @return a Maybe which out references to the upstream producer and downstream MaybeObserver if + * @return a Maybe which nulls out references to the upstream producer and downstream MaybeObserver if * the sequence is terminated or downstream calls dispose() */ @CheckReturnValue diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index e74c102fef..58b2e9b007 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2468,6 +2468,24 @@ public final Single onErrorResumeNext( return RxJavaPlugins.onAssembly(new SingleResumeNext(this, resumeFunctionInCaseOfError)); } + /** + * Nulls out references to the upstream producer and downstream SingleObserver if + * the sequence is terminated or downstream calls dispose(). + *
+ *
Scheduler:
+ *
{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.
+ *
+ * @return a Single which nulls out references to the upstream producer and downstream SingleObserver if + * the sequence is terminated or downstream calls dispose() + * @since 2.1.5 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final Single onTerminateDetach() { + return RxJavaPlugins.onAssembly(new SingleDetach(this)); + } + /** * Repeatedly re-subscribes to the current Single and emits each success value. *
diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java new file mode 100644 index 0000000000..48de66f017 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java @@ -0,0 +1,91 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; + +/** + * Breaks the references between the upstream and downstream when the Completable terminates. + * + * @since 2.1.5 - experimental + */ +@Experimental +public final class CompletableDetach extends Completable { + + final CompletableSource source; + + public CompletableDetach(CompletableSource source) { + this.source = source; + } + + @Override + protected void subscribeActual(CompletableObserver observer) { + source.subscribe(new DetachCompletableObserver(observer)); + } + + static final class DetachCompletableObserver implements CompletableObserver, Disposable { + + CompletableObserver actual; + + Disposable d; + + DetachCompletableObserver(CompletableObserver actual) { + this.actual = actual; + } + + @Override + public void dispose() { + actual = null; + d.dispose(); + d = DisposableHelper.DISPOSED; + } + + @Override + public boolean isDisposed() { + return d.isDisposed(); + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.d, d)) { + this.d = d; + + actual.onSubscribe(this); + } + } + + @Override + public void onError(Throwable e) { + d = DisposableHelper.DISPOSED; + CompletableObserver a = actual; + if (a != null) { + actual = null; + a.onError(e); + } + } + + @Override + public void onComplete() { + d = DisposableHelper.DISPOSED; + CompletableObserver a = actual; + if (a != null) { + actual = null; + a.onComplete(); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDetach.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDetach.java index a0e098cc85..8d0883c45e 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDetach.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDetach.java @@ -69,6 +69,7 @@ public void onSuccess(T value) { d = DisposableHelper.DISPOSED; MaybeObserver a = actual; if (a != null) { + actual = null; a.onSuccess(value); } } @@ -78,6 +79,7 @@ public void onError(Throwable e) { d = DisposableHelper.DISPOSED; MaybeObserver a = actual; if (a != null) { + actual = null; a.onError(e); } } @@ -87,6 +89,7 @@ public void onComplete() { d = DisposableHelper.DISPOSED; MaybeObserver a = actual; if (a != null) { + actual = null; a.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java b/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java new file mode 100644 index 0000000000..d51eb2d4a6 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java @@ -0,0 +1,92 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.single; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; + +/** + * Breaks the references between the upstream and downstream when the Maybe terminates. + * + * @param the value type + * @since 2.1.5 - experimental + */ +@Experimental +public final class SingleDetach extends Single { + + final SingleSource source; + + public SingleDetach(SingleSource source) { + this.source = source; + } + + @Override + protected void subscribeActual(SingleObserver observer) { + source.subscribe(new DetachSingleObserver(observer)); + } + + static final class DetachSingleObserver implements SingleObserver, Disposable { + + SingleObserver actual; + + Disposable d; + + DetachSingleObserver(SingleObserver actual) { + this.actual = actual; + } + + @Override + public void dispose() { + actual = null; + d.dispose(); + d = DisposableHelper.DISPOSED; + } + + @Override + public boolean isDisposed() { + return d.isDisposed(); + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.d, d)) { + this.d = d; + + actual.onSubscribe(this); + } + } + + @Override + public void onSuccess(T value) { + d = DisposableHelper.DISPOSED; + SingleObserver a = actual; + if (a != null) { + actual = null; + a.onSuccess(value); + } + } + + @Override + public void onError(Throwable e) { + d = DisposableHelper.DISPOSED; + SingleObserver a = actual; + if (a != null) { + actual = null; + a.onError(e); + } + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableDetachTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableDetachTest.java new file mode 100644 index 0000000000..850365b2fc --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableDetachTest.java @@ -0,0 +1,141 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import static org.junit.Assert.assertNull; + +import java.io.IOException; +import java.lang.ref.WeakReference; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.observers.TestObserver; +import io.reactivex.processors.PublishProcessor; + +public class CompletableDetachTest { + + @Test + public void doubleSubscribe() { + + TestHelper.checkDoubleOnSubscribeCompletable(new Function() { + @Override + public CompletableSource apply(Completable m) throws Exception { + return m.onTerminateDetach(); + } + }); + } + + @Test + public void dispose() { + TestHelper.checkDisposed(PublishProcessor.create().ignoreElements().onTerminateDetach()); + } + + @Test + public void onError() { + Completable.error(new TestException()) + .onTerminateDetach() + .test() + .assertFailure(TestException.class); + } + + @Test + public void onComplete() { + Completable.complete() + .onTerminateDetach() + .test() + .assertResult(); + } + + @Test + public void cancelDetaches() throws Exception { + Disposable d = Disposables.empty(); + final WeakReference wr = new WeakReference(d); + + TestObserver to = new Completable() { + @Override + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(wr.get()); + }; + } + .onTerminateDetach() + .test(); + + d = null; + + to.cancel(); + + System.gc(); + Thread.sleep(200); + + to.assertEmpty(); + + assertNull(wr.get()); + } + + @Test + public void completeDetaches() throws Exception { + Disposable d = Disposables.empty(); + final WeakReference wr = new WeakReference(d); + + TestObserver to = new Completable() { + @Override + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(wr.get()); + observer.onComplete(); + observer.onComplete(); + }; + } + .onTerminateDetach() + .test(); + + d = null; + + System.gc(); + Thread.sleep(200); + + to.assertResult(); + + assertNull(wr.get()); + } + + @Test + public void errorDetaches() throws Exception { + Disposable d = Disposables.empty(); + final WeakReference wr = new WeakReference(d); + + TestObserver to = new Completable() { + @Override + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(wr.get()); + observer.onError(new TestException()); + observer.onError(new IOException()); + }; + } + .onTerminateDetach() + .test(); + + d = null; + + System.gc(); + Thread.sleep(200); + + to.assertFailure(TestException.class); + + assertNull(wr.get()); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDetachTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDetachTest.java index 7022339ed3..d1a28f2c47 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDetachTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDetachTest.java @@ -13,11 +13,18 @@ package io.reactivex.internal.operators.maybe; +import static org.junit.Assert.assertNull; + +import java.io.IOException; +import java.lang.ref.WeakReference; + import org.junit.Test; import io.reactivex.*; +import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; +import io.reactivex.observers.TestObserver; import io.reactivex.processors.PublishProcessor; public class MaybeDetachTest { @@ -53,4 +60,108 @@ public void onComplete() { .test() .assertResult(); } + + @Test + public void cancelDetaches() throws Exception { + Disposable d = Disposables.empty(); + final WeakReference wr = new WeakReference(d); + + TestObserver to = new Maybe() { + @Override + protected void subscribeActual(MaybeObserver observer) { + observer.onSubscribe(wr.get()); + }; + } + .onTerminateDetach() + .test(); + + d = null; + + to.cancel(); + + System.gc(); + Thread.sleep(200); + + to.assertEmpty(); + + assertNull(wr.get()); + } + + @Test + public void completeDetaches() throws Exception { + Disposable d = Disposables.empty(); + final WeakReference wr = new WeakReference(d); + + TestObserver to = new Maybe() { + @Override + protected void subscribeActual(MaybeObserver observer) { + observer.onSubscribe(wr.get()); + observer.onComplete(); + observer.onComplete(); + }; + } + .onTerminateDetach() + .test(); + + d = null; + + System.gc(); + Thread.sleep(200); + + to.assertResult(); + + assertNull(wr.get()); + } + + @Test + public void errorDetaches() throws Exception { + Disposable d = Disposables.empty(); + final WeakReference wr = new WeakReference(d); + + TestObserver to = new Maybe() { + @Override + protected void subscribeActual(MaybeObserver observer) { + observer.onSubscribe(wr.get()); + observer.onError(new TestException()); + observer.onError(new IOException()); + }; + } + .onTerminateDetach() + .test(); + + d = null; + + System.gc(); + Thread.sleep(200); + + to.assertFailure(TestException.class); + + assertNull(wr.get()); + } + + @Test + public void successDetaches() throws Exception { + Disposable d = Disposables.empty(); + final WeakReference wr = new WeakReference(d); + + TestObserver to = new Maybe() { + @Override + protected void subscribeActual(MaybeObserver observer) { + observer.onSubscribe(wr.get()); + observer.onSuccess(1); + observer.onSuccess(2); + }; + } + .onTerminateDetach() + .test(); + + d = null; + + System.gc(); + Thread.sleep(200); + + to.assertResult(1); + + assertNull(wr.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleDetachTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleDetachTest.java new file mode 100644 index 0000000000..0b5c5bb3fa --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/single/SingleDetachTest.java @@ -0,0 +1,141 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.single; + +import static org.junit.Assert.assertNull; + +import java.io.IOException; +import java.lang.ref.WeakReference; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.observers.TestObserver; +import io.reactivex.processors.PublishProcessor; + +public class SingleDetachTest { + + @Test + public void doubleSubscribe() { + + TestHelper.checkDoubleOnSubscribeSingle(new Function, SingleSource>() { + @Override + public SingleSource apply(Single m) throws Exception { + return m.onTerminateDetach(); + } + }); + } + + @Test + public void dispose() { + TestHelper.checkDisposed(PublishProcessor.create().singleOrError().onTerminateDetach()); + } + + @Test + public void onError() { + Single.error(new TestException()) + .onTerminateDetach() + .test() + .assertFailure(TestException.class); + } + + @Test + public void onSuccess() { + Single.just(1) + .onTerminateDetach() + .test() + .assertResult(1); + } + + @Test + public void cancelDetaches() throws Exception { + Disposable d = Disposables.empty(); + final WeakReference wr = new WeakReference(d); + + TestObserver to = new Single() { + @Override + protected void subscribeActual(SingleObserver observer) { + observer.onSubscribe(wr.get()); + }; + } + .onTerminateDetach() + .test(); + + d = null; + + to.cancel(); + + System.gc(); + Thread.sleep(200); + + to.assertEmpty(); + + assertNull(wr.get()); + } + + @Test + public void errorDetaches() throws Exception { + Disposable d = Disposables.empty(); + final WeakReference wr = new WeakReference(d); + + TestObserver to = new Single() { + @Override + protected void subscribeActual(SingleObserver observer) { + observer.onSubscribe(wr.get()); + observer.onError(new TestException()); + observer.onError(new IOException()); + }; + } + .onTerminateDetach() + .test(); + + d = null; + + System.gc(); + Thread.sleep(200); + + to.assertFailure(TestException.class); + + assertNull(wr.get()); + } + + @Test + public void successDetaches() throws Exception { + Disposable d = Disposables.empty(); + final WeakReference wr = new WeakReference(d); + + TestObserver to = new Single() { + @Override + protected void subscribeActual(SingleObserver observer) { + observer.onSubscribe(wr.get()); + observer.onSuccess(1); + observer.onSuccess(2); + }; + } + .onTerminateDetach() + .test(); + + d = null; + + System.gc(); + Thread.sleep(200); + + to.assertResult(1); + + assertNull(wr.get()); + } +} From da922d22ba731663d57abd23f468c92c5ddfe72d Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 3 Oct 2017 09:59:14 +0200 Subject: [PATCH 003/417] 2.x: Upgrade to Gradle 4.2, remove nebula, custom rls (#5633) --- .travis.yml | 4 +- HEADER | 10 + build.gradle | 319 ++++++++++++------ gradle.properties | 2 +- gradle/buildViaTravis.sh | 7 +- gradle/wrapper/gradle-wrapper.jar | Bin 53319 -> 54708 bytes gradle/wrapper/gradle-wrapper.properties | 3 +- gradlew | 26 +- gradlew.bat | 6 - .../java/io/reactivex/BlockingGetPerf.java | 0 .../java/io/reactivex/BlockingPerf.java | 0 .../java/io/reactivex/CallableAsyncPerf.java | 0 .../io/reactivex/EachTypeFlatMapPerf.java | 0 .../java/io/reactivex/FlatMapJustPerf.java | 0 .../io/reactivex/FlattenCrossMapPerf.java | 0 .../java/io/reactivex/FlattenJustPerf.java | 0 .../InputWithIncrementingInteger.java | 0 .../java/io/reactivex/JustAsyncPerf.java | 0 .../io/reactivex/LatchedSingleObserver.java | 0 .../io/reactivex/ObservableFlatMapPerf.java | 0 .../io/reactivex/OperatorFlatMapPerf.java | 0 .../java/io/reactivex/OperatorMergePerf.java | 0 .../java/io/reactivex/PerfAsyncConsumer.java | 0 .../java/io/reactivex/PerfConsumer.java | 0 .../io/reactivex/PerfInteropConsumer.java | 0 .../java/io/reactivex/PerfObserver.java | 0 .../java/io/reactivex/PerfSubscriber.java | 0 .../java/io/reactivex/RangePerf.java | 0 .../java/io/reactivex/ReducePerf.java | 0 .../java/io/reactivex/RxVsStreamPerf.java | 0 .../java/io/reactivex/StrictPerf.java | 0 .../java/io/reactivex/ToFlowablePerf.java | 0 .../java/io/reactivex/XMapYPerf.java | 0 .../io/reactivex/parallel/ParallelPerf.java | 0 34 files changed, 248 insertions(+), 129 deletions(-) create mode 100644 HEADER rename src/{perf => jmh}/java/io/reactivex/BlockingGetPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/BlockingPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/CallableAsyncPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/EachTypeFlatMapPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/FlatMapJustPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/FlattenCrossMapPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/FlattenJustPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/InputWithIncrementingInteger.java (100%) rename src/{perf => jmh}/java/io/reactivex/JustAsyncPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/LatchedSingleObserver.java (100%) rename src/{perf => jmh}/java/io/reactivex/ObservableFlatMapPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/OperatorFlatMapPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/OperatorMergePerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/PerfAsyncConsumer.java (100%) rename src/{perf => jmh}/java/io/reactivex/PerfConsumer.java (100%) rename src/{perf => jmh}/java/io/reactivex/PerfInteropConsumer.java (100%) rename src/{perf => jmh}/java/io/reactivex/PerfObserver.java (100%) rename src/{perf => jmh}/java/io/reactivex/PerfSubscriber.java (100%) rename src/{perf => jmh}/java/io/reactivex/RangePerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/ReducePerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/RxVsStreamPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/StrictPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/ToFlowablePerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/XMapYPerf.java (100%) rename src/{perf => jmh}/java/io/reactivex/parallel/ParallelPerf.java (100%) diff --git a/.travis.yml b/.travis.yml index ebedf605a4..972c0c4cc0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,9 +10,9 @@ jdk: # prevent travis running gradle assemble; let the build script do it anyway install: true - + +# running in container causes test failures and 2x-3x longer build, use standalone instances sudo: required -# as per http://blog.travis-ci.com/2014-12-17-faster-builds-with-container-based-infrastructure/ # script for build and release via Travis to Bintray script: gradle/buildViaTravis.sh diff --git a/HEADER b/HEADER new file mode 100644 index 0000000000..3949e0b453 --- /dev/null +++ b/HEADER @@ -0,0 +1,10 @@ +Copyright (c) 2016-present, RxJava Contributors. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in +compliance with the License. You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is +distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See +the License for the specific language governing permissions and limitations under the License. diff --git a/build.gradle b/build.gradle index 1b3e557648..927fde214a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,22 +1,47 @@ buildscript { - repositories { jcenter() } + repositories { + jcenter() + mavenCentral() + maven { + url "https://plugins.gradle.org/m2/" + } + } dependencies { - classpath 'com.netflix.nebula:gradle-rxjava-project-plugin:4.0.0' - classpath 'ru.vyarus:gradle-animalsniffer-plugin:1.1.0' + classpath "ru.vyarus:gradle-animalsniffer-plugin:1.2.0" + classpath "gradle.plugin.nl.javadude.gradle.plugins:license-gradle-plugin:0.13.1" + classpath "me.champeau.gradle:jmh-gradle-plugin:0.4.4" + classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3" + classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.5.2" } } -group = 'io.reactivex.rxjava2' +group = "io.reactivex.rxjava2" +ext.githubProjectName = "rxjava" + +version = project.properties["release.version"] + +def releaseTag = System.getenv("TRAVIS_TAG"); +if (releaseTag != null && !releaseTag.isEmpty()) { + if (releaseTag.startsWith("v")) { + releaseTag = releaseTag.substring(1); + } + version = releaseTag; + + println("Releasing with version " + project.properties["release.version"]); +} -description = 'RxJava: Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.' +description = "RxJava: Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM." -apply plugin: 'java' -// apply plugin: 'pmd' // disabled because runs out of memory on Travis -// apply plugin: 'findbugs' // disabled because runs out of memory on Travis -apply plugin: 'checkstyle' -apply plugin: 'jacoco' -apply plugin: 'ru.vyarus.animalsniffer' -apply plugin: 'nebula.rxjava-project' +apply plugin: "java" +apply plugin: "checkstyle" +apply plugin: "jacoco" +apply plugin: "ru.vyarus.animalsniffer" +apply plugin: "maven" +apply plugin: "osgi" +apply plugin: "me.champeau.gradle.jmh" +apply plugin: "com.github.hierynomus.license" +apply plugin: "com.jfrog.bintray" +apply plugin: "com.jfrog.artifactory" sourceCompatibility = JavaVersion.VERSION_1_6 targetCompatibility = JavaVersion.VERSION_1_6 @@ -32,61 +57,158 @@ def testNgVersion = "6.9.10" // -------------------------------------- +repositories { + mavenCentral() +} + dependencies { - signature 'org.codehaus.mojo.signature:java16:1.1@signature' + signature "org.codehaus.mojo.signature:java16:1.1@signature" compile "org.reactivestreams:reactive-streams:$reactiveStreamsVersion" testCompile "junit:junit:$junitVersion" testCompile "org.mockito:mockito-core:$mockitoVersion" - perfCompile "org.openjdk.jmh:jmh-core:$jmhVersion" - perfCompile "org.openjdk.jmh:jmh-generator-annprocess:$jmhVersion" - testCompile "org.reactivestreams:reactive-streams-tck:$reactiveStreamsVersion" testCompile "org.testng:testng:$testNgVersion" } javadoc { + failOnError = false exclude "**/internal/**" exclude "**/test/**" exclude "**/perf/**" + exclude "**/jmh/**" options { windowTitle = "RxJava Javadoc ${project.version}" } // Clear the following options to make the docs consistent with the old format - options.addStringOption('top').value = '' - options.addStringOption('doctitle').value = '' - options.addStringOption('header').value = '' + options.addStringOption("top").value = "" + options.addStringOption("doctitle").value = "" + options.addStringOption("header").value = "" options.links("http://docs.oracle.com/javase/7/docs/api/") options.links("http://www.reactive-streams.org/reactive-streams-$%7BreactiveStreamsVersion%7D-javadoc/") if (JavaVersion.current().isJava7()) { // "./gradle/stylesheet.css" only supports Java 7 - options.addStringOption('stylesheetfile', rootProject.file('./gradle/stylesheet.css').toString()) + options.addStringOption("stylesheetfile", rootProject.file("./gradle/stylesheet.css").toString()) } } animalsniffer { - annotation = 'io.reactivex.internal.util.SuppressAnimalSniffer' + annotation = "io.reactivex.internal.util.SuppressAnimalSniffer" +} + +task sourcesJar(type: Jar, dependsOn: classes) { + classifier = "sources" + from sourceSets.main.allSource +} + +task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = "javadoc" + from javadoc.destinationDir +} + +artifacts { + archives jar + archives sourcesJar + archives javadocJar +} + +jar { + manifest { + name = "rxjava" + instruction "Bundle-Vendor", "RxJava Contributors" + instruction "Bundle-DocURL", "https://github.com/ReactiveX/RxJava" + instruction "Import-Package", "!org.junit,!junit.framework,!org.mockito.*,!org.testng.*,*" + instruction "Eclipse-ExtensibleAPI", "true" + } +} + +license { + header rootProject.file("HEADER") + ext.year = Calendar.getInstance().get(Calendar.YEAR) + skipExistingHeaders true + ignoreFailures true + excludes(["**/*.md", "**/*.txt"]) +} + +apply plugin: "maven-publish" + +install { + repositories.mavenInstaller.pom.project { + name "RxJava" + description "Reactive Extensions for Java" + url "https://github.com/ReactiveX/RxJava" + licenses { + license { + name "The Apache Software License, Version 2.0" + url "http://www.apache.org/licenses/LICENSE-2.0.txt" + distribution "repo" + } + } + developers { + developer { + id "akarnokd" + name "David Karnok" + email "akarnokd@gmail.com" + } + } + scm { + connection "scm:git:git@github.com:ReactiveX/RxJava.git" + url "scm:git:git@github.com:ReactiveX/RxJava.git" + developerConnection "scm:git:git@github.com:ReactiveX/RxJava.git" + } + issueManagement { + system "github" + url "https://github.com/ReactiveX/RxJava/issues" + } + } +} + +publishing { + publications { + mavenJava(MavenPublication) { + from components.java + artifact (sourcesJar) { + classifier = "sources" + } + } + } +} + +// Reactive-Streams as compile dependency +publishing.publications.all { + pom.withXml { + asNode().dependencies."*".findAll() { + it.scope.text() == "runtime" && project.configurations.compile.allDependencies.find { dep -> + dep.name == it.artifactId.text() + } + }.each { it.scope*.value = "compile"} + } } -// support for snapshot/final releases with the various branches RxJava uses -nebulaRelease { - addReleaseBranchPattern(/\d+\.\d+\.\d+/) - addReleaseBranchPattern('HEAD') +jmh { + jmhVersion = "1.19" + humanOutputFile = null + + if (project.hasProperty("jmh")) { + include = ".*" + project.jmh + ".*" + println("JMH: " + include); + } + } -if (project.hasProperty('release.useLastTag')) { - tasks.prepare.enabled = false +plugins.withType(EclipsePlugin) { + project.eclipse.classpath.plusConfigurations += [ configurations.jmh ] } test { testLogging { // showing skipped occasionally should prevent CI timeout due to lack of standard output - events=['skipped', 'failed'] // "started", "passed" + events=["skipped", "failed"] // "started", "passed" // showStandardStreams = true exceptionFormat="full" @@ -102,7 +224,7 @@ test { maxHeapSize = "1200m" - if (System.getenv('CI') == null) { + if (System.getenv("CI") == null) { maxParallelForks = Runtime.runtime.availableProcessors().intdiv(2) ?: 1 } } @@ -110,7 +232,7 @@ test { task testng(type: Test) { useTestNG() testLogging { - events=['skipped', 'failed'] + events=["skipped", "failed"] exceptionFormat="full" debug.events = ["skipped", "failed"] @@ -127,10 +249,10 @@ task testng(type: Test) { check.dependsOn testng jacoco { - toolVersion = '0.7.7.201606060606' // See http://www.eclemma.org/jacoco/. + toolVersion = "0.7.9" // See http://www.eclemma.org/jacoco/. } -task GCandMem(dependsOn: 'check') << { +task GCandMem(dependsOn: "check") doLast { print("Memory usage before: ") println(java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1024.0 / 1024.0) System.gc() @@ -139,7 +261,7 @@ task GCandMem(dependsOn: 'check') << { println(java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1024.0 / 1024.0) } -task GCandMem2(dependsOn: 'test') << { +task GCandMem2(dependsOn: "test") doLast { print("Memory usage before: ") println(java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1024.0 / 1024.0) System.gc() @@ -159,7 +281,7 @@ jacocoTestReport { afterEvaluate { classDirectories = files(classDirectories.files.collect { fileTree(dir: it, - exclude: ['io/reactivex/tck/**']) + exclude: ["io/reactivex/tck/**"]) }) } } @@ -168,84 +290,71 @@ jacocoTestReport.dependsOn GCandMem build.dependsOn jacocoTestReport -// pmd { -// toolVersion = '5.4.2' -// ignoreFailures = true -// sourceSets = [sourceSets.main] -// ruleSets = [] -// ruleSetFiles = files('pmd.xml') -// } - -// pmdMain { -// reports { -// html.enabled = true -// xml.enabled = true -// } -// } - -// build.dependsOn pmdMain - -// task pmdPrint(dependsOn: 'pmdMain') << { -// File file = new File('build/reports/pmd/main.xml') -// if (file.exists()) { - -// println("Listing first 100 PMD violations") - -// file.eachLine { line, count -> -// if (count <= 100) { -// println(line) -// } -// } - -// } else { -// println("PMD file not found.") -// } -// } - -// build.dependsOn pmdPrint - checkstyle { - configFile file('checkstyle.xml') + configFile file("checkstyle.xml") ignoreFailures = true toolVersion ="6.19" } -/* -findbugs { - ignoreFailures true - toolVersion = '3.0.1' - effort = 'max' - reportLevel = 'low' - sourceSets = [sourceSets.main] -} - -findbugsMain { - reports { - html.enabled = false // Findbugs can only have on report enabled - xml.enabled = true - } -} -*/ - -// from https://discuss.gradle.org/t/maven-publish-plugin-generated-pom-making-dependency-scope-runtime/7494/10 +if (rootProject.hasProperty("releaseMode")) { -publishing.publications.all { - pom.withXml { - asNode().dependencies.'*'.findAll() { - it.scope.text() == 'runtime' && project.configurations.compile.allDependencies.find { dep -> - dep.name == it.artifactId.text() - } - }.each { it.scope*.value = 'compile'} - - asNode().developers.'*'.findAll() { - it.id.text() == 'benjchristensen' - } .each { - it.id*.value = 'akarnokd' - it.name*.value = 'David Karnok' - it.email*.value = 'akarnokd@gmail.com' + if ("branch".equals(rootProject.releaseMode)) { + // From https://github.com/ReactiveX/RxAndroid/blob/2.x/rxandroid/build.gradle#L94 + + println("ReleaseMode: " + rootProject.releaseMode); + artifactory { + contextUrl = "https://oss.jfrog.org/" + + publish { + repository { + repoKey = "oss-snapshot-local" + + username = rootProject.bintrayUser + password = rootProject.bintrayKey + } + + defaults { + publishConfigs("archives") + } + } } - asNode().properties.nebula_Module_Owner*.value = 'akarnokd@gmail.com' - asNode().properties.nebula_Module_Email*.value = 'akarnokd@gmail.com' + build.finalizedBy(artifactoryPublish) } + + if ("full".equals(rootProject.releaseMode)) { + // based on https://github.com/bintray/gradle-bintray-plugin + println("ReleaseMode: " + rootProject.releaseMode); + + bintray { + user = rootProject.bintrayUser + key = rootProject.bintrayKey + configurations = ["archives"] + publications = ["mavenJava"] + publish = true + pkg { + repo = "generic" + name = "rxjava" + userOrg = "reactivex" + labels = ["rxjava", "reactivex"] + licenses = ["Apache-2.0"] + vcsUrl = "https://github.com/ReactiveX/RxJava.git" + version { + name = rver + gpg { + sign = true + } + mavenCentralSync { + sync = true + user = rootProject.sonatypeUsername + password = rootProject.sonatypePassword + close = "1" + } + } + } + } + + build.finalizedBy(bintrayUpload) + } } + diff --git a/gradle.properties b/gradle.properties index 5d8d80efe5..53ddd3a0ff 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,2 +1,2 @@ release.scope=patch -release.version=2.0.0-DP0-SNAPSHOT +release.version=2.2.0-SNAPSHOT diff --git a/gradle/buildViaTravis.sh b/gradle/buildViaTravis.sh index 4456600e36..f8ef3a8440 100755 --- a/gradle/buildViaTravis.sh +++ b/gradle/buildViaTravis.sh @@ -12,14 +12,13 @@ export GRADLE_OPTS=-Xmx1024m if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then echo -e "Build Pull Request #$TRAVIS_PULL_REQUEST => Branch [$TRAVIS_BRANCH]" - ./gradlew -Prelease.useLastTag=true build + ./gradlew -PreleaseMode=pr build elif [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_TAG" == "" ]; then echo -e 'Build Branch with Snapshot => Branch ['$TRAVIS_BRANCH']' - ./gradlew -Prelease.travisci=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" build snapshot --stacktrace + ./gradlew -PreleaseMode=branch -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" build --stacktrace elif [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_TAG" != "" ]; then echo -e 'Build Branch for Release => Branch ['$TRAVIS_BRANCH'] Tag ['$TRAVIS_TAG']' - ./gradlew -Prelease.travisci=true -Prelease.useLastTag=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" final --stacktrace + ./gradlew -PreleaseMode=full -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" build --stacktrace else echo -e 'WARN: Should not be here => Branch ['$TRAVIS_BRANCH'] Tag ['$TRAVIS_TAG'] Pull Request ['$TRAVIS_PULL_REQUEST']' - ./gradlew -Prelease.useLastTag=true build fi diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index d3b83982b9b1bccad955349d702be9b884c6e049..736fb7d3f94c051b359fc7ae7212d351bc094bdd 100644 GIT binary patch delta 25563 zcmZ6yV{j!**shz2ZQHhO+qP}3XeF7L6Wg{|oJ>41C$?>C&U;SnQ+t2AtGcTiPygz= zyZU2Usc@5WC*zi?n+Oew6t zu~WW>@PYB#dOnNVsNa~A=@gRKHa}ow5y^&U%r)fg880#jCTK# z?dXL0(oJz?h^u=s?kTGdi8kl{ccjP=Ax(8{i&qVksDWed^##)+?kM@_L# zfIC&TgEnBsS;_KJGFpj7m(SAEGSOm+-*J$f-=32PH>X>qr-V<>UewzUDRXvaXK>r* zyaFaGWl(8xEP(9Srn0eiS?)@LOXk~_jGp?k=d?SG2jb2@^oXuR4q<+JP)(AX~Rai^3GP2~PIb+{)L zd&`3RT?7bFUS~gKWcHdJLn8i#(`9UEsRib_0x0=bGdr%7SO8zs*0YLJZj%oNdLTQ8 za<$|_HM;xkB!wy~itYhMm?_s*I+f`^BR$8OGHtabmZo*#4IDpl2aAJ|JMHX}5NJx84Zepn=W@T};OViJ1I~d{Ztfl>wPoUC~+Qw~2S7>aZ{s%z&8L$^>Kl zQM|p2Y`2j{dEkk;k3uZv<%_-KU zpD`T)NZV2%4U@HibJCC5JkwjU0{CLu64g6E&J2pO;c!3Ol$YcXbXP86x4p1(CSw=Y z#!qB;B^J4z3&Ldm7V%HWw&7{)iuwcr0>h0(RXDYGU}9V1sSIo7%JnHVDEa0zA#czg zaWeC^nb&GpSKac%t&u8>vI4c*GR20-j*(zy7ZF-t!zvkG+mK?bmJ!zMRus2YrCV z?b|ay9%l;9j;bW{I?8IF^q0us`EtHR=-L!izw+E!8Y|9ac1KF^{@Q!EE!~Jby6r_p zio9Zb4T)bPA>MR-a-t9AKq+x0(T&3vq&cElr}%~in>W_Lg0}(`@B%<9ahXA=cZl~t zNvuH&eoxc5tag ztVoEaSYyl#-W}XwqwYX{Bd$9As=xuthlCO3R^HuH5si`9jUp)_5H$*Y;+6Vr+lPYj zJN#S5@P-Ew*7p)}wnQL8SwHg6#}9CK)Re~~k!Ul+->}+f15V(RQ9~vDr_#Ey`32N$ zN2C)L_-^9pzlr1}avc-NqYoYpq$wR}PXB3%PdnugJ5YL6rz2#%@ZW8d#>l2FT88(L zwxw#1TLeE(s<35d0THii%z;pQWmPsFeH#10zNa>Eibzp3zR>iz@I;lnyA+Uv-zFq6 zgDn5PA21`?i_BP1R9Mxe4rlWQ5t9w_gJFMUQ_GH>1;miLReBt9hZ5(Ku?Bgfy(krX z6=rbm4C;Zes-%g?&?H5+rzB4*lfMe^-n`0v!~8F8h527{oWk&9{r}L)2^W43l>fw5 z^gq4i{QtC)MF;i=Wy;-eTwt1pkqf#QrVvExh?Sk2R^zg~lS6nl<0}@@Xqc&@Vw9b_ zllePmI9%=8^)Itu_pyor3pg9L`zW_EcsF2L;&6WhGyPBUJ#K`2te;OBTtvW9?^dPJ z`3R8Rv6s<1>@0`~;2fzN9XAcQL9QFpm;i(g>}%HHg14fE0uITCaG+3xt`axYkop$N z$i?6I8rQqcshry9J(u3gx2Wq`H%!cB5uq-pG?Fok?Qi`znvHyrIFD;Pz<)O z3u{KmBo;PflZTfeBI*JHLyOZ$K=k1)WDztRQU5Zt^AnO_nSc&X_0{rj=xCET&kl%d zcuda@$9_7;anW4w4uqL3F;SgTew+%e4}TUA1_z(n$W8u4lPWm`;C@EMw(?Ve8yb=k zNIzI+>cwDn;6^zlL3`653M9%Nvi z9)c<6ikFbe`W9ZiG>Nusqv@^rZ|rw`f}c!?(&*rj$*B62&8CittrT` z1%F?$uNuE zs}%&aGp;XIzxl4t9boMeU5plR57aS^^q;Qxl-p;CL0h6ZtCysY4A8wl8P}TyBxc|{%y|WPg zbJ~UcmKo#m{A`GD!C#Hc@C=AG891O0`_)UoE~`nvOAg)zi%(9;X>^)hnWPcHZ0}`e z@0&q=j;O|h?>Ya+Xarv=j0-ql8r#-oyDS;Yyo`s7bK!+HKLXu(BW+Layf8v-bAJGDr|HD`WR=Yb_CV+IcOKfB;&cj6$oRXhPKG z!k2Ak;pKEY61w+hUE|HlmtJ1S=5vX-_-{$ryEO!l-bHcQXoMGeEJM`@Sn+XevF#}E za~N`W2%7nym0rMd&iG%)*;Fh_jJLW7xIfIu=a6`^@YAix$E7EE^w0Im(VX4joH`gu z)umv$^(He4ktl}Q%_m3XSp*2|Fho1ggg^!+%XJ@#>jJH4+*Q9&3fI3tw&hF_PvyJYaesgK727v@99qo0@u3pQ(0^ z;SYDUjia94IId#FAyEu`8J3Gsb>;reLS=nPfnaRouf2$V1_}wKpn7V={hj{axmSxReLk*Gd(Ft z%C$0#4Af}d;|rng+$L5uHNNn2e!}W{|!`!vfc}I6= z2EnV%SBNhwr;Z~3tml+SWtKzhwrY{V@X6UHp10Vi@EsjS@J)*Nb?!qy>0sVKca8O- z*krP469ZAKgArJMiUY&NW*Q^0-$<7rJCdJ_12l9}KmNhOakBxZM94M5#zr}(iMVwj zRS72vj~!*)x-gGE%3OuBcDNR)#73UrV7`P&Gn`3nUd~H5s>DVXq39-$zr`4yMYkP> zqlA_*Z8z@_!_n;1?>N)E*N2k%iuYM7s`^gv6azCN0iL1qln{@YK$wtF0atUHltLp@ z0;Cs{%&>{7^dERGPM2_6e8%($@}z^44CK+5?NnozLSX>PVDzZ<99l{*cuL7=a4-I} zRG`5VoL5vct&Po0**9c)lNBbZV~`0jq0Uktz@4a~sgrOFLY&PqSI>8sr&KhHwL8Wb z-;ipmsuxa6;$*Xk(Hl^-V=Tj`zH6@J29EH#2`A>NKRZb!yc<^YogI5l#L_GAX3J)o zE8jv6+@(bF!?Eg2v6L`0a%=q&2Up|suew+;tae~OqwGS~?>l0d+E5(u4DPa9p7MYY zsn92BkaP)obGK_@GnO6a>$aS2f$EU^sdKBu@5gpFTfhHd$$#Dv#F>{>;8P_*4xH$O zqK-SAk2Zr^i_GeB7u!xlamSPHaZXoBIL63(%(IDUMdVHE>|#EA$jl-+deD$?=56OJ z={&19T<2Uh;C8A~1iATl`TO&)cM0|Ce6^R9I>4J)$~Ma@n;Ta(@^`fM*tLa$QgSk& ztsDpL>J+HzX-5XYFPNyS^~IB;fxkXp5zg;*wSv2X4Pw|Q3>hW0F0tK>uc3NwB)O~>&Wnyqg>UwSEURF*xc6Ek_ zjAzLwHmUQt%0RjJrXt1RX7uW^dw4WCi?}ru8(m)JwHFY)l-$uhC?A^+NY{~>EU(zy zgPsDV`0pM(i5s6$>0cQEl%SRdw88A7Trs+0Ztm0lk@aXwA8lMl23V)wM4du8Oa^n} zg1nn%c~o(b5>`2#$q|~nR`p`(Sl^X@sO~R`NOBhztLuWcp3K$`4l5Q0e?P3YfLYa? z=bL>t@hf;9g}7+elyX=bpmcs)RqX`7pXPZF2z}IdDb{#_rkX1|z*QAp`yp@qttvGq zoePZ!Hz&Kz%6NWNWWW5&&?Oa)Wv8Xo#Oqnv(lN`!YM1!FHj7WIY`UM!v@RF#^Iy|A zN0_ZWLmKmgY2R%c+4@@q{q5&8eXM%FZ_~I(wSt0cf?&LAXG zO7?*r@a7<=P=+z#W4&>{YSz<@qjg(pll}mPTZdoIAI9RMfNp_~t-Q+{^$jTx#*q@v zUAG>sXxrabz@GSA7aNh^S!~Y*w6Hb!G}wnKzFxJ5exX+@bD1OA`Ey=j2P^ZK6}xS* zw#3n4&9-N7t!*;kvAQw}4L9@TA+D6gR!wB+f6OgZT$LD%7yLc>y6oE3S}H)+Dn^vJ z^DV2GJ4PB$jK}q69@soU)M*xS{O#lsrj;fx;%!hA@QS5;Md2Mk(e(F zpC3`c*stN0z{i^({AD=)^JBmdwx}O*=wxh!qmT)#uh4k5GSRgbl5?y??4dMngeocL z7`!0`%nNA?_JGVU@GXTiH4&l@31w7IeMN*tCmBPOGFZL@n-kT#!Vc3f zI)t{7+Uz06{5J^r zEVU`L@J0{L5_V%(QOoF;A5lfvpOJ6_yW>yvu^+oi(#H}D;WVY+`)NHdBbiZw7U|c) zxhkl1WJaV!P)6{=CdF9R`Zcn;VG`H-<(nQ+MgFq&S}9KfRoCvGuCi^2kM==JHJnBR z`2J=@M)nDVY39WgHvGaP95;6@r3e6OCL}`fCg|{((T=X=i&l^hxMEWX4akzBAD+AR zbO{9r#;T#m^@L*R{J~GDrJ2;F_@NfvL*q(xaCaLP_n^U|A(!`u@SvaVxMxiB-dB=n z&GbXNz7OdFQ0ZKrN?hy`_Zo}lb`sS&7S%o$&1qNsarX99`pTPRtaM)Ys`d;7&(%vL z8G7(s=ga2edEq7cI(UV9Hjis8uv94r(Zn7Hs%ItRupfP6mPF{L_D3Fa+zap~U$5c? zVQ}2L^3Hgd9zZ)=2e?f6=Y{|an`mMe^Y{`?$b@GY&FZC$5LD(VZc6BHY?8mhetw*x zo7^zcw`de4y>P7Gd7QtqUg5k_Dfq(gW#INOTM}DqUq$}sb8<@byIb$;W%&Wg0{6siqs&RnIHl? zAfwonVW#41{pAE_kX17+!8hYrG1D1%uBuie*}^7f&xli-Q75NMn-?WH$!nwLpqE}d zA`;H}etb{Og1iz(ae)p?)JhRK7rrR`i0{1{^ndZ{peR-}V`wn2BZL%ESOK7c2gV6r zkg(pu`UMv^GB4T~*PJB#YUraVeK)1_fF`L&v)e(K`0_$zuWwsTy>_sIik!lFsgs}l zdW8F8&N2C7mNhjR>TH-{8%M8mMSo#N=b4g?pW1sscXJX-2gdBHKwsoZ;LeG^4)E(n zh6I8)Y=b|4uoGD@8jefRo)_3akwAxJvY0f?*9H))E8n;)&Nfk}!CAWX;xg16qC#S6 zA5x#hBNC!Lh3{>Z0}=TRHu0{`T)5F&|X0T0*rHM zFPr+Nodc;yOJ$-mraGlMD5DPG#iWf@=X}ZoNTtBP?n`Fw!`@fBQKIBVw3g+N`+x?; zk?Z2C35}ZkjgRk9EUoB~>mfP1M`&g>+88lZek_rYWKGp6Jtoa+R{xQUplA_d z_$kNkw&_hck^%CJNLx2-!nU^DzO%n~+)57_@_Z6{L^GC@qG1t`S1*Bdk-h7+fdefhwl4%ga1lwOr{c% zyU-J&^LGHX&t(^;!)}+0>l2kn?=q5m=C9EcVMYqGE9=eQyyi2%5WV{{EZG+OD$495 zD)6ifp&iXub{32byIq;2k`<)f-*O=|#8OltnZW7a1i;s(hyvVKx@}I?;f{y`yjQ*; zvN=AyHt5A}$7dTBa<0QP`UE}PiuAz+0Sxv<2*PH?C{N$ncAQ+d?{r;EMsRm zn`MVAIpEO_6NZ-G)sucaHPq4&O3$gR=}i}lML1cplJ>FQO4K(?gwbR@)TZ}(TYAL2 z((e)uuGuP>`#7vAI7cHC+^e(HDHgBT@3K?wQyc*vOw)RBU=gnOtWjd?@?`-NRaP#A zLuS9^bW-yKPLgoZ+?6a2_r&%LQVvXAV+&tRED*GL*Di!lICNV^QI~BP;%;7q{Rh70 zSiioaa`wBWJeD=8ak{X8>}i(s`LlC5dYONQCrLMpJ6w_idnywI390uYe{Hm(O!WZ^u9i*Uxb`JhMbq?Gos`TS&RWwRgG@}-vciPG|k6OeG! zDFClu1{wI9b$bXFe@TCsR)~10f;RzJ6bx(${0BpG2PTC!WLLC@s78nrNE>y=OH1Oi*ULnEg9KF#lwB-a?Zn9mq9S3Fwi#ncb@)10sB$$W+KZRSXFfelfqdo2nco zP7b}TZ~_A`R`C9b{0h8(bNuPZN{%Q7#^M;B6t)_+)P#gmjm*o-r|s>kuz9}Px&>|dZzrc&9LR4_^(@Fve`2j_yr}h^|9T)@?o6+IXjg2 zW0jPlPw=p zNlen?`u4|kumY6U-P;ZOuE&V(UkHK%G)CHQouGE^4!VN&Xx~(g%f+)V#t4 zRqxu+L*IFXtP_1*FS#r4J*b+$Y{LFZUSKo zWX}!`r0IKxwy%A>h5Q)hN&?`%;Th{ibRC+aI`r%`>RM!(aU-7hC~n|yttnXf#3 zuS%K)rXjBw<8w+%)YoEricya(t$csq|Hu}h zKx!|~CX8O@A=aKpxp5k+1#he3PKMWWzp-O4;S{|cD9TmoG7}|7U~RALOanQ@_$L4J z2Pji9eOb=np2_P>{YsMGFtjhX!c5(FgBhrTsZM5Ju%^c1T3;Mydkp(soa?+beiwHX zELTl5GrUjnCA}0CZ@|Zy6WB*haKVyGEp=?dMN|B66vl6wv$r(4UmWU`1kPm`d%+pE zuZ`5cYmFr1#?d_=4lg&vatq`%(mGX^jsPMME*vAW<&0%w;s-^W(7m=r?CiD=^HHn1 zGh%R@wkZ9RfwO-l3ToIxc`XSQv3uqC9xTnKtIYHBtCb;Hxz+hp8rr!-L9*Md+QZDR z8W=Q!|E}6Id2Ro#j`HF)*+-bzvMY!zFpV+ZQI*&T!%IWMDTvdqzykcX0d17iJ)bV? z`tv(cuBvIE-}D=vf-eC`O{VkHK^;kVc#WPLx@5zG<@!N>bB2-4R^?3cpa-nIMagK| zzhQ$>@FH3mRvmdxhx!o$ZPJB;1(KD;h6{F%I38zrF_m+YWtHl~;7W{`KcqArilrIV zhs~9iVyHaV0rtt?`M~jvZ^eZes<_P}O^V8>vg{7o^9uoS4z4CeMx52c-5_SPov3N&MSd{r6~PuT{3O? zXfmbRd3!fDi4BJc$JAf3=-Joknq(=2MZi@2hV=SqF7rC-qjM(-i z&!^r^4?$j(SYY3ouwOoC>4cqyWO4DTYF=?rRv$;5X-sDZQpUU_3lqV?No|9PTiO^v z^}NKU;~+Q|D#+e_c1MrTRr_h+HvSl|B}hwqO-SMTM93T?$b1>+gaqZ!Cuvpdz4iqD z6yCw<{S+<(M?a~*Y2w==ux0NtFUwl7W(l%_dNF8P0rp1Dgoii7b$|E7^)iQ_jotwG zYsNOfF^52*r(^W`d6GUSnZUXh3cn70Y{2o~YFn2wp;N(Z8Lp<6PM_kd5 zeUu`gV{0(q3yO<7T`9|=CK~di+qPblF$v0Uxof1NgB~uFm%hcIW2() zd>I1xr+q*GKH#rWj;|Qx$POVQE}p`|$Y2}_OWnZt#R!g2SJVkQz6E;D!N2@mnRMf`UVv`ny%ug!Zg#) zis$^$k##MDyeSaJqQhxThg6`v8Z2x8vc-xzoKaRAq!o(Wo?+TYHPgn9=q*75noIwZ zJo2cJ)AA@7OfIYJ7i)7>ax0syxi&h&Pj*6UE1Dlcifia{5k9JzK0z|)58}J)=ZtjW zb^DP0_F~%VNl0IwH$tkEqDU`+%V{DOm=EpsT<2O9-Ej;RJC!qx*l2|EDa2v{4r=F) zrt!vlZ}=P}0Hb_{k+&%VxD)0JtTIL8OxQ_L?tbt^yrn*XIZNj1`kRr5PzDA;{Nore zOC?0!$5mIQt;riY!Tn4HWhJ&CcIK5EkGX~3@!CzIo$m3NxHxB)9C9W0dp#avo<|Ts zJYm>oLT(vcgl6B1av)cgnv2o^tLLRM9NXjdFB=DyG{K)&)HZ0f`ofGtGP(d-%HB#d z{TxthfAcbojzA`&*zJe9t=+zDph3Ob6BCa@D%6?%WH?7!%axR|dhW4=2G5MGFVDOs ze;qDv>n6I`X+6X25v%SS2`Ni>gNPhz*Acx5TclR2rYB>@q~E{O`ed4bPQF10zbWgp ze{;-qO|+`)o^ya|p&qA?>ZuuMA#h0@qvphxOi46sL{d)iwQqhH4512j1q0jn^fv#p z`p%Ae{ITQ9Hp(>VOEju0ux3?w6_BihAky=^b`Ai?0$Cd+@NZ-d3y>=<+1Y3m3d9-- zT~x4nE5tqZ3dV32*rl}rG2z~4u0gYYdbfc#|l)WR6}&DU8Sx(kvU0q>0W;L2Z-58~H#E zD8?WekdfN6Xbxz`AQ_|Kzmp4)k5Hj;6&o&)+i!U_L@&rNO?eduSE0IX6%?iz!WsEi zkQ4uIjr%^ig-@^MjYok;6YhJ7kFjKXI3w33(Q2c;VNqnNGYTm$+ED)s6K=sX(-fO9Bv+-_LZ5 zH-9YV(hPOO%rNhocVibnjaao8VvQ)|PAKa@s~PvH`H892Ga|0?QsgZ@x=FU77E2=x zX{!u))j1i$NHoV1LvFfGhv?}?$Ai8S&rxx&GJk`MoJSk^hrfxKrGJRD69=7&$Xi@& zWCBvUU4_&N*m@Srae&n#NM;~AO}p$B{=p{$6U@x1H9r7XF8jFHmBw&-|p<( zlS&3yp_M1BWyZ~yH}$|90)0hj9B0c0Qvp|Imvl;Ny&;{>@OS5*wIuocR>xEe&1^NN zxIrT&D}k|C+55i+-eOL&5(AN7~pqk#Ab{=dgJoU@LEE#DWJ z4MtWx1rr-CaDO}JeU+JvdE;FVArlF>^(VZTW+aFO{Orq?ID4fg*3{jQFZsfnWX{Y_ zi1ig4`|pLJ?H22=Kjvd86oumzfU~oB7l;=`+MIDKfh4kU$IeVQ3`#|uUAeOWd|`a1 zs$D#lJ|OMi*#Pl_>JM;U%MwiXnj>^PKk@tL-Jn|dt2?UAl*hPws`t7Qc47*4LY9n$ z9M{WPlx69um!D=9w;X(ph6wnB5=CrZOATQfqnV={2YjktslSU48hjPT zHump>9fP*i8EIJP`T_mGc#1c{-+Zbr_d~>_L zaSZ?02h{y;odj`}jpGZFaGA6;M)=!Uw}EO3Vu{)OJF+1l$7b$9D^+QjUWQy}>{qz2J(Ab87-wyAq!j&n0Y*pAY} z-Kr-ok8U+j1Hqg(Y^#h5xITx6^RYq$%qrav?|(ZwCDuAGJMQ>pcoDr`OM(pKj=OeAXDJ|Ou)fNa8*SJOExPQh8ez!enAFPO-KksCVv3q?4 z!!vz#SWIO0eUIV!t98AJ#t(Gn@#-Jx(|sCtRYxXjdcIWgtIYpO)$SNdy-3v-iAJ*q zH2ER78zD1wn*?L`hS^%8tjzOm3U^(TD+5{ZY^DQpLu~2wN7mu)gd=^HG`lr4Piyv( z>9yQ!UfuILRHPcr0wJqxPp|5u`D^($g;0Br-ULwjT-<7T6fp;ZE*){L?{$2nb3jER z4xf%B0AUoAn}x^fl;Ms*Qj8JuD%syaLI=KQ3MJ($@&b3u1xkP>X=M3$@yQ{vG_sLd z+D_@nP7}$$->Bc=W^KeUOVq~l?7q54dxh1zXkI@emmYAnSoRzJ;1Z#0vxeE<0bnR> z%Bkr&cdP~buQYm`p+7B=0U8II`aq#*nOAKybt1}ai9;Q+t1;RvVza|`*G$C(_ECDj zn~Ez7F5`%sQQSRRDmD4h?&qYUG4Tj!lcYwT^s3^Ud-TVIzlBrXd%S3;{U~EU-ypY1 zdUA$gGU0E5S|hWZuOBS`^Fqu+=oF>I00Vob0|O)dFU6A5PC^cZ3&1*R6QOxIo|&F* zgc9$lr9dAi_U5F;PbO_5BQ;|q-KX?Pj@zV~$x}eT&?eE=zbf`>$MUHx)6zueqz8Ge ztn1f-mX~cD0Me>`;Kb=dGtL50-jt{gcKwZ-bzrP z+(hxEvI{u@3t_%Y1Srv#1JpwJ7HU zyM-{UeBxp{L5bs8O<(O_Hj%!_4)6u&#b<&%!xi^}XLRYuoZ%;tw#bPnZg3e9mFbg* zEr!|fcJvROF*R7msE6V3EXjDW5}XAYvi}xHSyE2i(O!U_cmfoXQid3ZSoeY)iL?7@ zWWqVKaC>#yds<}r$i}!eDdoo5&_#{jv4M=86Yi{nK^ie>h(L>7X58=Iz!%q zE*EiL+4645@~> znkGd$na*&hvCCUyag^vOo{4~mvwpp`$<62?;R)DAu)>PPX;gf(P*dX9)6z8pn({q? zFL(2b_FY&$c(xYG4rSJ1gDQ@mQ64hSo=0U>? zLIhl^?xp1<^!V`yYKHTmyf^u*I9X->Vv&olZ?!BZ>(eVbYJjt7JdR+xN;k*MX^D-N zShn?Ie!9zQ!l!G|#V6}_Q&DARKgSkxA#$BbqCMV^!;T|wuWA7M1uoJ%GmlQ8eOfX= zs_Md%Lyd_WO{di+ks~dimChFPhySFb!Z`4Snqh)-n~H?z@?41kpRJ75UtS@j&-Sc2 zT{F&3T~o7R7GLw#-jgT(+FIY;kYSdf1wI#R&(K95uPDMxo9NhJ+W9SlDFma$Ae{>9 z8+q1QPZ&Y4<7@Wc8vl&E}S_ z)|#Q8%UrWtZM*wpJ;W~X-t5#ymIM}o9k<|8>t|7@k$Sb^N3rIdwN*d)iMANZkFkY? zo2bo`m5{F?Bi`5G5Bt1c*=dt-2m-1vU%OkW$e0*q%=dB7_37!eYp);J|NO0KUXNoc z(YvL5rZ%<+7?+%|=OGk4A?V$b?sk&QO)^~y$JAWx+51&jZPH!~fK7HPxjIh7cSAhP zw7u7#n(1(^V6>=3kY0Rb9d9i)<9P(v1nIif<$m;a*#>445Qhj$XRL}ktQvvWNwTUJp&H_>F zj6tL64~>+QbgtI^JWu+GGb7SzaXW0J7Jb^<9-lEX?feg;@=84NR$16QzoQeqXgbf2=Ujor?B zwkg$3~+w!a%?AGc_@2|Y~>XF%F86V5g>dSXgePalK0G(JcaJdwrepFAG95hIT zJ0hV?Gdb8ZsFl(NluYp4@u2=)!)P|gl01b9chP>s?$bKjcm;Z=-Rue^>GwE5hu^5b z<$N-w-5mGQ?+m@jdlXE(#6qJ~evjL~HvHoAS^m zJ1A>^7gksF+3Lkne|9IV*wVO0O_`%*hjf;w(}JN7)7)YGXr7YrY=^+{@LsKIf%ssu z;tkiO6%_RnJpg>J`E=TzZ2igz=RnenOzo)Iv22yx|M;$-*!ii|F-g}l zYl+^=A{?1sISdnn2QM0}BsWN^WDRbRc|q4CRr zZTfn_i8F$Gr)4w0!OH-SvGs#fw@byhQ?^EtqK;k&xedrgr_aR!cc5ELL5Pt=mF+Cn z>d6fuP3V1gq#v0UW!GhGP*u7*$y8V^$;Q;Zu%xQ-*LGxl|5a6gsgy94tX;t3?%C5x z=YSX9vQ@uAlz^k~o+5NqMoailBHd@lgi6!_ikk@Ne6Ll{LC^0$3wj#NDN!2ALkhhJ zmCMgtyf2{QFG72cgELsnSHbwLH(jV1*j1#z+nrZNO^`9DJNIP@T0s#nuxU10!h^GP zpMhyWQd35J0tdSo{a7;yGl{m`Wg){UJ0iFm>6FutqQTjkPw*R(m~}QS!kJIvk5+;5 z``FK9*{5dChPX!6@(GPMt?i%YVxMG9kLz=-Nq>Ra6AhECYX!!QY-xX~)aRox&c_dE zqw4$um*!GJIh2$K&{JIb$!9KISyxNOoT5iDk72(T&|0d{qDAE>YxXOzG{4dMi*6IO zzTx_-?p5BH;+{IJ3MX71W;KH%cchTc^*$;e1-?56`&HkB#Ku_OzQ`03tL8Pou>z+0 zu`hvBgjaE16fx~~Yjk}6vY)ph9Z&{yBxe}mBARbJ0r3<4M;l27iM=$1&qU`*zhs`; zPY+ebCGx#CGmbcxCe%yPIk_i1zTu2v3+;!|JSe}Ssme-RAj{*kQ@uv>)%O9_%Lx^D ziwP;6Ki(8q;Gjx|y_J#io+23LQID;hvAu!7<7S)EzskCNH-3zT6|?MZ`7jtTYpVzw z8h>8hy1S4E<-!s=4qSP3Xn7AbnAu%TBi<8&?z~U?=MGGb{c>}DjT4_CoWUkWnYwRO zFG$;_o+q4wQbkT(&G4g2rEW7)Cy>TVld{G;sixX793og0;1%$N?y!Hml`USo?~4L` zqw|hD`ASNiFF&Wgh@QN5Ykb3TMSV`S{(?_* zkI9PHR4K<+tVJly1Qu~|-4LT?vIFC4nh~qxN$Wy#-SZ|J>57sXAhJ77_moQsD=?Aw zMk&jJe=8E%do7oiiT^=3gT7+-220>$c0#04;=!a`Ai$l4BG|iLNPf()<1lCZy(kok z{1lD%Vd-GUCuBtORI_3X!!6ZaO{c1gikJsXxexN3X)Jjyg0Sy3le1idn|iCY>4|?V z8zXdf4ocxQb4;7hg$7bvnbvwlRZSa&59sHe{%~c{S0W~sH^Go|Q5|d=?*t<7Ka~FB zJC>Haw>ln_ZXSF0teWs#hs&}YL7mwIOI~8)(ah0j|F`!CUw7{?xLgtiod!PMjCjpM z5I|c=8n^95GzMECed5e`*0u8xLu;7q6#AbRD?A?pwu)J(liLgrNsS_63i0>hSiG^o z7oXqI)Nn00N7ssB$g1)SJvUJBa+HmS>+c#jt{Z|EV~^rpF%_08CzSEgKL{Uwp=*+S&%delHhhelezmpsSH?y`qXE;zf9Pz=H8|&bT zv+DSid|=ui07lj-0Hex1mnUg5a=T%EWu9VzupE`nx1RB)0?uJx(UI9dbo9VV zJznJUrXn=k5TIBOR|quZWtG*?pBxNvb(R7gfnhx_E}c}K&a1hni;uCZ)(6+7asI3( zeFK-7;bLx&%Vju|?gGN0A1&ZLB6Z->2NwOiE&9_!UJwe$Q{gL-W6T?tnp6BU}7t)KV9Va1zeqN7g_XYa_UN zm|N`M9#nxDeK0&$1g~g*oJg4!Y~-pA%s-7hau^Cq7jcENxn&;=5ad5+RqbjTijP=- zY#qt4>W64H^9UL8`K`WCY8|QKi}o>s>Di|IT7$Or`2iFb(u5&Egy`ifv1@@q^xj4u zBwI5#SPZ& zC^Jpkk22m~IF}jQPhZ}gNM9CRWvN~|6qZ(iR8jbfv|DqXn(@kYhr%_MdW#yPi~7S_ zeCG)ZLS6gL5|B%3ZB)5isEq*oYK*p{K?rB83Pb_?o%36RTRb5 zEamvh*ZxIba5sJPguCXrE*$Y);?xoDp1LteH;A(BNNk-L+?3)9aV;#+-W0Q!;=QHJ z%aSngJ^>#m(M0^P21(pnS9&1?crc{RIl*3RkO6P&Jh_MQ;cw9kzkbljR;cm`DabSi z;k$n4{_MiLJ$t!JXBf1?tX2A8gSFr9&5e86%$GQQ3$a)y*}nn!4JcK73U?e9{j(rF zXFQDg`BQUA-?-5|c*b~g`lqL|!!BO6(-T&0=mq@wF7InYpH(pa<|hdM4XIw>MVbG< zA8tUrQZ80)ivhsbBcB^5@z>Ilio?tNxtP5(QK?rQJMarEPehb}Qlr&$U=&|!s=ca> z`js3jJS}vZd1+`MJ!rid3Lu3(2sQm-TRrK`VEnMPf{^p0d%^K|Lxv+`AT;*Y9kmOG zy!eG8@y~k3lC?c}V+2fy za9P+uZuK~1XXtfv9?AF}%SUi>?$P^9F`h7eRQNOsJUlW`&5^!6{578$_`_U)q?%Q z1mZ9Q=}>v%iD>mIMR#B+d`P_G?jH~x@sVA(H`LS@i`pNF?$V3$Q^yt!6Q?LW*oe)# zSEfH~^#F}Hc`i`b1ApotgUsO(o(EHfiNNthQqBL<*H=JQxqNTa-QArkNJ^u0d1#Q7 z?viefgmef80qGVHkdl%{x|J4??i4N{`G4_u@AVw-x4v1tYt5{Ao|!!}d*)1TZcfUl zP?QOf1hCb^c0DsVs~VZa(h@R3O$HrY-O8l9WCf1Z*jWf)NqTG3PWct+f;GU{F&_DWdSP*bL?F}Z*9 z4t0tK6`CsY>V|(vH3zKpO*$~Vs?5@Z z9PbwMT25G}7T(Xlz%{SI zsMiY|z8$^w89SmCR1m(E11qI@i1snEdGJF zE>;`hXhd^VCk`CEpwHT2CYK0P(Y zWA*4_IiQ0}@!Qt{8Qz~twM}zQjyKL0n%>M*^xP6F75GTc8i$vEs~Q*Idg`1_UlBtVl(~Zq*)m1^gUnn z_4cB5{Z8AB>LorRLc2N<*5Q@3fqQ%y&y~6I6QMe5V?wU;oNR=4V~NnjFJVLF=x_^9 zoUq$!=H*D``G&>rXVU44?ttYEBLBs%j)J1JNT&85-MZ0}K!?^9Ee(UNads$gRm`h$hYD?)_y(vVk=wm z0qF0$eKc0KmcZ>fnR?Q=?@*LEQ)DH0ISlVB>e!?`uR1ZX>Yrylro68%cS1Gu-CAi| zmh~$Wa2)jma*-Iq;U6kAA!Jc9lRoL)t%>PYeq1l+iTO66Sg$euofHTXs^Ft+OTJU# z_{BPY?6|Y|Vk)SbXhiLQkldFwI z`#45PG4*6rqC6op3OTns`hcmvJ+k-EHWm5y8YUYBGp|NNDu$c~He2W+!&+`}u`aw# zbc&GhYhLiUeLn=nL`)^(eKBu2?W&toi)z*G9wPk%)$DhC19oJ(G9p^f9?;`of`8EG zqkr#9gt7s^k_QMjAfJ^xHyg z**&Y}_CDRu=Qb*;D9*U2reIY})y;&Y^6m9d;z+2?Uprk4eOl>nzA||4CFrYZpy`tv zbzIyU@~j5c$ufVoU3IAHq_5L%Oby~|0hL@wrg}d-;woLVFvzD28#+SbW003J#dV*#AY}SC7u{o-?A@AEjGqhej$aiB!bZrbx_%Hpz*C?U|a2w zqDi|Qze%rM?c|CT+knrhB~0oi{AG(h4~{T+ z)0ziQY80K68~O4USs%$Nw5#Yo_11itzs10(-w7T`xjeoXihYG?d6hs868BFCns!KZ z(Zy$TR376M=jM+g$NySJRcypgW@QB2$8K$RBEE`!){4sf{foWUWTmU{yaNou0Si|uBLGSA$%EK^mVmmX0hWe(|Y>#F#r&XtR9&de`fN^89l<8PJW zrrD7}AVC(=eiK^DrZAc(n5TE+-}X&tujwx*_Mrg7=<$aflj1Z3W)lY_O8gU|-051H zKtpPQWF9Z+p$)g{TkOqG@K-rz62AA+PkIV|*L@OHrp)Pso@N#-LX{T&z2PH{N?JGh zjWWKPHC>9ErQXVZOUQS$3x-~Ok6_owNcW6PhswQXhwHGYv+c0-P`W-6Sf3q7(n^=} z{NP!?oQryYXo6?SVpZ|3tPaf9cZ`Luzsv~S&Ycgyom+lu^zg)2r>{Jh+0XIpI=aXi zOuMtW1LnT&w|Rm|(-th<99bl6&v@}V?756va@cbzx4N*Fu+2^yAF(kp8Xrc6xojKi zB^nOP?ODEu^z;6ktbOpgjcO|Qvn}AiY$9ySuEfh&Ad%ovapbi`kEXw*%pW6}3n7Y$ z^hf(ZIEqc?0#7R`f0%IO9g@|vjm#G<3tnwg(h+TB%WT0Yh-RMB(VbI~V?pZ+KThJEaMUfbCboh3en7_AbC+|WDq*fGQu!x!m~<-fVYAc zd?RKBIH0Kr0whtVM|ubFMP8;Z~znd zrajDcf8y2Jbt>Mz;F*Zu>JhOUx2!7~ma^hWnlx4)(=_wsF?^jFvWKdhXTrE+W53wv zhPZOyhtK2uQ`!U4JK=?I;pnM8BhST=Zq8~jxWMN=Gezo=X4-g>KK!IqFd#w4*>rr2 zR&0jvN14Tz0rk)xQMNR#42O5HM$i}V5>M*-n1qNvJIDH%P;$|nwzPC>T0jd83K+MP zmD;{bk#b;+`g5~jpup>W0RrOepY+RdpBlfK;xbgk_ttvbx55k2%xHJVu3%0J-Anq^ zKW&)Ca-Hu62gu2LJQLB#qvW&O`+i!TU?>Per)<;>RRf z2J_3V+isr7<-RJvSS(2OdMsHv2sRO7reoZ%QfWXZ35dF!C6 zir@$*c(jGt>%5o^30U%y#87=RaiMycuQfeE7RoM6!$?e>&lpnEE30@xubUawNF4Eu zq--0>vaelKMN^dsm6=Ver* ziWh2;U1qE8D>@+E=}^{)+eFsby>gDbzgUhY;TT?q*s_rG?C{A_%4VXE5=pj%^XoU+ zUmau-4Vnb>9YIu?r_wb;6Z7kvNxjdLz+b_C%(7NqjT+Ga2bqBN5jaNRvvM&px3}Q% zbb1O?N%b^#6IfV0G~J@$JnXF5E#L{StvV$x%c|l>G5pY>3v}n~G51 z^sB_IeWl(-Ui2(Rut>DKJ(d}vzTZz%JR`+JdVz4%&Xl%i>C@{2vEd&YZpy>M7-+b$ z^7#y_pOIa~Z$1jHuuaqq9V;z-Px+Uv1V1g?D-7o#-Mk{rT4IeAwj<~@Do}y7(_2{(zXRx_c8smon9|&CNe(T62ACg$wPNv?^rm&SrCsPS z7k-2#ZlV;kn%apAgH>AUbCxlMxJ|Fxpg3KZWn4#-*4tFP6GL^Hg?z@?L~{K~i*P zZm|o0aAX^gW$C@gHahD1y}k=ugLV! zP0VVolWy=eM$MCM6nVIKmwQGPHgPql6Yo2fscEL6$%qziuh&$SPdmDUz4rW0w;uT@ zSDam(|0pKfGoJLQESi-rM(8I0Wo|eDI5%<{qSoDl2I_{-j4bLcl1w(qmi4@< zjXrn+LMJD&CwHg%vF00!X?WBhZW>rV-LOvZ>YC#1siLQR!H`RH$+pL3KhI#3ZThHa zjOY(-*4YuTxlreMpVyl+;vFOs{$0QPhnR`|Id)xc zSJzmy#r(0dp$BjKO(a&(oJD;RWWeth+p_I6n-B7IH4Ka<8N z6fSLADKM{azL$gB10UDjA7xpkLYiE`L77~Uj>JLneC~rSne86=Qu*rvPseIJV~UNQ z9m5M16Yzxl$2_nZ&m;J4OtPtUCqhS_)K9$-qVRD~AWT-(4!fLh*6|9#36paWSKFZ!kfDX@A z2_r!*Kv$Fb3WR}|Ka;>XCkvr7XM#iyFoO&341B5KiFy9i(IJhhktr)KBjzyjP%?@R z#C!AEoX`|xeGw3dxnMct;E~+jx(r_IN=`jD_B)j$-{7Q-M(+BIw?CL6=4v^-yL(1! z)Pi8W`1xgQLSVG8x>s)OJ7FBH`qI3Tyu!TU*NzI$LLEY-8(fB8?|MnKSB$+W_X3M# zoV)^eU*gDM7&^6Oxb7>t#|8HtHe->U3X9^^QlbgG&S@fO9!=h_UjcD8j7W`GaXCy8 z2lOmS(6KGKPaXG6PH#xb=^)DKg=D<&EGlVP381_BLeb9>EFSJS-fhz0+y0?`?S-fP zQ2fxEd{-gW0Z(G)H&ve`xTqf1e0wmP93zV5cjL!*}_{O}Wje}6G z;we?9Y47)Zp2`RgYQFyD+e;p>Sr(@0v|d5@lJRv7*`t*S!QNmh3Q9AEYY%Lblo* z9zss=IB9G!p`6)4?uz^dujL#$nkjVThHcq*5`{I52vWAuEPAlklzcih5tjw0=yjhl zMux1SZ5o(?BKwWR1%}f z(e8cstxyT;>k-P-A#CcPo?q5 z5D-euQKbd@Rue}@vP|fe;V9NM|NA8}iKwZviw_}sffjb)$Yye*C=M5nskx+Q0^fC; zey$iUk=ENGlVbrd>^RUrkWcPUpI0PhF!C+vw_k5C+uxsVr%Y{5+cTa9$71U~@~d7x zFI>?NbT{?r$&8j@OL_9vAY>M%^( z9R=8%R~4xiV8gkJ3v@ZD&hN`6dkIcwXpJu_d>$+rH~$ZU%obwWa!k4=&5 znT-}0N9C-$%qMKq@H$;A415@a2G4l1yCUiFN-g&d-b?N|R3j-{HS?=C>C9UO86r~4 z2+OP*2WP%snXWm$;Dmyip3M*nIEw%csnrA4} zm*DOgW*y~*$nkJ0f0szFz&WQs z`osbF7-mpk%bP)fx|2?J?XU_4`hXTPB)*&j^3;kRyrq}@BhUC_xK2(%ulf@-cKQSs z77zt@`|C{yHVBXTCnb-%&tPQb1<~m!Qh7e^%Q|hYGB}yG2L;MBi$1E%uTz+1NdhI3q0}b6?{Em!X{i`7)@+jM<5Jfs z_gk=~0n6VO2)^j$)jQtqm?3TX;xT0tB6rVN{vb1?-}Ow=s39hDN)*2ZO)QIE*WGaI z85KTK!izNi5vOTvBP!u96W z>hAwVR6?{OGozU5kGp8=`zjTW$~!<_@bn_A(gj>Ly5C+|8n*UaCC4_XE&R}b(fgYRAIyA1Ha3R8|2fE@5iRe1C60T;gCocHhd_!PRs3VT2!MGFRJ6m3pC`b^Hyl3jsVc!E5W)T4 z8HaGUl7RnC0}dpkDZ!zjEDPL-g+={qjv7D$Tqp-zlKo8sNhmAG%4leEf@J?p;f?}y z;a?7zTtT^1INSf(uKxc~Frf%=a4kUS&f4|=R%} zJIE04mMs!pB#`^~)c1&l z07lmseERefkm2CoV*lA}olcOWJ`R|Y;q=^)Sy3e!#dY3X?vr|1Ugd zHRXS517>jyL(&NRMT#7NY3IkJ*0()?Kw-cbECz!=3jT%fwWET7`;nmqQX2 z2IwfPV1&^CNBloR)wWf*rT~NzfB>5baon#=?v_g}7RMYjalv{05YZnssTHe5+?tf7gavie+u_|;`?Xe zPT&4Zd}>AVr;r@P)lm@SeF32BhXrR|8?TGW6k=7 z$MU4PD-?|Wwhr9suSG5ZV1Qf?V8TSk_1{I}eT2llXMha#!$yh^-9>IT0g;^lDRYzr zzr7z&!I(e=3;z}b@a?xkZu=#m<%YnCyuHI-0kR9hU_06&i^ET#vADOL&+eu!1i(iN zgMHHp!5d|~_rDp>KNBnHITP^91m)H{A!9}qB&tftfXdy~FAtm%Ftd96`7ZQ-qfl%9 delta 24167 zcmZ5{V~}RSvTa+_wr$(CZQHiLwr$(CZQI7Q?e1yJoBQ66d(NwfT~QgiGk<05T6?X` zmTJ)P0#JBG8Bj17ARs6xAYSP?$wYVpl>fCbSTM^4fq;P25(Slbu`jT)?wuc;fr0)v zgy~<%KR*!2|7`yj*uTfY*@6M||9dBKh6v{WrTw3X#5bz{u#!z7wlMzJIl33RhWam` zVVbQ-{RI`sZjn)(6P< z;+ST^R6<~syWzQO-lrK}p6<8fv-LZmDNk$S*dS=YFK|#BsvY*mxL8zn70tC%iY?BNO2v{8X#-BjIZ+pTN9==NB1Ab7+J{A?3 z<(@o?Ro#87WgngrPdy2#q{^g;Nk}D=Ktm%@S-EQzqKB)XNm^KNEMvL~y(fia|0S z_mCY2)~4fvn?oYJOL+J=oH!$N2IfKl zr;+E{B@*qTT$wa|RP?ra#7|jySS{`3V8U@T?OG!cTV0ZDLHG}(PHCmslYXL~J^37Y zlR^2dF)n2T#|zlg@v2#%9aO_!077e!AVC=N2=Q z&}l-BVM$1g2Xh|>J`9awG2~$~;E(LLXQ%by!GGZYJ-hq+hh5<3a}^E<;W(MFt*{vc zsbpm7M8X46ANTE86p`OGY8oKrbO~Lcacw2UMV8h_C||rE9|$xDrbH6K#)&h+;>j+l zG7s(qKmS<>#z=|E0&E(Zg)K@KMx8k9h=@I>VGPzqQ0$NCpMktq5=X&3??$R}bLOq! z=1TfW7NUHX%0yO1BTm0&qmz|rlc<==7#mcJ>7HMNp$3iC#$J^r)(xm86q1&%n9J_U zW3^qyR&f=2ZnX|GCrDGomm|mdL+XiQo)*PMHLKViT^wAMst)0%_Rhi*wO6j0)sY^d z@1t3qsyWr-+?Z2p>c+-yPxaAbJ-WqU`fMzOqr$_gXE$xSB3vlLl#*kORH5Jmg}hZ{ zkDG;s;!Jm2YiZ+6YXZQ|EHbMM!;_)xqUUX6or(VQe&EGsvYe4mq~o4Fiy4oUY;P`3 zy3&~h0cR10Hmvv(bR1|D6CqpqbjZZ=%P3+Y1!Q*RF9IPn@ZmgL)0lEh4c8^aRTBIB z=8e_}%7Dzo=?<+>wj)DItzO38$S+$sd|f;v8}41_j6XtaBC~*PY@86k#p)B-QF`r_ zJ8QY|bn};cztvHKeq zT4EL&2BTeOaZJs6trq4|=C%4AH=od^7|KUx{2_U)?go`0UIA$=hJmC8rw3C!Dr;}` zR#Q~NX-eamn?``fe9QzUMhGSSM8-h0e-G)gSr4(%vb0$GLF1U2?nt%2Zqfs`etP17 zihmE$v7Bs^!R^N_6}GYOSrbtq^G%$~2yPSW|xhgnbf+xNTRSop-}Lt;#Pq6Hu?ohme>>@&*=e)uRaNf8~5 zt$wQV6;#`X|K7nglDaFUSG8DGkg2xqB8l``vuzXu z6B&=2J888h2=r$rsKT29rj2_lj6p7#Qa-)xDvM^OoN|H@xtXNTjy*{&%=fAaWG329 zt|aH|CJ=yDn~LAzCAd6%jdWVoQ&3HPbrp+`lDI0CTy0hrcCZcct4zOT6(x#q21}2A z-LJVq!yD&39wEK2BgLiu?KE}Ra3HO!S~^gCjXu*4;x{k+m!`x!=oI3Z`!&$M=pHW= zF)4ZOSpufJgs|}yhojwZy8vdh9UJU&A~yR@7zKdIu3CzoQ;G+VwSL`phrI+ioW}A! zzA|wgc2)z1qx?|p@0<`4gn6dxV$@yF%lE=`;7JzHyMbG(l=%S;MmT}^Kq}RcAl))W zF1XI_$Q>%x+_WQoDt&*r)meTjd??612}p+4zA=WwOjZ7G*jbheEK8W$%(1Nwj_X`u zN__x+*(JBcpWAsO>Usp9PQ_B&M{IW8J|2>5*4YC00x-gs#Jtc+DqEOPFY=<=7bg>!JpTK{4Kb0qFh_rT@V4^LnI#>* zShrjEp-a-3S9i9tDz-}`u&9{`FFJT%3I6*gn1Rz5PyB~8J|L0{2(XeTrm&lxv{FI- z^KwvCT?6}1J6baGzx4fC&F#7xZLVHUz*gU(}OU0gCR; zP1<1^#Gxr0QDU!f4s1j?se}#0gnLH9OH+@em}`>Txg^nA?P%%MK1H2H^_qBNIyEJ! z1NkM7J4d!D;t@mtxB010&e`9bJ6{9+@6Tn4 zNJ}CBVgdhL`WQtlaV)?fD+q)Y*lKLD9J_!Szy2N!;URk-oN@rg%r=QN8B}*dr6d#k zfH)7mfTu$<>jDN6lr`02;wuwo{_*J=Xx>Qfa2eDUdmio{i&w#0x`a#R@B=t&_!v}o z$_%*b*!iO-p-efe%1L*Y4Tjq7C@JWlw#VatbdwGKK zs-rz{@l*?#KY0T2tXA=K3rGvb7`rUBN+?sJtU-b~`}C@PW~K5C9Lj%mY0h7ll8_0Q zJAPTRg}M*zQ94`$sy%t|-y@x$T~Y=2{NJXW@v&B0dd(CI3&Th=NYI-7pg{S3&8z`v@oYDG4$aRFa`|Kmw( zb-`p4jV~qiXp`xi=xI@&XqdH#tKhokO8)FPQgI=5zPl@4RJMsfA`Rf&Lx~=FVO+Lt zkCcPEa5`M7)zNdCEJ3o1hdSxB|Hb}$Zm?)MW>1kcmDK~wW+p-j0|smIH#c9|cGGHy zk|pmUNCM!gmer)JHR>X1DSq+ln2oD*!%Qcm=jEYckhO6$28*uJvO963#6*!75#b_{ z&U+~3&b55~k~vwHMUN}mffz}W0E!HDml=DeWYo2-8bT+R0(Z;Ey$rd_Y|Mma3b#D_ z0lP7>gE)m}PSt&?q(BMt8pYg4x{rf`SQZ8MkqIzdwb|1MtrF#2-r{}{oknjXCzeSr zA^H-QBNSRM;_)Up&MpBX9leRU9FRCQ== z8)L7Pruxouj|?GF300Fz@^@$HP<3i2XmZ)?nYl6200np3D0x1bSlFCvIa!=Cm9e%j z%MB1f?zm~_jx8ml?hXYJ)x?`+yi4`V6^<`TDNN1xrZNs*$bav36{_!*KR~G6wG4#O zjnpuUU%G1bm3kp#(@N8=@gAMT$o=_b%i4q&UXl*8aNqJpoT!p>eHBieIfbzs55arb z9OP2gS>2FVdD(W$TOJ1=*l#zJazT7Xj|-5qO|8{Eoydn5^P(qiX`$@f+~V5OLa_?r zR3(bXFc9WFA$@_gy$n9-NsYv8>lx4D-5r}?7IK3G7zspGUEVoNsIJmbAU!2AZ;Nlq z<}e;%Ot2`TvSi~i=}MKxEY@R8DvOpXqkyY!#3*PQiNc8yU6CaRpNObQTxo-vHU*%Q zoO?7Fg>YbdZ%8Fd(cmg*X%TMKtdF25?KWLQ??EYJpS!k`@SS10i4fCIy1PxqaHcdA zE~YG^n2unEJ-uum=p=#%_7+h=q(!Q7#N_jk9gqgKK2V;=c<^5yFIM1-q*Q7mDb!4R zugco9nQW95w3fHn;-JP*=(uWWAp+Qm!%CJzqDvW-q{^;uKp&5$2`+<-p+Oh&ns(Xl zhlMEx(7KmGj$Cw2sMe7_#Al?R&HRkEv1Du#lCjN1lTdLJXMvG9v52o+{)D#9F5$47 znka_UQE4@EhC7?kqOmne>2@+Fzeh>9D2TWkQ||4iCkJO#$>_NxcdNp$83O3yW62dn zX)zY;qUUrP41raeui(=*Z^v??9=$Onn-#OfL~77sXx?U-ho{^=r`I^Kgrh?irW#SE zY6F>D(DQTFq+Dde){qO;*wD4N!_XO0M=|n-jv7x_d-g^}bkm^I(M;Su>|0DF=?I$J znmShH&)|<%pL?t`%a)#=g8R zG2^O^Q$_PtE!p;p7v6trhPu`I0v%L8$oGox&wd}9r#c+!sQvKnN8NmkNY8@SNS*r$ zoiIG67l_p*L7lI)x~WyDp#C&X`Fya0x!;E5ID#X23mtB&^#%7AJpwd7}yu+Rw>S1&_mDcB!{S8Rvumi4zG! zwA&^cIu_G%J-WTZ&dG(sVWGoi8Dp|W_JI{QdDXk+u4lclHG52^*`?y$CJP(BvQ;%b z) zno*I9$GSCl)Co&B_gHpo!4nDa*!W7{2m+0F=+u1Fae`C->ot+gX8Od1Pg1`sUO@qs z4=91s$K^+MC_w&VcF=FZZY&wd!htg^+Xad$r?5eK75}sFt|F%uqP!EC^r|n~J0xle zHU6=AsxQ6NehNccd^{VgDD7$^V53ZD`78XYvz9o|BK72RAN@lN)gOL=l*lcmP+XM- zvugJ-RsTc-2U&Zew;1A|%QOQ#aU?+$n+I z>u5iTQv#>?6<;d;peB6sWEGFuu=)L?0uor4+CLS~M1O@3+tq$b3yw9uVf708tuXl(cT>WTm;?;{F-~deF}=y}45}icZ+fqolrsxO=Ey z<49{O5Vmg`{i$SUXt;ULp1&r=H%E#`(F~G2I0ABH!d@jm)jEE z<7)ZD9FxDxn631oQM?bDl*T5ywk>o6QFCyG$cE+RSLckjB7eGGO?i`=U?a;9vrP%8 zLEjgH>4@K83_(k zZTg?4F4FgtJB?rpp3bQx9=e8R;l}c?XlJI?hZ-@+f5>pNZva;X zsV2gw6*6R#>6<(_llVAGrPRxr<)%q!SUFt4q?J1KmF(^2f6o$G8iwY8XCLrM~d~#bYR$S%6sR z&7ZX|<`Z$u+0D^17CSE<#XPv%8v%nv9C2MWm6NT54bc@Shh|kcbd>=lPE6MR2+Z9= z8D1S9;} zGUT3IDGrm8okFShg<8?q?1_=rY{^uM{zzT?XaBsu0Q|&LC~(O^7d0^fIo)t`Wtop; zR$zu?n_eLY0kpN#X%p#Mgzw|vKB25Fb^K@WCmNb6h>D8*GCqmX_}GMISnjl7XEM{; zA}m$7NsJBWI=2q96J0Tb5&(lxkuP_4pRA7%nV`%$`^I{3>xnDRF7&Lq;JlwJhWTu1 zrYpyu?=xG?tMSQtBgC1S1cAM<0T2lXs=R>kpj)u3w$3QftmOmklYE}&{JYIlbdT4k zmAM*Yf4({W6S~(O*H8MCVP83v^c=V2SMZd7mfkPAvlh4n^=i+w4?y&n(Ej45<)A4y z{xjMKhJj0nd_5f$`t!2xT`wzrg{=01f`u&{^%9%ImAwD~=a0AIMR^iYb4}r-WxMco zv?XyXF!uJr&<$%iec49~XjoUs95LQ0)ZzzfS*+=T*@_Uk+Y*}P=Yj{Fm@SIC;NWz_ zAAQWq0Q!Q`XSlBTFF=v&S`Ej-HzP7JL^XZ^B+;nome_s?D5DJ#*#%L}eUNxapBTb$ zP4&Rbw&&AfXB7OB$3dAcsDN;M8SoRVIG8ovNrR2Q%&Lkj`7p;aq?NypQRSN!wat@i z8$MA%_YtNzO``N`d3d!ryiZ=yC9gE-L^5ar%>p^03vz)RFo3_iBG20;U@vL4WfTHp z+aZ3C*h{lB4Sw;s;0BY%TcWyJN`J)~#`DW^lwXND zgrCCV6z^6S4}qkAyYmD`vt3ZTQ0?|%Hcv%LUr@sjH2|zHcrH{k6NmwP>#jZ6m0E3} zOQO-A+tGhUd>8ipnXBg{+EEMqYRUgOILniP;fk;POzPQpo&DzR-X~ArafzxQlpg&2 zFJc6@1%Vd=oU)US*kKhgw+CK3?2?yVpG9TetV#!V9ZgO6@j-vs8nCtN<2Lqhj*i=} z?sHgDPJmg$+K{GPD8}=0`N*Q@vx|zvnwlx~l z{%M=`-)L1_RhV{8MT9>(pH^4uztN=r0d=SspiTWIb zWbY(Kcq1r1p_3#6`Vr=`!z-p(S%6@|kdNXmVm1s6sf?@;#m;(>Xl zEQl64NNdqxEBH`Whg9+f9e2%>$xyGX`QQZQhR&X$xNvLU7`HsNX6i=h9DV!YYUefL z1Dk-Jra(iTN8Fv8M9smKP!VCyhrh(I&j4i2-WWqqaB?3ss%tjVuXHP<71YAC06l2) zUb+5|4HQKDqy;`r7xHfyc*MkXi`mv3f4giN1^dtC?me*sQlSQq1a8y*E7ycovWv}> zXWOF_=P)97ZpZlRV&laUW&Wat(tKmV3!Gq7$dT^tuvoYSG|&`5V8mx>4d!zkLV(Oc z9=G5z-a&cLR3qrP14dbQ$+AN~`1d%xP%)k>m!Z(R)+<01v(D^ni zv^Qko2k*HiG~ImRTLRNQWa)nJ8UdyJUm$6Kp#3+ArC$j56@kzNi7Fysj=a!o!+O7X zf2fV8VfF{Unr!rLcFT#uFJX`K6%bT4V2^xRj3BfMiuD>WOhDvA-ri>PrEqZYdrfD7 z0+A~7T1;+HSt(Sz$S(8EK1)%{Oaqw@GVU*y;kg)Uxj4ELK<8s!XP@vA zU=|2eq=h6?um-F%f=v0^*V{hZ=wXXss4V-}^lZ5%BKhlizTh@uBZ3Q`7m)f0V{7?S zs61kUl4HcOl0)^(U=;@QZL>uVBbqYH+T9-TZg8=`Or#uKJ~Nd*@>^cpjhwTj@m-+c z>U^|MMdynHb3#iuTONeJ`^(Yb2CS2zI(2>##`P!rXFN9U?Ev%Qi{aZ~YX-*O*L9Q)BkKp}9Hx^WtvU!{wf9?)T*!uLnE9-CVcx4s;EpOI|k9 zM(!(gjF1;C@6$#!x8S2a{_dby#V^O2rnAMrp#M$U?GDIBj{K7bQ=$JaX(tDa2hiD8 zN8}r70s1VPOnl~<9*DPV;TZNN-2Oye$zZeS1>O{<_qIZvav`o#IOmEOnB z5LWLixBtoTX9ck6US}H2@wkfMk(tTkGB?v}^8GRIzyRD6NMQEvq#@2=PTIp@q%KZ# zYPvJr69Z2BXe1Q|$%Hknc{u#-4d6XU3V+c|MNDTTEk?3IUNf^bR2hPNk#yvUe{UEK zAAfmQ9Fut09HMwp{BYJ0$4Ej}2JuzND%@NK;Vrxm19BRZWde?6nl+^9oMCTXTd~U} z{mIBweSuqDdha7dz0sqiA;e{=b!D}yq{RaJ{~W4F`IN-A_A&&JGIac8^USEy$Zx2!Ot6Lu4w&B7XW{!`He zgRAva>4fuH;j;0zSh})i$7Ic^y2zZ}C9d5D2$$r|yH5N2PdXZF~r z!gI+W(6<-0mg2g&n`{{r06UBROkTCA_T^z^ooAcFq}%Om%M;QEr5lSes_x0dp5s?(PgkUDDKxmYEL=wK^WEeXfwbJ9&*XR800JK~+-Ai_E-PsnyK zSKS0|VChQnLHH$PcQnh5dd=xL4Ar6?nQ4iJYC!lJs;Wgbc6si~Ilr)gRh8)DS7#wMC-iPuN9+siWX1g5rVRelytJSRHLy}?;IN;QAzY1 zqd0<+y6SGUWlJqQs4|;7ijVqQX=`Xs4w`53Dj&XhMCzf|0R_ul_dk%rtFz@%hJo6R zWIJ_E=GB+7?`pBfQ)1lKTUkzq{DnNe)vPf-`_n_HqKDRr0ew;I%E2YcP+fVt^EgJ7 zx~npz#Jxq25W0Ck&E&hPRK+Y*s&h z5PqHn59ngY09P&1OSB8uc-&$4LFjJh#fxW9JPQiNN7#ly^~mWr2lgCRT90xB3%uA+7D(-dJ z-}_{>;rs!0$9&q6xO-aCX*r_zLHq7UJ0A%D{i%~&YbRa)r%aPz0s&Db3u)mcbL%1k zybN*Gu>Q(5P1>_Bhu9~zQBl#7*)7eAP4A|WNU2~?tlBPR6|GI)vTAKyhiq=*L%~o| zQWxP8ql${vwhLWALNdqKCqsBwNQG{~h6rytDr>|9*KV5{Oadb|p(`X-)2ylQDIMW_ba1bC&TE!at{q zXA|u6r%^q#=WTPlICH!<9BHhI#!NYu^$b3BDM?uSFOtsnS!U{B+rx|&T z$dhq}JKVGN+6P-%l1o3-;Vee3P;~IO%QL8ccr%*ISTqz<;)O2W+6tq9R;TPnUh|Sy zQgYOqE0&qaIB1nNTXM;$fu#sEdP2M+?-kb785r)bxO}UA^dQ-`YcQ*fFZaqg&&g3R!74NzRw3aRadniUo_}fB;<8qd(3a5R7 zES9?F{```a#VqXvHg5Xu`M84`Z|r{L(0;Quh87>S`>`4IScA-Hsb^zU`avl*{DCwY z6(;phfPk{rj!M0rwzkFt1#j_@TZhzWzL*~Vc!IfH)qAw#mm2$3PxhizY`P^YOX-nA zTuinaFO4nWGBxsovbc~3`-i^!@5Htv*k2X)A2J*^F>ltyYj)k9!!?Iyw>2zJ_>|ksvJ%8qcTIFsI6Q%fS!{5k~ zCht4&*}LW1xsd9z1Mc)AGZ9<*sw#55m`=rzl#j)p zxyvY!Jzbtd^*n9t<@_nP80Y?xl1*0kLBH`QW$5s6U^zV2Gl8Z6+D2DXP$G z$@mWoG?MY&=MYOgyw8&*9^U6FQvDMEk$N#nd-pjJ=gw_|y}Q@+b^d;}ihwYuyof|> zK`sSgnzMqK*+NrVWa`{d2Y54+W=e<5P{3Fk&Y9*Miy(_@+;oo0hRIbzrlpaZAu$CH zaR2No`XsRup`Yy6I^} zXiq0@>y&#QAVe?H+W$u`lJIkT?JoA7+HlqrJ21ViZ2ZD%uD_i8(PzbK*`nzCTb2Njc z?WS%752tkEUUnW)tL!G)LERh0%q2F@ym|5)PI@1A&Kx8c1v*y-PRkb7?g$au&b{)< z_VSDO5+uDVK?FS)bx{m}wEJCKNM|Phic)o+!O+5=B{naw+*+$;>j#CAYIsJZ`nr8< zyG@nX8llosAChM7Ox2hc3W4qq4Z1pv_|n{QOzV(r5_Zy?uCFWSFuD)*ePvN}J<9)h zXXYk(5B`dy3oCtZechft0fH^`A#qUjAZ<)^sKXY%#{}Z*1o#EG=?&@c6M=%CXpi;M z5iYJ$lo;b4Yo*5sNd;5s5&~aUS2Bv&R2_E!Jwyi`W?!jx7VDjw6SyF2_2jB+(({<< z$`a_i+4*S-G=Mf6sI2`Nl23gI;W_B4TFA87dBVH>VCFLLe5am2Y}z@ramtOBN)nez zhi>KGf@J@*rF{v=d<}lXFx_VxdDKq3ck2X6an4}qM${L3M)Ps!BT+V<*AHHQv`sMI zmsIrS0wVqS;yB`N*rXd3EDM?+<_A%3-n>n(Eo zvSP?_RLIqc_<7hvS@>|Q+YMjs|!zrM@Rubj{VjBk#wU7xD5DUx$?Rs+1FYYhYcW#u9 z(u~VDB9|o_lR5e1k5F?sDK?|zu2CuEJ-qK`FM4@CEIiz}cj<%;`VeMsdc3}Sz3$)? z_@C~Jf!3m9soM_e(QxjWJ9~8L>lN>%(ZG>)0{|LSoX6wU-=48Mz3QV^j_m|*?+@PK z4vI?TjZ^pHUY_+)9EYI_x9j-56Aw{-t|!@ zp7}v<)taFQ6`EnqF!+i}B%M3q2-NQh1PE0Xqv2{LOhoYN}UhVHIH@IF(=P`ML=)V|mSM|l&SGv~|=%a}2uRnr(FVyufIU0YD zjLJW-rd*b2s#!vrbgdwPrOTbrwk`G(7f#5VW$Hy6_b>9fISNvL$MWctWz9g27zR5;g51{rB{(ikJa~_=!$xC-7g`6mBC1C z!#qVy!R4jL(8=NIE0WR?0ZEK<)qK)BLr#2&tnZE7I`fjW*!C>rW6$pmtnT@-BI065 zEdD_;q=ROiV7=wZX-sVlB-GJDfNfSRFUr#nG_x;W(Jkk&=JN>sycr`I46fJG8cSMU z&~$h1o^e!>(=wma9NR`)O`by_b2vQoS!rby$i795t{bRoXj_hf!KI4@UOm_02 z{Jc3=pn<7w&BaVU6rk1I#<;N>zYEsS#+(zY<=SE%yLefJ^r!I*cN&Ji0g&823gdL& zs^UgR?E!jV9={Q#OIOQH^_W2o#I-P}YT4x<^r;~bqZPS8V zcR;LLV-C_`+mFd%#~qTZ1B!p?k;3(lEW4`J@nEt2r1F%=Q5mzxGE=dB!St)&7b`yV52Hz04mCnpjxwg=UWH95WLs0b&Zq;04P_o$DZVF$DEhI*}IwGcQu&-Xy!-OQ9n2{$Nx7=Jq!2252Z_%r#Co07CflOaYCh3K zd}L_^rcqfM*2*{)6$5sgqm$}T_e6_dn~vVx@-2%9hwOJz2%xMQOigk$oT_xGy2PeP zyk>DkTZyJ2l6OZNC2D(=JO!77c(GW?gcCLPp9<7We95X5Z=;pRH}#8T-MmbaV_RgI z-|2)+#smj-u_Dr~C~{pX!A=t;{eWGpCjIRgo%^t7R8-j^;f4sEMd5YaA>s-9S(YO< ztLx7P>z?rPD&Wm|{=pC)op0IAHLhvpn3(~8HMur2aU}z(oxVgntUd=iPFzA6TEB+P z%Zy_mbMq1Ay3(X?%`*;M%hY|*ga(_b=DJRkZ@2Lg5_~k*1gtJgqIlwHXsV->--02$ zB4w4jTEBoEBYmu{@19b~%nJk3g{NDk*4;-QvF)OE1Q3rf?X}#UeWF0yd^3CD{n2=j zFNSdfPZgraL19v_&a?~9t6-t#uM=Rrp}s&A-qSRu60#i2JKxh4N_Tej)Xg&u4u??uo&&kr&=MvvG!7yj%>@j9xL30GjEJ)I@# zVKZ&q?KI`9YTjcEMnYaMvyy{_gNLr&X8O70;8v@GHo2A)K}CLIb#v|#M=paR*N2la zTdEwTZEvE&s9!SXn2JvvKsQJ3fqj+sCs@>w2!OeaHBQ4DXvt=to#6KH;|KT;S-ZvCXK!OyR*<{8#lUv*jnz;S+ zXw4HmoX4^Imv?t8!}dk>Teyb>&-vzy@q@5N7}i;|FRL4z^2ndkrrsIAXk#$+U0CBsMHS+^=GYsT!1%iZ4wY3_kk_yn z_f*>wRO7(AE-M%aPvTuC1S%|2%-AXHC<@xg7x`BgHbrAYcC^DCDohx;;>OXhKTC=b z!F@pz2L#%fl$Usq;46EqQOgVF17yg$)PTWY6-p8_FBzc*!6kZ_KiEr9EvWKEMPks@ zA?WgjNtDscnn~hn2^6bzKL!0($U>c3Tgol;nyiu0+A9THjG<;CgGE%dXV{udk*O$9 zaz?9)3j%?wC>@?KY`}pGgFO@?Ax0uv3C5YiID7s1dhL^Bh`4lREJ0w*TAe8ILi3l{9~RSy+gVnwz~q^U%Wb(p zcE3)m=ippJdeHCN)B19RZxlre>;WJz$pyjHx{4;~mSaSvs<4(4;N0g)cx_5Dxau8= z(gQ!-<~XHO7)>8lXZ(99_$qT+|7^G8?V16j!t2t)iLU))H!3_zHDGvA&0DV znFC)sue+Kz)XX*>UT&MZ)9aGG@9GA^SlP>*tgzEd8?EO3C@->xP7BANbpcLs%-SG2 zOB>z@Rb-5grFTfSINBQvJdrmjo@-nhnQPFxZfj|3^832C)=fdo0s2D_P&XoEe=@m) zWs9o400`zi8j}gTQD+H#IZ{u$yz!3xzI5GP{IiJY_Z|UV5L-)@`^)!W(zbrwxMc2( zZXWJz%E@}Mfpe_x9`)H{8vqifwVM+qjpa>rukfy*J{OVYdlu#N-y4XO(z+)5yA`fUsoCFF zxC#9EqIa^tbFW({i9$}+s_;+Upgc8 zSR-GR{{QOM<{Xk|0R#|G3w$yGJvG3_17{U&cO6?RidPC37+5JBjFFILLmC#ER9+Z` zCqRgaNd9O{PG@Y1FrFn(NrHr;5TT%Fh-3kzG{b`c(NYFSyN0s_F5bPiZq@%W)OtIJ7q#6#3qW8_Vgmk=-%Q3z>* zWNH#Yj1h<>0&BwTsp$PdIab;#%0hG$0i`oy3R~=0!S#sfZJ=@v8 zh-v1&W3k)n$jL>;h0?QXAlZi#NTK=migE*h}QKHd0*2NO?` z&a9geVqUzZ&ETyRt>l5Hy6|Tgx4DnmgzHq%%6aDb6~{z5+*5qYdEuTGOCvR_Mj069 zPr)%`kR56?IompIW5!&pZo9Yzt*TE`bz>hBpovlATTwo0$JmWp7ax=P)7^W4qZ4Kw zPHv;-n0=?N7=d9?!;cb=!K8gCH8x~Zt?4@F;^Li4fAQg0&y@E|hlH!_ zbO%EHg(sfFxu?pAPLU7J9c73QOxW4gduatA)PP01*4VX6p7)zP$iuBCT!njY91`hE zef;j;2an(gfgA7>v5e$fa;)&~0!DC^fh1sdeP+aHxK+j=FNs6G@)Ebai!~$es6I}? zi7{y4`h|9u*$Fx)qFzYYMmoT~UwT;nE<1kqEWkQ9YEEmhBs@ZIc1nulU zg=>Xc*XM{EH0xb4EA`^4ak5G@p5ee!2XIGA$qE)Xoy3Y#OD`Tvb1wZ?}jtn*0J*%R@2sZPEC8$Ej$fqs zxxKj^jV`*em!T~Hn%d5aSD3 zst>r>k8mg=c;q~i6Q=QYct9#6ThTc~#E03(Dj#G*5`j(7t$ zZ+J{h-|l?>H>F}FmYu$2|2Ih8-}+oiXnA2OW;?##(8S@@K&Ly3_!S!jBa)@x=Do3y(#wif2ls&>6qFZQkY zY9;z;I`L_3wv-D;YO1{2wdy)w7+)AGXW6^gNa`~TA8~J=d&fTcXFg}ssepU{_<;MD zikV4h11Q(x4g)qo$LyHWQSG;r>{t;D__$im04Ozo2txEJiSc|eHU5x-Lwns`n`6|CHGFvf9(mZqSSLpP2 z%CZ|1M^CGaNw!CR z$E2*2PPf%=tO3v6)yZaTro)FcMzsF;SleY?y33sOU7{9smm}6f)`Ym9(Pjhkd9wy1 zA$6shr7IWdDQV$u&LU%6?gjU*6@9j*v>fvdPHGyEGhOo3*2p}#2aR1c)SN_3CAoo2 z2VsGIJMgSpgK9m7jX7-!#~`bvP-;6|csI6HD@tU>X+K80X&&h`K6la7`9*cZF^JVLAFCTEl!#k8P^EH%0G~_U~sje-` zVSNG!RZ>2s*KU2R3u$xaP4?nQ_sH}XF(_~oa2fGjU-u-NmL;JI`agAC1yodB*B(l8 zfFXx2K|qjJq@+X|k&=+^1_?oML=dE72?(boE-YWQLqjBmj>ce=hHK9y?Q_OZW{3LG7b%&y=eH8 zVD_{z{z!ZpK0DE9!jEh2>bE4MBeg}YcD_iFolt3SyE*cjXPFY5v~wTKwX}%WLHaEHMJ1a8|4+x1+Hmz zpZHLHCAc!P@!`%H-Me0F9i3bFpNj;w4X;j)L#nA}j2TGeNuoWv>^bk7w$#^%CBMSK ze7iTTY#2ZKb0dPh*l1{Dqd9Zr9e%E|>e+RHTwO^80@KsAwG1LsE%+6eLS4r6$<2D0 zVo9>Fy`tooO)4f&h3Y!SSt6T}q56-h12vuItdB3WICE-P^Y*-K);ErcFdwR-_Fy#g zPG_TMG|`7{%n8l*9xi*e%*}^_u9{xEaGi0f2@zs={Y|NT3$EF&|Dq_5lz{P#jc*uR zQ{n!OJ)-v;CWjySACkS;%BbG)Jj}Q$2lHOgKjI=t+bx-E^TK-Kc+Kt5I;a9C(zb_I zp@x{D9)5Z5ruehPE8C@w^Lu17A@*2_i`8%b}6*V)OGH>okiS?6{&C#$FsJ;av9y6N*QJgrVzPS#JCfFw{Z` zZPgJDZ^_!pV@)v}F5Fa@B<_d6>P1+o5mdX>70&#Ks?zT{f-i%-3S*_^xlH}dZF&zc zatyQFX$`)FIF`5??80d}hU2In^oj?TeR3ytn%4L3LS9{=gWIy~`mUDk<|9bUjvCIa zAA+2=X}smxD1w$dYi}QxaiIH(s)CoSo`{`{lX=>kX3ihSBfVQK(BQ;VzvNbpip_&@ zkowoBpwoN%$L6d|%ygYFRVhKC$KGa?Ugm6GvE zIQd~Ln7HAHdFlvH>pQ2JsFJnBO=k%?;Y@ZA-|b}ytMWTuPpc+59|l&v!Vd=V-ij{X zfm*x9{EUbjJ{*l!<=ZaEl*4|I)Ql8_F3om$vCh8rLNINS-(#NTYczcz z?csiuXuV?Ps3Cm2m?dN9u#-GMkvRiT;mK|gee5!R-n9%{;)6;Sr=_)>sI~sW?H&3d z#BQ^y3?{F{yf33CAxT3*&zEHu`LO)3fCOUt4;%DaZ5ooEWAj~(W|*tZ;gVcsF2QU! zN+UjSo?+IA$iGy0J}*U;QIcfLMD}EMn?O%QJ*17%67iv+mp|a zx|5=+28Qq46rbRwmBuCJec+LMqiwRa^xde-{g3iVJV7kEAaP7nV$(}PvE+46)_bHw zLvo@MuKL$93h{Dx7<%zKHODCn+ti%ZGl}$_7Ne}&;=%$1!Tqe*f9)Da>Z>lc3i!Qi z9Qhw!;JJi)nkC{06Qww>OVk9B+tLH!;1ms*nN#-HT+`Yo2HCeQxtM{s6)!^ZDGZGe*r8HAzxcD^8Cnyv7^3H0GHTbP4rV)%$sdqTCsm#TG zzbCdFJP{V=Pn`ufW`X>anV#M@AL0;x6JI@zauPk7MYuHR$@?Q z4zR@3s4TMxT=X%CvRX83igLN$LiDk4LXvUJpR{N>7n>u-TJhf6V1-+UUE`e+UKmx! z1HM`)zV5|yMr*a%;x$!t2=($0X?q#pZBmAD75 z6pOo8OEEUn7R!}x`S$&rU*$t?uqe2h7PtcI&M+DeAO?;Pcem#n6D0!$veVgy45#j| zWU!Rgw#Ytwdj-Nr>YFuT=a+dZ*9yBOFwhgTviy97ymwED;yZ<|568utch0nsJM$Ow zW#h!_*gj(lCdQ zGtZe~XvBQS`7a31y?Vwm0t3~J&jO)%C~i#eKvg*ixbX~}DNY*Zq%n4z;*s;@h^83S zMQaB~o`}xH>M=7BB+Z~q7baLT#YgB~rs^$JyJrdw~UN31Srv?67GGpbtv9U`(D2$cvF7J5a z-^8aQGZyl2f+j9H!2~b5fA_yoY00!fYW;iHTS)Q;rR=im+wUeXD8_cx8?HI z{Y8v|2j(kn-s|=`(>p}1P7w#*spFaBN>2H_5p=icz52aU@#*ZsVv(`i_%nzSImT7^ zYJH=S4?MS*dEzGn&T&lBQ|29>Znm#hOEvxtt^AN}#1p>Jdvvf1hqN#0?JlL*+w0yd z^^G!{2oH#4)@r!AJl_^;ycd>E`-lL@THslP=;p=2*CsylsMNnq;WNRpjcK`FM(e4v zmm-myaK=#ki6;NJoQQ5$fBK?*gZ;JilopGfx?ZoK%(Za>!F9cz3x;HMG`idG$z&2| zQZLgvefX(GHqXroTV(KD8I%=p>JS$nsWyai;jp}M0YV$M0}9!cwqES)Hy!e zb-SV7t1`=-NKP{^mnzzYko(@f!zawbFHai$4C%Bz=i^?@vYVPgouge+Jn|o3kqMNs z8`jDBG6L2cxE0w|J3_ElrUmD-2xxI>7MAee_oQIiNz9!C!8WxG?8;)&q(XKAu`vSo zx0aN>p0dOxfF7GkU}s8mYp(xH?~SV|8%Seu!`LMhzxDM};}w?8A+MM3x(Ht!wLEl| zmk9Km4tp1lO)bEQNXKrAZlvcA(QMeqi#~yue85+l-MgM)9^qH8ZoYgmG}%dPu6oCV zsZaK`qQ{KZa%-* zPCrH7`{T%N;OH|CBSK8ZM^%ffDt?N(h84~lseGeK^H`?vZr8fWAF&{kDU5|03nMNA zIH>;j{q~8^m$k&v2Y|b31Y%Y7zUUuvd<3gJCl#^Fd_nRfyhpwcQBU8VFTQu7|bgG0G z$mO0tTpMaw8i_vboW+zy~mVHe0yLyE?O5CJaOBlAQ_`SIH4p`+?k6qhDTM)N29wsSwmKQ zJMlu!O>m*b(AICj27+b9awo!tr1+i2&%PE8UqZ8aO9M)I+SP-E#&vGs4JR4ffvw-=~ZsUfB+(S>T2yGk(V+U6h^W?5?>1P=gWdG2| zVCxX#Z=k8tT}y@(AJl2$U0!j6OQ?JEyAi&Eylu`&@yj@1p6Gbf;snkC48nG7h}4TcsF&PNws_ee&};2d zqJ744QCp8PdE5&Z(4F^bUJbPk83@$P4FYih&c;@qo8v}?>YZG^8>r)#YL=v_-zn3O z-ui%JN!t|Il0!=fm$sFMdDH4poDvhM3MQ{U$rj-#RU)Fq1eey?@d_)Cjhpt}EDW`~ z?DZHwnZnxD`kDM$;C9){LzB;hPDUzvnI{aV#GaV}%$5~-`t3_b2U9lNF0dbI{zuE@ zCNNxAoEwUwAv3Ir>}g#L^CgP);Tr5Etb+xayCahLG$l%Rd%8)l!gjxtwn!&lJH*|| z!zQV_P$3!Q=GS#e{Iw7B63fDwV&^2QJJIQje1`+Fz-#nV=A?;{IsN=`BOad3x_!l~ z{_G|kO3W4%@m~|o?fvG-2o5r=1&oHF)?CJd3Fi8d)cpn$39lTrxZbDcYwD;OYL!~$ z-qGA=z1HNoj(bsi5F6HUS4mP=Z1&}JO14l$2wSrMigaiaWi!R_bbfx4qGx-a@2y(O z(h@3~eBTm%94!ZZdLHO;nQl=s_H_y={5q`Zd~<`KaPq}+F^k}-$qA~lX&oE8iw*BeQ#?96R1)jo zB>2iWu~O`Ut*#X(cyxJH{aB{kn<|*;u8yIq)ck4~vrWx|+ zy3F>(M=YR#+mPabj(_vr7D72W&*0|7=0T|S^GEk;v)$=nkJg9OUu3rL5iIvi=*?@D zSlpHWWK_@B(NR-e{P9Zg*`;S?pW9=;^wc?+%ye{}3Kv!&ikGytmRLx)N&1GPQ36T$pcly{*-%T`bN_3E{n@yxE9csOA*~rPKo;dElB3D68X?J>Y z-1bLg#Y6ARE|@ih2O;6ne$t>OLHIZ)r0Ub`M~No#x`txG{m;e%B*UXr;RuG6#U<`RWGNzw5HBM zUXoXVkKUPsk0#B9De0i^PbVEfn6+?hkFb_C2x~Nb8_Z+OfIL8mU?e(r9#1EWf7AN) zgBYsA(@Q>wTAAVQZ@@%XnHkKUnVpP6EQ2#EWCMkW_!b+uRPh29FDOv?%Pb5-!$&;! z@hprTZ**N8d@W;w6@bsOPR@93N7v!gHg%=V$F|Q|EzQ&F2eyzmskvNV6S5#{rU^XmsiS_v2V~1&?96WiPH_FgO?}y_75#Qz*||?WV_)|L zq}-0jQPu~ZO0Q@#fJOJ<TIDiZ;IYe7M z?+o-6S&KDqN$JN}Lq5DFe)3L25U(Wq6g;75HwepriiH!wP^X zkjP)hivW05Cj;!4z5kVr^&cQ9=tL$J_=!x-ifa2$2H|hRASC0>FNTe~nWdxE|4#(^ z4iJ#^?AL*0ZXlOvlKy!m_;42#yC#4E1CG&88P`pD2}L(r*4N*rfbW_B49tJv_@sa4 zfrT4%Goad7`*Qbw5x|)NKCEaqys?os;Oe|2e~XIkL5ecNIY*eXUVy)0qTu;c`hQtL zK_DSC(|CC2L;@P-zexY(mji)#(MXKM=cL|#CRF{Fz5@$!KtC#p4+8O{;g3nr@%H_! zsQ5e|{zhHEvq6B@Goj(9DbMj`ibQaiJ{(kz`H|h_bs!RGiGj`@jpGCbIJ~G>v}|^0 z*kq=2`>G<~zY6`|{@gzc{Z;Usq=rEYf768~3T>ks+J!Jg&pB*wX;FotEC&VwgO-1f zngCk4bG#`l^nMHfG^{*17*T>ndxjM9i8tsrSgZ$Tcwd$?Z*GF(ke|7jY21vz1XM){&@xX zXIbG81hU3)ERi7iZ3Of0nnN1>_t6+2LK4j=t_@runhP$Tg5K;PN$`vTq{Tfuz#={T z-2gqR#T(SNXFa$ePzca~p<4`fI9I?QM2~jQkrw}bv;hRtH8dH;_s?ah#gU>lH0Ltr zMv*cGz0S?jkFlZ3VD;@Yhyx0h4E{4L34PCHM+`zx@oA1m!vz>1P(IM-h@vT2gqw2V=;K&j-MX#{oaCz3{g@)o~=EE)-7CD)Co|(I%v5*9!|jFHc+m`(Grq zi3J)-GzuP&!}%A%ghXmI7w|DI;D(^LvddY(RXE`$zTm%wSB@ZsPv)MN`)(4^UuOTC zpMXH(XgV760oRp9tynn9NP-6qd%qZ{J0Vmo+Qr)1Zx$(EulXFjWtUSM^KgTIh zt;vm0t!@Cf(+}u`CD5!5RGn9`x!0Y8qEj%&mC~N z{@fZ#I^=JCr-R6<6l($yl7C%`r!9sOg1qTQSWb+^ZB832N K`jG<&(EkDPr&!Mb diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index d19bad0fda..74bb77845e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Tue Jun 28 11:19:41 CEST 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.14-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.2.1-bin.zip diff --git a/gradlew b/gradlew index 27309d9231..cccdd3d517 100755 --- a/gradlew +++ b/gradlew @@ -1,4 +1,4 @@ -#!/usr/bin/env bash +#!/usr/bin/env sh ############################################################################## ## @@ -33,11 +33,11 @@ DEFAULT_JVM_OPTS="" # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" -warn ( ) { +warn () { echo "$*" } -die ( ) { +die () { echo echo "$*" echo @@ -154,11 +154,19 @@ if $cygwin ; then esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " } -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" +APP_ARGS=$(save "$@") -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 832fdb6079..f9553162f1 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -49,7 +49,6 @@ goto fail @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. @@ -60,11 +59,6 @@ set _SKIP=2 if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ :execute @rem Setup the command line diff --git a/src/perf/java/io/reactivex/BlockingGetPerf.java b/src/jmh/java/io/reactivex/BlockingGetPerf.java similarity index 100% rename from src/perf/java/io/reactivex/BlockingGetPerf.java rename to src/jmh/java/io/reactivex/BlockingGetPerf.java diff --git a/src/perf/java/io/reactivex/BlockingPerf.java b/src/jmh/java/io/reactivex/BlockingPerf.java similarity index 100% rename from src/perf/java/io/reactivex/BlockingPerf.java rename to src/jmh/java/io/reactivex/BlockingPerf.java diff --git a/src/perf/java/io/reactivex/CallableAsyncPerf.java b/src/jmh/java/io/reactivex/CallableAsyncPerf.java similarity index 100% rename from src/perf/java/io/reactivex/CallableAsyncPerf.java rename to src/jmh/java/io/reactivex/CallableAsyncPerf.java diff --git a/src/perf/java/io/reactivex/EachTypeFlatMapPerf.java b/src/jmh/java/io/reactivex/EachTypeFlatMapPerf.java similarity index 100% rename from src/perf/java/io/reactivex/EachTypeFlatMapPerf.java rename to src/jmh/java/io/reactivex/EachTypeFlatMapPerf.java diff --git a/src/perf/java/io/reactivex/FlatMapJustPerf.java b/src/jmh/java/io/reactivex/FlatMapJustPerf.java similarity index 100% rename from src/perf/java/io/reactivex/FlatMapJustPerf.java rename to src/jmh/java/io/reactivex/FlatMapJustPerf.java diff --git a/src/perf/java/io/reactivex/FlattenCrossMapPerf.java b/src/jmh/java/io/reactivex/FlattenCrossMapPerf.java similarity index 100% rename from src/perf/java/io/reactivex/FlattenCrossMapPerf.java rename to src/jmh/java/io/reactivex/FlattenCrossMapPerf.java diff --git a/src/perf/java/io/reactivex/FlattenJustPerf.java b/src/jmh/java/io/reactivex/FlattenJustPerf.java similarity index 100% rename from src/perf/java/io/reactivex/FlattenJustPerf.java rename to src/jmh/java/io/reactivex/FlattenJustPerf.java diff --git a/src/perf/java/io/reactivex/InputWithIncrementingInteger.java b/src/jmh/java/io/reactivex/InputWithIncrementingInteger.java similarity index 100% rename from src/perf/java/io/reactivex/InputWithIncrementingInteger.java rename to src/jmh/java/io/reactivex/InputWithIncrementingInteger.java diff --git a/src/perf/java/io/reactivex/JustAsyncPerf.java b/src/jmh/java/io/reactivex/JustAsyncPerf.java similarity index 100% rename from src/perf/java/io/reactivex/JustAsyncPerf.java rename to src/jmh/java/io/reactivex/JustAsyncPerf.java diff --git a/src/perf/java/io/reactivex/LatchedSingleObserver.java b/src/jmh/java/io/reactivex/LatchedSingleObserver.java similarity index 100% rename from src/perf/java/io/reactivex/LatchedSingleObserver.java rename to src/jmh/java/io/reactivex/LatchedSingleObserver.java diff --git a/src/perf/java/io/reactivex/ObservableFlatMapPerf.java b/src/jmh/java/io/reactivex/ObservableFlatMapPerf.java similarity index 100% rename from src/perf/java/io/reactivex/ObservableFlatMapPerf.java rename to src/jmh/java/io/reactivex/ObservableFlatMapPerf.java diff --git a/src/perf/java/io/reactivex/OperatorFlatMapPerf.java b/src/jmh/java/io/reactivex/OperatorFlatMapPerf.java similarity index 100% rename from src/perf/java/io/reactivex/OperatorFlatMapPerf.java rename to src/jmh/java/io/reactivex/OperatorFlatMapPerf.java diff --git a/src/perf/java/io/reactivex/OperatorMergePerf.java b/src/jmh/java/io/reactivex/OperatorMergePerf.java similarity index 100% rename from src/perf/java/io/reactivex/OperatorMergePerf.java rename to src/jmh/java/io/reactivex/OperatorMergePerf.java diff --git a/src/perf/java/io/reactivex/PerfAsyncConsumer.java b/src/jmh/java/io/reactivex/PerfAsyncConsumer.java similarity index 100% rename from src/perf/java/io/reactivex/PerfAsyncConsumer.java rename to src/jmh/java/io/reactivex/PerfAsyncConsumer.java diff --git a/src/perf/java/io/reactivex/PerfConsumer.java b/src/jmh/java/io/reactivex/PerfConsumer.java similarity index 100% rename from src/perf/java/io/reactivex/PerfConsumer.java rename to src/jmh/java/io/reactivex/PerfConsumer.java diff --git a/src/perf/java/io/reactivex/PerfInteropConsumer.java b/src/jmh/java/io/reactivex/PerfInteropConsumer.java similarity index 100% rename from src/perf/java/io/reactivex/PerfInteropConsumer.java rename to src/jmh/java/io/reactivex/PerfInteropConsumer.java diff --git a/src/perf/java/io/reactivex/PerfObserver.java b/src/jmh/java/io/reactivex/PerfObserver.java similarity index 100% rename from src/perf/java/io/reactivex/PerfObserver.java rename to src/jmh/java/io/reactivex/PerfObserver.java diff --git a/src/perf/java/io/reactivex/PerfSubscriber.java b/src/jmh/java/io/reactivex/PerfSubscriber.java similarity index 100% rename from src/perf/java/io/reactivex/PerfSubscriber.java rename to src/jmh/java/io/reactivex/PerfSubscriber.java diff --git a/src/perf/java/io/reactivex/RangePerf.java b/src/jmh/java/io/reactivex/RangePerf.java similarity index 100% rename from src/perf/java/io/reactivex/RangePerf.java rename to src/jmh/java/io/reactivex/RangePerf.java diff --git a/src/perf/java/io/reactivex/ReducePerf.java b/src/jmh/java/io/reactivex/ReducePerf.java similarity index 100% rename from src/perf/java/io/reactivex/ReducePerf.java rename to src/jmh/java/io/reactivex/ReducePerf.java diff --git a/src/perf/java/io/reactivex/RxVsStreamPerf.java b/src/jmh/java/io/reactivex/RxVsStreamPerf.java similarity index 100% rename from src/perf/java/io/reactivex/RxVsStreamPerf.java rename to src/jmh/java/io/reactivex/RxVsStreamPerf.java diff --git a/src/perf/java/io/reactivex/StrictPerf.java b/src/jmh/java/io/reactivex/StrictPerf.java similarity index 100% rename from src/perf/java/io/reactivex/StrictPerf.java rename to src/jmh/java/io/reactivex/StrictPerf.java diff --git a/src/perf/java/io/reactivex/ToFlowablePerf.java b/src/jmh/java/io/reactivex/ToFlowablePerf.java similarity index 100% rename from src/perf/java/io/reactivex/ToFlowablePerf.java rename to src/jmh/java/io/reactivex/ToFlowablePerf.java diff --git a/src/perf/java/io/reactivex/XMapYPerf.java b/src/jmh/java/io/reactivex/XMapYPerf.java similarity index 100% rename from src/perf/java/io/reactivex/XMapYPerf.java rename to src/jmh/java/io/reactivex/XMapYPerf.java diff --git a/src/perf/java/io/reactivex/parallel/ParallelPerf.java b/src/jmh/java/io/reactivex/parallel/ParallelPerf.java similarity index 100% rename from src/perf/java/io/reactivex/parallel/ParallelPerf.java rename to src/jmh/java/io/reactivex/parallel/ParallelPerf.java From c40be8ea3f823fbe9b77eef0c5d0f03fc6af7774 Mon Sep 17 00:00:00 2001 From: akarnokd Date: Tue, 3 Oct 2017 10:22:20 +0200 Subject: [PATCH 004/417] 2.x: fix "full" mode gradle code --- build.gradle | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index 927fde214a..9636a48be6 100644 --- a/build.gradle +++ b/build.gradle @@ -26,8 +26,9 @@ if (releaseTag != null && !releaseTag.isEmpty()) { releaseTag = releaseTag.substring(1); } version = releaseTag; - - println("Releasing with version " + project.properties["release.version"]); + project.properties.put("release.version", releaseTag); + + println("Releasing with version " + version); } description = "RxJava: Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM." @@ -324,8 +325,10 @@ if (rootProject.hasProperty("releaseMode")) { if ("full".equals(rootProject.releaseMode)) { // based on https://github.com/bintray/gradle-bintray-plugin - println("ReleaseMode: " + rootProject.releaseMode); - + def rver = version; + + println("ReleaseMode: " + rootProject.releaseMode + " version " + rver); + bintray { user = rootProject.bintrayUser key = rootProject.bintrayKey From ddc86403de6c12c3bf76c8c25941e2d4700c0a63 Mon Sep 17 00:00:00 2001 From: akarnokd Date: Tue, 3 Oct 2017 11:09:39 +0200 Subject: [PATCH 005/417] 2.x: fix bintray repo and name config --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 9636a48be6..1712748df7 100644 --- a/build.gradle +++ b/build.gradle @@ -336,8 +336,8 @@ if (rootProject.hasProperty("releaseMode")) { publications = ["mavenJava"] publish = true pkg { - repo = "generic" - name = "rxjava" + repo = "RxJava" + name = "RxJava" userOrg = "reactivex" labels = ["rxjava", "reactivex"] licenses = ["Apache-2.0"] From 126e7b52d0127d5e9c749f7e2c52a8de16ba9efc Mon Sep 17 00:00:00 2001 From: akarnokd Date: Tue, 3 Oct 2017 11:34:11 +0200 Subject: [PATCH 006/417] 2.x: RC4 fix maven-POM generation again --- build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/build.gradle b/build.gradle index 1712748df7..bda32b0c8b 100644 --- a/build.gradle +++ b/build.gradle @@ -333,7 +333,6 @@ if (rootProject.hasProperty("releaseMode")) { user = rootProject.bintrayUser key = rootProject.bintrayKey configurations = ["archives"] - publications = ["mavenJava"] publish = true pkg { repo = "RxJava" From 3e11dc0609bf6267be381c4723bba0f13769eb1c Mon Sep 17 00:00:00 2001 From: Igor Levaja Date: Tue, 3 Oct 2017 15:35:49 +0200 Subject: [PATCH 007/417] Fixing JavaDoc warnings (#5637) --- src/main/java/io/reactivex/Completable.java | 1 - src/main/java/io/reactivex/Flowable.java | 36 +++++-------------- src/main/java/io/reactivex/Maybe.java | 6 ---- src/main/java/io/reactivex/Observable.java | 23 +++++------- src/main/java/io/reactivex/Scheduler.java | 8 ++--- src/main/java/io/reactivex/Single.java | 15 ++++---- .../reactivex/observers/DefaultObserver.java | 2 +- .../DisposableCompletableObserver.java | 2 +- .../observers/DisposableMaybeObserver.java | 2 +- .../observers/DisposableObserver.java | 2 +- .../observers/DisposableSingleObserver.java | 2 +- .../ResourceCompletableObserver.java | 2 +- .../observers/ResourceMaybeObserver.java | 4 +-- .../reactivex/observers/ResourceObserver.java | 4 +-- .../observers/ResourceSingleObserver.java | 4 +-- src/main/java/io/reactivex/package-info.java | 2 +- .../processors/BehaviorProcessor.java | 1 - .../processors/PublishProcessor.java | 1 - .../reactivex/processors/ReplayProcessor.java | 1 - .../reactivex/subjects/BehaviorSubject.java | 1 - .../io/reactivex/subjects/PublishSubject.java | 1 - .../io/reactivex/subjects/ReplaySubject.java | 1 - .../java/io/reactivex/subjects/Subject.java | 2 +- .../subscribers/DefaultSubscriber.java | 2 +- .../subscribers/DisposableSubscriber.java | 2 +- .../subscribers/ResourceSubscriber.java | 4 +-- 26 files changed, 45 insertions(+), 86 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index fd541b03fe..5a2c01db35 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -207,7 +207,6 @@ public static Completable concat(Publisher sources, * * }); * - *

*

*
Scheduler:
*
{@code create} does not operate by default on a particular {@link Scheduler}.
diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index a85aa4a25d..d58c6faad8 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -2121,7 +2121,6 @@ public static Flowable fromPublisher(final Publisher source) /** * Returns a cold, synchronous, stateless and backpressure-aware generator of values. - *

*

*
Backpressure:
*
The operator honors downstream backpressure.
@@ -2148,7 +2147,6 @@ public static Flowable generate(final Consumer> generator) { /** * Returns a cold, synchronous, stateful and backpressure-aware generator of values. - *

*

*
Backpressure:
*
The operator honors downstream backpressure.
@@ -2176,7 +2174,6 @@ public static Flowable generate(Callable initialState, final BiCons /** * Returns a cold, synchronous, stateful and backpressure-aware generator of values. - *

*

*
Backpressure:
*
The operator honors downstream backpressure.
@@ -2206,7 +2203,6 @@ public static Flowable generate(Callable initialState, final BiCons /** * Returns a cold, synchronous, stateful and backpressure-aware generator of values. - *

*

*
Backpressure:
*
The operator honors downstream backpressure.
@@ -2233,7 +2229,6 @@ public static Flowable generate(Callable initialState, BiFunction *
*
Backpressure:
*
The operator honors downstream backpressure.
@@ -5617,7 +5612,6 @@ public final void blockingSubscribe() { * If the Flowable emits an error, it is wrapped into an * {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} * and routed to the RxJavaPlugins.onError handler. - *

*

*
Backpressure:
*
The operator consumes the source {@code Flowable} in an unbounded manner @@ -5676,7 +5670,6 @@ public final void blockingSubscribe(Consumer onNext, Consumeron the current thread. - *

*

*
Backpressure:
*
The supplied {@code Subscriber} determines how backpressure is applied.
@@ -6909,7 +6902,6 @@ public final Flowable concatMapEagerDelayError(Function * *
*
Backpressure:
@@ -6939,7 +6931,6 @@ public final Flowable concatMapIterable(Function * *
*
Backpressure:
@@ -7091,7 +7082,6 @@ public final Flowable debounce(Function * *

* Information on debounce vs throttle: - *

*

    *
  • Debounce and Throttle: visual explanation
  • *
  • Debouncing: javascript methods
  • @@ -7133,7 +7123,6 @@ public final Flowable debounce(long timeout, TimeUnit unit) { * *

    * Information on debounce vs throttle: - *

    *

      *
    • Debounce and Throttle: visual explanation
    • *
    • Debouncing: javascript methods
    • @@ -7393,7 +7382,6 @@ public final Flowable delay(Publisher subscriptionIndicator, /** * Returns a Flowable that delays the subscription to this Publisher * until the other Publisher emits an element or completes normally. - *

      *

      *
      Backpressure:
      *
      The operator forwards the backpressure requests to this Publisher once @@ -8336,7 +8324,7 @@ public final Flowable flatMap(Function + * * *
      *
      Backpressure:
      @@ -8372,7 +8360,7 @@ public final Flowable flatMap(Function + * * *
      *
      Backpressure:
      @@ -8411,7 +8399,7 @@ public final Flowable flatMap(Function + * * *
      *
      Backpressure:
      @@ -8505,7 +8493,7 @@ public final Flowable flatMap( * Returns a Flowable that applies a function to each item emitted or notification raised by the source * Publisher and then flattens the Publishers returned from these functions and emits the resulting items, * while limiting the maximum number of concurrent subscriptions to these Publishers. - *

      + * * *

      *
      Backpressure:
      @@ -8628,7 +8616,7 @@ public final Flowable flatMap(Function + * * *
      *
      Backpressure:
      @@ -8671,7 +8659,7 @@ public final Flowable flatMap(Function + * * *
      *
      Backpressure:
      @@ -8720,7 +8708,7 @@ public final Flowable flatMap(final Function + * * *
      *
      Backpressure:
      @@ -10111,7 +10099,7 @@ public final Flowable onBackpressureBuffer(int capacity, Action onOverflow) { * cancelling the source, and notifying the producer with {@code onOverflow}. *
    • {@code BackpressureOverflow.Strategy.ON_OVERFLOW_DROP_LATEST} will drop any new items emitted by the producer while * the buffer is full, without generating any {@code onError}. Each drop will however invoke {@code onOverflow} - * to signal the overflow to the producer.
    • j + * to signal the overflow to the producer. *
    • {@code BackpressureOverflow.Strategy.ON_OVERFLOW_DROP_OLDEST} will drop the oldest items in the buffer in order to make * room for newly emitted ones. Overflow will not generate an{@code onError}, but each drop will invoke * {@code onOverflow} to signal the overflow to the producer.
    • @@ -10212,7 +10200,6 @@ public final Flowable onBackpressureDrop(Consumer onDrop) { *

      * Note that due to the nature of how backpressure requests are propagated through subscribeOn/observeOn, * requesting more than 1 from downstream doesn't guarantee a continuous delivery of onNext events. - *

      *

      *
      Backpressure:
      *
      The operator honors backpressure from downstream and consumes the source {@code Publisher} in an unbounded @@ -13125,8 +13112,8 @@ public final Flowable subscribeOn(@NonNull Scheduler scheduler, boolean reque /** * Returns a Flowable that emits the items emitted by the source Publisher or the items of an alternate * Publisher if the source Publisher is empty. + *

      * - *

      *

      *
      Backpressure:
      *
      If the source {@code Publisher} is empty, the alternate {@code Publisher} is expected to honor backpressure. @@ -13953,7 +13940,6 @@ public final Flowable throttleLast(long intervalDuration, TimeUnit unit, Sche * *

      * Information on debounce vs throttle: - *

      *

        *
      • Debounce and Throttle: visual explanation
      • *
      • Debouncing: javascript methods
      • @@ -13995,7 +13981,6 @@ public final Flowable throttleWithTimeout(long timeout, TimeUnit unit) { * *

        * Information on debounce vs throttle: - *

        *

          *
        • Debounce and Throttle: visual explanation
        • *
        • Debouncing: javascript methods
        • @@ -16064,7 +16049,6 @@ public final Flowable zipWith(Iterable other, BiFunction - *

          * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling @@ -16112,7 +16096,6 @@ public final Flowable zipWith(Publisher other, BiFunction * Returns a Flowable that emits items that are the result of applying a specified function to pairs of * values, one each from the source Publisher and another specified Publisher. *

          - *

          * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling @@ -16163,7 +16146,6 @@ public final Flowable zipWith(Publisher other, * Returns a Flowable that emits items that are the result of applying a specified function to pairs of * values, one each from the source Publisher and another specified Publisher. *

          - *

          * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index deae7c020c..7a2a6bc241 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -463,7 +463,6 @@ public static Flowable concatEager(Publisher - *

          *

          *
          Scheduler:
          *
          {@code create} does not operate by default on a particular {@link Scheduler}.
          @@ -837,7 +836,6 @@ public static Flowable merge(Publisher * emitted by the nested {@code MaybeSource}, without any transformation. *

          * - *

          *

          *
          Scheduler:
          *
          {@code merge} does not operate by default on a particular {@link Scheduler}.
          @@ -2271,7 +2269,6 @@ public final Maybe delay(long delay, TimeUnit unit, Scheduler scheduler) { * Delays the emission of this Maybe until the given Publisher signals an item or completes. *

          * - *

          *

          *
          Backpressure:
          *
          The {@code delayIndicator} is consumed in an unbounded manner but is cancelled after @@ -2301,7 +2298,6 @@ public final Maybe delay(Publisher delayIndicator) { /** * Returns a Maybe that delays the subscription to this Maybe * until the other Publisher emits an element or completes normally. - *

          *

          *
          Backpressure:
          *
          The {@code Publisher} source is consumed in an unbounded fashion (without applying backpressure).
          @@ -3803,7 +3799,6 @@ public final > E subscribeWith(E observer) { * MaybeSource if the current Maybe is empty. *

          * - *

          *

          *
          Scheduler:
          *
          {@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.
          @@ -3826,7 +3821,6 @@ public final Maybe switchIfEmpty(MaybeSource other) { * SingleSource if the current Maybe is empty. *

          * - *

          *

          *
          Scheduler:
          *
          {@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.
          diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index e378c2c192..ab3f0689bf 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -5168,7 +5168,6 @@ public final void blockingSubscribe(Consumer onNext, Consumeron the current thread. - *

          *

          *
          Scheduler:
          *
          {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
          @@ -6243,7 +6242,6 @@ public final Observable concatMapEagerDelayError(Function * *
          *
          Scheduler:
          @@ -6269,7 +6267,6 @@ public final Observable concatMapIterable(final Function * *
          *
          Scheduler:
          @@ -6398,7 +6395,6 @@ public final Observable debounce(Function *

          * Information on debounce vs throttle: - *

          *

            *
          • Debounce and Throttle: visual explanation
          • *
          • Debouncing: javascript methods
          • @@ -6436,7 +6432,6 @@ public final Observable debounce(long timeout, TimeUnit unit) { * *

            * Information on debounce vs throttle: - *

            *

              *
            • Debounce and Throttle: visual explanation
            • *
            • Debouncing: javascript methods
            • @@ -7439,7 +7434,7 @@ public final Observable flatMap(Function + * * *
              *
              Scheduler:
              @@ -7472,7 +7467,7 @@ public final Observable flatMap(Function + * * *
              *
              Scheduler:
              @@ -7554,7 +7549,7 @@ public final Observable flatMap( * Returns an Observable that applies a function to each item emitted or notification raised by the source * ObservableSource and then flattens the ObservableSources returned from these functions and emits the resulting items, * while limiting the maximum number of concurrent subscriptions to these ObservableSources. - *

              + * * *

              *
              Scheduler:
              @@ -7596,7 +7591,7 @@ public final Observable flatMap( * by the source ObservableSource, where that function returns an ObservableSource, and then merging those resulting * ObservableSources and emitting the results of this merger, while limiting the maximum number of concurrent * subscriptions to these ObservableSources. - *

              + * * *

              *
              Scheduler:
              @@ -7688,7 +7683,7 @@ public final Observable flatMap(Function + * * *
              *
              Scheduler:
              @@ -7725,7 +7720,7 @@ public final Observable flatMap(Function + * * *
              *
              Scheduler:
              @@ -7766,7 +7761,7 @@ public final Observable flatMap(final Function + * * *
              *
              Scheduler:
              @@ -10982,8 +10977,8 @@ public final Observable subscribeOn(Scheduler scheduler) { /** * Returns an Observable that emits the items emitted by the source ObservableSource or the items of an alternate * ObservableSource if the source ObservableSource is empty. + *

              * - *

              *

              *
              Scheduler:
              *
              {@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.
              @@ -11759,7 +11754,6 @@ public final Observable throttleLast(long intervalDuration, TimeUnit unit, Sc * *

              * Information on debounce vs throttle: - *

              *

                *
              • Debounce and Throttle: visual explanation
              • *
              • Debouncing: javascript methods
              • @@ -11797,7 +11791,6 @@ public final Observable throttleWithTimeout(long timeout, TimeUnit unit) { * *

                * Information on debounce vs throttle: - *

                *

                  *
                • Debounce and Throttle: visual explanation
                • *
                • Debouncing: javascript methods
                • diff --git a/src/main/java/io/reactivex/Scheduler.java b/src/main/java/io/reactivex/Scheduler.java index 00eb314006..136d20d842 100644 --- a/src/main/java/io/reactivex/Scheduler.java +++ b/src/main/java/io/reactivex/Scheduler.java @@ -199,7 +199,7 @@ public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initial * size thread pool: * *
                  -     * Scheduler limitScheduler = Schedulers.computation().when(workers -> {
                  +     * Scheduler limitScheduler = Schedulers.computation().when(workers -> {
                        *  // use merge max concurrent to limit the number of concurrent
                        *  // callbacks two at a time
                        *  return Completable.merge(Flowable.merge(workers), 2);
                  @@ -217,7 +217,7 @@ public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initial
                        * subscription to the second.
                        * 
                        * 
                  -     * Scheduler limitScheduler = Schedulers.computation().when(workers -> {
                  +     * Scheduler limitScheduler = Schedulers.computation().when(workers -> {
                        *  // use merge max concurrent to limit the number of concurrent
                        *  // Flowables two at a time
                        *  return Completable.merge(Flowable.merge(workers, 2));
                  @@ -230,9 +230,9 @@ public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initial
                        * bucket algorithm).
                        * 
                        * 
                  -     * Scheduler slowScheduler = Schedulers.computation().when(workers -> {
                  +     * Scheduler slowScheduler = Schedulers.computation().when(workers -> {
                        *  // use concatenate to make each worker happen one at a time.
                  -     *  return Completable.concat(workers.map(actions -> {
                  +     *  return Completable.concat(workers.map(actions -> {
                        *      // delay the starting of the next worker by 1 second.
                        *      return Completable.merge(actions.delaySubscription(1, TimeUnit.SECONDS));
                        *  }));
                  diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java
                  index 58b2e9b007..76b27aae6f 100644
                  --- a/src/main/java/io/reactivex/Single.java
                  +++ b/src/main/java/io/reactivex/Single.java
                  @@ -344,7 +344,6 @@ public static  Flowable concatArray(SingleSource... sources)
                        *
                        * });
                        * 
                  - *

                  *

                  *
                  Scheduler:
                  *
                  {@code create} does not operate by default on a particular {@link Scheduler}.
                  @@ -602,7 +601,6 @@ public static Single fromPublisher(final Publisher publisher * Wraps a specific ObservableSource into a Single and signals its single element or error. *

                  If the ObservableSource is empty, a NoSuchElementException is signalled. * If the source has more than one element, an IndexOutOfBoundsException is signalled. - *

                  *

                  *
                  Scheduler:
                  *
                  {@code fromObservable} does not operate by default on a particular {@link Scheduler}.
                  @@ -695,7 +693,6 @@ public static Flowable merge(Publisher * - *

                  *

                  *
                  Scheduler:
                  *
                  {@code merge} does not operate by default on a particular {@link Scheduler}.
                  @@ -2401,9 +2398,9 @@ public final Single onErrorReturnItem(final T value) { /** * Instructs a Single to pass control to another Single rather than invoking * {@link SingleObserver#onError(Throwable)} if it encounters an error. - *

                  + *

                  * - *

                  + *

                  * By default, when a Single encounters an error that prevents it from emitting the expected item to * its {@link SingleObserver}, the Single invokes its SingleObserver's {@code onError} method, and then quits * without invoking any more of its SingleObserver's methods. The {@code onErrorResumeNext} method changes this @@ -2413,7 +2410,7 @@ public final Single onErrorReturnItem(final T value) { * will invoke the SingleObserver's {@link SingleObserver#onSuccess onSuccess} method if it is able to do so. In such a case, * because no Single necessarily invokes {@code onError}, the SingleObserver may never know that an error * happened. - *

                  + *

                  * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. *

                  @@ -2435,9 +2432,9 @@ public final Single onErrorResumeNext(final Single resumeSingleI /** * Instructs a Single to pass control to another Single rather than invoking * {@link SingleObserver#onError(Throwable)} if it encounters an error. - *

                  + *

                  * - *

                  + *

                  * By default, when a Single encounters an error that prevents it from emitting the expected item to * its {@link SingleObserver}, the Single invokes its SingleObserver's {@code onError} method, and then quits * without invoking any more of its SingleObserver's methods. The {@code onErrorResumeNext} method changes this @@ -2447,7 +2444,7 @@ public final Single onErrorResumeNext(final Single resumeSingleI * will invoke the SingleObserver's {@link SingleObserver#onSuccess onSuccess} method if it is able to do so. In such a case, * because no Single necessarily invokes {@code onError}, the SingleObserver may never know that an error * happened. - *

                  + *

                  * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. *

                  diff --git a/src/main/java/io/reactivex/observers/DefaultObserver.java b/src/main/java/io/reactivex/observers/DefaultObserver.java index 7ae2f25d9a..b09f8b7e89 100644 --- a/src/main/java/io/reactivex/observers/DefaultObserver.java +++ b/src/main/java/io/reactivex/observers/DefaultObserver.java @@ -40,7 +40,7 @@ * *

                  Example

                  
                    * Observable.range(1, 5)
                  - *     .subscribe(new DefaultObserver<Integer>() {
                  + *     .subscribe(new DefaultObserver<Integer>() {
                    *         @Override public void onStart() {
                    *             System.out.println("Start!");
                    *         }
                  diff --git a/src/main/java/io/reactivex/observers/DisposableCompletableObserver.java b/src/main/java/io/reactivex/observers/DisposableCompletableObserver.java
                  index 31a02f4831..e07cb508c7 100644
                  --- a/src/main/java/io/reactivex/observers/DisposableCompletableObserver.java
                  +++ b/src/main/java/io/reactivex/observers/DisposableCompletableObserver.java
                  @@ -36,7 +36,7 @@
                    * 

                  Example

                  
                    * Disposable d =
                    *     Completable.complete().delay(1, TimeUnit.SECONDS)
                  - *     .subscribeWith(new DisposableMaybeObserver<Integer>() {
                  + *     .subscribeWith(new DisposableMaybeObserver<Integer>() {
                    *         @Override public void onStart() {
                    *             System.out.println("Start!");
                    *         }
                  diff --git a/src/main/java/io/reactivex/observers/DisposableMaybeObserver.java b/src/main/java/io/reactivex/observers/DisposableMaybeObserver.java
                  index 059fe0efb7..ebf8a579f2 100644
                  --- a/src/main/java/io/reactivex/observers/DisposableMaybeObserver.java
                  +++ b/src/main/java/io/reactivex/observers/DisposableMaybeObserver.java
                  @@ -40,7 +40,7 @@
                    * 

                  Example

                  
                    * Disposable d =
                    *     Maybe.just(1).delay(1, TimeUnit.SECONDS)
                  - *     .subscribeWith(new DisposableMaybeObserver<Integer>() {
                  + *     .subscribeWith(new DisposableMaybeObserver<Integer>() {
                    *         @Override public void onStart() {
                    *             System.out.println("Start!");
                    *         }
                  diff --git a/src/main/java/io/reactivex/observers/DisposableObserver.java b/src/main/java/io/reactivex/observers/DisposableObserver.java
                  index f08785874b..c835b853a2 100644
                  --- a/src/main/java/io/reactivex/observers/DisposableObserver.java
                  +++ b/src/main/java/io/reactivex/observers/DisposableObserver.java
                  @@ -41,7 +41,7 @@
                    * 

                  Example

                  
                    * Disposable d =
                    *     Observable.range(1, 5)
                  - *     .subscribeWith(new DisposableObserver<Integer>() {
                  + *     .subscribeWith(new DisposableObserver<Integer>() {
                    *         @Override public void onStart() {
                    *             System.out.println("Start!");
                    *         }
                  diff --git a/src/main/java/io/reactivex/observers/DisposableSingleObserver.java b/src/main/java/io/reactivex/observers/DisposableSingleObserver.java
                  index 84f67170a3..2d339e3400 100644
                  --- a/src/main/java/io/reactivex/observers/DisposableSingleObserver.java
                  +++ b/src/main/java/io/reactivex/observers/DisposableSingleObserver.java
                  @@ -36,7 +36,7 @@
                    * 

                  Example

                  
                    * Disposable d =
                    *     Single.just(1).delay(1, TimeUnit.SECONDS)
                  - *     .subscribeWith(new DisposableSingleObserver<Integer>() {
                  + *     .subscribeWith(new DisposableSingleObserver<Integer>() {
                    *         @Override public void onStart() {
                    *             System.out.println("Start!");
                    *         }
                  diff --git a/src/main/java/io/reactivex/observers/ResourceCompletableObserver.java b/src/main/java/io/reactivex/observers/ResourceCompletableObserver.java
                  index e9300ee977..f4b4261807 100644
                  --- a/src/main/java/io/reactivex/observers/ResourceCompletableObserver.java
                  +++ b/src/main/java/io/reactivex/observers/ResourceCompletableObserver.java
                  @@ -56,7 +56,7 @@
                    *     .subscribeWith(new ResourceCompletableObserver() {
                    *         @Override public void onStart() {
                    *             add(Schedulers.single()
                  - *                 .scheduleDirect(() -> System.out.println("Time!"),
                  + *                 .scheduleDirect(() -> System.out.println("Time!"),
                    *                     2, TimeUnit.SECONDS));
                    *         }
                    *         @Override public void onError(Throwable t) {
                  diff --git a/src/main/java/io/reactivex/observers/ResourceMaybeObserver.java b/src/main/java/io/reactivex/observers/ResourceMaybeObserver.java
                  index 6b97f2219e..a48fb06872 100644
                  --- a/src/main/java/io/reactivex/observers/ResourceMaybeObserver.java
                  +++ b/src/main/java/io/reactivex/observers/ResourceMaybeObserver.java
                  @@ -57,10 +57,10 @@
                    * 

                  Example

                  
                    * Disposable d =
                    *     Maybe.just(1).delay(1, TimeUnit.SECONDS)
                  - *     .subscribeWith(new ResourceMaybeObserver<Integer>() {
                  + *     .subscribeWith(new ResourceMaybeObserver<Integer>() {
                    *         @Override public void onStart() {
                    *             add(Schedulers.single()
                  - *                 .scheduleDirect(() -> System.out.println("Time!"),
                  + *                 .scheduleDirect(() -> System.out.println("Time!"),
                    *                     2, TimeUnit.SECONDS));
                    *         }
                    *         @Override public void onSuccess(Integer t) {
                  diff --git a/src/main/java/io/reactivex/observers/ResourceObserver.java b/src/main/java/io/reactivex/observers/ResourceObserver.java
                  index 413cd5429d..f42353db13 100644
                  --- a/src/main/java/io/reactivex/observers/ResourceObserver.java
                  +++ b/src/main/java/io/reactivex/observers/ResourceObserver.java
                  @@ -52,10 +52,10 @@
                    * 

                  Example

                  
                    * Disposable d =
                    *     Observable.range(1, 5)
                  - *     .subscribeWith(new ResourceObserver<Integer>() {
                  + *     .subscribeWith(new ResourceObserver<Integer>() {
                    *         @Override public void onStart() {
                    *             add(Schedulers.single()
                  - *                 .scheduleDirect(() -> System.out.println("Time!"),
                  + *                 .scheduleDirect(() -> System.out.println("Time!"),
                    *                     2, TimeUnit.SECONDS));
                    *             request(1);
                    *         }
                  diff --git a/src/main/java/io/reactivex/observers/ResourceSingleObserver.java b/src/main/java/io/reactivex/observers/ResourceSingleObserver.java
                  index c62ebcb2db..9f28fd0791 100644
                  --- a/src/main/java/io/reactivex/observers/ResourceSingleObserver.java
                  +++ b/src/main/java/io/reactivex/observers/ResourceSingleObserver.java
                  @@ -54,10 +54,10 @@
                    * 

                  Example

                  
                    * Disposable d =
                    *     Single.just(1).delay(1, TimeUnit.SECONDS)
                  - *     .subscribeWith(new ResourceSingleObserver<Integer>() {
                  + *     .subscribeWith(new ResourceSingleObserver<Integer>() {
                    *         @Override public void onStart() {
                    *             add(Schedulers.single()
                  - *                 .scheduleDirect(() -> System.out.println("Time!"),
                  + *                 .scheduleDirect(() -> System.out.println("Time!"),
                    *                     2, TimeUnit.SECONDS));
                    *         }
                    *         @Override public void onSuccess(Integer t) {
                  diff --git a/src/main/java/io/reactivex/package-info.java b/src/main/java/io/reactivex/package-info.java
                  index 5ad6fdca2f..5c9065ddb8 100644
                  --- a/src/main/java/io/reactivex/package-info.java
                  +++ b/src/main/java/io/reactivex/package-info.java
                  @@ -40,7 +40,7 @@
                    * 
                • Subscriber == IAsyncEnumerator
                • *
                * The Single and Completable reactive base types have no equivalent in Rx.NET as of 3.x. - *

                + * *

                Services which intend on exposing data asynchronously and wish * to allow reactive processing and composition can implement the * {@link io.reactivex.Flowable}, {@link io.reactivex.Observable}, {@link io.reactivex.Single} diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index d033d636c0..eb9d3196e7 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -34,7 +34,6 @@ * *

                * Example usage: - *

                *

                 {@code
                 
                   // observer will receive all events.
                diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java
                index 51ff0f6326..fb3b2ead83 100644
                --- a/src/main/java/io/reactivex/processors/PublishProcessor.java
                +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java
                @@ -40,7 +40,6 @@
                  * {@code new} but must be created via the {@link #create()} method.
                  *
                  * Example usage:
                - * 

                *

                 {@code
                 
                   PublishProcessor processor = PublishProcessor.create();
                diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java
                index 1eef113864..8021170a45 100644
                --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java
                +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java
                @@ -44,7 +44,6 @@
                  *
                  * 

                * Example usage: - *

                *

                 {@code
                 
                   ReplayProcessor processor = new ReplayProcessor();
                diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java
                index 196ad8301f..8a80cf4a24 100644
                --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java
                +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java
                @@ -32,7 +32,6 @@
                  * 
                  * 

                * Example usage: - *

                *

                 {@code
                 
                   // observer will receive all 4 events (including "default").
                diff --git a/src/main/java/io/reactivex/subjects/PublishSubject.java b/src/main/java/io/reactivex/subjects/PublishSubject.java
                index 297e6e6363..4608afc432 100644
                --- a/src/main/java/io/reactivex/subjects/PublishSubject.java
                +++ b/src/main/java/io/reactivex/subjects/PublishSubject.java
                @@ -27,7 +27,6 @@
                  * 
                  * 

                * Example usage: - *

                *

                 {@code
                 
                   PublishSubject subject = PublishSubject.create();
                diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java
                index 4b684e31bf..d5bd4bac51 100644
                --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java
                +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java
                @@ -32,7 +32,6 @@
                  * 
                  * 

                * Example usage: - *

                *

                 {@code
                 
                   ReplaySubject subject = new ReplaySubject<>();
                diff --git a/src/main/java/io/reactivex/subjects/Subject.java b/src/main/java/io/reactivex/subjects/Subject.java
                index 79bcb3934b..6bd105be85 100644
                --- a/src/main/java/io/reactivex/subjects/Subject.java
                +++ b/src/main/java/io/reactivex/subjects/Subject.java
                @@ -37,7 +37,7 @@ public abstract class Subject extends Observable implements Observer {
                      * 

                The method is thread-safe. * @return true if the subject has reached a terminal state through an error event * @see #getThrowable() - * &see {@link #hasComplete()} + * @see #hasComplete() */ public abstract boolean hasThrowable(); diff --git a/src/main/java/io/reactivex/subscribers/DefaultSubscriber.java b/src/main/java/io/reactivex/subscribers/DefaultSubscriber.java index d73c054af7..0b6c538cf9 100644 --- a/src/main/java/io/reactivex/subscribers/DefaultSubscriber.java +++ b/src/main/java/io/reactivex/subscribers/DefaultSubscriber.java @@ -51,7 +51,7 @@ * *

                Example

                
                  * Flowable.range(1, 5)
                - *     .subscribe(new DefaultSubscriber<Integer>() {
                + *     .subscribe(new DefaultSubscriber<Integer>() {
                  *         @Override public void onStart() {
                  *             System.out.println("Start!");
                  *             request(1);
                diff --git a/src/main/java/io/reactivex/subscribers/DisposableSubscriber.java b/src/main/java/io/reactivex/subscribers/DisposableSubscriber.java
                index 3cb1be5d70..5c460de70b 100644
                --- a/src/main/java/io/reactivex/subscribers/DisposableSubscriber.java
                +++ b/src/main/java/io/reactivex/subscribers/DisposableSubscriber.java
                @@ -50,7 +50,7 @@
                  * 

                Example

                
                  * Disposable d =
                  *     Flowable.range(1, 5)
                - *     .subscribeWith(new DisposableSubscriber<Integer>() {
                + *     .subscribeWith(new DisposableSubscriber<Integer>() {
                  *         @Override public void onStart() {
                  *             request(1);
                  *         }
                diff --git a/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java b/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java
                index a90942486c..66c282842c 100644
                --- a/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java
                +++ b/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java
                @@ -63,10 +63,10 @@
                  * 

                Example

                
                  * Disposable d =
                  *     Flowable.range(1, 5)
                - *     .subscribeWith(new ResourceSubscriber<Integer>() {
                + *     .subscribeWith(new ResourceSubscriber<Integer>() {
                  *         @Override public void onStart() {
                  *             add(Schedulers.single()
                - *                 .scheduleDirect(() -> System.out.println("Time!"),
                + *                 .scheduleDirect(() -> System.out.println("Time!"),
                  *                     2, TimeUnit.SECONDS));
                  *             request(1);
                  *         }
                
                From 182de289450e3a0ea8081dbd1efd617f15f700b8 Mon Sep 17 00:00:00 2001
                From: Igor Levaja 
                Date: Wed, 4 Oct 2017 15:51:12 +0200
                Subject: [PATCH 008/417] Added Automatic-Module-Name instruction in
                 build.gradle (#5644)
                
                ---
                 build.gradle | 1 +
                 1 file changed, 1 insertion(+)
                
                diff --git a/build.gradle b/build.gradle
                index bda32b0c8b..a831cca29b 100644
                --- a/build.gradle
                +++ b/build.gradle
                @@ -124,6 +124,7 @@ jar {
                         instruction "Bundle-DocURL", "https://github.com/ReactiveX/RxJava"
                         instruction "Import-Package", "!org.junit,!junit.framework,!org.mockito.*,!org.testng.*,*"
                         instruction "Eclipse-ExtensibleAPI", "true"
                +        instruction "Automatic-Module-Name", "io.reactivex.rxjava2"
                     }
                 }
                 
                
                From 89581b46ba676c97fc987518d72c054e8b7d00b9 Mon Sep 17 00:00:00 2001
                From: David Karnok 
                Date: Wed, 4 Oct 2017 18:32:57 +0200
                Subject: [PATCH 009/417] 2.x: additional warnings for fromPublisher() (#5640)
                
                * 2.x: additional warnings for fromPublisher()
                
                * Add "that is" to the sentences
                ---
                 src/main/java/io/reactivex/Completable.java | 12 ++++++++++++
                 src/main/java/io/reactivex/Flowable.java    | 12 ++++++++++++
                 src/main/java/io/reactivex/Observable.java  | 12 ++++++++++++
                 src/main/java/io/reactivex/Single.java      | 12 ++++++++++++
                 4 files changed, 48 insertions(+)
                
                diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java
                index 5a2c01db35..df628bc2a2 100644
                --- a/src/main/java/io/reactivex/Completable.java
                +++ b/src/main/java/io/reactivex/Completable.java
                @@ -394,6 +394,17 @@ public static  Completable fromObservable(final ObservableSource observabl
                     /**
                      * Returns a Completable instance that subscribes to the given publisher, ignores all values and
                      * emits only the terminal event.
                +     * 

                + * The {@link Publisher} must follow the + * Reactive-Streams specification. + * Violating the specification may result in undefined behavior. + *

                + * If possible, use {@link #create(CompletableOnSubscribe)} to create a + * source-like {@code Completable} instead. + *

                + * Note that even though {@link Publisher} appears to be a functional interface, it + * is not recommended to implement it through a lambda as the specification requires + * state management that is not achievable with a stateless lambda. *

                *
                Backpressure:
                *
                The returned {@code Completable} honors the backpressure of the downstream consumer @@ -405,6 +416,7 @@ public static Completable fromObservable(final ObservableSource observabl * @param publisher the Publisher instance to subscribe to, not null * @return the new Completable instance * @throws NullPointerException if publisher is null + * @see #create(CompletableOnSubscribe) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index d58c6faad8..a6a8624a6d 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -2094,6 +2094,17 @@ public static Flowable fromIterable(Iterable source) { /** * Converts an arbitrary Reactive-Streams Publisher into a Flowable if not already a * Flowable. + *

                + * The {@link Publisher} must follow the + * Reactive-Streams specification. + * Violating the specification may result in undefined behavior. + *

                + * If possible, use {@link #create(FlowableOnSubscribe, BackpressureStrategy)} to create a + * source-like {@code Flowable} instead. + *

                + * Note that even though {@link Publisher} appears to be a functional interface, it + * is not recommended to implement it through a lambda as the specification requires + * state management that is not achievable with a stateless lambda. *

                *
                Backpressure:
                *
                The operator is a pass-through for backpressure and its behavior is determined by the @@ -2105,6 +2116,7 @@ public static Flowable fromIterable(Iterable source) { * @param source the Publisher to convert * @return the new Flowable instance * @throws NullPointerException if publisher is null + * @see #create(FlowableOnSubscribe, BackpressureStrategy) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.PASS_THROUGH) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index ab3f0689bf..f5a025add7 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -1897,6 +1897,17 @@ public static Observable fromIterable(Iterable source) { /** * Converts an arbitrary Reactive-Streams Publisher into an Observable. + *

                + * The {@link Publisher} must follow the + * Reactive-Streams specification. + * Violating the specification may result in undefined behavior. + *

                + * If possible, use {@link #create(ObservableOnSubscribe)} to create a + * source-like {@code Observable} instead. + *

                + * Note that even though {@link Publisher} appears to be a functional interface, it + * is not recommended to implement it through a lambda as the specification requires + * state management that is not achievable with a stateless lambda. *

                *
                Backpressure:
                *
                The source {@code publisher} is consumed in an unbounded fashion without applying any @@ -1908,6 +1919,7 @@ public static Observable fromIterable(Iterable source) { * @param publisher the Publisher to convert * @return the new Observable instance * @throws NullPointerException if publisher is null + * @see #create(ObservableOnSubscribe) */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 76b27aae6f..f58005046c 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -578,6 +578,17 @@ public static Single fromFuture(Future future, Scheduler sch * Wraps a specific Publisher into a Single and signals its single element or error. *

                If the source Publisher is empty, a NoSuchElementException is signalled. If * the source has more than one element, an IndexOutOfBoundsException is signalled. + *

                + * The {@link Publisher} must follow the + * Reactive-Streams specification. + * Violating the specification may result in undefined behavior. + *

                + * If possible, use {@link #create(SingleOnSubscribe)} to create a + * source-like {@code Single} instead. + *

                + * Note that even though {@link Publisher} appears to be a functional interface, it + * is not recommended to implement it through a lambda as the specification requires + * state management that is not achievable with a stateless lambda. *

                *
                Backpressure:
                *
                The {@code publisher} is consumed in an unbounded fashion but will be cancelled @@ -588,6 +599,7 @@ public static Single fromFuture(Future future, Scheduler sch * @param the value type * @param publisher the source Publisher instance, not null * @return the new Single instance + * @see #create(SingleOnSubscribe) */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue From 831f6c8d171015974f1285e46ad4c55828ec0fc5 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 5 Oct 2017 09:58:14 +0200 Subject: [PATCH 010/417] 2.x: Readme.md update snapshot links (#5645) * 2.x: Readme.md update snapshot links * Use plain link and only the current snapshot dependency --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index acb596daac..44470d2ad9 100644 --- a/README.md +++ b/README.md @@ -231,7 +231,7 @@ and for Ivy: ``` -Snapshots are available via [JFrog](https://oss.jfrog.org/webapp/#/home): +Snapshots are available via https://oss.jfrog.org/libs-snapshot/io/reactivex/rxjava2/rxjava/ ```groovy repositories { @@ -239,7 +239,7 @@ repositories { } dependencies { - compile 'io.reactivex.rxjava2:rxjava:2.0.0-DP0-SNAPSHOT' + compile 'io.reactivex.rxjava2:rxjava:2.2.0-SNAPSHOT' } ``` From 4f10ad8e3db7729070ec55f17c1d3ea9c23ff6d0 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 5 Oct 2017 10:06:27 +0200 Subject: [PATCH 011/417] Release 2.1.5 changes.md update --- CHANGES.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index bc87514542..2538899841 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,32 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +Note that there might be a couple of 2.1.5-RCx tags before this release in order to iron out the nebula-plugin free release process. + +### Version 2.1.5 - October 5, 2017 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.5%7C)) + +#### API changes + +- [Pull 5616](https://github.com/ReactiveX/RxJava/pull/5616): Add `Single.delay` overload that delays errors. +- [Pull 5624](https://github.com/ReactiveX/RxJava/pull/5624): add `onTerminateDetach` to `Single` and `Completable`. + +#### Documentation changes + +- [Pull 5617](https://github.com/ReactiveX/RxJava/pull/5617): Fix `Observable.delay` & `Flowable.delay` javadoc. +- [Pull 5637](https://github.com/ReactiveX/RxJava/pull/5637): Fixing JavaDoc warnings. +- [Pull 5640](https://github.com/ReactiveX/RxJava/pull/5640): Additional warnings for `fromPublisher()`. + +#### Bugfixes + +- No bugs were reported. + +#### Other + +- [Pull 5615](https://github.com/ReactiveX/RxJava/pull/5615): Add missing license headers. +- [Pull 5623](https://github.com/ReactiveX/RxJava/pull/5623): Fix incorrect error message in `SubscriptionHelper.setOnce` +- [Pull 5633](https://github.com/ReactiveX/RxJava/pull/5633): Upgrade to Gradle 4.2.1, remove nebula plugin, replace it with custom release logic. + + ### Version 2.1.4 - September 22, 2017 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.4%7C)) #### API changes From 748fb50f63b9239350d1d02c76667fde61a5f78b Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 6 Oct 2017 15:17:59 +0200 Subject: [PATCH 012/417] 2.x: improve package JavaDoc (#5648) --- src/main/java/io/reactivex/observers/package-info.java | 7 +++++-- src/main/java/io/reactivex/package-info.java | 8 ++++---- src/main/java/io/reactivex/subscribers/package-info.java | 6 ++++-- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/main/java/io/reactivex/observers/package-info.java b/src/main/java/io/reactivex/observers/package-info.java index cb00733554..ad5e8d4d7a 100644 --- a/src/main/java/io/reactivex/observers/package-info.java +++ b/src/main/java/io/reactivex/observers/package-info.java @@ -15,7 +15,10 @@ */ /** - * Default wrappers and implementations for Observer-based consumer classes and interfaces; - * utility classes for creating them from callbacks. + * Default wrappers and implementations for Observer-based consumer classes and interfaces, + * including disposable and resource-tracking variants and + * the {@link io.reactivex.subscribers.TestObserver} that allows unit testing + * {@link io.reactivex.Observable}-, {@link io.reactivex.Single}-, {@link io.reactivex.Maybe}- + * and {@link io.reactivex.Completable}-based flows. */ package io.reactivex.observers; diff --git a/src/main/java/io/reactivex/package-info.java b/src/main/java/io/reactivex/package-info.java index 5c9065ddb8..0df7f0aaf5 100644 --- a/src/main/java/io/reactivex/package-info.java +++ b/src/main/java/io/reactivex/package-info.java @@ -14,7 +14,7 @@ * limitations under the License. */ /** - * Base reactive classes: Flowable, Observable, Single and Completable; base reactive consumers; + * Base reactive classes: Flowable, Observable, Single, Maybe and Completable; base reactive consumers; * other common base interfaces. * *

                A library that enables subscribing to and composing asynchronous events and @@ -43,9 +43,9 @@ * *

                Services which intend on exposing data asynchronously and wish * to allow reactive processing and composition can implement the - * {@link io.reactivex.Flowable}, {@link io.reactivex.Observable}, {@link io.reactivex.Single} - * or {@link io.reactivex.Completable} class which then allow consumers to subscribe to them - * and receive events.

                + * {@link io.reactivex.Flowable}, {@link io.reactivex.Observable}, {@link io.reactivex.Single}, + * {@link io.reactivex.Maybe} or {@link io.reactivex.Completable} class which then allow + * consumers to subscribe to them and receive events.

                *

                Usage examples can be found on the {@link io.reactivex.Flowable}/{@link io.reactivex.Observable} and {@link org.reactivestreams.Subscriber} classes.

                */ package io.reactivex; diff --git a/src/main/java/io/reactivex/subscribers/package-info.java b/src/main/java/io/reactivex/subscribers/package-info.java index 22838c91c3..409efd6e79 100644 --- a/src/main/java/io/reactivex/subscribers/package-info.java +++ b/src/main/java/io/reactivex/subscribers/package-info.java @@ -15,7 +15,9 @@ */ /** - * Default wrappers and implementations for Subscriber-based consumer classes and interfaces; - * utility classes for creating them from callbacks. + * Default wrappers and implementations for Subscriber-based consumer classes and interfaces, + * including disposable and resource-tracking variants and + * the {@link io.reactivex.subscribers.TestSubscriber} that allows unit testing + * {@link io.reactivex.Flowable}-based flows. */ package io.reactivex.subscribers; From bb1e313a8ba4954ee187f9572b418176c901bfc2 Mon Sep 17 00:00:00 2001 From: dimsuz Date: Mon, 9 Oct 2017 10:19:57 +0200 Subject: [PATCH 013/417] 2.x: Fix subscribeWith documentation examples (#5647) --- src/main/java/io/reactivex/Completable.java | 6 +++--- src/main/java/io/reactivex/Maybe.java | 4 ++-- src/main/java/io/reactivex/Observable.java | 4 ++-- src/main/java/io/reactivex/Single.java | 6 +++--- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index df628bc2a2..3c3c4040ca 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1686,11 +1686,11 @@ public final void subscribe(CompletableObserver s) { * Completable source = Completable.complete().delay(1, TimeUnit.SECONDS); * CompositeDisposable composite = new CompositeDisposable(); * - * class ResourceCompletableObserver implements CompletableObserver, Disposable { + * DisposableCompletableObserver ds = new DisposableCompletableObserver() { * // ... - * } + * }; * - * composite.add(source.subscribeWith(new ResourceCompletableObserver())); + * composite.add(source.subscribeWith(ds)); *
                *
                *
                Scheduler:
                diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 7a2a6bc241..ed6d684460 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3772,11 +3772,11 @@ public final Maybe subscribeOn(Scheduler scheduler) { * Maybe<Integer> source = Maybe.just(1); * CompositeDisposable composite = new CompositeDisposable(); * - * MaybeObserver<Integer> ms = new MaybeObserver<>() { + * DisposableMaybeObserver<Integer> ds = new DisposableMaybeObserver<>() { * // ... * }; * - * composite.add(source.subscribeWith(ms)); + * composite.add(source.subscribeWith(ds)); *
                *
                *
                Scheduler:
                diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index f5a025add7..86893c714b 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -10939,11 +10939,11 @@ public final void subscribe(Observer observer) { * Observable<Integer> source = Observable.range(1, 10); * CompositeDisposable composite = new CompositeDisposable(); * - * ResourceObserver<Integer> rs = new ResourceObserver<>() { + * DisposableObserver<Integer> ds = new DisposableObserver<>() { * // ... * }; * - * composite.add(source.subscribeWith(rs)); + * composite.add(source.subscribeWith(ds)); *
                *
                *
                Scheduler:
                diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index f58005046c..df7d40c18f 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2801,11 +2801,11 @@ public final void subscribe(SingleObserver subscriber) { * Single<Integer> source = Single.just(1); * CompositeDisposable composite = new CompositeDisposable(); * - * class ResourceSingleObserver implements SingleObserver<Integer>, Disposable { + * DisposableSingleObserver<Integer> ds = new DisposableSingleObserver<>() { * // ... - * } + * }; * - * composite.add(source.subscribeWith(new ResourceSingleObserver())); + * composite.add(source.subscribeWith(ds)); *
                *
                *
                Scheduler:
                From e1cb606ab23590c6537af7f6c53dd72d01618dc1 Mon Sep 17 00:00:00 2001 From: Peter Hewitt Date: Mon, 9 Oct 2017 04:44:35 -0400 Subject: [PATCH 014/417] 2.x Add concatMapCompletable() to Observable (#5649) * Initial implementation of Observable.concatMapCompletable() * Update serialVersionUID * Fix javadoc and verify prefetch is positive * Put back auto-changed whitespace * Put back more whitespace intellij is removing * More javadoc fixes * switch from testng to junit * Add experimental annotation and change prefetch to capacityHint --- src/main/java/io/reactivex/Observable.java | 46 ++++ .../ObservableConcatMapCompletable.java | 247 +++++++++++++++++ .../ObservableConcatMapCompletableTest.java | 255 ++++++++++++++++++ 3 files changed, 548 insertions(+) create mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java create mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 86893c714b..2336256436 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -6251,6 +6251,52 @@ public final Observable concatMapEagerDelayError(Function(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, maxConcurrency, prefetch)); } + /** + * Maps each element of the upstream Observable into CompletableSources, subscribes to them one at a time in + * order and waits until the upstream and all CompletableSources complete. + *
                + *
                Scheduler:
                + *
                {@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param mapper + * a function that, when applied to an item emitted by the source ObservableSource, returns a CompletableSource + * @return a Completable that signals {@code onComplete} when the upstream and all CompletableSources complete + * @since 2.1.6 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final Completable concatMapCompletable(Function mapper) { + return concatMapCompletable(mapper, 2); + } + + /** + * Maps each element of the upstream Observable into CompletableSources, subscribes to them one at a time in + * order and waits until the upstream and all CompletableSources complete. + *
                + *
                Scheduler:
                + *
                {@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param mapper + * a function that, when applied to an item emitted by the source ObservableSource, returns a CompletableSource + * + * @param capacityHint + * the number of upstream items expected to be buffered until the current CompletableSource, mapped from + * the current item, completes. + * @return a Completable that signals {@code onComplete} when the upstream and all CompletableSources complete + * @since 2.1.6 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final Completable concatMapCompletable(Function mapper, int capacityHint) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(capacityHint, "capacityHint"); + return RxJavaPlugins.onAssembly(new ObservableConcatMapCompletable(this, mapper, capacityHint)); + } + /** * Returns an Observable that concatenate each item emitted by the source ObservableSource with the values in an * Iterable corresponding to that item that is generated by a selector. diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java new file mode 100644 index 0000000000..909ba644f3 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java @@ -0,0 +1,247 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ +package io.reactivex.internal.operators.observable; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.disposables.SequentialDisposable; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.SimpleQueue; +import io.reactivex.internal.queue.SpscLinkedArrayQueue; +import io.reactivex.plugins.RxJavaPlugins; + +import java.util.concurrent.atomic.AtomicInteger; + +public final class ObservableConcatMapCompletable extends Completable { + + final ObservableSource source; + final Function mapper; + final int bufferSize; + + public ObservableConcatMapCompletable(ObservableSource source, + Function mapper, int bufferSize) { + this.source = source; + this.mapper = mapper; + this.bufferSize = Math.max(8, bufferSize); + } + @Override + public void subscribeActual(CompletableObserver observer) { + source.subscribe(new SourceObserver(observer, mapper, bufferSize)); + } + + static final class SourceObserver extends AtomicInteger implements Observer, Disposable { + + private static final long serialVersionUID = 6893587405571511048L; + final CompletableObserver actual; + final SequentialDisposable sa; + final Function mapper; + final CompletableObserver inner; + final int bufferSize; + + SimpleQueue queue; + + Disposable s; + + volatile boolean active; + + volatile boolean disposed; + + volatile boolean done; + + int sourceMode; + + SourceObserver(CompletableObserver actual, + Function mapper, int bufferSize) { + this.actual = actual; + this.mapper = mapper; + this.bufferSize = bufferSize; + this.inner = new InnerObserver(actual, this); + this.sa = new SequentialDisposable(); + } + @Override + public void onSubscribe(Disposable s) { + if (DisposableHelper.validate(this.s, s)) { + this.s = s; + if (s instanceof QueueDisposable) { + @SuppressWarnings("unchecked") + QueueDisposable qd = (QueueDisposable) s; + + int m = qd.requestFusion(QueueDisposable.ANY); + if (m == QueueDisposable.SYNC) { + sourceMode = m; + queue = qd; + done = true; + + actual.onSubscribe(this); + + drain(); + return; + } + + if (m == QueueDisposable.ASYNC) { + sourceMode = m; + queue = qd; + + actual.onSubscribe(this); + + return; + } + } + + queue = new SpscLinkedArrayQueue(bufferSize); + + actual.onSubscribe(this); + } + } + @Override + public void onNext(T t) { + if (done) { + return; + } + if (sourceMode == QueueDisposable.NONE) { + queue.offer(t); + } + drain(); + } + @Override + public void onError(Throwable t) { + if (done) { + RxJavaPlugins.onError(t); + return; + } + done = true; + dispose(); + actual.onError(t); + } + @Override + public void onComplete() { + if (done) { + return; + } + done = true; + drain(); + } + + void innerComplete() { + active = false; + drain(); + } + + @Override + public boolean isDisposed() { + return disposed; + } + + @Override + public void dispose() { + disposed = true; + sa.dispose(); + s.dispose(); + + if (getAndIncrement() == 0) { + queue.clear(); + } + } + + void innerSubscribe(Disposable s) { + sa.update(s); + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + for (;;) { + if (disposed) { + queue.clear(); + return; + } + if (!active) { + + boolean d = done; + + T t; + + try { + t = queue.poll(); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + dispose(); + queue.clear(); + actual.onError(ex); + return; + } + + boolean empty = t == null; + + if (d && empty) { + disposed = true; + actual.onComplete(); + return; + } + + if (!empty) { + CompletableSource c; + + try { + c = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null CompletableSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + dispose(); + queue.clear(); + actual.onError(ex); + return; + } + + active = true; + c.subscribe(inner); + } + } + + if (decrementAndGet() == 0) { + break; + } + } + } + + static final class InnerObserver implements CompletableObserver { + final CompletableObserver actual; + final SourceObserver parent; + + InnerObserver(CompletableObserver actual, SourceObserver parent) { + this.actual = actual; + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable s) { + parent.innerSubscribe(s); + } + + @Override + public void onError(Throwable t) { + parent.dispose(); + actual.onError(t); + } + @Override + public void onComplete() { + parent.innerComplete(); + } + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java new file mode 100644 index 0000000000..bc99769d71 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java @@ -0,0 +1,255 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + *

                + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + *

                + * http://www.apache.org/licenses/LICENSE-2.0 + *

                + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ +package io.reactivex.internal.operators.observable; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.subjects.PublishSubject; +import io.reactivex.subjects.UnicastSubject; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class ObservableConcatMapCompletableTest { + + @Test + public void asyncFused() throws Exception { + UnicastSubject us = UnicastSubject.create(); + + TestObserver to = us.concatMapCompletable(completableComplete(), 2).test(); + + us.onNext(1); + us.onComplete(); + + to.assertComplete(); + to.assertValueCount(0); + } + + @Test + public void notFused() throws Exception { + UnicastSubject us = UnicastSubject.create(); + TestObserver to = us.hide().concatMapCompletable(completableComplete(), 2).test(); + + us.onNext(1); + us.onNext(2); + us.onComplete(); + + to.assertComplete(); + to.assertValueCount(0); + to.assertNoErrors(); + } + + @Test + public void dispose() { + TestHelper.checkDisposed(Observable.just(1).hide() + .concatMapCompletable(completableError())); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .concatMapCompletable(completableComplete()) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Observable.just(1).hide() + .concatMapCompletable(completableError()) + .test() + .assertFailure(TestException.class); + } + + @Test + public void badSource() { + List errors = TestHelper.trackPluginErrors(); + try { + new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + + observer.onNext(1); + observer.onComplete(); + observer.onNext(2); + observer.onError(new TestException()); + observer.onComplete(); + } + } + .concatMapCompletable(completableComplete()) + .test() + .assertComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void onErrorRace() { + for (int i = 0; i < 500; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps1 = PublishSubject.create(); + final PublishSubject ps2 = PublishSubject.create(); + + TestObserver to = ps1.concatMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return Completable.fromObservable(ps2); + } + }).test(); + + final TestException ex1 = new TestException(); + final TestException ex2 = new TestException(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps1.onError(ex1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ps2.onError(ex2); + } + }; + + TestHelper.race(r1, r2, Schedulers.single()); + + to.assertFailure(TestException.class); + + if (!errors.isEmpty()) { + TestHelper.assertError(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void mapperThrows() { + Observable.just(1).hide() + .concatMapCompletable(completableThrows()) + .test() + .assertFailure(TestException.class); + } + + + @Test + public void fusedPollThrows() { + Observable.just(1) + .map(new Function() { + @Override + public Integer apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .concatMapCompletable(completableComplete()) + .test() + .assertFailure(TestException.class); + } + + @SuppressWarnings("unchecked") + @Test + public void concatReportsDisposedOnComplete() { + final Disposable[] disposable = { null }; + + Observable.just(1) + .hide() + .concatMapCompletable(completableComplete()) + .subscribe(new CompletableObserver() { + + @Override + public void onSubscribe(Disposable d) { + disposable[0] = d; + } + + @Override + public void onError(Throwable e) { + } + + @Override + public void onComplete() { + } + }); + + assertTrue(disposable[0].isDisposed()); + } + + @SuppressWarnings("unchecked") + @Test + public void concatReportsDisposedOnError() { + final Disposable[] disposable = { null }; + + Observable.just(1) + .hide() + .concatMapCompletable(completableError()) + .subscribe(new CompletableObserver() { + + @Override + public void onSubscribe(Disposable d) { + disposable[0] = d; + } + + @Override + public void onError(Throwable e) { + } + + @Override + public void onComplete() { + } + }); + + assertTrue(disposable[0].isDisposed()); + } + + private Function completableComplete() { + return new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return Completable.complete(); + } + }; + } + + private Function completableError() { + return new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return Completable.error(new TestException()); + } + }; + } + + private Function completableThrows() { + return new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + throw new TestException(); + } + }; + } +} \ No newline at end of file From 3abd86a52446b1c82115329e43f4b5fc840bec50 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 9 Oct 2017 14:19:01 +0200 Subject: [PATCH 015/417] 2.x: update Obs.just(2..10) & switchOnNextDelayError marbles (#5651) --- src/main/java/io/reactivex/Observable.java | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 2336256436..f1b28fde2e 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -2265,7 +2265,7 @@ public static Observable just(T item) { /** * Converts two items into an ObservableSource that emits those items. *

                - * + * *

                *
                Scheduler:
                *
                {@code just} does not operate by default on a particular {@link Scheduler}.
                @@ -2293,7 +2293,7 @@ public static Observable just(T item1, T item2) { /** * Converts three items into an ObservableSource that emits those items. *

                - * + * *

                *
                Scheduler:
                *
                {@code just} does not operate by default on a particular {@link Scheduler}.
                @@ -2324,7 +2324,7 @@ public static Observable just(T item1, T item2, T item3) { /** * Converts four items into an ObservableSource that emits those items. *

                - * + * *

                *
                Scheduler:
                *
                {@code just} does not operate by default on a particular {@link Scheduler}.
                @@ -2358,7 +2358,7 @@ public static Observable just(T item1, T item2, T item3, T item4) { /** * Converts five items into an ObservableSource that emits those items. *

                - * + * *

                *
                Scheduler:
                *
                {@code just} does not operate by default on a particular {@link Scheduler}.
                @@ -2395,7 +2395,7 @@ public static Observable just(T item1, T item2, T item3, T item4, T item5 /** * Converts six items into an ObservableSource that emits those items. *

                - * + * *

                *
                Scheduler:
                *
                {@code just} does not operate by default on a particular {@link Scheduler}.
                @@ -2435,7 +2435,7 @@ public static Observable just(T item1, T item2, T item3, T item4, T item5 /** * Converts seven items into an ObservableSource that emits those items. *

                - * + * *

                *
                Scheduler:
                *
                {@code just} does not operate by default on a particular {@link Scheduler}.
                @@ -2478,7 +2478,7 @@ public static Observable just(T item1, T item2, T item3, T item4, T item5 /** * Converts eight items into an ObservableSource that emits those items. *

                - * + * *

                *
                Scheduler:
                *
                {@code just} does not operate by default on a particular {@link Scheduler}.
                @@ -2524,7 +2524,7 @@ public static Observable just(T item1, T item2, T item3, T item4, T item5 /** * Converts nine items into an ObservableSource that emits those items. *

                - * + * *

                *
                Scheduler:
                *
                {@code just} does not operate by default on a particular {@link Scheduler}.
                @@ -2573,7 +2573,7 @@ public static Observable just(T item1, T item2, T item3, T item4, T item5 /** * Converts ten items into an ObservableSource that emits those items. *

                - * + * *

                *
                Scheduler:
                *
                {@code just} does not operate by default on a particular {@link Scheduler}.
                @@ -3582,7 +3582,7 @@ public static Observable switchOnNext(ObservableSource - * + * *

                * {@code switchOnNext} subscribes to an ObservableSource that emits ObservableSources. Each time it observes one of * these emitted ObservableSources, the ObservableSource returned by {@code switchOnNext} begins emitting the items @@ -3615,7 +3615,7 @@ public static Observable switchOnNextDelayError(ObservableSource - * + * *

                * {@code switchOnNext} subscribes to an ObservableSource that emits ObservableSources. Each time it observes one of * these emitted ObservableSources, the ObservableSource returned by {@code switchOnNext} begins emitting the items From 1b0cd2a40a45ec57e0b6ccf961f084a30c3165c7 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 9 Oct 2017 21:31:40 +0200 Subject: [PATCH 016/417] 2.x: inline disposability in Obs.concatMap(Completable) (#5652) --- .../observable/ObservableConcatMap.java | 38 ++++++++++--------- .../ObservableConcatMapCompletable.java | 27 ++++++------- 2 files changed, 33 insertions(+), 32 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java index b3cb5ff531..8e66db0bdc 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java @@ -13,7 +13,7 @@ package io.reactivex.internal.operators.observable; import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.*; import io.reactivex.*; import io.reactivex.disposables.Disposable; @@ -59,9 +59,8 @@ static final class SourceObserver extends AtomicInteger implements Observe private static final long serialVersionUID = 8828587559905699186L; final Observer actual; - final SequentialDisposable sa; final Function> mapper; - final Observer inner; + final InnerObserver inner; final int bufferSize; SimpleQueue queue; @@ -82,7 +81,6 @@ static final class SourceObserver extends AtomicInteger implements Observe this.mapper = mapper; this.bufferSize = bufferSize; this.inner = new InnerObserver(actual, this); - this.sa = new SequentialDisposable(); } @Override public void onSubscribe(Disposable s) { @@ -161,7 +159,7 @@ public boolean isDisposed() { @Override public void dispose() { disposed = true; - sa.dispose(); + inner.dispose(); s.dispose(); if (getAndIncrement() == 0) { @@ -169,10 +167,6 @@ public void dispose() { } } - void innerSubscribe(Disposable s) { - sa.update(s); - } - void drain() { if (getAndIncrement() != 0) { return; @@ -231,7 +225,10 @@ void drain() { } } - static final class InnerObserver implements Observer { + static final class InnerObserver extends AtomicReference implements Observer { + + private static final long serialVersionUID = -7449079488798789337L; + final Observer actual; final SourceObserver parent; @@ -242,7 +239,7 @@ static final class InnerObserver implements Observer { @Override public void onSubscribe(Disposable s) { - parent.innerSubscribe(s); + DisposableHelper.set(this, s); } @Override @@ -258,6 +255,10 @@ public void onError(Throwable t) { public void onComplete() { parent.innerComplete(); } + + void dispose() { + DisposableHelper.dispose(this); + } } } @@ -278,8 +279,6 @@ static final class ConcatMapDelayErrorObserver final DelayErrorInnerObserver observer; - final SequentialDisposable arbiter; - final boolean tillTheEnd; SimpleQueue queue; @@ -303,7 +302,6 @@ static final class ConcatMapDelayErrorObserver this.tillTheEnd = tillTheEnd; this.error = new AtomicThrowable(); this.observer = new DelayErrorInnerObserver(actual, this); - this.arbiter = new SequentialDisposable(); } @Override @@ -375,7 +373,7 @@ public boolean isDisposed() { public void dispose() { cancelled = true; d.dispose(); - arbiter.dispose(); + observer.dispose(); } @SuppressWarnings("unchecked") @@ -479,7 +477,9 @@ void drain() { } } - static final class DelayErrorInnerObserver implements Observer { + static final class DelayErrorInnerObserver extends AtomicReference implements Observer { + + private static final long serialVersionUID = 2620149119579502636L; final Observer actual; @@ -492,7 +492,7 @@ static final class DelayErrorInnerObserver implements Observer { @Override public void onSubscribe(Disposable d) { - parent.arbiter.replace(d); + DisposableHelper.replace(this, d); } @Override @@ -520,6 +520,10 @@ public void onComplete() { p.active = false; p.drain(); } + + void dispose() { + DisposableHelper.dispose(this); + } } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java index 909ba644f3..b53de7cde7 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java @@ -12,20 +12,18 @@ */ package io.reactivex.internal.operators.observable; +import java.util.concurrent.atomic.*; + import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; import io.reactivex.internal.disposables.DisposableHelper; -import io.reactivex.internal.disposables.SequentialDisposable; import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.fuseable.QueueDisposable; -import io.reactivex.internal.fuseable.SimpleQueue; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.queue.SpscLinkedArrayQueue; import io.reactivex.plugins.RxJavaPlugins; -import java.util.concurrent.atomic.AtomicInteger; - public final class ObservableConcatMapCompletable extends Completable { final ObservableSource source; @@ -47,9 +45,8 @@ static final class SourceObserver extends AtomicInteger implements Observer mapper; - final CompletableObserver inner; + final InnerObserver inner; final int bufferSize; SimpleQueue queue; @@ -70,7 +67,6 @@ static final class SourceObserver extends AtomicInteger implements Observer implements CompletableObserver { + private static final long serialVersionUID = -5987419458390772447L; final CompletableObserver actual; final SourceObserver parent; @@ -230,7 +223,7 @@ static final class InnerObserver implements CompletableObserver { @Override public void onSubscribe(Disposable s) { - parent.innerSubscribe(s); + DisposableHelper.set(this, s); } @Override @@ -242,6 +235,10 @@ public void onError(Throwable t) { public void onComplete() { parent.innerComplete(); } + + void dispose() { + DisposableHelper.dispose(this); + } } } } From 54e98620ede2d51232d577b0a6d4307f76cfc466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Karnok?= Date: Mon, 9 Oct 2017 21:51:02 +0200 Subject: [PATCH 017/417] Fix mistakes in observers package info, fix generics --- src/main/java/io/reactivex/observers/package-info.java | 2 +- .../observable/ObservableConcatMapCompletableTest.java | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/observers/package-info.java b/src/main/java/io/reactivex/observers/package-info.java index ad5e8d4d7a..d12329ab03 100644 --- a/src/main/java/io/reactivex/observers/package-info.java +++ b/src/main/java/io/reactivex/observers/package-info.java @@ -17,7 +17,7 @@ /** * Default wrappers and implementations for Observer-based consumer classes and interfaces, * including disposable and resource-tracking variants and - * the {@link io.reactivex.subscribers.TestObserver} that allows unit testing + * the {@link io.reactivex.observers.TestObserver} that allows unit testing * {@link io.reactivex.Observable}-, {@link io.reactivex.Single}-, {@link io.reactivex.Maybe}- * and {@link io.reactivex.Completable}-based flows. */ diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java index bc99769d71..bf07d82430 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java @@ -34,7 +34,7 @@ public class ObservableConcatMapCompletableTest { public void asyncFused() throws Exception { UnicastSubject us = UnicastSubject.create(); - TestObserver to = us.concatMapCompletable(completableComplete(), 2).test(); + TestObserver to = us.concatMapCompletable(completableComplete(), 2).test(); us.onNext(1); us.onComplete(); @@ -46,7 +46,7 @@ public void asyncFused() throws Exception { @Test public void notFused() throws Exception { UnicastSubject us = UnicastSubject.create(); - TestObserver to = us.hide().concatMapCompletable(completableComplete(), 2).test(); + TestObserver to = us.hide().concatMapCompletable(completableComplete(), 2).test(); us.onNext(1); us.onNext(2); @@ -113,7 +113,7 @@ public void onErrorRace() { final PublishSubject ps1 = PublishSubject.create(); final PublishSubject ps2 = PublishSubject.create(); - TestObserver to = ps1.concatMapCompletable(new Function() { + TestObserver to = ps1.concatMapCompletable(new Function() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.fromObservable(ps2); @@ -172,7 +172,6 @@ public Integer apply(Integer v) throws Exception { .assertFailure(TestException.class); } - @SuppressWarnings("unchecked") @Test public void concatReportsDisposedOnComplete() { final Disposable[] disposable = { null }; @@ -199,7 +198,6 @@ public void onComplete() { assertTrue(disposable[0].isDisposed()); } - @SuppressWarnings("unchecked") @Test public void concatReportsDisposedOnError() { final Disposable[] disposable = { null }; From e02cb58f6ca1c96e025a9a6970f66fa56ae769c0 Mon Sep 17 00:00:00 2001 From: Peter Hewitt Date: Mon, 9 Oct 2017 16:00:10 -0400 Subject: [PATCH 018/417] Upgrade testng to get method names to show up in gradle console when skipping, and in testng html output. (#5653) --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index a831cca29b..f342a51e62 100644 --- a/build.gradle +++ b/build.gradle @@ -54,7 +54,7 @@ def junitVersion = "4.12" def reactiveStreamsVersion = "1.0.1" def mockitoVersion = "2.1.0" def jmhVersion = "1.16" -def testNgVersion = "6.9.10" +def testNgVersion = "6.11" // -------------------------------------- From bffc7f2944749b384426e4fb2c6b9ae087603d76 Mon Sep 17 00:00:00 2001 From: Benjamin Wicks Date: Wed, 11 Oct 2017 08:48:26 -0500 Subject: [PATCH 019/417] Fix broken license link (#5662) --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 62f2249abf..93050459df 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,7 @@ When submitting code, please make every effort to follow existing conventions an ## License -By contributing your code, you agree to license your contribution under the terms of the APLv2: https://github.com/ReactiveX/RxJava/blob/master/LICENSE +By contributing your code, you agree to license your contribution under the terms of the APLv2: https://github.com/ReactiveX/RxJava/blob/2.x/LICENSE All files are released with the Apache 2.0 license. From 5387e206af84b2dea77ecb1ed552b16dc1aed2c8 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 13 Oct 2017 22:53:01 +0200 Subject: [PATCH 020/417] 2.x: improve Flowable.timeout() (#5661) * 2.x: improve Flowable.timeout() * Remove the now unused FullArbiter(Subscriber) * Don't read the volatile twice --- .../operators/flowable/FlowableTimeout.java | 408 ++++++++++-------- .../flowable/FlowableTimeoutTimed.java | 298 +++++++------ .../subscribers/FullArbiterSubscriber.java | 57 --- .../internal/subscriptions/FullArbiter.java | 232 ---------- .../reactivex/schedulers/TestScheduler.java | 6 +- .../reactivex/flowable/FlowableNullTests.java | 2 +- .../flowable/FlowableTimeoutTests.java | 90 +++- .../FlowableTimeoutWithSelectorTest.java | 218 ++++++++++ .../subscriptions/FullArbiterTest.java | 129 ------ 9 files changed, 692 insertions(+), 748 deletions(-) delete mode 100644 src/main/java/io/reactivex/internal/subscribers/FullArbiterSubscriber.java delete mode 100644 src/main/java/io/reactivex/internal/subscriptions/FullArbiter.java delete mode 100644 src/test/java/io/reactivex/internal/subscriptions/FullArbiterTest.java diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java index 7f9e7568eb..e01fb5b525 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java @@ -14,7 +14,7 @@ package io.reactivex.internal.operators.flowable; import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.*; import org.reactivestreams.*; @@ -22,12 +22,11 @@ import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; -import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.disposables.SequentialDisposable; import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.subscribers.FullArbiterSubscriber; +import io.reactivex.internal.operators.flowable.FlowableTimeoutTimed.TimeoutSupport; import io.reactivex.internal.subscriptions.*; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.subscribers.*; public final class FlowableTimeout extends AbstractFlowableWithUpstream { final Publisher firstTimeoutIndicator; @@ -48,299 +47,344 @@ public FlowableTimeout( @Override protected void subscribeActual(Subscriber s) { if (other == null) { - source.subscribe(new TimeoutSubscriber( - new SerializedSubscriber(s), - firstTimeoutIndicator, itemTimeoutIndicator)); + TimeoutSubscriber parent = new TimeoutSubscriber(s, itemTimeoutIndicator); + s.onSubscribe(parent); + parent.startFirstTimeout(firstTimeoutIndicator); + source.subscribe(parent); } else { - source.subscribe(new TimeoutOtherSubscriber( - s, firstTimeoutIndicator, itemTimeoutIndicator, other)); + TimeoutFallbackSubscriber parent = new TimeoutFallbackSubscriber(s, itemTimeoutIndicator, other); + s.onSubscribe(parent); + parent.startFirstTimeout(firstTimeoutIndicator); + source.subscribe(parent); } } - static final class TimeoutSubscriber implements FlowableSubscriber, Subscription, OnTimeout { + interface TimeoutSelectorSupport extends TimeoutSupport { + void onTimeoutError(long idx, Throwable ex); + } + + static final class TimeoutSubscriber extends AtomicLong + implements FlowableSubscriber, Subscription, TimeoutSelectorSupport { + + private static final long serialVersionUID = 3764492702657003550L; + final Subscriber actual; - final Publisher firstTimeoutIndicator; - final Function> itemTimeoutIndicator; - Subscription s; + final Function> itemTimeoutIndicator; - volatile boolean cancelled; + final SequentialDisposable task; - volatile long index; + final AtomicReference upstream; - final AtomicReference timeout = new AtomicReference(); + final AtomicLong requested; - TimeoutSubscriber(Subscriber actual, - Publisher firstTimeoutIndicator, - Function> itemTimeoutIndicator) { + TimeoutSubscriber(Subscriber actual, Function> itemTimeoutIndicator) { this.actual = actual; - this.firstTimeoutIndicator = firstTimeoutIndicator; this.itemTimeoutIndicator = itemTimeoutIndicator; + this.task = new SequentialDisposable(); + this.upstream = new AtomicReference(); + this.requested = new AtomicLong(); } @Override public void onSubscribe(Subscription s) { - if (!SubscriptionHelper.validate(this.s, s)) { - return; - } - this.s = s; - - if (cancelled) { - return; - } - - Subscriber a = actual; - - Publisher p = firstTimeoutIndicator; - - if (p != null) { - TimeoutInnerSubscriber tis = new TimeoutInnerSubscriber(this, 0); - - if (timeout.compareAndSet(null, tis)) { - a.onSubscribe(this); - p.subscribe(tis); - } - } else { - a.onSubscribe(this); - } + SubscriptionHelper.deferredSetOnce(upstream, requested, s); } @Override public void onNext(T t) { - long idx = index + 1; - index = idx; - - actual.onNext(t); + long idx = get(); + if (idx == Long.MAX_VALUE || !compareAndSet(idx, idx + 1)) { + return; + } - Disposable d = timeout.get(); + Disposable d = task.get(); if (d != null) { d.dispose(); } - Publisher p; + actual.onNext(t); + + Publisher itemTimeoutPublisher; try { - p = ObjectHelper.requireNonNull(itemTimeoutIndicator.apply(t), "The publisher returned is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - cancel(); - actual.onError(e); + itemTimeoutPublisher = ObjectHelper.requireNonNull( + itemTimeoutIndicator.apply(t), + "The itemTimeoutIndicator returned a null Publisher."); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.get().cancel(); + getAndSet(Long.MAX_VALUE); + actual.onError(ex); return; } - TimeoutInnerSubscriber tis = new TimeoutInnerSubscriber(this, idx); + TimeoutConsumer consumer = new TimeoutConsumer(idx + 1, this); + if (task.replace(consumer)) { + itemTimeoutPublisher.subscribe(consumer); + } + } - if (timeout.compareAndSet(d, tis)) { - p.subscribe(tis); + void startFirstTimeout(Publisher firstTimeoutIndicator) { + if (firstTimeoutIndicator != null) { + TimeoutConsumer consumer = new TimeoutConsumer(0L, this); + if (task.replace(consumer)) { + firstTimeoutIndicator.subscribe(consumer); + } } } @Override public void onError(Throwable t) { - cancel(); - actual.onError(t); + if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onError(t); + } else { + RxJavaPlugins.onError(t); + } } @Override public void onComplete() { - cancel(); - actual.onComplete(); - } + if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); - @Override - public void request(long n) { - s.request(n); + actual.onComplete(); + } } @Override - public void cancel() { - cancelled = true; - s.cancel(); - DisposableHelper.dispose(timeout); - } + public void onTimeout(long idx) { + if (compareAndSet(idx, Long.MAX_VALUE)) { + SubscriptionHelper.cancel(upstream); - @Override - public void timeout(long idx) { - if (idx == index) { - cancel(); actual.onError(new TimeoutException()); } } - } - - interface OnTimeout { - void timeout(long index); - - void onError(Throwable e); - } - - static final class TimeoutInnerSubscriber extends DisposableSubscriber { - final OnTimeout parent; - final long index; - - boolean done; - - TimeoutInnerSubscriber(OnTimeout parent, final long index) { - this.parent = parent; - this.index = index; - } @Override - public void onNext(Object t) { - if (done) { - return; + public void onTimeoutError(long idx, Throwable ex) { + if (compareAndSet(idx, Long.MAX_VALUE)) { + SubscriptionHelper.cancel(upstream); + + actual.onError(ex); + } else { + RxJavaPlugins.onError(ex); } - done = true; - cancel(); - parent.timeout(index); } @Override - public void onError(Throwable t) { - if (done) { - RxJavaPlugins.onError(t); - return; - } - done = true; - parent.onError(t); + public void request(long n) { + SubscriptionHelper.deferredRequest(upstream, requested, n); } @Override - public void onComplete() { - if (done) { - return; - } - done = true; - parent.timeout(index); + public void cancel() { + SubscriptionHelper.cancel(upstream); + task.dispose(); } } - static final class TimeoutOtherSubscriber implements FlowableSubscriber, Disposable, OnTimeout { + static final class TimeoutFallbackSubscriber extends SubscriptionArbiter + implements FlowableSubscriber, TimeoutSelectorSupport { + + private static final long serialVersionUID = 3764492702657003550L; + final Subscriber actual; - final Publisher firstTimeoutIndicator; - final Function> itemTimeoutIndicator; - final Publisher other; - final FullArbiter arbiter; - Subscription s; + final Function> itemTimeoutIndicator; - boolean done; + final SequentialDisposable task; - volatile boolean cancelled; + final AtomicReference upstream; - volatile long index; + final AtomicLong index; - final AtomicReference timeout = new AtomicReference(); + Publisher fallback; - TimeoutOtherSubscriber(Subscriber actual, - Publisher firstTimeoutIndicator, - Function> itemTimeoutIndicator, Publisher other) { + long consumed; + + TimeoutFallbackSubscriber(Subscriber actual, + Function> itemTimeoutIndicator, + Publisher fallback) { this.actual = actual; - this.firstTimeoutIndicator = firstTimeoutIndicator; this.itemTimeoutIndicator = itemTimeoutIndicator; - this.other = other; - this.arbiter = new FullArbiter(actual, this, 8); + this.task = new SequentialDisposable(); + this.upstream = new AtomicReference(); + this.fallback = fallback; + this.index = new AtomicLong(); } @Override public void onSubscribe(Subscription s) { - if (!SubscriptionHelper.validate(this.s, s)) { - return; + if (SubscriptionHelper.setOnce(this.upstream, s)) { + setSubscription(s); } - this.s = s; + } - if (!arbiter.setSubscription(s)) { + @Override + public void onNext(T t) { + long idx = index.get(); + if (idx == Long.MAX_VALUE || !index.compareAndSet(idx, idx + 1)) { return; } - Subscriber a = actual; - Publisher p = firstTimeoutIndicator; + Disposable d = task.get(); + if (d != null) { + d.dispose(); + } + + consumed++; + + actual.onNext(t); - if (p != null) { - TimeoutInnerSubscriber tis = new TimeoutInnerSubscriber(this, 0); + Publisher itemTimeoutPublisher; + + try { + itemTimeoutPublisher = ObjectHelper.requireNonNull( + itemTimeoutIndicator.apply(t), + "The itemTimeoutIndicator returned a null Publisher."); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.get().cancel(); + index.getAndSet(Long.MAX_VALUE); + actual.onError(ex); + return; + } - if (timeout.compareAndSet(null, tis)) { - a.onSubscribe(arbiter); - p.subscribe(tis); + TimeoutConsumer consumer = new TimeoutConsumer(idx + 1, this); + if (task.replace(consumer)) { + itemTimeoutPublisher.subscribe(consumer); + } + } + + void startFirstTimeout(Publisher firstTimeoutIndicator) { + if (firstTimeoutIndicator != null) { + TimeoutConsumer consumer = new TimeoutConsumer(0L, this); + if (task.replace(consumer)) { + firstTimeoutIndicator.subscribe(consumer); } - } else { - a.onSubscribe(arbiter); } } @Override - public void onNext(T t) { - if (done) { - return; + public void onError(Throwable t) { + if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onError(t); + + task.dispose(); + } else { + RxJavaPlugins.onError(t); } - long idx = index + 1; - index = idx; + } - if (!arbiter.onNext(t, s)) { - return; + @Override + public void onComplete() { + if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onComplete(); + + task.dispose(); } + } - Disposable d = timeout.get(); - if (d != null) { - d.dispose(); + @Override + public void onTimeout(long idx) { + if (index.compareAndSet(idx, Long.MAX_VALUE)) { + SubscriptionHelper.cancel(upstream); + + Publisher f = fallback; + fallback = null; + + long c = consumed; + if (c != 0L) { + produced(c); + } + + f.subscribe(new FlowableTimeoutTimed.FallbackSubscriber(actual, this)); } + } - Publisher p; + @Override + public void onTimeoutError(long idx, Throwable ex) { + if (index.compareAndSet(idx, Long.MAX_VALUE)) { + SubscriptionHelper.cancel(upstream); - try { - p = ObjectHelper.requireNonNull(itemTimeoutIndicator.apply(t), "The publisher returned is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - actual.onError(e); - return; + actual.onError(ex); + } else { + RxJavaPlugins.onError(ex); } + } - TimeoutInnerSubscriber tis = new TimeoutInnerSubscriber(this, idx); + @Override + public void cancel() { + super.cancel(); + task.dispose(); + } + } + + static final class TimeoutConsumer extends AtomicReference + implements FlowableSubscriber, Disposable { + + private static final long serialVersionUID = 8708641127342403073L; - if (timeout.compareAndSet(d, tis)) { - p.subscribe(tis); + final TimeoutSelectorSupport parent; + + final long idx; + + TimeoutConsumer(long idx, TimeoutSelectorSupport parent) { + this.idx = idx; + this.parent = parent; + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.setOnce(this, s)) { + s.request(Long.MAX_VALUE); + } + } + + @Override + public void onNext(Object t) { + Subscription upstream = get(); + if (upstream != SubscriptionHelper.CANCELLED) { + upstream.cancel(); + lazySet(SubscriptionHelper.CANCELLED); + parent.onTimeout(idx); } } @Override public void onError(Throwable t) { - if (done) { + if (get() != SubscriptionHelper.CANCELLED) { + lazySet(SubscriptionHelper.CANCELLED); + parent.onTimeoutError(idx, t); + } else { RxJavaPlugins.onError(t); - return; } - done = true; - dispose(); - arbiter.onError(t, s); } @Override public void onComplete() { - if (done) { - return; + if (get() != SubscriptionHelper.CANCELLED) { + lazySet(SubscriptionHelper.CANCELLED); + parent.onTimeout(idx); } - done = true; - dispose(); - arbiter.onComplete(s); } @Override public void dispose() { - cancelled = true; - s.cancel(); - DisposableHelper.dispose(timeout); + SubscriptionHelper.cancel(this); } @Override public boolean isDisposed() { - return cancelled; - } - - @Override - public void timeout(long idx) { - if (idx == index) { - dispose(); - other.subscribe(new FullArbiterSubscriber(arbiter)); - } + return SubscriptionHelper.isCancelled(this.get()); } } + } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java index 5a42761cd9..e16f894736 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java @@ -14,16 +14,14 @@ package io.reactivex.internal.operators.flowable; import java.util.concurrent.*; +import java.util.concurrent.atomic.*; import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.Scheduler.Worker; -import io.reactivex.disposables.Disposable; -import io.reactivex.internal.subscribers.FullArbiterSubscriber; +import io.reactivex.internal.disposables.SequentialDisposable; import io.reactivex.internal.subscriptions.*; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.subscribers.SerializedSubscriber; public final class FlowableTimeoutTimed extends AbstractFlowableWithUpstream { final long timeout; @@ -31,8 +29,6 @@ public final class FlowableTimeoutTimed extends AbstractFlowableWithUpstream< final Scheduler scheduler; final Publisher other; - static final Disposable NEW_TIMER = new EmptyDispose(); - public FlowableTimeoutTimed(Flowable source, long timeout, TimeUnit unit, Scheduler scheduler, Publisher other) { super(source); @@ -45,256 +41,282 @@ public FlowableTimeoutTimed(Flowable source, @Override protected void subscribeActual(Subscriber s) { if (other == null) { - source.subscribe(new TimeoutTimedSubscriber( - new SerializedSubscriber(s), // because errors can race - timeout, unit, scheduler.createWorker())); + TimeoutSubscriber parent = new TimeoutSubscriber(s, timeout, unit, scheduler.createWorker()); + s.onSubscribe(parent); + parent.startTimeout(0L); + source.subscribe(parent); } else { - source.subscribe(new TimeoutTimedOtherSubscriber( - s, // the FullArbiter serializes - timeout, unit, scheduler.createWorker(), other)); + TimeoutFallbackSubscriber parent = new TimeoutFallbackSubscriber(s, timeout, unit, scheduler.createWorker(), other); + s.onSubscribe(parent); + parent.startTimeout(0L); + source.subscribe(parent); } } - static final class TimeoutTimedOtherSubscriber implements FlowableSubscriber, Disposable { + static final class TimeoutSubscriber extends AtomicLong + implements FlowableSubscriber, Subscription, TimeoutSupport { + + private static final long serialVersionUID = 3764492702657003550L; + final Subscriber actual; + final long timeout; - final TimeUnit unit; - final Scheduler.Worker worker; - final Publisher other; - Subscription s; + final TimeUnit unit; - final FullArbiter arbiter; + final Scheduler.Worker worker; - Disposable timer; + final SequentialDisposable task; - volatile long index; + final AtomicReference upstream; - volatile boolean done; + final AtomicLong requested; - TimeoutTimedOtherSubscriber(Subscriber actual, long timeout, TimeUnit unit, Worker worker, - Publisher other) { + TimeoutSubscriber(Subscriber actual, long timeout, TimeUnit unit, Scheduler.Worker worker) { this.actual = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; - this.other = other; - this.arbiter = new FullArbiter(actual, this, 8); + this.task = new SequentialDisposable(); + this.upstream = new AtomicReference(); + this.requested = new AtomicLong(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - if (arbiter.setSubscription(s)) { - actual.onSubscribe(arbiter); - - scheduleTimeout(0L); - } - } + SubscriptionHelper.deferredSetOnce(upstream, requested, s); } @Override public void onNext(T t) { - if (done) { + long idx = get(); + if (idx == Long.MAX_VALUE || !compareAndSet(idx, idx + 1)) { return; } - long idx = index + 1; - index = idx; - if (arbiter.onNext(t, s)) { - scheduleTimeout(idx); - } - } + task.get().dispose(); - void scheduleTimeout(final long idx) { - if (timer != null) { - timer.dispose(); - } + actual.onNext(t); - timer = worker.schedule(new TimeoutTask(idx), timeout, unit); + startTimeout(idx + 1); } - void subscribeNext() { - other.subscribe(new FullArbiterSubscriber(arbiter)); + void startTimeout(long nextIndex) { + task.replace(worker.schedule(new TimeoutTask(nextIndex, this), timeout, unit)); } @Override public void onError(Throwable t) { - if (done) { + if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onError(t); + + worker.dispose(); + } else { RxJavaPlugins.onError(t); - return; } - done = true; - arbiter.onError(t, s); - worker.dispose(); } @Override public void onComplete() { - if (done) { - return; + if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onComplete(); + + worker.dispose(); } - done = true; - arbiter.onComplete(s); - worker.dispose(); } @Override - public void dispose() { - s.cancel(); - worker.dispose(); + public void onTimeout(long idx) { + if (compareAndSet(idx, Long.MAX_VALUE)) { + SubscriptionHelper.cancel(upstream); + + actual.onError(new TimeoutException()); + + worker.dispose(); + } } @Override - public boolean isDisposed() { - return worker.isDisposed(); + public void request(long n) { + SubscriptionHelper.deferredRequest(upstream, requested, n); } - final class TimeoutTask implements Runnable { - private final long idx; + @Override + public void cancel() { + SubscriptionHelper.cancel(upstream); + worker.dispose(); + } + } - TimeoutTask(long idx) { - this.idx = idx; - } - @Override - public void run() { - if (idx == index) { - done = true; - s.cancel(); - worker.dispose(); + static final class TimeoutTask implements Runnable { - subscribeNext(); + final TimeoutSupport parent; - } - } + final long idx; + + TimeoutTask(long idx, TimeoutSupport parent) { + this.idx = idx; + this.parent = parent; + } + + @Override + public void run() { + parent.onTimeout(idx); } } - static final class TimeoutTimedSubscriber implements FlowableSubscriber, Disposable, Subscription { + static final class TimeoutFallbackSubscriber extends SubscriptionArbiter + implements FlowableSubscriber, TimeoutSupport { + + private static final long serialVersionUID = 3764492702657003550L; + final Subscriber actual; + final long timeout; + final TimeUnit unit; + final Scheduler.Worker worker; - Subscription s; + final SequentialDisposable task; - Disposable timer; + final AtomicReference upstream; - volatile long index; + final AtomicLong index; - volatile boolean done; + long consumed; - TimeoutTimedSubscriber(Subscriber actual, long timeout, TimeUnit unit, Worker worker) { + Publisher fallback; + + TimeoutFallbackSubscriber(Subscriber actual, long timeout, TimeUnit unit, + Scheduler.Worker worker, Publisher fallback) { this.actual = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; + this.fallback = fallback; + this.task = new SequentialDisposable(); + this.upstream = new AtomicReference(); + this.index = new AtomicLong(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); - scheduleTimeout(0L); + if (SubscriptionHelper.setOnce(upstream, s)) { + setSubscription(s); } } @Override public void onNext(T t) { - if (done) { + long idx = index.get(); + if (idx == Long.MAX_VALUE || !index.compareAndSet(idx, idx + 1)) { return; } - long idx = index + 1; - index = idx; + + task.get().dispose(); + + consumed++; actual.onNext(t); - scheduleTimeout(idx); + startTimeout(idx + 1); } - void scheduleTimeout(final long idx) { - if (timer != null) { - timer.dispose(); - } - - timer = worker.schedule(new TimeoutTask(idx), timeout, unit); + void startTimeout(long nextIndex) { + task.replace(worker.schedule(new TimeoutTask(nextIndex, this), timeout, unit)); } @Override public void onError(Throwable t) { - if (done) { + if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onError(t); + + worker.dispose(); + } else { RxJavaPlugins.onError(t); - return; } - done = true; - - actual.onError(t); - worker.dispose(); } @Override public void onComplete() { - if (done) { - return; - } - done = true; + if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); - actual.onComplete(); - worker.dispose(); - } + actual.onComplete(); - @Override - public void dispose() { - s.cancel(); - worker.dispose(); + worker.dispose(); + } } @Override - public boolean isDisposed() { - return worker.isDisposed(); - } + public void onTimeout(long idx) { + if (index.compareAndSet(idx, Long.MAX_VALUE)) { + SubscriptionHelper.cancel(upstream); - @Override - public void request(long n) { - s.request(n); + long c = consumed; + if (c != 0L) { + produced(c); + } + + Publisher f = fallback; + fallback = null; + + f.subscribe(new FallbackSubscriber(actual, this)); + + worker.dispose(); + } } @Override public void cancel() { - dispose(); + super.cancel(); + worker.dispose(); } + } - final class TimeoutTask implements Runnable { - private final long idx; + static final class FallbackSubscriber implements FlowableSubscriber { - TimeoutTask(long idx) { - this.idx = idx; - } + final Subscriber actual; - @Override - public void run() { - if (idx == index) { - done = true; - dispose(); + final SubscriptionArbiter arbiter; - actual.onError(new TimeoutException()); - } - } + FallbackSubscriber(Subscriber actual, SubscriptionArbiter arbiter) { + this.actual = actual; + this.arbiter = arbiter; + } + + @Override + public void onSubscribe(Subscription s) { + arbiter.setSubscription(s); } - } - static final class EmptyDispose implements Disposable { @Override - public void dispose() { } + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public void onError(Throwable t) { + actual.onError(t); + } @Override - public boolean isDisposed() { - return true; + public void onComplete() { + actual.onComplete(); } } + interface TimeoutSupport { + + void onTimeout(long idx); + } } diff --git a/src/main/java/io/reactivex/internal/subscribers/FullArbiterSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/FullArbiterSubscriber.java deleted file mode 100644 index e145489296..0000000000 --- a/src/main/java/io/reactivex/internal/subscribers/FullArbiterSubscriber.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ - -package io.reactivex.internal.subscribers; - -import org.reactivestreams.Subscription; - -import io.reactivex.FlowableSubscriber; -import io.reactivex.internal.subscriptions.*; - -/** - * Subscriber that communicates with a FullArbiter. - * - * @param the value type - */ -public final class FullArbiterSubscriber implements FlowableSubscriber { - final FullArbiter arbiter; - - Subscription s; - - public FullArbiterSubscriber(FullArbiter arbiter) { - this.arbiter = arbiter; - } - - @Override - public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - arbiter.setSubscription(s); - } - } - - @Override - public void onNext(T t) { - arbiter.onNext(t, s); - } - - @Override - public void onError(Throwable t) { - arbiter.onError(t, s); - } - - @Override - public void onComplete() { - arbiter.onComplete(s); - } -} diff --git a/src/main/java/io/reactivex/internal/subscriptions/FullArbiter.java b/src/main/java/io/reactivex/internal/subscriptions/FullArbiter.java deleted file mode 100644 index 283ad2d2a9..0000000000 --- a/src/main/java/io/reactivex/internal/subscriptions/FullArbiter.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ - -package io.reactivex.internal.subscriptions; - -import java.util.concurrent.atomic.*; - -import org.reactivestreams.*; - -import io.reactivex.disposables.Disposable; -import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.queue.SpscLinkedArrayQueue; -import io.reactivex.internal.util.*; -import io.reactivex.plugins.RxJavaPlugins; - -/** - * Performs full arbitration of Subscriber events with strict drain (i.e., old emissions of another - * subscriber are dropped). - * - * @param the value type - */ -public final class FullArbiter extends FullArbiterPad2 implements Subscription { - final Subscriber actual; - final SpscLinkedArrayQueue queue; - - long requested; - - volatile Subscription s; - static final Subscription INITIAL = new InitialSubscription(); - - - Disposable resource; - - volatile boolean cancelled; - - static final Object REQUEST = new Object(); - - public FullArbiter(Subscriber actual, Disposable resource, int capacity) { - this.actual = actual; - this.resource = resource; - this.queue = new SpscLinkedArrayQueue(capacity); - this.s = INITIAL; - } - - @Override - public void request(long n) { - if (SubscriptionHelper.validate(n)) { - BackpressureHelper.add(missedRequested, n); - queue.offer(REQUEST, REQUEST); - drain(); - } - } - - @Override - public void cancel() { - if (!cancelled) { - cancelled = true; - dispose(); - } - } - - void dispose() { - Disposable d = resource; - resource = null; - if (d != null) { - d.dispose(); - } - } - - public boolean setSubscription(Subscription s) { - if (cancelled) { - if (s != null) { - s.cancel(); - } - return false; - } - - ObjectHelper.requireNonNull(s, "s is null"); - queue.offer(this.s, NotificationLite.subscription(s)); - drain(); - return true; - } - - public boolean onNext(T value, Subscription s) { - if (cancelled) { - return false; - } - - queue.offer(s, NotificationLite.next(value)); - drain(); - return true; - } - - public void onError(Throwable value, Subscription s) { - if (cancelled) { - RxJavaPlugins.onError(value); - return; - } - queue.offer(s, NotificationLite.error(value)); - drain(); - } - - public void onComplete(Subscription s) { - queue.offer(s, NotificationLite.complete()); - drain(); - } - - void drain() { - if (wip.getAndIncrement() != 0) { - return; - } - - int missed = 1; - - final SpscLinkedArrayQueue q = queue; - final Subscriber a = actual; - - for (;;) { - - for (;;) { - - Object o = q.poll(); - if (o == null) { - break; - } - Object v = q.poll(); - - if (o == REQUEST) { - long mr = missedRequested.getAndSet(0L); - if (mr != 0L) { - requested = BackpressureHelper.addCap(requested, mr); - s.request(mr); - } - } else - if (o == s) { - if (NotificationLite.isSubscription(v)) { - Subscription next = NotificationLite.getSubscription(v); - if (!cancelled) { - s = next; - long r = requested; - if (r != 0L) { - next.request(r); - } - } else { - next.cancel(); - } - } else if (NotificationLite.isError(v)) { - q.clear(); - dispose(); - - Throwable ex = NotificationLite.getError(v); - if (!cancelled) { - cancelled = true; - a.onError(ex); - } else { - RxJavaPlugins.onError(ex); - } - } else if (NotificationLite.isComplete(v)) { - q.clear(); - dispose(); - - if (!cancelled) { - cancelled = true; - a.onComplete(); - } - } else { - long r = requested; - if (r != 0) { - a.onNext(NotificationLite.getValue(v)); - requested = r - 1; - } - } - } - } - - missed = wip.addAndGet(-missed); - if (missed == 0) { - break; - } - } - } - - static final class InitialSubscription implements Subscription { - @Override - public void request(long n) { - // deliberately no op - } - - @Override - public void cancel() { - // deliberately no op - } - } -} - -/** Pads the object header away. */ -class FullArbiterPad0 { - volatile long p1a, p2a, p3a, p4a, p5a, p6a, p7a; - volatile long p8a, p9a, p10a, p11a, p12a, p13a, p14a, p15a; -} - -/** The work-in-progress counter. */ -class FullArbiterWip extends FullArbiterPad0 { - final AtomicInteger wip = new AtomicInteger(); -} - -/** Pads the wip counter away. */ -class FullArbiterPad1 extends FullArbiterWip { - volatile long p1b, p2b, p3b, p4b, p5b, p6b, p7b; - volatile long p8b, p9b, p10b, p11b, p12b, p13b, p14b, p15b; -} - -/** The missed request counter. */ -class FullArbiterMissed extends FullArbiterPad1 { - final AtomicLong missedRequested = new AtomicLong(); -} - -/** Pads the missed request counter away. */ -class FullArbiterPad2 extends FullArbiterMissed { - volatile long p1c, p2c, p3c, p4c, p5c, p6c, p7c; - volatile long p8c, p9c, p10c, p11c, p12c, p13c, p14c, p15c; -} diff --git a/src/main/java/io/reactivex/schedulers/TestScheduler.java b/src/main/java/io/reactivex/schedulers/TestScheduler.java index 929fa22432..b2ca366978 100644 --- a/src/main/java/io/reactivex/schedulers/TestScheduler.java +++ b/src/main/java/io/reactivex/schedulers/TestScheduler.java @@ -102,14 +102,14 @@ public void triggerActions() { } private void triggerActions(long targetTimeInNanoseconds) { - while (!queue.isEmpty()) { + for (;;) { TimedRunnable current = queue.peek(); - if (current.time > targetTimeInNanoseconds) { + if (current == null || current.time > targetTimeInNanoseconds) { break; } // if scheduled time is 0 (immediate) use current virtual time time = current.time == 0 ? time : current.time; - queue.remove(); + queue.remove(current); // Only execute if not unsubscribed if (!current.scheduler.disposed) { diff --git a/src/test/java/io/reactivex/flowable/FlowableNullTests.java b/src/test/java/io/reactivex/flowable/FlowableNullTests.java index 7ff326dfbf..72fc7289d6 100644 --- a/src/test/java/io/reactivex/flowable/FlowableNullTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableNullTests.java @@ -2328,7 +2328,7 @@ public void timeoutFirstItemNull() { @Test(expected = NullPointerException.class) public void timeoutFirstItemReturnsNull() { - just1.timeout(just1, new Function>() { + just1.timeout(Flowable.never(), new Function>() { @Override public Publisher apply(Integer v) { return null; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java index 0aa0318543..296627e2fe 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java @@ -425,12 +425,6 @@ public void timedEmpty() { .assertResult(); } - @Test - public void newTimer() { - FlowableTimeoutTimed.NEW_TIMER.dispose(); - assertTrue(FlowableTimeoutTimed.NEW_TIMER.isDisposed()); - } - @Test public void badSource() { List errors = TestHelper.trackPluginErrors(); @@ -518,4 +512,88 @@ public void timedFallbackTake() { to.assertResult(1); } + @Test + public void fallbackErrors() { + Flowable.never() + .timeout(1, TimeUnit.MILLISECONDS, Flowable.error(new TestException())) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertFailure(TestException.class); + } + + @Test + public void onNextOnTimeoutRace() { + for (int i = 0; i < 1000; i++) { + final TestScheduler sch = new TestScheduler(); + + final PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = pp.timeout(1, TimeUnit.SECONDS, sch).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + sch.advanceTimeBy(1, TimeUnit.SECONDS); + } + }; + + TestHelper.race(r1, r2); + + if (ts.valueCount() != 0) { + if (ts.errorCount() != 0) { + ts.assertFailure(TimeoutException.class, 1); + } else { + ts.assertValuesOnly(1); + } + } else { + ts.assertFailure(TimeoutException.class); + } + } + } + + @Test + public void onNextOnTimeoutRaceFallback() { + for (int i = 0; i < 1000; i++) { + final TestScheduler sch = new TestScheduler(); + + final PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = pp.timeout(1, TimeUnit.SECONDS, sch, Flowable.just(2)).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + sch.advanceTimeBy(1, TimeUnit.SECONDS); + } + }; + + TestHelper.race(r1, r2); + + if (ts.isTerminated()) { + int c = ts.valueCount(); + if (c == 1) { + int v = ts.values().get(0); + assertTrue("" + v, v == 1 || v == 2); + } else { + ts.assertResult(1, 2); + } + } else { + ts.assertValuesOnly(1); + } + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java index 77a5112305..0482ff5e68 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java @@ -28,6 +28,7 @@ import org.reactivestreams.*; import io.reactivex.*; +import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; @@ -545,4 +546,221 @@ public void selectorFallbackTake() { to.assertResult(1); } + + @Test + public void lateOnTimeoutError() { + for (int i = 0; i < 1000; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final Subscriber[] sub = { null, null }; + + final Flowable pp2 = new Flowable() { + + int count; + + @Override + protected void subscribeActual( + Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + sub[count++] = s; + } + }; + + TestSubscriber ts = pp.timeout(Functions.justFunction(pp2)).test(); + + pp.onNext(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + final Throwable ex = new TestException(); + + Runnable r2 = new Runnable() { + @Override + public void run() { + sub[0].onError(ex); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValueAt(0, 0); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void lateOnTimeoutFallbackRace() { + for (int i = 0; i < 1000; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final Subscriber[] sub = { null, null }; + + final Flowable pp2 = new Flowable() { + + int count; + + @Override + protected void subscribeActual( + Subscriber s) { + assertFalse(((Disposable)s).isDisposed()); + s.onSubscribe(new BooleanSubscription()); + sub[count++] = s; + } + }; + + TestSubscriber ts = pp.timeout(Functions.justFunction(pp2), Flowable.never()).test(); + + pp.onNext(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + final Throwable ex = new TestException(); + + Runnable r2 = new Runnable() { + @Override + public void run() { + sub[0].onError(ex); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValueAt(0, 0); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void onErrorOnTimeoutRace() { + for (int i = 0; i < 1000; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final Subscriber[] sub = { null, null }; + + final Flowable pp2 = new Flowable() { + + int count; + + @Override + protected void subscribeActual( + Subscriber s) { + assertFalse(((Disposable)s).isDisposed()); + s.onSubscribe(new BooleanSubscription()); + sub[count++] = s; + } + }; + + TestSubscriber ts = pp.timeout(Functions.justFunction(pp2)).test(); + + pp.onNext(0); + + final Throwable ex = new TestException(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onError(ex); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + sub[0].onComplete(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValueAt(0, 0); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void onECompleteOnTimeoutRace() { + for (int i = 0; i < 1000; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final Subscriber[] sub = { null, null }; + + final Flowable pp2 = new Flowable() { + + int count; + + @Override + protected void subscribeActual( + Subscriber s) { + assertFalse(((Disposable)s).isDisposed()); + s.onSubscribe(new BooleanSubscription()); + sub[count++] = s; + } + }; + + TestSubscriber ts = pp.timeout(Functions.justFunction(pp2)).test(); + + pp.onNext(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onComplete(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + sub[0].onComplete(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValueAt(0, 0); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } } diff --git a/src/test/java/io/reactivex/internal/subscriptions/FullArbiterTest.java b/src/test/java/io/reactivex/internal/subscriptions/FullArbiterTest.java deleted file mode 100644 index e5dd5d20ce..0000000000 --- a/src/test/java/io/reactivex/internal/subscriptions/FullArbiterTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ - -package io.reactivex.internal.subscriptions; - -import static org.junit.Assert.*; - -import java.util.List; - -import org.junit.Test; - -import io.reactivex.TestHelper; -import io.reactivex.exceptions.TestException; -import io.reactivex.internal.util.NotificationLite; -import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.subscribers.TestSubscriber; - -public class FullArbiterTest { - - @Test - public void initialRequested() { - FullArbiter.INITIAL.request(-99); - } - - @Test - public void initialCancel() { - FullArbiter.INITIAL.cancel(); - } - - @Test - public void invalidDeferredRequest() { - List errors = TestHelper.trackPluginErrors(); - try { - new FullArbiter(new TestSubscriber(), null, 128).request(-99); - - TestHelper.assertError(errors, 0, IllegalArgumentException.class, "n > 0 required but it was -99"); - } finally { - RxJavaPlugins.reset(); - } - } - - @Test - public void setSubscriptionAfterCancel() { - FullArbiter fa = new FullArbiter(new TestSubscriber(), null, 128); - - fa.cancel(); - - BooleanSubscription bs = new BooleanSubscription(); - - assertFalse(fa.setSubscription(bs)); - - assertFalse(fa.setSubscription(null)); - } - - @Test - public void cancelAfterPoll() { - FullArbiter fa = new FullArbiter(new TestSubscriber(), null, 128); - - BooleanSubscription bs = new BooleanSubscription(); - - fa.queue.offer(fa.s, NotificationLite.subscription(bs)); - - fa.cancel(); - - fa.drain(); - - assertTrue(bs.isCancelled()); - } - - @Test - public void errorAfterCancel() { - FullArbiter fa = new FullArbiter(new TestSubscriber(), null, 128); - - BooleanSubscription bs = new BooleanSubscription(); - - fa.cancel(); - - List errors = TestHelper.trackPluginErrors(); - try { - fa.onError(new TestException(), bs); - - TestHelper.assertUndeliverable(errors, 0, TestException.class); - } finally { - RxJavaPlugins.reset(); - } - } - - @Test - public void cancelAfterError() { - FullArbiter fa = new FullArbiter(new TestSubscriber(), null, 128); - - List errors = TestHelper.trackPluginErrors(); - try { - fa.queue.offer(fa.s, NotificationLite.error(new TestException())); - - fa.cancel(); - - fa.drain(); - TestHelper.assertUndeliverable(errors, 0, TestException.class); - } finally { - RxJavaPlugins.reset(); - } - } - - @Test - public void offerDifferentSubscription() { - TestSubscriber ts = new TestSubscriber(); - - FullArbiter fa = new FullArbiter(ts, null, 128); - - BooleanSubscription bs = new BooleanSubscription(); - - fa.queue.offer(bs, NotificationLite.next(1)); - - fa.drain(); - - ts.assertNoValues(); - } -} From cd6bc08c5bf1faea7cd36800c4e85cedd2f684c5 Mon Sep 17 00:00:00 2001 From: VeskoI Date: Sun, 15 Oct 2017 11:06:23 +0100 Subject: [PATCH 021/417] Fix a misleading documentation of Observable.singleElement() (#5668) * Fix a misleading documentation of Observable.singleElement() * Reduce the first part of Observable.singleElement() JavaDoc to a single sentence. * Update the Marble diagram of Observable.singleElement() --- src/main/java/io/reactivex/Observable.java | 7 +++---- .../operators/observable/ObservableSingleTest.java | 1 + 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index f1b28fde2e..fac498aaf1 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -10277,11 +10277,10 @@ public final Observable share() { } /** - * Returns a Maybe that emits the single item emitted by this Observable if this Observable - * emits only a single item, otherwise if this Observable emits more than one item or no items, an - * {@code IllegalArgumentException} or {@code NoSuchElementException} is signalled respectively. + * Returns a Maybe that completes if this Observable is empty or emits the single item emitted by this Observable, + * or signals an {@code IllegalArgumentException} if this Observable emits more than one item. *

                - * + * *

                *
                Scheduler:
                *
                {@code singleElement} does not operate by default on a particular {@link Scheduler}.
                diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSingleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSingleTest.java index a0a6b841cc..597ac731c2 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSingleTest.java @@ -282,6 +282,7 @@ public void testSingleWithEmpty() { InOrder inOrder = inOrder(observer); inOrder.verify(observer).onComplete(); + inOrder.verify(observer, never()).onError(any(Throwable.class)); inOrder.verifyNoMoreInteractions(); } From 7f2ceb419674fc53452cf6d0577d3cb6dda22cec Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 15 Oct 2017 23:25:27 +0200 Subject: [PATCH 022/417] 2.x: fix PublishProcessor cancel/emission overflow bug (#5669) --- .../processors/PublishProcessor.java | 4 +-- .../processors/BehaviorProcessorTest.java | 33 +++++++++++++++++++ .../processors/PublishProcessorTest.java | 33 +++++++++++++++++++ 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index fb3b2ead83..b9341ce961 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -313,9 +313,7 @@ public void onNext(T t) { } if (r != 0L) { actual.onNext(t); - if (r != Long.MAX_VALUE) { - decrementAndGet(); - } + BackpressureHelper.producedCancel(this, 1); } else { cancel(); actual.onError(new MissingBackpressureException("Could not emit value due to lack of requests")); diff --git a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java index 8a1766f724..9cb392adba 100644 --- a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java +++ b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java @@ -812,4 +812,37 @@ public void run() { ts.assertFailure(TestException.class); } } + + @Test(timeout = 10000) + public void subscriberCancelOfferRace() { + for (int i = 0; i < 1000; i++) { + final BehaviorProcessor pp = BehaviorProcessor.create(); + + final TestSubscriber ts = pp.test(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + for (int i = 0; i < 2; i++) { + while (!pp.offer(i)) ; + } + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + TestHelper.race(r1, r2); + + if (ts.valueCount() > 0) { + ts.assertValuesOnly(0); + } else { + ts.assertEmpty(); + } + } + } } diff --git a/src/test/java/io/reactivex/processors/PublishProcessorTest.java b/src/test/java/io/reactivex/processors/PublishProcessorTest.java index 3078250ac0..918650c8a1 100644 --- a/src/test/java/io/reactivex/processors/PublishProcessorTest.java +++ b/src/test/java/io/reactivex/processors/PublishProcessorTest.java @@ -677,4 +677,37 @@ public void run() { .awaitDone(5, TimeUnit.SECONDS) .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } + + @Test(timeout = 10000) + public void subscriberCancelOfferRace() { + for (int i = 0; i < 1000; i++) { + final PublishProcessor pp = PublishProcessor.create(); + + final TestSubscriber ts = pp.test(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + for (int i = 0; i < 2; i++) { + while (!pp.offer(i)) ; + } + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + TestHelper.race(r1, r2); + + if (ts.valueCount() > 0) { + ts.assertValuesOnly(0); + } else { + ts.assertEmpty(); + } + } + } } From b0bc478fbbb8f01aab8678b3eb846d9b6c3d098b Mon Sep 17 00:00:00 2001 From: Jihong Park Date: Tue, 17 Oct 2017 01:03:49 +0900 Subject: [PATCH 023/417] 2.x: coverage, add SingleToFlowableTest (#5673) --- src/test/java/io/reactivex/TestHelper.java | 54 +++++++++++++++++++ .../single/SingleToFlowableTest.java | 39 ++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 src/test/java/io/reactivex/internal/operators/single/SingleToFlowableTest.java diff --git a/src/test/java/io/reactivex/TestHelper.java b/src/test/java/io/reactivex/TestHelper.java index eabe17035b..9ed96562e8 100644 --- a/src/test/java/io/reactivex/TestHelper.java +++ b/src/test/java/io/reactivex/TestHelper.java @@ -1230,6 +1230,60 @@ protected void subscribeActual(SingleObserver observer) { } } + /** + * Check if the given transformed reactive type reports multiple onSubscribe calls to + * RxJavaPlugins. + * @param the input value type + * @param the output value type + * @param transform the transform to drive an operator + */ + public static void checkDoubleOnSubscribeSingleToFlowable(Function, ? extends Publisher> transform) { + List errors = trackPluginErrors(); + try { + final Boolean[] b = { null, null }; + final CountDownLatch cdl = new CountDownLatch(1); + + Single source = new Single() { + @Override + protected void subscribeActual(SingleObserver observer) { + try { + Disposable d1 = Disposables.empty(); + + observer.onSubscribe(d1); + + Disposable d2 = Disposables.empty(); + + observer.onSubscribe(d2); + + b[0] = d1.isDisposed(); + b[1] = d2.isDisposed(); + } finally { + cdl.countDown(); + } + } + }; + + Publisher out = transform.apply(source); + + out.subscribe(NoOpConsumer.INSTANCE); + + try { + assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + + assertEquals("First disposed?", false, b[0]); + assertEquals("Second not disposed?", true, b[1]); + + assertError(errors, 0, IllegalStateException.class, "Disposable already set!"); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } finally { + RxJavaPlugins.reset(); + } + } + /** * Check if the given transformed reactive type reports multiple onSubscribe calls to * RxJavaPlugins. diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleToFlowableTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleToFlowableTest.java new file mode 100644 index 0000000000..3b6766e8a8 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/single/SingleToFlowableTest.java @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.single; + +import io.reactivex.Single; +import io.reactivex.TestHelper; +import io.reactivex.functions.Function; +import io.reactivex.subjects.PublishSubject; +import org.junit.Test; +import org.reactivestreams.Publisher; + +public class SingleToFlowableTest { + + @Test + public void dispose() { + TestHelper.checkDisposed(PublishSubject.create().singleOrError().toFlowable()); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeSingleToFlowable(new Function, Publisher>() { + @Override + public Publisher apply(Single s) throws Exception { + return s.toFlowable(); + } + }); + } +} From 1ad6647319e3a6ecfbf96d942611d253d58301ca Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 17 Oct 2017 11:23:44 +0200 Subject: [PATCH 024/417] 2.x: Add PublishProcessor JMH perf comparison (#5675) --- build.gradle | 5 +- .../io/reactivex/PerfBoundedSubscriber.java | 56 +++++++++ .../io/reactivex/PublishProcessorPerf.java | 109 ++++++++++++++++++ 3 files changed, 168 insertions(+), 2 deletions(-) create mode 100644 src/jmh/java/io/reactivex/PerfBoundedSubscriber.java create mode 100644 src/jmh/java/io/reactivex/PublishProcessorPerf.java diff --git a/build.gradle b/build.gradle index f342a51e62..576aedae63 100644 --- a/build.gradle +++ b/build.gradle @@ -53,7 +53,7 @@ targetCompatibility = JavaVersion.VERSION_1_6 def junitVersion = "4.12" def reactiveStreamsVersion = "1.0.1" def mockitoVersion = "2.1.0" -def jmhVersion = "1.16" +def jmhLibVersion = "1.19" def testNgVersion = "6.11" // -------------------------------------- @@ -192,8 +192,9 @@ publishing.publications.all { } jmh { - jmhVersion = "1.19" + jmhVersion = jmhLibVersion humanOutputFile = null + includeTests = false if (project.hasProperty("jmh")) { include = ".*" + project.jmh + ".*" diff --git a/src/jmh/java/io/reactivex/PerfBoundedSubscriber.java b/src/jmh/java/io/reactivex/PerfBoundedSubscriber.java new file mode 100644 index 0000000000..39cc6f551b --- /dev/null +++ b/src/jmh/java/io/reactivex/PerfBoundedSubscriber.java @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import java.util.concurrent.CountDownLatch; + +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Subscription; + +/** + * Performance subscriber with a one-time request from the upstream. + */ +public class PerfBoundedSubscriber extends CountDownLatch implements FlowableSubscriber { + + final Blackhole bh; + + final long request; + + public PerfBoundedSubscriber(Blackhole bh, long request) { + super(1); + this.bh = bh; + this.request = request; + } + + @Override + public void onSubscribe(Subscription s) { + s.request(request); + } + + @Override + public void onComplete() { + countDown(); + } + + @Override + public void onError(Throwable e) { + countDown(); + } + + @Override + public void onNext(Object t) { + bh.consume(t); + } + +} diff --git a/src/jmh/java/io/reactivex/PublishProcessorPerf.java b/src/jmh/java/io/reactivex/PublishProcessorPerf.java new file mode 100644 index 0000000000..37afebfa4f --- /dev/null +++ b/src/jmh/java/io/reactivex/PublishProcessorPerf.java @@ -0,0 +1,109 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.PublishSubject; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class PublishProcessorPerf { + + PublishProcessor unbounded; + + PublishProcessor bounded; + + PublishSubject subject; + + @Setup + public void setup(Blackhole bh) { + unbounded = PublishProcessor.create(); + unbounded.subscribe(new PerfConsumer(bh)); + + bounded = PublishProcessor.create(); + bounded.subscribe(new PerfBoundedSubscriber(bh, 1000 * 1000)); + + subject = PublishSubject.create(); + subject.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void unbounded1() { + unbounded.onNext(1); + } + + @Benchmark + public void unbounded1k() { + for (int i = 0; i < 1000; i++) { + unbounded.onNext(1); + } + } + + @Benchmark + public void unbounded1m() { + for (int i = 0; i < 1000000; i++) { + unbounded.onNext(1); + } + } + + @Benchmark + public void bounded1() { + bounded.onNext(1); + } + + + @Benchmark + public void bounded1k() { + for (int i = 0; i < 1000; i++) { + bounded.onNext(1); + } + } + + @Benchmark + public void bounded1m() { + for (int i = 0; i < 1000000; i++) { + bounded.onNext(1); + } + } + + + @Benchmark + public void subject1() { + subject.onNext(1); + } + + + @Benchmark + public void subject1k() { + for (int i = 0; i < 1000; i++) { + subject.onNext(1); + } + } + + @Benchmark + public void subject1m() { + for (int i = 0; i < 1000000; i++) { + subject.onNext(1); + } + } +} From ddd9b67f7e4848a16c491f495876dfd2f890d499 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 17 Oct 2017 21:57:49 +0200 Subject: [PATCH 025/417] 2.x: make parallel() a fusion-async-boundary (#5677) --- .../parallel/ParallelFromPublisher.java | 2 +- .../parallel/ParallelFromPublisherTest.java | 103 +++++++++++++++++- 2 files changed, 101 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java index e50246a988..5eb11d3e4e 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java @@ -116,7 +116,7 @@ public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") QueueSubscription qs = (QueueSubscription) s; - int m = qs.requestFusion(QueueSubscription.ANY); + int m = qs.requestFusion(QueueSubscription.ANY | QueueSubscription.BOUNDARY); if (m == QueueSubscription.SYNC) { sourceMode = m; diff --git a/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java b/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java index 874fd62fba..69ccfc3db6 100644 --- a/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java +++ b/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java @@ -14,15 +14,22 @@ package io.reactivex.parallel; import static org.junit.Assert.*; + +import java.util.*; +import java.util.concurrent.*; + import org.junit.Test; -import org.reactivestreams.Subscriber; +import org.reactivestreams.*; -import io.reactivex.Flowable; +import io.reactivex.*; import io.reactivex.exceptions.*; -import io.reactivex.functions.Function; +import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.subscribers.BasicFuseableSubscriber; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.processors.UnicastProcessor; +import io.reactivex.schedulers.Schedulers; public class ParallelFromPublisherTest { @@ -53,6 +60,53 @@ public void fusedFilterBecomesEmpty() { .assertResult(); } + static final class StripBoundary extends Flowable implements FlowableTransformer { + + final Flowable source; + + StripBoundary(Flowable source) { + this.source = source; + } + + @Override + public Publisher apply(Flowable upstream) { + return new StripBoundary(upstream); + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new StripBoundarySubscriber(s)); + } + + static final class StripBoundarySubscriber extends BasicFuseableSubscriber { + + StripBoundarySubscriber(Subscriber actual) { + super(actual); + } + + @Override + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public int requestFusion(int mode) { + QueueSubscription fs = qs; + if (fs != null) { + int m = fs.requestFusion(mode & ~QueueSubscription.BOUNDARY); + this.sourceMode = m; + return m; + } + return QueueSubscription.NONE; + } + + @Override + public T poll() throws Exception { + return qs.poll(); + } + } + } + @Test public void syncFusedMapCrash() { Flowable.just(1) @@ -62,6 +116,7 @@ public Object apply(Integer v) throws Exception { throw new TestException(); } }) + .compose(new StripBoundary(null)) .parallel() .sequential() .test() @@ -81,6 +136,7 @@ public Object apply(Integer v) throws Exception { throw new TestException(); } }) + .compose(new StripBoundary(null)) .parallel() .sequential() .test() @@ -88,4 +144,45 @@ public Object apply(Integer v) throws Exception { assertFalse(up.hasSubscribers()); } + + @Test + public void boundaryConfinement() { + final Set between = new HashSet(); + final ConcurrentHashMap processing = new ConcurrentHashMap(); + + Flowable.range(1, 10) + .observeOn(Schedulers.single(), false, 1) + .doOnNext(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + between.add(Thread.currentThread().getName()); + } + }) + .parallel(2, 1) + .runOn(Schedulers.computation(), 1) + .map(new Function() { + @Override + public Object apply(Integer v) throws Exception { + processing.putIfAbsent(Thread.currentThread().getName(), ""); + return v; + } + }) + .sequential() + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertSubscribed() + .assertValueSet(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) + .assertComplete() + .assertNoErrors() + ; + + assertEquals(between.toString(), 1, between.size()); + assertTrue(between.toString(), between.iterator().next().contains("RxSingleScheduler")); + + Map map = processing; // AnimalSniffer: CHM.keySet() in Java 8 returns KeySetView + + for (String e : map.keySet()) { + assertTrue(map.toString(), e.contains("RxComputationThreadPool")); + } + } } From 0f4a5e77cb7858cc8b166f4083ef2ba48f803557 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 18 Oct 2017 15:39:33 +0200 Subject: [PATCH 026/417] 2.x: add limit() to limit both item count and request amount (#5655) * 2.x: add limit() to limit both item count and request amount * Address some feedback. * Use the cancelled constant value. --- src/main/java/io/reactivex/Flowable.java | 47 ++++ .../operators/flowable/FlowableLimit.java | 137 ++++++++++++ .../reactivex/ParamValidationCheckerTest.java | 3 +- .../operators/flowable/FlowableLimitTest.java | 210 ++++++++++++++++++ 4 files changed, 396 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index a6a8624a6d..56908d2050 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -9676,6 +9676,53 @@ public final Flowable lift(FlowableOperator lifte return RxJavaPlugins.onAssembly(new FlowableLift(this, lifter)); } + /** + * Limits both the number of upstream items (after which the sequence completes) + * and the total downstream request amount requested from the upstream to + * possibly prevent the creation of excess items by the upstream. + *

                + * The operator requests at most the given {@code count} of items from upstream even + * if the downstream requests more than that. For example, given a {@code limit(5)}, + * if the downstream requests 1, a request of 1 is submitted to the upstream + * and the operator remembers that only 4 items can be requested now on. A request + * of 5 at this point will request 4 from the upstream and any subsequent requests will + * be ignored. + *

                + * Note that requests are negotiated on an operator boundary and {@code limit}'s amount + * may not be preserved further upstream. For example, + * {@code source.observeOn(Schedulers.computation()).limit(5)} will still request the + * default (128) elements from the given {@code source}. + *

                + * The main use of this operator is with sources that are async boundaries that + * don't interfere with request amounts, such as certain {@code Flowable}-based + * network endpoints that relay downstream request amounts unchanged and are, therefore, + * prone to trigger excessive item creation/transmission over the network. + *

                + *
                Backpressure:
                + *
                The operator requests a total of the given {@code count} items from the upstream.
                + *
                Scheduler:
                + *
                {@code limit} does not operate by default on a particular {@link Scheduler}.
                + *
                + + * @param count the maximum number of items and the total request amount, non-negative. + * Zero will immediately cancel the upstream on subscription and complete + * the downstream. + * @return the new Flowable instance + * @see #take(long) + * @see #rebatchRequests(int) + * @since 2.1.6 - experimental + */ + @Experimental + @BackpressureSupport(BackpressureKind.SPECIAL) + @SchedulerSupport(SchedulerSupport.NONE) + @CheckReturnValue + public final Flowable limit(long count) { + if (count < 0) { + throw new IllegalArgumentException("count >= 0 required but it was " + count); + } + return RxJavaPlugins.onAssembly(new FlowableLimit(this, count)); + } + /** * Returns a Flowable that applies a specified function to each item emitted by the source Publisher and * emits the results of these function applications. diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java new file mode 100644 index 0000000000..01b1f24f76 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java @@ -0,0 +1,137 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import java.util.concurrent.atomic.AtomicLong; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.internal.subscriptions.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Limits both the total request amount and items received from the upstream. + * + * @param the source and output value type + * @since 2.1.6 - experimental + */ +@Experimental +public final class FlowableLimit extends AbstractFlowableWithUpstream { + + final long n; + + public FlowableLimit(Flowable source, long n) { + super(source); + this.n = n; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new LimitSubscriber(s, n)); + } + + static final class LimitSubscriber + extends AtomicLong + implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = 2288246011222124525L; + + final Subscriber actual; + + long remaining; + + Subscription upstream; + + LimitSubscriber(Subscriber actual, long remaining) { + this.actual = actual; + this.remaining = remaining; + lazySet(remaining); + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(this.upstream, s)) { + if (remaining == 0L) { + s.cancel(); + EmptySubscription.complete(actual); + } else { + this.upstream = s; + actual.onSubscribe(this); + } + } + } + + @Override + public void onNext(T t) { + long r = remaining; + if (r > 0L) { + remaining = --r; + actual.onNext(t); + if (r == 0L) { + upstream.cancel(); + actual.onComplete(); + } + } + } + + @Override + public void onError(Throwable t) { + if (remaining > 0L) { + remaining = 0L; + actual.onError(t); + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + if (remaining > 0L) { + remaining = 0L; + actual.onComplete(); + } + } + + @Override + public void request(long n) { + if (SubscriptionHelper.validate(n)) { + for (;;) { + long r = get(); + if (r == 0L) { + break; + } + long toRequest; + if (r <= n) { + toRequest = r; + } else { + toRequest = n; + } + long u = r - toRequest; + if (compareAndSet(r, u)) { + upstream.request(toRequest); + break; + } + } + } + } + + @Override + public void cancel() { + upstream.cancel(); + } + + } +} diff --git a/src/test/java/io/reactivex/ParamValidationCheckerTest.java b/src/test/java/io/reactivex/ParamValidationCheckerTest.java index 92ff38d58c..6fef3b0273 100644 --- a/src/test/java/io/reactivex/ParamValidationCheckerTest.java +++ b/src/test/java/io/reactivex/ParamValidationCheckerTest.java @@ -182,8 +182,9 @@ public void checkParallelFlowable() { addOverride(new ParamOverride(Flowable.class, 0, ParamMode.ANY, "take", Long.TYPE, TimeUnit.class)); addOverride(new ParamOverride(Flowable.class, 0, ParamMode.ANY, "take", Long.TYPE, TimeUnit.class, Scheduler.class)); - // zero retry is allowed + // zero take/limit is allowed addOverride(new ParamOverride(Flowable.class, 0, ParamMode.NON_NEGATIVE, "take", Long.TYPE)); + addOverride(new ParamOverride(Flowable.class, 0, ParamMode.NON_NEGATIVE, "limit", Long.TYPE)); // negative time is considered as zero time addOverride(new ParamOverride(Flowable.class, 0, ParamMode.ANY, "sample", Long.TYPE, TimeUnit.class)); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java new file mode 100644 index 0000000000..553085ace2 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java @@ -0,0 +1,210 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import static org.junit.Assert.*; + +import java.util.*; + +import org.junit.Test; +import org.reactivestreams.Subscriber; + +import io.reactivex.*; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableLimitTest implements LongConsumer, Action { + + final List requests = new ArrayList(); + + static final Long CANCELLED = -100L; + + @Override + public void accept(long t) throws Exception { + requests.add(t); + } + + @Override + public void run() throws Exception { + requests.add(CANCELLED); + } + + @Test + public void shorterSequence() { + Flowable.range(1, 5) + .doOnRequest(this) + .limit(6) + .test() + .assertResult(1, 2, 3, 4, 5); + + assertEquals(6, requests.get(0).intValue()); + } + + @Test + public void exactSequence() { + Flowable.range(1, 5) + .doOnRequest(this) + .doOnCancel(this) + .limit(5) + .test() + .assertResult(1, 2, 3, 4, 5); + + assertEquals(2, requests.size()); + assertEquals(5, requests.get(0).intValue()); + assertEquals(CANCELLED, requests.get(1)); + } + + @Test + public void longerSequence() { + Flowable.range(1, 6) + .doOnRequest(this) + .limit(5) + .test() + .assertResult(1, 2, 3, 4, 5); + + assertEquals(5, requests.get(0).intValue()); + } + + @Test + public void error() { + Flowable.error(new TestException()) + .limit(5) + .test() + .assertFailure(TestException.class); + } + + @Test + public void limitZero() { + Flowable.range(1, 5) + .doOnCancel(this) + .doOnRequest(this) + .limit(0) + .test() + .assertResult(); + + assertEquals(1, requests.size()); + assertEquals(CANCELLED, requests.get(0)); + } + + @Test + public void limitStep() { + TestSubscriber ts = Flowable.range(1, 6) + .doOnRequest(this) + .limit(5) + .test(0L); + + assertEquals(0, requests.size()); + + ts.request(1); + ts.assertValue(1); + + ts.request(2); + ts.assertValues(1, 2, 3); + + ts.request(3); + ts.assertResult(1, 2, 3, 4, 5); + + assertEquals(Arrays.asList(1L, 2L, 2L), requests); + } + + @Test + public void limitAndTake() { + Flowable.range(1, 5) + .doOnCancel(this) + .doOnRequest(this) + .limit(6) + .take(5) + .test() + .assertResult(1, 2, 3, 4, 5); + + assertEquals(Arrays.asList(6L, CANCELLED), requests); + } + + @Test + public void noOverrequest() { + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = pp + .doOnRequest(this) + .limit(5) + .test(0L); + + ts.request(5); + ts.request(10); + + assertTrue(pp.offer(1)); + pp.onComplete(); + + ts.assertResult(1); + } + + @Test + public void cancelIgnored() { + List errors = TestHelper.trackPluginErrors(); + try { + new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + BooleanSubscription bs = new BooleanSubscription(); + s.onSubscribe(bs); + + assertTrue(bs.isCancelled()); + + s.onNext(1); + s.onComplete(); + s.onError(new TestException()); + + s.onSubscribe(null); + } + } + .limit(0) + .test() + .assertResult(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + TestHelper.assertError(errors, 1, NullPointerException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void badRequest() { + TestHelper.assertBadRequestReported(Flowable.range(1, 5).limit(3)); + } + + @Test + public void requestRace() { + for (int i = 0; i < 1000; i++) { + final TestSubscriber ts = Flowable.range(1, 10) + .limit(5) + .test(0L); + + Runnable r = new Runnable() { + @Override + public void run() { + ts.request(3); + } + }; + + TestHelper.race(r, r); + + ts.assertResult(1, 2, 3, 4, 5); + } + } +} From e7a3f12a7f9472680963596780cbcc6382481d0f Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 18 Oct 2017 15:53:47 +0200 Subject: [PATCH 027/417] 2.x: More Observable marble fixes (10/18) (#5680) --- src/main/java/io/reactivex/Observable.java | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index fac498aaf1..38baae0931 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -4689,7 +4689,7 @@ public static Observable zipArray(Function} passed to the method would trigger a {@code ClassCastException}. * *

                - * + * *

                *
                Scheduler:
                *
                {@code zipIterable} does not operate by default on a particular {@link Scheduler}.
                @@ -4752,7 +4752,7 @@ public final Single all(Predicate predicate) { * Mirrors the ObservableSource (current or provided) that first either emits an item or sends a termination * notification. *

                - * + * *

                *
                Scheduler:
                *
                {@code ambWith} does not operate by default on a particular {@link Scheduler}.
                @@ -4854,7 +4854,7 @@ public final T blockingFirst(T defaultItem) { *

                * Note: This will block even if the underlying Observable is asynchronous. *

                - * + * *

                * This is similar to {@link Observable#subscribe(Observer)}, but it blocks. Because it blocks it does not * need the {@link Observer#onComplete()} or {@link Observer#onError(Throwable)} methods. If the @@ -4892,7 +4892,7 @@ public final void blockingForEach(Consumer onNext) { /** * Converts this {@code Observable} into an {@link Iterable}. *

                - * + * *

                *
                Scheduler:
                *
                {@code blockingIterable} does not operate by default on a particular {@link Scheduler}.
                @@ -4931,7 +4931,7 @@ public final Iterable blockingIterable(int bufferSize) { * Returns the last item emitted by this {@code Observable}, or throws * {@code NoSuchElementException} if this {@code Observable} emits no items. *

                - * + * *

                *
                Scheduler:
                *
                {@code blockingLast} does not operate by default on a particular {@link Scheduler}.
                @@ -4958,7 +4958,7 @@ public final T blockingLast() { * Returns the last item emitted by this {@code Observable}, or a default value if it emits no * items. *

                - * + * *

                *
                Scheduler:
                *
                {@code blockingLast} does not operate by default on a particular {@link Scheduler}.
                @@ -5006,7 +5006,7 @@ public final Iterable blockingLatest() { * Returns an {@link Iterable} that always returns the item most recently emitted by this * {@code Observable}. *

                - * + * *

                *
                Scheduler:
                *
                {@code blockingMostRecent} does not operate by default on a particular {@link Scheduler}.
                @@ -5029,7 +5029,7 @@ public final Iterable blockingMostRecent(T initialValue) { * Returns an {@link Iterable} that blocks until this {@code Observable} emits another item, then * returns that item. *

                - * + * *

                *
                Scheduler:
                *
                {@code blockingNext} does not operate by default on a particular {@link Scheduler}.
                @@ -5049,7 +5049,7 @@ public final Iterable blockingNext() { * If this {@code Observable} completes after emitting a single item, return that item, otherwise * throw a {@code NoSuchElementException}. *

                - * + * *

                *
                Scheduler:
                *
                {@code blockingSingle} does not operate by default on a particular {@link Scheduler}.
                @@ -5073,7 +5073,7 @@ public final T blockingSingle() { * more than one item, throw an {@code IllegalArgumentException}; if it emits no items, return a default * value. *

                - * + * *

                *
                Scheduler:
                *
                {@code blockingSingle} does not operate by default on a particular {@link Scheduler}.
                @@ -5854,7 +5854,7 @@ public final Observable cache() { * Returns an Observable that subscribes to this ObservableSource lazily, caches all of its events * and replays them, in the same order as received, to all the downstream subscribers. *

                - * + * *

                * This is useful when you want an ObservableSource to cache responses and you can't control the * subscribe/dispose behavior of all the {@link Observer}s. From aff44822dd2d7b74091d2f351b1cb08ff87b30fd Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 19 Oct 2017 21:00:42 +0200 Subject: [PATCH 028/417] 2.x: Add TCK test for limit() (#5683) --- .../java/io/reactivex/tck/LimitTckTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/test/java/io/reactivex/tck/LimitTckTest.java diff --git a/src/test/java/io/reactivex/tck/LimitTckTest.java b/src/test/java/io/reactivex/tck/LimitTckTest.java new file mode 100644 index 0000000000..f12682396b --- /dev/null +++ b/src/test/java/io/reactivex/tck/LimitTckTest.java @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.Flowable; + +@Test +public class LimitTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + return + Flowable.range(0, (int)elements * 2).limit(elements) + ; + } +} From 615e541fc221f09d0f68f7851cb3d3af2d6ffeab Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 27 Oct 2017 09:20:13 +0200 Subject: [PATCH 029/417] Release 2.1.6 --- CHANGES.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 2538899841..1eb4a6a13f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,7 +2,31 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md -Note that there might be a couple of 2.1.5-RCx tags before this release in order to iron out the nebula-plugin free release process. +### Version 2.1.6 - October 27, 2017 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.6%7C)) + +#### API changes + +- [Pull 5649](https://github.com/ReactiveX/RxJava/pull/5649): Add `Observable.concatMapCompletable()`. +- [Pull 5655](https://github.com/ReactiveX/RxJava/pull/5655): Add `Flowable.limit()` to limit both item count and request amount. + +#### Documentation changes + +- [Pull 5648](https://github.com/ReactiveX/RxJava/pull/5648): Improve package JavaDoc of `io.reactivex` and `io.reactivex.observers`. +- [Pull 5647](https://github.com/ReactiveX/RxJava/pull/5647): Fix `subscribeWith` documentation examples. +- [Pull 5651](https://github.com/ReactiveX/RxJava/pull/5651): Update `Observable.just(2..10)` and `switchOnNextDelayError` marbles. +- [Pull 5668](https://github.com/ReactiveX/RxJava/pull/5668): Fix a misleading documentation of `Observable.singleElement()`. +- [Pull 5680](https://github.com/ReactiveX/RxJava/pull/5680): More `Observable` marble fixes. + +#### Bugfixes + +- [Pull 5669](https://github.com/ReactiveX/RxJava/pull/5669): Fix `PublishProcessor` cancel/emission overflow bug. +- [Pull 5677](https://github.com/ReactiveX/RxJava/pull/5677): Make `parallel()` a fusion-async-boundary. + +#### Other + +- [Pull 5652](https://github.com/ReactiveX/RxJava/pull/5652): Inline disposability in `Observable.concatMap(Completable)`. +- [Pull 5653](https://github.com/ReactiveX/RxJava/pull/5653): Upgrade testng to get method names to show up in gradle console when skipping, and in testng html output. +- [Pull 5661](https://github.com/ReactiveX/RxJava/pull/5661): Improve `Flowable.timeout()`. ### Version 2.1.5 - October 5, 2017 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.5%7C)) From 283ca57f3ac4e7cfe4743b833d3c3092a39b6818 Mon Sep 17 00:00:00 2001 From: "Artem Zinnatullin :slowpoke" Date: Fri, 27 Oct 2017 00:52:36 -0700 Subject: [PATCH 030/417] =?UTF-8?q?Update=20'java'=20=E2=86=92=20'java-lib?= =?UTF-8?q?rary'=20Gradle=20plugin,=20update=20deps=20configurations.=20(#?= =?UTF-8?q?5682)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 576aedae63..33c1adae30 100644 --- a/build.gradle +++ b/build.gradle @@ -33,7 +33,7 @@ if (releaseTag != null && !releaseTag.isEmpty()) { description = "RxJava: Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM." -apply plugin: "java" +apply plugin: "java-library" apply plugin: "checkstyle" apply plugin: "jacoco" apply plugin: "ru.vyarus.animalsniffer" @@ -65,13 +65,14 @@ repositories { dependencies { signature "org.codehaus.mojo.signature:java16:1.1@signature" - compile "org.reactivestreams:reactive-streams:$reactiveStreamsVersion" + api "org.reactivestreams:reactive-streams:$reactiveStreamsVersion" + jmh "org.reactivestreams:reactive-streams:$reactiveStreamsVersion" - testCompile "junit:junit:$junitVersion" - testCompile "org.mockito:mockito-core:$mockitoVersion" + testImplementation "junit:junit:$junitVersion" + testImplementation "org.mockito:mockito-core:$mockitoVersion" - testCompile "org.reactivestreams:reactive-streams-tck:$reactiveStreamsVersion" - testCompile "org.testng:testng:$testNgVersion" + testImplementation "org.reactivestreams:reactive-streams-tck:$reactiveStreamsVersion" + testImplementation "org.testng:testng:$testNgVersion" } javadoc { From 98ee8bc7be8777c91252f525d46286414608b702 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 31 Oct 2017 19:58:54 +0100 Subject: [PATCH 031/417] 2.x: fix Completable.concat to use replace (don't dispose old) (#5695) * 2.x: fix Completable.concat to use replace (don't dispose old) * Remove comments from original issue report --- .../completable/CompletableConcatArray.java | 2 +- .../CompletableConcatIterable.java | 2 +- .../completable/CompletableAndThenTest.java | 41 +++++++++++++++++++ .../completable/CompletableConcatTest.java | 40 +++++++++++++++++- 4 files changed, 82 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java index caccf81c79..3972a7b31c 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java @@ -52,7 +52,7 @@ static final class ConcatInnerObserver extends AtomicInteger implements Completa @Override public void onSubscribe(Disposable d) { - sd.update(d); + sd.replace(d); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java index 624047a627..47f4fad3bc 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java @@ -64,7 +64,7 @@ static final class ConcatInnerObserver extends AtomicInteger implements Completa @Override public void onSubscribe(Disposable d) { - sd.update(d); + sd.replace(d); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenTest.java index abe412b831..a5d9b3a279 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenTest.java @@ -15,7 +15,13 @@ import io.reactivex.Completable; import io.reactivex.Maybe; +import io.reactivex.functions.Action; +import io.reactivex.schedulers.Schedulers; + +import java.util.concurrent.CountDownLatch; + import org.junit.Test; +import static org.junit.Assert.*; public class CompletableAndThenTest { @Test(expected = NullPointerException.class) @@ -63,4 +69,39 @@ public void andThenMaybeError() { .assertError(RuntimeException.class) .assertErrorMessage("bla"); } + + @Test + public void andThenNoInterrupt() throws InterruptedException { + for (int k = 0; k < 100; k++) { + final int count = 10; + final CountDownLatch latch = new CountDownLatch(count); + final boolean[] interrupted = { false }; + + for (int i = 0; i < count; i++) { + Completable.complete() + .subscribeOn(Schedulers.io()) + .observeOn(Schedulers.io()) + .andThen(Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + System.out.println("Interrupted! " + Thread.currentThread()); + interrupted[0] = true; + } + } + })) + .subscribe(new Action() { + @Override + public void run() throws Exception { + latch.countDown(); + } + }); + } + + latch.await(); + assertFalse("The second Completable was interrupted!", interrupted[0]); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java index efc76109a5..9c2c080104 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java @@ -16,6 +16,7 @@ import static org.junit.Assert.*; import java.util.*; +import java.util.concurrent.CountDownLatch; import org.junit.Test; import org.reactivestreams.*; @@ -23,7 +24,7 @@ import io.reactivex.*; import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.*; -import io.reactivex.functions.Function; +import io.reactivex.functions.*; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; @@ -254,4 +255,41 @@ public void run() { TestHelper.race(r1, r2, Schedulers.single()); } } + + @Test + public void noInterrupt() throws InterruptedException { + for (int k = 0; k < 100; k++) { + final int count = 10; + final CountDownLatch latch = new CountDownLatch(count); + final boolean[] interrupted = { false }; + + for (int i = 0; i < count; i++) { + Completable c0 = Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + System.out.println("Interrupted! " + Thread.currentThread()); + interrupted[0] = true; + } + } + }); + Completable.concat(Arrays.asList(Completable.complete() + .subscribeOn(Schedulers.io()) + .observeOn(Schedulers.io()), + c0) + ) + .subscribe(new Action() { + @Override + public void run() throws Exception { + latch.countDown(); + } + }); + } + + latch.await(); + assertFalse("The second Completable was interrupted!", interrupted[0]); + } + } } From 0a6c9f5bdce537c88e8215f72176195e6f512602 Mon Sep 17 00:00:00 2001 From: Daniel Rees Date: Sat, 4 Nov 2017 13:05:33 -0400 Subject: [PATCH 032/417] Moved tests to FromCallableTest from FromCompletableTest (#5705) --- .../ObservableFromCallableTest.java | 74 ++++++++++++++ .../ObservableFromCompletableTest.java | 97 ------------------- 2 files changed, 74 insertions(+), 97 deletions(-) delete mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservableFromCompletableTest.java diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java index d0f8234da6..56d7b7ee47 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java @@ -20,8 +20,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +import java.util.List; import java.util.concurrent.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.plugins.RxJavaPlugins; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -239,4 +242,75 @@ public Object call() throws Exception { .test() .assertFailure(NullPointerException.class); } + + @Test + public void disposedOnArrival() { + final int[] count = { 0 }; + Observable.fromCallable(new Callable() { + @Override + public Object call() throws Exception { + count[0]++; + return 1; + } + }) + .test(true) + .assertEmpty(); + + assertEquals(0, count[0]); + } + + @Test + public void disposedOnCall() { + final TestObserver to = new TestObserver(); + + Observable.fromCallable(new Callable() { + @Override + public Integer call() throws Exception { + to.cancel(); + return 1; + } + }) + .subscribe(to); + + to.assertEmpty(); + } + + @Test + public void disposedOnCallThrows() { + List errors = TestHelper.trackPluginErrors(); + try { + final TestObserver to = new TestObserver(); + + Observable.fromCallable(new Callable() { + @Override + public Integer call() throws Exception { + to.cancel(); + throw new TestException(); + } + }) + .subscribe(to); + + to.assertEmpty(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void take() { + Observable.fromCallable(new Callable() { + @Override + public Object call() throws Exception { + return 1; + } + }) + .take(1) + .test() + .assertResult(1); + } + + + } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCompletableTest.java deleted file mode 100644 index 0defa55503..0000000000 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCompletableTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ - -package io.reactivex.internal.operators.observable; - -import static org.junit.Assert.assertEquals; - -import java.util.List; -import java.util.concurrent.Callable; - -import org.junit.Test; - -import io.reactivex.*; -import io.reactivex.exceptions.TestException; -import io.reactivex.observers.TestObserver; -import io.reactivex.plugins.RxJavaPlugins; - -public class ObservableFromCompletableTest { - - @Test - public void disposedOnArrival() { - final int[] count = { 0 }; - Observable.fromCallable(new Callable() { - @Override - public Object call() throws Exception { - count[0]++; - return 1; - } - }) - .test(true) - .assertEmpty(); - - assertEquals(0, count[0]); - } - - @Test - public void disposedOnCall() { - final TestObserver to = new TestObserver(); - - Observable.fromCallable(new Callable() { - @Override - public Integer call() throws Exception { - to.cancel(); - return 1; - } - }) - .subscribe(to); - - to.assertEmpty(); - } - - @Test - public void disposedOnCallThrows() { - List errors = TestHelper.trackPluginErrors(); - try { - final TestObserver to = new TestObserver(); - - Observable.fromCallable(new Callable() { - @Override - public Integer call() throws Exception { - to.cancel(); - throw new TestException(); - } - }) - .subscribe(to); - - to.assertEmpty(); - - TestHelper.assertUndeliverable(errors, 0, TestException.class); - } finally { - RxJavaPlugins.reset(); - } - } - - @Test - public void take() { - Observable.fromCallable(new Callable() { - @Override - public Object call() throws Exception { - return 1; - } - }) - .take(1) - .test() - .assertResult(1); - } -} From 1099084407654f8601bf62986df1248bd5162312 Mon Sep 17 00:00:00 2001 From: "Artem Zinnatullin :slowpoke" Date: Mon, 6 Nov 2017 00:31:10 -0800 Subject: [PATCH 033/417] Remove mentions of Main thread from Schedulers.single() javadoc. (#5706) --- src/main/java/io/reactivex/schedulers/Schedulers.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/schedulers/Schedulers.java b/src/main/java/io/reactivex/schedulers/Schedulers.java index 12d9d50332..1332a3a019 100644 --- a/src/main/java/io/reactivex/schedulers/Schedulers.java +++ b/src/main/java/io/reactivex/schedulers/Schedulers.java @@ -243,9 +243,9 @@ public static Scheduler newThread() { *

                * Uses: *

                  - *
                • main event loop
                • + *
                • event loop
                • *
                • support Schedulers.from(Executor) and from(ExecutorService) with delayed scheduling
                • - *
                • support benchmarks that pipeline data from the main thread to some other thread and + *
                • support benchmarks that pipeline data from some thread to another thread and * avoid core-bashing of computation's round-robin nature
                • *
                *

                From 3f9ffae961506ba560a8d43e936a94eb5f563d3c Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 9 Nov 2017 01:07:54 +0100 Subject: [PATCH 034/417] 2.x: Improve Javadocs of flatMapSingle and flatMapMaybe (#5709) --- src/main/java/io/reactivex/Flowable.java | 18 ++++++++++-------- src/main/java/io/reactivex/Observable.java | 18 ++++++++++-------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 56908d2050..d15f735a44 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -8945,8 +8945,8 @@ public final Flowable flatMapIterable(final Function *

                Backpressure:
                *
                The operator consumes the upstream in an unbounded manner.
                @@ -8965,8 +8965,9 @@ public final Flowable flatMapMaybe(Function *
                Backpressure:
                *
                If {@code maxConcurrency == Integer.MAX_VALUE} the operator consumes the upstream in an unbounded manner. @@ -8992,8 +8993,8 @@ public final Flowable flatMapMaybe(Function *
                Backpressure:
                *
                The operator consumes the upstream in an unbounded manner.
                @@ -9012,8 +9013,9 @@ public final Flowable flatMapSingle(Function *
                Backpressure:
                *
                If {@code maxConcurrency == Integer.MAX_VALUE} the operator consumes the upstream in an unbounded manner. diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 38baae0931..ba82c99c7a 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7944,8 +7944,8 @@ public final Observable flatMapIterable(final Function * *
                @@ -7963,8 +7963,9 @@ public final Observable flatMapMaybe(Function * *
                @@ -7985,8 +7986,8 @@ public final Observable flatMapMaybe(Function * *
                @@ -8004,8 +8005,9 @@ public final Observable flatMapSingle(Function * *
                From 07ddc7a95a8198929d4f09aaf0b84b9581178472 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 9 Nov 2017 22:50:29 +0100 Subject: [PATCH 035/417] 2.x: BaseTestConsumer values() and errors() thread-safety clarifications (#5713) --- .../reactivex/observers/BaseTestConsumer.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/main/java/io/reactivex/observers/BaseTestConsumer.java b/src/main/java/io/reactivex/observers/BaseTestConsumer.java index 8144a22c40..a1598c5732 100644 --- a/src/main/java/io/reactivex/observers/BaseTestConsumer.java +++ b/src/main/java/io/reactivex/observers/BaseTestConsumer.java @@ -75,6 +75,20 @@ public final Thread lastThread() { /** * Returns a shared list of received onNext values. + *

                + * Note that accessing the items via certain methods of the {@link List} + * interface while the upstream is still actively emitting + * more items may result in a {@code ConcurrentModificationException}. + *

                + * The {@link List#size()} method will return the number of items + * already received by this TestObserver/TestSubscriber in a thread-safe + * manner that can be read via {@link List#get(int)}) method + * (index range of 0 to {@code List.size() - 1}). + *

                + * A view of the returned List can be created via {@link List#subList(int, int)} + * by using the bounds 0 (inclusive) to {@link List#size()} (exclusive) which, + * when accessed in a read-only fashion, should be also thread-safe and not throw any + * {@code ConcurrentModificationException}. * @return a list of received onNext values */ public final List values() { @@ -83,6 +97,20 @@ public final List values() { /** * Returns a shared list of received onError exceptions. + *

                + * Note that accessing the errors via certain methods of the {@link List} + * interface while the upstream is still actively emitting + * more items or errors may result in a {@code ConcurrentModificationException}. + *

                + * The {@link List#size()} method will return the number of errors + * already received by this TestObserver/TestSubscriber in a thread-safe + * manner that can be read via {@link List#get(int)}) method + * (index range of 0 to {@code List.size() - 1}). + *

                + * A view of the returned List can be created via {@link List#subList(int, int)} + * by using the bounds 0 (inclusive) to {@link List#size()} (exclusive) which, + * when accessed in a read-only fashion, should be also thread-safe and not throw any + * {@code ConcurrentModificationException}. * @return a list of received events onError exceptions */ public final List errors() { From da380362afe82b9b77b14952309a156cfda0a152 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 10 Nov 2017 20:48:05 +0100 Subject: [PATCH 036/417] 2.x: Javadocs: add period to custom scheduler use sentences (#5717) --- src/main/java/io/reactivex/Flowable.java | 90 +++++++++++----------- src/main/java/io/reactivex/Maybe.java | 14 ++-- src/main/java/io/reactivex/Observable.java | 88 ++++++++++----------- src/main/java/io/reactivex/Single.java | 6 +- 4 files changed, 99 insertions(+), 99 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index d15f735a44..b28a1685b3 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -2040,7 +2040,7 @@ public static Flowable fromFuture(Future future, long timeou *

                Backpressure:
                *
                The operator honors backpressure from downstream.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param future @@ -2313,7 +2313,7 @@ public static Flowable interval(long initialDelay, long period, TimeUnit u * may lead to {@code MissingBackpressureException} at some point in the chain. * Consumers should consider applying one of the {@code onBackpressureXXX} operators as well.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param initialDelay @@ -2375,7 +2375,7 @@ public static Flowable interval(long period, TimeUnit unit) { * may lead to {@code MissingBackpressureException} at some point in the chain. * Consumers should consider applying one of the {@code onBackpressureXXX} operators as well. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param period @@ -4061,7 +4061,7 @@ public static Flowable timer(long delay, TimeUnit unit) { *
                This operator does not support backpressure as it uses time. If the downstream needs a slower rate * it should slow the timer or use something like {@link #onBackpressureDrop}.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param delay @@ -5879,7 +5879,7 @@ public final Flowable> buffer(long timespan, long timeskip, TimeUnit uni *
                This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timespan @@ -5914,7 +5914,7 @@ public final Flowable> buffer(long timespan, long timeskip, TimeUnit uni *
                This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param the collection subclass type to buffer into @@ -6024,7 +6024,7 @@ public final Flowable> buffer(long timespan, TimeUnit unit, int count) { *
                This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timespan @@ -6062,7 +6062,7 @@ public final Flowable> buffer(long timespan, TimeUnit unit, Scheduler sc *
                This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param the collection subclass type to buffer into @@ -6113,7 +6113,7 @@ public final > Flowable buffer( *
                This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timespan @@ -7144,7 +7144,7 @@ public final Flowable debounce(long timeout, TimeUnit unit) { *
                Backpressure:
                *
                This operator does not support backpressure as it uses time to control data flow.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timeout @@ -7298,7 +7298,7 @@ public final Flowable delay(long delay, TimeUnit unit, boolean delayError) { *
                Backpressure:
                *
                The operator doesn't interfere with the backpressure behavior which is determined by the source {@code Publisher}.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param delay @@ -7326,7 +7326,7 @@ public final Flowable delay(long delay, TimeUnit unit, Scheduler scheduler) { *
                Backpressure:
                *
                The operator doesn't interfere with the backpressure behavior which is determined by the source {@code Publisher}.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param delay @@ -7451,7 +7451,7 @@ public final Flowable delaySubscription(long delay, TimeUnit unit) { *
                Backpressure:
                *
                The operator doesn't interfere with the backpressure behavior which is determined by the source {@code Publisher}.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param delay @@ -9821,7 +9821,7 @@ public final Flowable mergeWith(Publisher other) { * such as {@code interval}, {@code timer}, {code PublishSubject} or {@code BehaviorSubject} and apply any * of the {@code onBackpressureXXX} operators before applying {@code observeOn} itself. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param scheduler @@ -9854,7 +9854,7 @@ public final Flowable observeOn(Scheduler scheduler) { * such as {@code interval}, {@code timer}, {code PublishSubject} or {@code BehaviorSubject} and apply any * of the {@code onBackpressureXXX} operators before applying {@code observeOn} itself. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param scheduler @@ -9891,7 +9891,7 @@ public final Flowable observeOn(Scheduler scheduler, boolean delayError) { * such as {@code interval}, {@code timer}, {code PublishSubject} or {@code BehaviorSubject} and apply any * of the {@code onBackpressureXXX} operators before applying {@code observeOn} itself. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param scheduler @@ -11151,7 +11151,7 @@ public final Flowable replay(Function, ? extends Publ * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Publisher sequence. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param @@ -11199,7 +11199,7 @@ public final Flowable replay(Function, ? extends Publ * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Publisher sequence. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param @@ -11276,7 +11276,7 @@ public final Flowable replay(Function, ? extends Publ * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Publisher sequence. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param @@ -11316,7 +11316,7 @@ public final Flowable replay(Function, ? extends Publ * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Publisher sequence. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param @@ -11418,7 +11418,7 @@ public final ConnectableFlowable replay(int bufferSize, long time, TimeUnit u * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Publisher sequence. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param bufferSize @@ -11460,7 +11460,7 @@ public final ConnectableFlowable replay(final int bufferSize, final long time * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Publisher sequence. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param bufferSize @@ -11523,7 +11523,7 @@ public final ConnectableFlowable replay(long time, TimeUnit unit) { * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Publisher sequence. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param time @@ -11558,7 +11558,7 @@ public final ConnectableFlowable replay(final long time, final TimeUnit unit, * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Publisher sequence. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param scheduler @@ -11895,7 +11895,7 @@ public final Flowable sample(long period, TimeUnit unit, boolean emitLast) { *
                Backpressure:
                *
                This operator does not support backpressure as it uses time to control data flow.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param period @@ -11929,7 +11929,7 @@ public final Flowable sample(long period, TimeUnit unit, Scheduler scheduler) *
                Backpressure:
                *
                This operator does not support backpressure as it uses time to control data flow.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * *

                History: 2.0.5 - experimental @@ -12556,7 +12556,7 @@ public final Flowable skipLast(long time, TimeUnit unit, Scheduler scheduler, *

                The operator doesn't support backpressure as it uses time to skip arbitrary number of elements and * thus has to consume the source {@code Publisher} in an unbounded manner (i.e., no backpressure applied to it).
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param time @@ -13112,7 +13112,7 @@ public final > E subscribeWith(E subscriber) { *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s backpressure * behavior.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param scheduler @@ -13146,7 +13146,7 @@ public final Flowable subscribeOn(@NonNull Scheduler scheduler) { *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s backpressure * behavior.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param scheduler @@ -13425,7 +13425,7 @@ public final Flowable take(long time, TimeUnit unit) { *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s backpressure * behavior.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param time @@ -13672,7 +13672,7 @@ public final Flowable takeLast(long time, TimeUnit unit, boolean delayError) * lead to {@code OutOfMemoryError} due to internal buffer bloat. * Consider using {@link #takeLast(long, long, TimeUnit, Scheduler)} in this case. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param time @@ -13706,7 +13706,7 @@ public final Flowable takeLast(long time, TimeUnit unit, Scheduler scheduler) * lead to {@code OutOfMemoryError} due to internal buffer bloat. * Consider using {@link #takeLast(long, long, TimeUnit, Scheduler)} in this case. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param time @@ -13743,7 +13743,7 @@ public final Flowable takeLast(long time, TimeUnit unit, Scheduler scheduler, * lead to {@code OutOfMemoryError} due to internal buffer bloat. * Consider using {@link #takeLast(long, long, TimeUnit, Scheduler)} in this case. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param time @@ -13901,7 +13901,7 @@ public final Flowable throttleFirst(long windowDuration, TimeUnit unit) { *
                Backpressure:
                *
                This operator does not support backpressure as it uses time to control data flow.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param skipDuration @@ -13968,7 +13968,7 @@ public final Flowable throttleLast(long intervalDuration, TimeUnit unit) { *
                Backpressure:
                *
                This operator does not support backpressure as it uses time to control data flow.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param intervalDuration @@ -14051,7 +14051,7 @@ public final Flowable throttleWithTimeout(long timeout, TimeUnit unit) { *
                Backpressure:
                *
                This operator does not support backpressure as it uses time to control data flow.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timeout @@ -14329,7 +14329,7 @@ public final Flowable timeout(long timeout, TimeUnit timeUnit, Publishermay throw an * {@code IllegalStateException} when the source {@code Publisher} completes. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timeout @@ -14364,7 +14364,7 @@ public final Flowable timeout(long timeout, TimeUnit timeUnit, Scheduler sche *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s backpressure * behavior.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timeout @@ -15117,7 +15117,7 @@ public final Single> toSortedList(int capacityHint) { *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s backpressure * behavior.
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param scheduler @@ -15283,7 +15283,7 @@ public final Flowable> window(long timespan, long timeskip, TimeUnit * backpressure but have an unbounded inner buffer that may lead to {@code OutOfMemoryError} * if left unconsumed. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timespan @@ -15320,7 +15320,7 @@ public final Flowable> window(long timespan, long timeskip, TimeUnit * backpressure but have an unbounded inner buffer that may lead to {@code OutOfMemoryError} * if left unconsumed. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timespan @@ -15474,7 +15474,7 @@ public final Flowable> window(long timespan, TimeUnit unit, * backpressure but have an unbounded inner buffer that may lead to {@code OutOfMemoryError} * if left unconsumed. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timespan @@ -15511,7 +15511,7 @@ public final Flowable> window(long timespan, TimeUnit unit, * time to control the creation of windows. The returned inner {@code Publisher}s honor * backpressure and may hold up to {@code count} elements at most. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timespan @@ -15551,7 +15551,7 @@ public final Flowable> window(long timespan, TimeUnit unit, * time to control the creation of windows. The returned inner {@code Publisher}s honor * backpressure and may hold up to {@code count} elements at most. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timespan @@ -15593,7 +15593,7 @@ public final Flowable> window(long timespan, TimeUnit unit, * time to control the creation of windows. The returned inner {@code Publisher}s honor * backpressure and may hold up to {@code count} elements at most. *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                * * * @param timespan diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index ed6d684460..13922ed8d3 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -1347,7 +1347,7 @@ public static Maybe timer(long delay, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param delay @@ -2245,7 +2245,7 @@ public final Maybe delay(long delay, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                you specify which {@link Scheduler} this operator will use
                + *
                you specify which {@link Scheduler} this operator will use.
                *
                * * @param delay @@ -2348,7 +2348,7 @@ public final Maybe delaySubscription(long delay, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param delay @@ -3008,7 +3008,7 @@ public final Flowable mergeWith(MaybeSource other) { * *
                *
                Scheduler:
                - *
                you specify which {@link Scheduler} this operator will use
                + *
                you specify which {@link Scheduler} this operator will use.
                *
                * * @param scheduler @@ -3747,7 +3747,7 @@ public final void subscribe(MaybeObserver observer) { * *
                *
                Scheduler:
                - *
                you specify which {@link Scheduler} this operator will use
                + *
                you specify which {@link Scheduler} this operator will use.
                *
                * * @param scheduler @@ -3953,7 +3953,7 @@ public final Maybe timeout(long timeout, TimeUnit timeUnit, MaybeSource *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timeout @@ -3983,7 +3983,7 @@ public final Maybe timeout(long timeout, TimeUnit timeUnit, Scheduler schedul * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timeout diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index ba82c99c7a..68788fe5b8 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -1849,7 +1849,7 @@ public static Observable fromFuture(Future future, long time * cancellation effect: {@code futureObservableSource.doOnCancel(() -> future.cancel(true));}. *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param future @@ -2098,7 +2098,7 @@ public static Observable interval(long initialDelay, long period, TimeUnit * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param initialDelay @@ -2152,7 +2152,7 @@ public static Observable interval(long period, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param period @@ -3678,7 +3678,7 @@ public static Observable timer(long delay, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param delay @@ -5347,7 +5347,7 @@ public final Observable> buffer(long timespan, long timeskip, TimeUnit u * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timespan @@ -5378,7 +5378,7 @@ public final Observable> buffer(long timespan, long timeskip, TimeUnit u * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param the collection subclass type to buffer into @@ -5475,7 +5475,7 @@ public final Observable> buffer(long timespan, TimeUnit unit, int count) * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timespan @@ -5509,7 +5509,7 @@ public final Observable> buffer(long timespan, TimeUnit unit, Scheduler * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param the collection subclass type to buffer into @@ -5556,7 +5556,7 @@ public final > Observable buffer( * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timespan @@ -6497,7 +6497,7 @@ public final Observable debounce(long timeout, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timeout @@ -6630,7 +6630,7 @@ public final Observable delay(long delay, TimeUnit unit, boolean delayError) * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param delay @@ -6655,7 +6655,7 @@ public final Observable delay(long delay, TimeUnit unit, Scheduler scheduler) * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param delay @@ -6767,7 +6767,7 @@ public final Observable delaySubscription(long delay, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param delay @@ -8660,7 +8660,7 @@ public final Observable mergeWith(ObservableSource other) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                *

                "Island size" indicates how large chunks the unbounded buffer allocates to store the excess elements waiting to be consumed * on the other side of the asynchronous boundary. @@ -8688,7 +8688,7 @@ public final Observable observeOn(Scheduler scheduler) { * *

                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                *

                "Island size" indicates how large chunks the unbounded buffer allocates to store the excess elements waiting to be consumed * on the other side of the asynchronous boundary. @@ -8720,7 +8720,7 @@ public final Observable observeOn(Scheduler scheduler, boolean delayError) { * *

                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                *

                "Island size" indicates how large chunks the unbounded buffer allocates to store the excess elements waiting to be consumed * on the other side of the asynchronous boundary. Values below 16 are not recommended in performance sensitive scenarios. @@ -9353,7 +9353,7 @@ public final Observable replay(Function, ? extends * *

                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param @@ -9396,7 +9396,7 @@ public final Observable replay(Function, ? extends * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param @@ -9462,7 +9462,7 @@ public final Observable replay(Function, ? extends * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param @@ -9497,7 +9497,7 @@ public final Observable replay(Function, ? extends * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param @@ -9584,7 +9584,7 @@ public final ConnectableObservable replay(int bufferSize, long time, TimeUnit * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param bufferSize @@ -9620,7 +9620,7 @@ public final ConnectableObservable replay(final int bufferSize, final long ti * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param bufferSize @@ -9673,7 +9673,7 @@ public final ConnectableObservable replay(long time, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param time @@ -9703,7 +9703,7 @@ public final ConnectableObservable replay(final long time, final TimeUnit uni * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param scheduler @@ -10001,7 +10001,7 @@ public final Observable sample(long period, TimeUnit unit, boolean emitLast) * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param period @@ -10031,7 +10031,7 @@ public final Observable sample(long period, TimeUnit unit, Scheduler schedule * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * *

                History: 2.0.5 - experimental @@ -10576,7 +10576,7 @@ public final Observable skipLast(long time, TimeUnit unit, Scheduler schedule * Note: this action will cache the latest items arriving in the specified time window. *

                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param time @@ -11015,7 +11015,7 @@ public final > E subscribeWith(E observer) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param scheduler @@ -11312,7 +11312,7 @@ public final Observable take(long time, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param time @@ -11525,7 +11525,7 @@ public final Observable takeLast(long time, TimeUnit unit, boolean delayError * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param time @@ -11553,7 +11553,7 @@ public final Observable takeLast(long time, TimeUnit unit, Scheduler schedule * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param time @@ -11584,7 +11584,7 @@ public final Observable takeLast(long time, TimeUnit unit, Scheduler schedule * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param time @@ -11723,7 +11723,7 @@ public final Observable throttleFirst(long windowDuration, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param skipDuration @@ -11782,7 +11782,7 @@ public final Observable throttleLast(long intervalDuration, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param intervalDuration @@ -11857,7 +11857,7 @@ public final Observable throttleWithTimeout(long timeout, TimeUnit unit) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timeout @@ -12091,7 +12091,7 @@ public final Observable timeout(long timeout, TimeUnit timeUnit, ObservableSo * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timeout @@ -12122,7 +12122,7 @@ public final Observable timeout(long timeout, TimeUnit timeUnit, Scheduler sc * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timeout @@ -12806,7 +12806,7 @@ public final Single> toSortedList(int capacityHint) { * {@link Scheduler}. *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param scheduler @@ -12946,7 +12946,7 @@ public final Observable> window(long timespan, long timeskip, Time * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timespan @@ -12976,7 +12976,7 @@ public final Observable> window(long timespan, long timeskip, Time * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timespan @@ -13105,7 +13105,7 @@ public final Observable> window(long timespan, TimeUnit unit, * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timespan @@ -13136,7 +13136,7 @@ public final Observable> window(long timespan, TimeUnit unit, * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timespan @@ -13170,7 +13170,7 @@ public final Observable> window(long timespan, TimeUnit unit, * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timespan @@ -13206,7 +13206,7 @@ public final Observable> window(long timespan, TimeUnit unit, * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param timespan diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index df7d40c18f..03b659a71a 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -554,7 +554,7 @@ public static Single fromFuture(Future future, long timeout, * {@code from} method. *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param future @@ -2338,7 +2338,7 @@ public final Flowable mergeWith(SingleSource other) { * *
                *
                Scheduler:
                - *
                you specify which {@link Scheduler} this operator will use
                + *
                you specify which {@link Scheduler} this operator will use.
                *
                * * @param scheduler @@ -2830,7 +2830,7 @@ public final > E subscribeWith(E observer) { * *
                *
                Scheduler:
                - *
                You specify which {@link Scheduler} this operator will use
                + *
                You specify which {@link Scheduler} this operator will use.
                *
                * * @param scheduler From bab4e8b8ec3c9463c3f932b7171fad259074a534 Mon Sep 17 00:00:00 2001 From: Sadegh Date: Sat, 11 Nov 2017 15:55:45 +0330 Subject: [PATCH 037/417] 2.x: Add a sentence to documentation of take() operator. (#5718) * Add a sentence to documentation of take() operator * Rephrase java doc for take() method --- src/main/java/io/reactivex/Flowable.java | 6 ++++++ src/main/java/io/reactivex/Observable.java | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index b28a1685b3..7bc45def95 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -13392,6 +13392,9 @@ public final Flowable take(long count) { * Returns a Flowable that emits those items emitted by source Publisher before a specified time runs * out. *

                + * If time runs out before the {@code Flowable} completes normally, the {@code onComplete} event will be + * signaled on the default {@code computation} {@link Scheduler}. + *

                * *

                *
                Backpressure:
                @@ -13419,6 +13422,9 @@ public final Flowable take(long time, TimeUnit unit) { * Returns a Flowable that emits those items emitted by source Publisher before a specified time (on a * specified Scheduler) runs out. *

                + * If time runs out before the {@code Flowable} completes normally, the {@code onComplete} event will be + * signaled on the provided {@link Scheduler}. + *

                * *

                *
                Backpressure:
                diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 68788fe5b8..336e5887cb 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -11286,6 +11286,9 @@ public final Observable take(long count) { * Returns an Observable that emits those items emitted by source ObservableSource before a specified time runs * out. *

                + * If time runs out before the {@code Observable} completes normally, the {@code onComplete} event will be + * signaled on the default {@code computation} {@link Scheduler}. + *

                * *

                *
                Scheduler:
                @@ -11309,6 +11312,9 @@ public final Observable take(long time, TimeUnit unit) { * Returns an Observable that emits those items emitted by source ObservableSource before a specified time (on a * specified Scheduler) runs out. *

                + * If time runs out before the {@code Observable} completes normally, the {@code onComplete} event will be + * signaled on the provided {@link Scheduler}. + *

                * *

                *
                Scheduler:
                From 205375dee0062a0d8aa0d9cf86436919aebdabfb Mon Sep 17 00:00:00 2001 From: Philip Leonard Date: Tue, 14 Nov 2017 12:55:47 +0100 Subject: [PATCH 038/417] Remove duplicate nullity check line (#5723) --- src/main/java/io/reactivex/Observable.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 336e5887cb..a124159e07 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -12538,7 +12538,6 @@ public final Single> toMap( final Function valueSelector, Callable> mapSupplier) { ObjectHelper.requireNonNull(keySelector, "keySelector is null"); - ObjectHelper.requireNonNull(keySelector, "keySelector is null"); ObjectHelper.requireNonNull(valueSelector, "valueSelector is null"); ObjectHelper.requireNonNull(mapSupplier, "mapSupplier is null"); return collect(mapSupplier, Functions.toMapKeyValueSelector(keySelector, valueSelector)); From b99efbfb71d3a76befccd4e36324cefadeefd65a Mon Sep 17 00:00:00 2001 From: Jihong Park Date: Tue, 14 Nov 2017 21:26:14 +0900 Subject: [PATCH 039/417] 2.x : Rename variable name "subject" to "processor" for exact expression (#5721) --- .../processors/AsyncProcessorTest.java | 114 +++++++++--------- .../processors/BehaviorProcessorTest.java | 84 ++++++------- .../processors/PublishProcessorTest.java | 70 +++++------ ...ReplayProcessorBoundedConcurrencyTest.java | 24 ++-- .../ReplayProcessorConcurrencyTest.java | 24 ++-- .../processors/ReplayProcessorTest.java | 98 +++++++-------- .../processors/SerializedProcessorTest.java | 8 +- 7 files changed, 211 insertions(+), 211 deletions(-) diff --git a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java index 847d363580..a3d17873e3 100644 --- a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java +++ b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java @@ -46,14 +46,14 @@ protected FlowableProcessor create() { @Test public void testNeverCompleted() { - AsyncProcessor subject = AsyncProcessor.create(); + AsyncProcessor processor = AsyncProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onNext("two"); - subject.onNext("three"); + processor.onNext("one"); + processor.onNext("two"); + processor.onNext("three"); verify(observer, Mockito.never()).onNext(anyString()); verify(observer, Mockito.never()).onError(testException); @@ -62,15 +62,15 @@ public void testNeverCompleted() { @Test public void testCompleted() { - AsyncProcessor subject = AsyncProcessor.create(); + AsyncProcessor processor = AsyncProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onNext("two"); - subject.onNext("three"); - subject.onComplete(); + processor.onNext("one"); + processor.onNext("two"); + processor.onNext("three"); + processor.onComplete(); verify(observer, times(1)).onNext("three"); verify(observer, Mockito.never()).onError(any(Throwable.class)); @@ -80,13 +80,13 @@ public void testCompleted() { @Test @Ignore("Null values not allowed") public void testNull() { - AsyncProcessor subject = AsyncProcessor.create(); + AsyncProcessor processor = AsyncProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext(null); - subject.onComplete(); + processor.onNext(null); + processor.onComplete(); verify(observer, times(1)).onNext(null); verify(observer, Mockito.never()).onError(any(Throwable.class)); @@ -95,16 +95,16 @@ public void testNull() { @Test public void testSubscribeAfterCompleted() { - AsyncProcessor subject = AsyncProcessor.create(); + AsyncProcessor processor = AsyncProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.onNext("one"); - subject.onNext("two"); - subject.onNext("three"); - subject.onComplete(); + processor.onNext("one"); + processor.onNext("two"); + processor.onNext("three"); + processor.onComplete(); - subject.subscribe(observer); + processor.subscribe(observer); verify(observer, times(1)).onNext("three"); verify(observer, Mockito.never()).onError(any(Throwable.class)); @@ -113,18 +113,18 @@ public void testSubscribeAfterCompleted() { @Test public void testSubscribeAfterError() { - AsyncProcessor subject = AsyncProcessor.create(); + AsyncProcessor processor = AsyncProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.onNext("one"); - subject.onNext("two"); - subject.onNext("three"); + processor.onNext("one"); + processor.onNext("two"); + processor.onNext("three"); RuntimeException re = new RuntimeException("failed"); - subject.onError(re); + processor.onError(re); - subject.subscribe(observer); + processor.subscribe(observer); verify(observer, times(1)).onError(re); verify(observer, Mockito.never()).onNext(any(String.class)); @@ -133,18 +133,18 @@ public void testSubscribeAfterError() { @Test public void testError() { - AsyncProcessor subject = AsyncProcessor.create(); + AsyncProcessor processor = AsyncProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onNext("two"); - subject.onNext("three"); - subject.onError(testException); - subject.onNext("four"); - subject.onError(new Throwable()); - subject.onComplete(); + processor.onNext("one"); + processor.onNext("two"); + processor.onNext("three"); + processor.onError(testException); + processor.onNext("four"); + processor.onError(new Throwable()); + processor.onComplete(); verify(observer, Mockito.never()).onNext(anyString()); verify(observer, times(1)).onError(testException); @@ -153,14 +153,14 @@ public void testError() { @Test public void testUnsubscribeBeforeCompleted() { - AsyncProcessor subject = AsyncProcessor.create(); + AsyncProcessor processor = AsyncProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); TestSubscriber ts = new TestSubscriber(observer); - subject.subscribe(ts); + processor.subscribe(ts); - subject.onNext("one"); - subject.onNext("two"); + processor.onNext("one"); + processor.onNext("two"); ts.dispose(); @@ -168,8 +168,8 @@ public void testUnsubscribeBeforeCompleted() { verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, Mockito.never()).onComplete(); - subject.onNext("three"); - subject.onComplete(); + processor.onNext("three"); + processor.onComplete(); verify(observer, Mockito.never()).onNext(anyString()); verify(observer, Mockito.never()).onError(any(Throwable.class)); @@ -178,12 +178,12 @@ public void testUnsubscribeBeforeCompleted() { @Test public void testEmptySubjectCompleted() { - AsyncProcessor subject = AsyncProcessor.create(); + AsyncProcessor processor = AsyncProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onComplete(); + processor.onComplete(); InOrder inOrder = inOrder(observer); inOrder.verify(observer, never()).onNext(null); @@ -204,10 +204,10 @@ public void testSubscribeCompletionRaceCondition() { * With the synchronization code in place I can not get this to fail on my laptop. */ for (int i = 0; i < 50; i++) { - final AsyncProcessor subject = AsyncProcessor.create(); + final AsyncProcessor processor = AsyncProcessor.create(); final AtomicReference value1 = new AtomicReference(); - subject.subscribe(new Consumer() { + processor.subscribe(new Consumer() { @Override public void accept(String t1) { @@ -226,15 +226,15 @@ public void accept(String t1) { @Override public void run() { - subject.onNext("value"); - subject.onComplete(); + processor.onNext("value"); + processor.onComplete(); } }); - SubjectSubscriberThread t2 = new SubjectSubscriberThread(subject); - SubjectSubscriberThread t3 = new SubjectSubscriberThread(subject); - SubjectSubscriberThread t4 = new SubjectSubscriberThread(subject); - SubjectSubscriberThread t5 = new SubjectSubscriberThread(subject); + SubjectSubscriberThread t2 = new SubjectSubscriberThread(processor); + SubjectSubscriberThread t3 = new SubjectSubscriberThread(processor); + SubjectSubscriberThread t4 = new SubjectSubscriberThread(processor); + SubjectSubscriberThread t5 = new SubjectSubscriberThread(processor); t2.start(); t3.start(); @@ -262,18 +262,18 @@ public void run() { private static class SubjectSubscriberThread extends Thread { - private final AsyncProcessor subject; + private final AsyncProcessor processor; private final AtomicReference value = new AtomicReference(); - SubjectSubscriberThread(AsyncProcessor subject) { - this.subject = subject; + SubjectSubscriberThread(AsyncProcessor processor) { + this.processor = processor; } @Override public void run() { try { // a timeout exception will happen if we don't get a terminal state - String v = subject.timeout(2000, TimeUnit.MILLISECONDS).blockingSingle(); + String v = processor.timeout(2000, TimeUnit.MILLISECONDS).blockingSingle(); value.set(v); } catch (Exception e) { e.printStackTrace(); diff --git a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java index 9cb392adba..1a58aaf004 100644 --- a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java +++ b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java @@ -50,14 +50,14 @@ protected FlowableProcessor create() { @Test public void testThatSubscriberReceivesDefaultValueAndSubsequentEvents() { - BehaviorProcessor subject = BehaviorProcessor.createDefault("default"); + BehaviorProcessor processor = BehaviorProcessor.createDefault("default"); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onNext("two"); - subject.onNext("three"); + processor.onNext("one"); + processor.onNext("two"); + processor.onNext("three"); verify(observer, times(1)).onNext("default"); verify(observer, times(1)).onNext("one"); @@ -69,15 +69,15 @@ public void testThatSubscriberReceivesDefaultValueAndSubsequentEvents() { @Test public void testThatSubscriberReceivesLatestAndThenSubsequentEvents() { - BehaviorProcessor subject = BehaviorProcessor.createDefault("default"); + BehaviorProcessor processor = BehaviorProcessor.createDefault("default"); - subject.onNext("one"); + processor.onNext("one"); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("two"); - subject.onNext("three"); + processor.onNext("two"); + processor.onNext("three"); verify(observer, Mockito.never()).onNext("default"); verify(observer, times(1)).onNext("one"); @@ -89,13 +89,13 @@ public void testThatSubscriberReceivesLatestAndThenSubsequentEvents() { @Test public void testSubscribeThenOnComplete() { - BehaviorProcessor subject = BehaviorProcessor.createDefault("default"); + BehaviorProcessor processor = BehaviorProcessor.createDefault("default"); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onComplete(); + processor.onNext("one"); + processor.onComplete(); verify(observer, times(1)).onNext("default"); verify(observer, times(1)).onNext("one"); @@ -105,12 +105,12 @@ public void testSubscribeThenOnComplete() { @Test public void testSubscribeToCompletedOnlyEmitsOnComplete() { - BehaviorProcessor subject = BehaviorProcessor.createDefault("default"); - subject.onNext("one"); - subject.onComplete(); + BehaviorProcessor processor = BehaviorProcessor.createDefault("default"); + processor.onNext("one"); + processor.onComplete(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); verify(observer, never()).onNext("default"); verify(observer, never()).onNext("one"); @@ -120,13 +120,13 @@ public void testSubscribeToCompletedOnlyEmitsOnComplete() { @Test public void testSubscribeToErrorOnlyEmitsOnError() { - BehaviorProcessor subject = BehaviorProcessor.createDefault("default"); - subject.onNext("one"); + BehaviorProcessor processor = BehaviorProcessor.createDefault("default"); + processor.onNext("one"); RuntimeException re = new RuntimeException("test error"); - subject.onError(re); + processor.onError(re); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); verify(observer, never()).onNext("default"); verify(observer, never()).onNext("one"); @@ -181,15 +181,15 @@ public void testCompletedStopsEmittingData() { @Test public void testCompletedAfterErrorIsNotSent() { - BehaviorProcessor subject = BehaviorProcessor.createDefault("default"); + BehaviorProcessor processor = BehaviorProcessor.createDefault("default"); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onError(testException); - subject.onNext("two"); - subject.onComplete(); + processor.onNext("one"); + processor.onError(testException); + processor.onNext("two"); + processor.onComplete(); verify(observer, times(1)).onNext("default"); verify(observer, times(1)).onNext("one"); @@ -200,15 +200,15 @@ public void testCompletedAfterErrorIsNotSent() { @Test public void testCompletedAfterErrorIsNotSent2() { - BehaviorProcessor subject = BehaviorProcessor.createDefault("default"); + BehaviorProcessor processor = BehaviorProcessor.createDefault("default"); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onError(testException); - subject.onNext("two"); - subject.onComplete(); + processor.onNext("one"); + processor.onError(testException); + processor.onNext("two"); + processor.onComplete(); verify(observer, times(1)).onNext("default"); verify(observer, times(1)).onNext("one"); @@ -217,7 +217,7 @@ public void testCompletedAfterErrorIsNotSent2() { verify(observer, never()).onComplete(); Subscriber o2 = TestHelper.mockSubscriber(); - subject.subscribe(o2); + processor.subscribe(o2); verify(o2, times(1)).onError(testException); verify(o2, never()).onNext(any()); verify(o2, never()).onComplete(); @@ -225,15 +225,15 @@ public void testCompletedAfterErrorIsNotSent2() { @Test public void testCompletedAfterErrorIsNotSent3() { - BehaviorProcessor subject = BehaviorProcessor.createDefault("default"); + BehaviorProcessor processor = BehaviorProcessor.createDefault("default"); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onComplete(); - subject.onNext("two"); - subject.onComplete(); + processor.onNext("one"); + processor.onComplete(); + processor.onNext("two"); + processor.onComplete(); verify(observer, times(1)).onNext("default"); verify(observer, times(1)).onNext("one"); @@ -242,7 +242,7 @@ public void testCompletedAfterErrorIsNotSent3() { verify(observer, never()).onNext("two"); Subscriber o2 = TestHelper.mockSubscriber(); - subject.subscribe(o2); + processor.subscribe(o2); verify(o2, times(1)).onComplete(); verify(o2, never()).onNext(any()); verify(observer, never()).onError(any(Throwable.class)); diff --git a/src/test/java/io/reactivex/processors/PublishProcessorTest.java b/src/test/java/io/reactivex/processors/PublishProcessorTest.java index 918650c8a1..42f43bb1a6 100644 --- a/src/test/java/io/reactivex/processors/PublishProcessorTest.java +++ b/src/test/java/io/reactivex/processors/PublishProcessorTest.java @@ -40,22 +40,22 @@ protected FlowableProcessor create() { @Test public void testCompleted() { - PublishProcessor subject = PublishProcessor.create(); + PublishProcessor processor = PublishProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onNext("two"); - subject.onNext("three"); - subject.onComplete(); + processor.onNext("one"); + processor.onNext("two"); + processor.onNext("three"); + processor.onComplete(); Subscriber anotherSubscriber = TestHelper.mockSubscriber(); - subject.subscribe(anotherSubscriber); + processor.subscribe(anotherSubscriber); - subject.onNext("four"); - subject.onComplete(); - subject.onError(new Throwable()); + processor.onNext("four"); + processor.onComplete(); + processor.onError(new Throwable()); assertCompletedSubscriber(observer); // todo bug? assertNeverSubscriber(anotherSubscriber); @@ -113,22 +113,22 @@ private void assertCompletedSubscriber(Subscriber observer) { @Test public void testError() { - PublishProcessor subject = PublishProcessor.create(); + PublishProcessor processor = PublishProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onNext("two"); - subject.onNext("three"); - subject.onError(testException); + processor.onNext("one"); + processor.onNext("two"); + processor.onNext("three"); + processor.onError(testException); Subscriber anotherSubscriber = TestHelper.mockSubscriber(); - subject.subscribe(anotherSubscriber); + processor.subscribe(anotherSubscriber); - subject.onNext("four"); - subject.onError(new Throwable()); - subject.onComplete(); + processor.onNext("four"); + processor.onError(new Throwable()); + processor.onComplete(); assertErrorSubscriber(observer); // todo bug? assertNeverSubscriber(anotherSubscriber); @@ -144,21 +144,21 @@ private void assertErrorSubscriber(Subscriber observer) { @Test public void testSubscribeMidSequence() { - PublishProcessor subject = PublishProcessor.create(); + PublishProcessor processor = PublishProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onNext("two"); + processor.onNext("one"); + processor.onNext("two"); assertObservedUntilTwo(observer); Subscriber anotherSubscriber = TestHelper.mockSubscriber(); - subject.subscribe(anotherSubscriber); + processor.subscribe(anotherSubscriber); - subject.onNext("three"); - subject.onComplete(); + processor.onNext("three"); + processor.onComplete(); assertCompletedSubscriber(observer); assertCompletedStartingWithThreeSubscriber(anotherSubscriber); @@ -174,23 +174,23 @@ private void assertCompletedStartingWithThreeSubscriber(Subscriber obser @Test public void testUnsubscribeFirstSubscriber() { - PublishProcessor subject = PublishProcessor.create(); + PublishProcessor processor = PublishProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); TestSubscriber ts = new TestSubscriber(observer); - subject.subscribe(ts); + processor.subscribe(ts); - subject.onNext("one"); - subject.onNext("two"); + processor.onNext("one"); + processor.onNext("two"); ts.dispose(); assertObservedUntilTwo(observer); Subscriber anotherSubscriber = TestHelper.mockSubscriber(); - subject.subscribe(anotherSubscriber); + processor.subscribe(anotherSubscriber); - subject.onNext("three"); - subject.onComplete(); + processor.onNext("three"); + processor.onComplete(); assertObservedUntilTwo(observer); assertCompletedStartingWithThreeSubscriber(anotherSubscriber); @@ -220,7 +220,7 @@ public void testNestedSubscribe() { public Flowable apply(final Integer v) { countParent.incrementAndGet(); - // then subscribe to subject again (it will not receive the previous value) + // then subscribe to processor again (it will not receive the previous value) return s.map(new Function() { @Override diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java index 5dcc0fb4e4..7edef31ecd 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java @@ -227,10 +227,10 @@ public void run() { @Test(timeout = 10000) public void testSubscribeCompletionRaceCondition() { for (int i = 0; i < 50; i++) { - final ReplayProcessor subject = ReplayProcessor.createUnbounded(); + final ReplayProcessor processor = ReplayProcessor.createUnbounded(); final AtomicReference value1 = new AtomicReference(); - subject.subscribe(new Consumer() { + processor.subscribe(new Consumer() { @Override public void accept(String t1) { @@ -249,15 +249,15 @@ public void accept(String t1) { @Override public void run() { - subject.onNext("value"); - subject.onComplete(); + processor.onNext("value"); + processor.onComplete(); } }); - SubjectObserverThread t2 = new SubjectObserverThread(subject); - SubjectObserverThread t3 = new SubjectObserverThread(subject); - SubjectObserverThread t4 = new SubjectObserverThread(subject); - SubjectObserverThread t5 = new SubjectObserverThread(subject); + SubjectObserverThread t2 = new SubjectObserverThread(processor); + SubjectObserverThread t3 = new SubjectObserverThread(processor); + SubjectObserverThread t4 = new SubjectObserverThread(processor); + SubjectObserverThread t5 = new SubjectObserverThread(processor); t2.start(); t3.start(); @@ -300,18 +300,18 @@ public void testRaceForTerminalState() { private static class SubjectObserverThread extends Thread { - private final ReplayProcessor subject; + private final ReplayProcessor processor; private final AtomicReference value = new AtomicReference(); - SubjectObserverThread(ReplayProcessor subject) { - this.subject = subject; + SubjectObserverThread(ReplayProcessor processor) { + this.processor = processor; } @Override public void run() { try { // a timeout exception will happen if we don't get a terminal state - String v = subject.timeout(2000, TimeUnit.MILLISECONDS).blockingSingle(); + String v = processor.timeout(2000, TimeUnit.MILLISECONDS).blockingSingle(); value.set(v); } catch (Exception e) { e.printStackTrace(); diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java index ff9168339c..62b0817678 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java @@ -227,10 +227,10 @@ public void run() { @Test(timeout = 10000) public void testSubscribeCompletionRaceCondition() { for (int i = 0; i < 50; i++) { - final ReplayProcessor subject = ReplayProcessor.create(); + final ReplayProcessor processor = ReplayProcessor.create(); final AtomicReference value1 = new AtomicReference(); - subject.subscribe(new Consumer() { + processor.subscribe(new Consumer() { @Override public void accept(String t1) { @@ -249,15 +249,15 @@ public void accept(String t1) { @Override public void run() { - subject.onNext("value"); - subject.onComplete(); + processor.onNext("value"); + processor.onComplete(); } }); - SubjectObserverThread t2 = new SubjectObserverThread(subject); - SubjectObserverThread t3 = new SubjectObserverThread(subject); - SubjectObserverThread t4 = new SubjectObserverThread(subject); - SubjectObserverThread t5 = new SubjectObserverThread(subject); + SubjectObserverThread t2 = new SubjectObserverThread(processor); + SubjectObserverThread t3 = new SubjectObserverThread(processor); + SubjectObserverThread t4 = new SubjectObserverThread(processor); + SubjectObserverThread t5 = new SubjectObserverThread(processor); t2.start(); t3.start(); @@ -300,18 +300,18 @@ public void testRaceForTerminalState() { static class SubjectObserverThread extends Thread { - private final ReplayProcessor subject; + private final ReplayProcessor processor; private final AtomicReference value = new AtomicReference(); - SubjectObserverThread(ReplayProcessor subject) { - this.subject = subject; + SubjectObserverThread(ReplayProcessor processor) { + this.processor = processor; } @Override public void run() { try { // a timeout exception will happen if we don't get a terminal state - String v = subject.timeout(2000, TimeUnit.MILLISECONDS).blockingSingle(); + String v = processor.timeout(2000, TimeUnit.MILLISECONDS).blockingSingle(); value.set(v); } catch (Exception e) { e.printStackTrace(); diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index 6a3f040fb2..e42f801f4a 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -44,25 +44,25 @@ protected FlowableProcessor create() { @Test public void testCompleted() { - ReplayProcessor subject = ReplayProcessor.create(); + ReplayProcessor processor = ReplayProcessor.create(); Subscriber o1 = TestHelper.mockSubscriber(); - subject.subscribe(o1); + processor.subscribe(o1); - subject.onNext("one"); - subject.onNext("two"); - subject.onNext("three"); - subject.onComplete(); + processor.onNext("one"); + processor.onNext("two"); + processor.onNext("three"); + processor.onComplete(); - subject.onNext("four"); - subject.onComplete(); - subject.onError(new Throwable()); + processor.onNext("four"); + processor.onComplete(); + processor.onError(new Throwable()); assertCompletedSubscriber(o1); // assert that subscribing a 2nd time gets the same data Subscriber o2 = TestHelper.mockSubscriber(); - subject.subscribe(o2); + processor.subscribe(o2); assertCompletedSubscriber(o2); } @@ -137,17 +137,17 @@ public void testCompletedStopsEmittingData() { @Test public void testCompletedAfterError() { - ReplayProcessor subject = ReplayProcessor.create(); + ReplayProcessor processor = ReplayProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.onNext("one"); - subject.onError(testException); - subject.onNext("two"); - subject.onComplete(); - subject.onError(new RuntimeException()); + processor.onNext("one"); + processor.onError(testException); + processor.onNext("two"); + processor.onComplete(); + processor.onError(new RuntimeException()); - subject.subscribe(observer); + processor.subscribe(observer); verify(observer).onSubscribe((Subscription)notNull()); verify(observer, times(1)).onNext("one"); verify(observer, times(1)).onError(testException); @@ -167,24 +167,24 @@ private void assertCompletedSubscriber(Subscriber observer) { @Test public void testError() { - ReplayProcessor subject = ReplayProcessor.create(); + ReplayProcessor processor = ReplayProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onNext("two"); - subject.onNext("three"); - subject.onError(testException); + processor.onNext("one"); + processor.onNext("two"); + processor.onNext("three"); + processor.onError(testException); - subject.onNext("four"); - subject.onError(new Throwable()); - subject.onComplete(); + processor.onNext("four"); + processor.onError(new Throwable()); + processor.onComplete(); assertErrorSubscriber(observer); observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); assertErrorSubscriber(observer); } @@ -198,22 +198,22 @@ private void assertErrorSubscriber(Subscriber observer) { @Test public void testSubscribeMidSequence() { - ReplayProcessor subject = ReplayProcessor.create(); + ReplayProcessor processor = ReplayProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); - subject.subscribe(observer); + processor.subscribe(observer); - subject.onNext("one"); - subject.onNext("two"); + processor.onNext("one"); + processor.onNext("two"); assertObservedUntilTwo(observer); Subscriber anotherSubscriber = TestHelper.mockSubscriber(); - subject.subscribe(anotherSubscriber); + processor.subscribe(anotherSubscriber); assertObservedUntilTwo(anotherSubscriber); - subject.onNext("three"); - subject.onComplete(); + processor.onNext("three"); + processor.onComplete(); assertCompletedSubscriber(observer); assertCompletedSubscriber(anotherSubscriber); @@ -221,24 +221,24 @@ public void testSubscribeMidSequence() { @Test public void testUnsubscribeFirstSubscriber() { - ReplayProcessor subject = ReplayProcessor.create(); + ReplayProcessor processor = ReplayProcessor.create(); Subscriber observer = TestHelper.mockSubscriber(); TestSubscriber ts = new TestSubscriber(observer); - subject.subscribe(ts); + processor.subscribe(ts); - subject.onNext("one"); - subject.onNext("two"); + processor.onNext("one"); + processor.onNext("two"); ts.dispose(); assertObservedUntilTwo(observer); Subscriber anotherSubscriber = TestHelper.mockSubscriber(); - subject.subscribe(anotherSubscriber); + processor.subscribe(anotherSubscriber); assertObservedUntilTwo(anotherSubscriber); - subject.onNext("three"); - subject.onComplete(); + processor.onNext("three"); + processor.onComplete(); assertObservedUntilTwo(observer); assertCompletedSubscriber(anotherSubscriber); @@ -309,15 +309,15 @@ public void onNext(String v) { }; - ReplayProcessor subject = ReplayProcessor.create(); - subject.subscribe(observer1); - subject.onNext("one"); + ReplayProcessor processor = ReplayProcessor.create(); + processor.subscribe(observer1); + processor.onNext("one"); assertEquals("one", lastValueForSubscriber1.get()); - subject.onNext("two"); + processor.onNext("two"); assertEquals("two", lastValueForSubscriber1.get()); // use subscribeOn to make this async otherwise we deadlock as we are using CountDownLatches - subject.subscribeOn(Schedulers.newThread()).subscribe(observer2); + processor.subscribeOn(Schedulers.newThread()).subscribe(observer2); System.out.println("before waiting for one"); @@ -326,7 +326,7 @@ public void onNext(String v) { System.out.println("after waiting for one"); - subject.onNext("three"); + processor.onNext("three"); System.out.println("sent three"); @@ -335,9 +335,9 @@ public void onNext(String v) { System.out.println("about to send onComplete"); - subject.onComplete(); + processor.onComplete(); - System.out.println("completed subject"); + System.out.println("completed processor"); // release makeSlow.countDown(); diff --git a/src/test/java/io/reactivex/processors/SerializedProcessorTest.java b/src/test/java/io/reactivex/processors/SerializedProcessorTest.java index ba981bde07..db60b5c793 100644 --- a/src/test/java/io/reactivex/processors/SerializedProcessorTest.java +++ b/src/test/java/io/reactivex/processors/SerializedProcessorTest.java @@ -30,11 +30,11 @@ public class SerializedProcessorTest { @Test public void testBasic() { - SerializedProcessor subject = new SerializedProcessor(PublishProcessor. create()); + SerializedProcessor processor = new SerializedProcessor(PublishProcessor. create()); TestSubscriber ts = new TestSubscriber(); - subject.subscribe(ts); - subject.onNext("hello"); - subject.onComplete(); + processor.subscribe(ts); + processor.onNext("hello"); + processor.onComplete(); ts.awaitTerminalEvent(); ts.assertValue("hello"); } From 9521512c0f0c980f074ec5b0fbfe954b00c56f1d Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 15 Nov 2017 11:24:45 +0100 Subject: [PATCH 040/417] 2.x: distinguish between sync and async dispose in ScheduledRunnable (#5715) * 2.x: distinguish between sync and async dispose in ScheduledRunnable * Coverage improvement and fix a missing state change * Add test case for the parent-done reordered check --- .../schedulers/ScheduledRunnable.java | 34 ++++-- .../schedulers/ScheduledRunnableTest.java | 111 ++++++++++++++++++ 2 files changed, 133 insertions(+), 12 deletions(-) diff --git a/src/main/java/io/reactivex/internal/schedulers/ScheduledRunnable.java b/src/main/java/io/reactivex/internal/schedulers/ScheduledRunnable.java index c942deacfa..61218fbe40 100644 --- a/src/main/java/io/reactivex/internal/schedulers/ScheduledRunnable.java +++ b/src/main/java/io/reactivex/internal/schedulers/ScheduledRunnable.java @@ -26,7 +26,12 @@ public final class ScheduledRunnable extends AtomicReferenceArray private static final long serialVersionUID = -6120223772001106981L; final Runnable actual; - static final Object DISPOSED = new Object(); + /** Indicates that the parent tracking this task has been notified about its completion. */ + static final Object PARENT_DISPOSED = new Object(); + /** Indicates the dispose() was called from within the run/call method. */ + static final Object SYNC_DISPOSED = new Object(); + /** Indicates the dispose() was called from another thread. */ + static final Object ASYNC_DISPOSED = new Object(); static final Object DONE = new Object(); @@ -66,13 +71,13 @@ public void run() { } finally { lazySet(THREAD_INDEX, null); Object o = get(PARENT_INDEX); - if (o != DISPOSED && o != null && compareAndSet(PARENT_INDEX, o, DONE)) { + if (o != PARENT_DISPOSED && compareAndSet(PARENT_INDEX, o, DONE) && o != null) { ((DisposableContainer)o).delete(this); } for (;;) { o = get(FUTURE_INDEX); - if (o == DISPOSED || compareAndSet(FUTURE_INDEX, o, DONE)) { + if (o == SYNC_DISPOSED || o == ASYNC_DISPOSED || compareAndSet(FUTURE_INDEX, o, DONE)) { break; } } @@ -85,8 +90,12 @@ public void setFuture(Future f) { if (o == DONE) { return; } - if (o == DISPOSED) { - f.cancel(get(THREAD_INDEX) != Thread.currentThread()); + if (o == SYNC_DISPOSED) { + f.cancel(false); + return; + } + if (o == ASYNC_DISPOSED) { + f.cancel(true); return; } if (compareAndSet(FUTURE_INDEX, o, f)) { @@ -99,12 +108,13 @@ public void setFuture(Future f) { public void dispose() { for (;;) { Object o = get(FUTURE_INDEX); - if (o == DONE || o == DISPOSED) { + if (o == DONE || o == SYNC_DISPOSED || o == ASYNC_DISPOSED) { break; } - if (compareAndSet(FUTURE_INDEX, o, DISPOSED)) { + boolean async = get(THREAD_INDEX) != Thread.currentThread(); + if (compareAndSet(FUTURE_INDEX, o, async ? ASYNC_DISPOSED : SYNC_DISPOSED)) { if (o != null) { - ((Future)o).cancel(get(THREAD_INDEX) != Thread.currentThread()); + ((Future)o).cancel(async); } break; } @@ -112,10 +122,10 @@ public void dispose() { for (;;) { Object o = get(PARENT_INDEX); - if (o == DONE || o == DISPOSED || o == null) { + if (o == DONE || o == PARENT_DISPOSED || o == null) { return; } - if (compareAndSet(PARENT_INDEX, o, DISPOSED)) { + if (compareAndSet(PARENT_INDEX, o, PARENT_DISPOSED)) { ((DisposableContainer)o).delete(this); return; } @@ -124,7 +134,7 @@ public void dispose() { @Override public boolean isDisposed() { - Object o = get(FUTURE_INDEX); - return o == DISPOSED || o == DONE; + Object o = get(PARENT_INDEX); + return o == PARENT_DISPOSED || o == DONE; } } diff --git a/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java b/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java index 169767d4c6..49d20edf80 100644 --- a/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java @@ -18,6 +18,7 @@ import java.lang.Thread.UncaughtExceptionHandler; import java.util.List; import java.util.concurrent.FutureTask; +import java.util.concurrent.atomic.*; import org.junit.Test; @@ -283,4 +284,114 @@ public void run() { TestHelper.race(r1, r2); } } + + @Test + public void syncWorkerCancelRace() { + for (int i = 0; i < 10000; i++) { + final CompositeDisposable set = new CompositeDisposable(); + final AtomicBoolean interrupted = new AtomicBoolean(); + final AtomicInteger sync = new AtomicInteger(2); + final AtomicInteger syncb = new AtomicInteger(2); + + Runnable r0 = new Runnable() { + @Override + public void run() { + set.dispose(); + if (sync.decrementAndGet() != 0) { + while (sync.get() != 0) { } + } + if (syncb.decrementAndGet() != 0) { + while (syncb.get() != 0) { } + } + for (int j = 0; j < 1000; j++) { + if (Thread.currentThread().isInterrupted()) { + interrupted.set(true); + break; + } + } + } + }; + + final ScheduledRunnable run = new ScheduledRunnable(r0, set); + set.add(run); + + final FutureTask ft = new FutureTask(run, null); + + Runnable r2 = new Runnable() { + @Override + public void run() { + if (sync.decrementAndGet() != 0) { + while (sync.get() != 0) { } + } + run.setFuture(ft); + if (syncb.decrementAndGet() != 0) { + while (syncb.get() != 0) { } + } + } + }; + + TestHelper.race(ft, r2); + + assertFalse("The task was interrupted", interrupted.get()); + } + } + + @Test + public void disposeAfterRun() { + final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); + + run.run(); + assertEquals(ScheduledRunnable.DONE, run.get(ScheduledRunnable.FUTURE_INDEX)); + + run.dispose(); + assertEquals(ScheduledRunnable.DONE, run.get(ScheduledRunnable.FUTURE_INDEX)); + } + + @Test + public void syncDisposeIdempotent() { + final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); + run.set(ScheduledRunnable.THREAD_INDEX, Thread.currentThread()); + + run.dispose(); + assertEquals(ScheduledRunnable.SYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); + run.dispose(); + assertEquals(ScheduledRunnable.SYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); + run.run(); + assertEquals(ScheduledRunnable.SYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); + } + + @Test + public void asyncDisposeIdempotent() { + final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); + + run.dispose(); + assertEquals(ScheduledRunnable.ASYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); + run.dispose(); + assertEquals(ScheduledRunnable.ASYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); + run.run(); + assertEquals(ScheduledRunnable.ASYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); + } + + + @Test + public void noParentIsDisposed() { + ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); + assertFalse(run.isDisposed()); + run.run(); + assertTrue(run.isDisposed()); + } + + @Test + public void withParentIsDisposed() { + CompositeDisposable set = new CompositeDisposable(); + ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); + set.add(run); + + assertFalse(run.isDisposed()); + + run.run(); + assertTrue(run.isDisposed()); + + assertFalse(set.remove(run)); + } } From 6a44e5d0543a48f1c378dc833a155f3f71333bc2 Mon Sep 17 00:00:00 2001 From: Zac Sweers Date: Sun, 19 Nov 2017 02:39:00 -0800 Subject: [PATCH 041/417] 2.x: Implement as() (#5729) * Implement Observable.as() * Implement Single.as() * Implement Maybe.as() * Implement Flowable.as() * Implement Completable.as() * Add Experimental annotations * Add throws doc * Fix docs and validation errors * Add @since 2.1.7 - experimental * ParallelFlowable.as() * Start ConverterTest * Fix tests and update validator * Remove exceptions from signatures * Remove exception signature from implementations * Assert the full execution of extend() tests * Use test() helpers --- src/main/java/io/reactivex/Completable.java | 22 ++ .../io/reactivex/CompletableConverter.java | 35 +++ src/main/java/io/reactivex/Flowable.java | 25 ++ .../java/io/reactivex/FlowableConverter.java | 36 +++ src/main/java/io/reactivex/Maybe.java | 22 ++ .../java/io/reactivex/MaybeConverter.java | 36 +++ src/main/java/io/reactivex/Observable.java | 22 ++ .../io/reactivex/ObservableConverter.java | 36 +++ src/main/java/io/reactivex/Single.java | 22 ++ .../java/io/reactivex/SingleConverter.java | 36 +++ .../reactivex/parallel/ParallelFlowable.java | 18 ++ .../parallel/ParallelFlowableConverter.java | 36 +++ src/test/java/io/reactivex/ConverterTest.java | 268 ++++++++++++++++++ .../reactivex/ParamValidationCheckerTest.java | 40 +++ .../completable/CompletableTest.java | 48 +++- .../reactivex/flowable/FlowableNullTests.java | 5 + .../io/reactivex/flowable/FlowableTests.java | 33 ++- .../java/io/reactivex/maybe/MaybeTest.java | 17 ++ .../observable/ObservableNullTests.java | 5 + .../reactivex/observable/ObservableTest.java | 32 ++- .../parallel/ParallelFlowableTest.java | 26 ++ .../io/reactivex/single/SingleNullTests.java | 5 + .../java/io/reactivex/single/SingleTest.java | 12 + 23 files changed, 826 insertions(+), 11 deletions(-) create mode 100644 src/main/java/io/reactivex/CompletableConverter.java create mode 100644 src/main/java/io/reactivex/FlowableConverter.java create mode 100644 src/main/java/io/reactivex/MaybeConverter.java create mode 100644 src/main/java/io/reactivex/ObservableConverter.java create mode 100644 src/main/java/io/reactivex/SingleConverter.java create mode 100644 src/main/java/io/reactivex/parallel/ParallelFlowableConverter.java create mode 100644 src/test/java/io/reactivex/ConverterTest.java diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 3c3c4040ca..34008f1a0c 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -908,6 +908,28 @@ public final Completable andThen(CompletableSource next) { return concatWith(next); } + /** + * Calls the specified converter function during assembly time and returns its resulting value. + *

                + * This allows fluent conversion to any other type. + *

                + *
                Scheduler:
                + *
                {@code as} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param the resulting object type + * @param converter the function that receives the current Completable instance and returns a value + * @return the converted value + * @throws NullPointerException if converter is null + * @since 2.1.7 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final R as(@NonNull CompletableConverter converter) { + return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); + } + /** * Subscribes to and awaits the termination of this Completable instance in a blocking manner and * rethrows any exception emitted. diff --git a/src/main/java/io/reactivex/CompletableConverter.java b/src/main/java/io/reactivex/CompletableConverter.java new file mode 100644 index 0000000000..39ec9b452b --- /dev/null +++ b/src/main/java/io/reactivex/CompletableConverter.java @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import io.reactivex.annotations.*; + +/** + * Convenience interface and callback used by the {@link Completable#as} operator to turn a Completable into another + * value fluently. + * + * @param the output type + * @since 2.1.7 - experimental + */ +@Experimental +public interface CompletableConverter { + /** + * Applies a function to the upstream Completable and returns a converted value of type {@code R}. + * + * @param upstream the upstream Completable instance + * @return the converted value + */ + @NonNull + R apply(@NonNull Completable upstream); +} diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 7bc45def95..b2da55c6fa 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -5237,6 +5237,31 @@ public final Single any(Predicate predicate) { return RxJavaPlugins.onAssembly(new FlowableAnySingle(this, predicate)); } + /** + * Calls the specified converter function during assembly time and returns its resulting value. + *

                + * This allows fluent conversion to any other type. + *

                + *
                Backpressure:
                + *
                The backpressure behavior depends on what happens in the {@code converter} function.
                + *
                Scheduler:
                + *
                {@code as} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param the resulting object type + * @param converter the function that receives the current Flowable instance and returns a value + * @return the converted value + * @throws NullPointerException if converter is null + * @since 2.1.7 - experimental + */ + @Experimental + @CheckReturnValue + @BackpressureSupport(BackpressureKind.SPECIAL) + @SchedulerSupport(SchedulerSupport.NONE) + public final R as(@NonNull FlowableConverter converter) { + return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); + } + /** * Returns the first item emitted by this {@code Flowable}, or throws * {@code NoSuchElementException} if it emits no items. diff --git a/src/main/java/io/reactivex/FlowableConverter.java b/src/main/java/io/reactivex/FlowableConverter.java new file mode 100644 index 0000000000..541e335bcd --- /dev/null +++ b/src/main/java/io/reactivex/FlowableConverter.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import io.reactivex.annotations.*; + +/** + * Convenience interface and callback used by the {@link Flowable#as} operator to turn a Flowable into another + * value fluently. + * + * @param the upstream type + * @param the output type + * @since 2.1.7 - experimental + */ +@Experimental +public interface FlowableConverter { + /** + * Applies a function to the upstream Flowable and returns a converted value of type {@code R}. + * + * @param upstream the upstream Flowable instance + * @return the converted value + */ + @NonNull + R apply(@NonNull Flowable upstream); +} diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 13922ed8d3..c2a88aacb3 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -1989,6 +1989,28 @@ public final Maybe ambWith(MaybeSource other) { return ambArray(this, other); } + /** + * Calls the specified converter function during assembly time and returns its resulting value. + *

                + * This allows fluent conversion to any other type. + *

                + *
                Scheduler:
                + *
                {@code as} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param the resulting object type + * @param converter the function that receives the current Maybe instance and returns a value + * @return the converted value + * @throws NullPointerException if converter is null + * @since 2.1.7 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final R as(@NonNull MaybeConverter converter) { + return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); + } + /** * Waits in a blocking fashion until the current Maybe signals a success value (which is returned), * null if completed or an exception (which is propagated). diff --git a/src/main/java/io/reactivex/MaybeConverter.java b/src/main/java/io/reactivex/MaybeConverter.java new file mode 100644 index 0000000000..e156ed5944 --- /dev/null +++ b/src/main/java/io/reactivex/MaybeConverter.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import io.reactivex.annotations.*; + +/** + * Convenience interface and callback used by the {@link Maybe#as} operator to turn a Maybe into another + * value fluently. + * + * @param the upstream type + * @param the output type + * @since 2.1.7 - experimental + */ +@Experimental +public interface MaybeConverter { + /** + * Applies a function to the upstream Maybe and returns a converted value of type {@code R}. + * + * @param upstream the upstream Maybe instance + * @return the converted value + */ + @NonNull + R apply(@NonNull Maybe upstream); +} diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index a124159e07..bfa3a19e4e 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -4800,6 +4800,28 @@ public final Single any(Predicate predicate) { return RxJavaPlugins.onAssembly(new ObservableAnySingle(this, predicate)); } + /** + * Calls the specified converter function during assembly time and returns its resulting value. + *

                + * This allows fluent conversion to any other type. + *

                + *
                Scheduler:
                + *
                {@code as} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param the resulting object type + * @param converter the function that receives the current Observable instance and returns a value + * @return the converted value + * @throws NullPointerException if converter is null + * @since 2.1.7 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final R as(@NonNull ObservableConverter converter) { + return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); + } + /** * Returns the first item emitted by this {@code Observable}, or throws * {@code NoSuchElementException} if it emits no items. diff --git a/src/main/java/io/reactivex/ObservableConverter.java b/src/main/java/io/reactivex/ObservableConverter.java new file mode 100644 index 0000000000..b413de69de --- /dev/null +++ b/src/main/java/io/reactivex/ObservableConverter.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import io.reactivex.annotations.*; + +/** + * Convenience interface and callback used by the {@link Observable#as} operator to turn an Observable into another + * value fluently. + * + * @param the upstream type + * @param the output type + * @since 2.1.7 - experimental + */ +@Experimental +public interface ObservableConverter { + /** + * Applies a function to the upstream Observable and returns a converted value of type {@code R}. + * + * @param upstream the upstream Observable instance + * @return the converted value + */ + @NonNull + R apply(@NonNull Observable upstream); +} diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 03b659a71a..72ee2872c6 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -1522,6 +1522,28 @@ public final Single ambWith(SingleSource other) { return ambArray(this, other); } + /** + * Calls the specified converter function during assembly time and returns its resulting value. + *

                + * This allows fluent conversion to any other type. + *

                + *
                Scheduler:
                + *
                {@code as} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param the resulting object type + * @param converter the function that receives the current Single instance and returns a value + * @return the converted value + * @throws NullPointerException if converter is null + * @since 2.1.7 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final R as(@NonNull SingleConverter converter) { + return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); + } + /** * Hides the identity of the current Single, including the Disposable that is sent * to the downstream via {@code onSubscribe()}. diff --git a/src/main/java/io/reactivex/SingleConverter.java b/src/main/java/io/reactivex/SingleConverter.java new file mode 100644 index 0000000000..9938b22cc7 --- /dev/null +++ b/src/main/java/io/reactivex/SingleConverter.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import io.reactivex.annotations.*; + +/** + * Convenience interface and callback used by the {@link Single#as} operator to turn a Single into another + * value fluently. + * + * @param the upstream type + * @param the output type + * @since 2.1.7 - experimental + */ +@Experimental +public interface SingleConverter { + /** + * Applies a function to the upstream Single and returns a converted value of type {@code R}. + * + * @param upstream the upstream Single instance + * @return the converted value + */ + @NonNull + R apply(@NonNull Single upstream); +} diff --git a/src/main/java/io/reactivex/parallel/ParallelFlowable.java b/src/main/java/io/reactivex/parallel/ParallelFlowable.java index b1f6d60322..4dd6dfd93d 100644 --- a/src/main/java/io/reactivex/parallel/ParallelFlowable.java +++ b/src/main/java/io/reactivex/parallel/ParallelFlowable.java @@ -122,6 +122,24 @@ public static ParallelFlowable from(@NonNull Publisher sourc return RxJavaPlugins.onAssembly(new ParallelFromPublisher(source, parallelism, prefetch)); } + /** + * Calls the specified converter function during assembly time and returns its resulting value. + *

                + * This allows fluent conversion to any other type. + * + * @param the resulting object type + * @param converter the function that receives the current ParallelFlowable instance and returns a value + * @return the converted value + * @throws NullPointerException if converter is null + * @since 2.1.7 - experimental + */ + @Experimental + @CheckReturnValue + @NonNull + public final R as(@NonNull ParallelFlowableConverter converter) { + return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); + } + /** * Maps the source values on each 'rail' to another value. *

                diff --git a/src/main/java/io/reactivex/parallel/ParallelFlowableConverter.java b/src/main/java/io/reactivex/parallel/ParallelFlowableConverter.java new file mode 100644 index 0000000000..f782eb7bb0 --- /dev/null +++ b/src/main/java/io/reactivex/parallel/ParallelFlowableConverter.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.parallel; + +import io.reactivex.annotations.*; + +/** + * Convenience interface and callback used by the {@link ParallelFlowable#as} operator to turn a ParallelFlowable into + * another value fluently. + * + * @param the upstream type + * @param the output type + * @since 2.1.7 - experimental + */ +@Experimental +public interface ParallelFlowableConverter { + /** + * Applies a function to the upstream ParallelFlowable and returns a converted value of type {@code R}. + * + * @param upstream the upstream ParallelFlowable instance + * @return the converted value + */ + @NonNull + R apply(@NonNull ParallelFlowable upstream); +} diff --git a/src/test/java/io/reactivex/ConverterTest.java b/src/test/java/io/reactivex/ConverterTest.java new file mode 100644 index 0000000000..d2f174cd2f --- /dev/null +++ b/src/test/java/io/reactivex/ConverterTest.java @@ -0,0 +1,268 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.exceptions.TestException; +import io.reactivex.parallel.*; + +public final class ConverterTest { + + @Test + public void flowableConverterThrows() { + try { + Flowable.just(1).as(new FlowableConverter() { + @Override + public Integer apply(Flowable v) { + throw new TestException("Forced failure"); + } + }); + fail("Should have thrown!"); + } catch (TestException ex) { + assertEquals("Forced failure", ex.getMessage()); + } + } + + @Test + public void observableConverterThrows() { + try { + Observable.just(1).as(new ObservableConverter() { + @Override + public Integer apply(Observable v) { + throw new TestException("Forced failure"); + } + }); + fail("Should have thrown!"); + } catch (TestException ex) { + assertEquals("Forced failure", ex.getMessage()); + } + } + + @Test + public void singleConverterThrows() { + try { + Single.just(1).as(new SingleConverter() { + @Override + public Integer apply(Single v) { + throw new TestException("Forced failure"); + } + }); + fail("Should have thrown!"); + } catch (TestException ex) { + assertEquals("Forced failure", ex.getMessage()); + } + } + + @Test + public void maybeConverterThrows() { + try { + Maybe.just(1).as(new MaybeConverter() { + @Override + public Integer apply(Maybe v) { + throw new TestException("Forced failure"); + } + }); + fail("Should have thrown!"); + } catch (TestException ex) { + assertEquals("Forced failure", ex.getMessage()); + } + } + + @Test + public void completableConverterThrows() { + try { + Completable.complete().as(new CompletableConverter() { + @Override + public Completable apply(Completable v) { + throw new TestException("Forced failure"); + } + }); + fail("Should have thrown!"); + } catch (TestException ex) { + assertEquals("Forced failure", ex.getMessage()); + } + } + + // Test demos for signature generics in compose() methods. Just needs to compile. + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void observableGenericsSignatureTest() { + A a = new A() { }; + + Observable.just(a).as((ObservableConverter)ConverterTest.testObservableConverterCreator()); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void singleGenericsSignatureTest() { + A a = new A() { }; + + Single.just(a).as((SingleConverter)ConverterTest.testSingleConverterCreator()); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void maybeGenericsSignatureTest() { + A a = new A() { }; + + Maybe.just(a).as((MaybeConverter)ConverterTest.testMaybeConverterCreator()); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void flowableGenericsSignatureTest() { + A a = new A() { }; + + Flowable.just(a).as((FlowableConverter)ConverterTest.testFlowableConverterCreator()); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void parallelFlowableGenericsSignatureTest() { + A a = new A() { }; + + Flowable.just(a).parallel().as((ParallelFlowableConverter)ConverterTest.testParallelFlowableConverterCreator()); + } + + @Test + public void compositeTest() { + CompositeConverter converter = new CompositeConverter(); + + Flowable.just(1) + .as(converter) + .test() + .assertValue(1); + + Observable.just(1) + .as(converter) + .test() + .assertValue(1); + + Maybe.just(1) + .as(converter) + .test() + .assertValue(1); + + Single.just(1) + .as(converter) + .test() + .assertValue(1); + + Completable.complete() + .as(converter) + .test() + .assertComplete(); + + Flowable.just(1) + .parallel() + .as(converter) + .test() + .assertValue(1); + } + + interface A { } + interface B { } + + private static ObservableConverter, B> testObservableConverterCreator() { + return new ObservableConverter, B>() { + @Override + public B apply(Observable> a) { + return new B() { + }; + } + }; + } + + private static SingleConverter, B> testSingleConverterCreator() { + return new SingleConverter, B>() { + @Override + public B apply(Single> a) { + return new B() { + }; + } + }; + } + + private static MaybeConverter, B> testMaybeConverterCreator() { + return new MaybeConverter, B>() { + @Override + public B apply(Maybe> a) { + return new B() { + }; + } + }; + } + + private static FlowableConverter, B> testFlowableConverterCreator() { + return new FlowableConverter, B>() { + @Override + public B apply(Flowable> a) { + return new B() { + }; + } + }; + } + + private static ParallelFlowableConverter, B> testParallelFlowableConverterCreator() { + return new ParallelFlowableConverter, B>() { + @Override + public B apply(ParallelFlowable> a) { + return new B() { + }; + } + }; + } + + static class CompositeConverter + implements ObservableConverter>, + ParallelFlowableConverter>, + FlowableConverter>, + MaybeConverter>, + SingleConverter>, + CompletableConverter> { + @Override + public Flowable apply(ParallelFlowable upstream) { + return upstream.sequential(); + } + + @Override + public Flowable apply(Completable upstream) { + return upstream.toFlowable(); + } + + @Override + public Observable apply(Flowable upstream) { + return upstream.toObservable(); + } + + @Override + public Flowable apply(Maybe upstream) { + return upstream.toFlowable(); + } + + @Override + public Flowable apply(Observable upstream) { + return upstream.toFlowable(BackpressureStrategy.MISSING); + } + + @Override + public Flowable apply(Single upstream) { + return upstream.toFlowable(); + } + } +} diff --git a/src/test/java/io/reactivex/ParamValidationCheckerTest.java b/src/test/java/io/reactivex/ParamValidationCheckerTest.java index 6fef3b0273..5ad5afbd96 100644 --- a/src/test/java/io/reactivex/ParamValidationCheckerTest.java +++ b/src/test/java/io/reactivex/ParamValidationCheckerTest.java @@ -560,6 +560,46 @@ public void checkParallelFlowable() { defaultValues.put(ParallelFailureHandling.class, ParallelFailureHandling.ERROR); + @SuppressWarnings("rawtypes") + class MixedConverters implements FlowableConverter, ObservableConverter, SingleConverter, + MaybeConverter, CompletableConverter, ParallelFlowableConverter { + + @Override + public Object apply(ParallelFlowable upstream) { + return upstream; + } + + @Override + public Object apply(Completable upstream) { + return upstream; + } + + @Override + public Object apply(Maybe upstream) { + return upstream; + } + + @Override + public Object apply(Single upstream) { + return upstream; + } + + @Override + public Object apply(Observable upstream) { + return upstream; + } + + @Override + public Object apply(Flowable upstream) { + return upstream; + } + } + + MixedConverters mc = new MixedConverters(); + for (Class c : MixedConverters.class.getInterfaces()) { + defaultValues.put(c, mc); + } + // ----------------------------------------------------------------------------------- defaultInstances = new HashMap, List>(); diff --git a/src/test/java/io/reactivex/completable/CompletableTest.java b/src/test/java/io/reactivex/completable/CompletableTest.java index a764d682f1..9b0b914a66 100644 --- a/src/test/java/io/reactivex/completable/CompletableTest.java +++ b/src/test/java/io/reactivex/completable/CompletableTest.java @@ -2783,17 +2783,42 @@ public void timeoutOtherNull() { @Test(timeout = 5000) public void toNormal() { - Flowable flow = normal.completable.to(new Function>() { - @Override - public Flowable apply(Completable c) { - return c.toFlowable(); - } - }); + normal.completable + .to(new Function>() { + @Override + public Flowable apply(Completable c) { + return c.toFlowable(); + } + }) + .test() + .assertComplete() + .assertNoValues(); + } + + @Test(timeout = 5000) + public void asNormal() { + normal.completable + .as(new CompletableConverter>() { + @Override + public Flowable apply(Completable c) { + return c.toFlowable(); + } + }) + .test() + .assertComplete() + .assertNoValues(); + } - flow.blockingForEach(new Consumer() { + @Test + public void as() { + Completable.complete().as(new CompletableConverter>() { @Override - public void accept(Object e) { } - }); + public Flowable apply(Completable v) { + return v.toFlowable(); + } + }) + .test() + .assertComplete(); } @Test(expected = NullPointerException.class) @@ -2801,6 +2826,11 @@ public void toNull() { normal.completable.to(null); } + @Test(expected = NullPointerException.class) + public void asNull() { + normal.completable.as(null); + } + @Test(timeout = 5000) public void toFlowableNormal() { normal.completable.toFlowable().blockingForEach(Functions.emptyConsumer()); diff --git a/src/test/java/io/reactivex/flowable/FlowableNullTests.java b/src/test/java/io/reactivex/flowable/FlowableNullTests.java index 72fc7289d6..fdba369d99 100644 --- a/src/test/java/io/reactivex/flowable/FlowableNullTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableNullTests.java @@ -2351,6 +2351,11 @@ public void toNull() { just1.to(null); } + @Test(expected = NullPointerException.class) + public void asNull() { + just1.as(null); + } + @Test(expected = NullPointerException.class) public void toListNull() { just1.toList(null); diff --git a/src/test/java/io/reactivex/flowable/FlowableTests.java b/src/test/java/io/reactivex/flowable/FlowableTests.java index 29e0d6974a..84c86a8504 100644 --- a/src/test/java/io/reactivex/flowable/FlowableTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableTests.java @@ -20,6 +20,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; +import io.reactivex.Observable; import org.junit.*; import org.mockito.InOrder; import org.reactivestreams.*; @@ -1113,7 +1114,7 @@ public void testForEachWithNull() { public void testExtend() { final TestSubscriber subscriber = new TestSubscriber(); final Object value = new Object(); - Flowable.just(value).to(new Function, Object>() { + Object returned = Flowable.just(value).to(new Function, Object>() { @Override public Object apply(Flowable onSubscribe) { onSubscribe.subscribe(subscriber); @@ -1123,6 +1124,36 @@ public Object apply(Flowable onSubscribe) { return subscriber.values().get(0); } }); + assertSame(returned, value); + } + + @Test + public void testAsExtend() { + final TestSubscriber subscriber = new TestSubscriber(); + final Object value = new Object(); + Object returned = Flowable.just(value).as(new FlowableConverter() { + @Override + public Object apply(Flowable onSubscribe) { + onSubscribe.subscribe(subscriber); + subscriber.assertNoErrors(); + subscriber.assertComplete(); + subscriber.assertValue(value); + return subscriber.values().get(0); + } + }); + assertSame(returned, value); + } + + @Test + public void as() { + Flowable.just(1).as(new FlowableConverter>() { + @Override + public Observable apply(Flowable v) { + return v.toObservable(); + } + }) + .test() + .assertResult(1); } @Test diff --git a/src/test/java/io/reactivex/maybe/MaybeTest.java b/src/test/java/io/reactivex/maybe/MaybeTest.java index e715b37c1e..c493f956b1 100644 --- a/src/test/java/io/reactivex/maybe/MaybeTest.java +++ b/src/test/java/io/reactivex/maybe/MaybeTest.java @@ -381,11 +381,28 @@ public Flowable apply(Maybe v) throws Exception { .assertResult(1); } + @Test + public void as() { + Maybe.just(1).as(new MaybeConverter>() { + @Override + public Flowable apply(Maybe v) { + return v.toFlowable(); + } + }) + .test() + .assertResult(1); + } + @Test(expected = NullPointerException.class) public void toNull() { Maybe.just(1).to(null); } + @Test(expected = NullPointerException.class) + public void asNull() { + Maybe.just(1).as(null); + } + @Test public void compose() { Maybe.just(1).compose(new MaybeTransformer() { diff --git a/src/test/java/io/reactivex/observable/ObservableNullTests.java b/src/test/java/io/reactivex/observable/ObservableNullTests.java index 7f58c9a057..8816bcfe10 100644 --- a/src/test/java/io/reactivex/observable/ObservableNullTests.java +++ b/src/test/java/io/reactivex/observable/ObservableNullTests.java @@ -2408,6 +2408,11 @@ public void toNull() { just1.to(null); } + @Test(expected = NullPointerException.class) + public void asNull() { + just1.as(null); + } + @Test(expected = NullPointerException.class) public void toListNull() { just1.toList(null); diff --git a/src/test/java/io/reactivex/observable/ObservableTest.java b/src/test/java/io/reactivex/observable/ObservableTest.java index 24653d1ff3..fc79edaa9c 100644 --- a/src/test/java/io/reactivex/observable/ObservableTest.java +++ b/src/test/java/io/reactivex/observable/ObservableTest.java @@ -1153,7 +1153,7 @@ public void testForEachWithNull() { public void testExtend() { final TestObserver subscriber = new TestObserver(); final Object value = new Object(); - Observable.just(value).to(new Function, Object>() { + Object returned = Observable.just(value).to(new Function, Object>() { @Override public Object apply(Observable onSubscribe) { onSubscribe.subscribe(subscriber); @@ -1163,6 +1163,36 @@ public Object apply(Observable onSubscribe) { return subscriber.values().get(0); } }); + assertSame(returned, value); + } + + @Test + public void testAsExtend() { + final TestObserver subscriber = new TestObserver(); + final Object value = new Object(); + Object returned = Observable.just(value).as(new ObservableConverter() { + @Override + public Object apply(Observable onSubscribe) { + onSubscribe.subscribe(subscriber); + subscriber.assertNoErrors(); + subscriber.assertComplete(); + subscriber.assertValue(value); + return subscriber.values().get(0); + } + }); + assertSame(returned, value); + } + + @Test + public void as() { + Observable.just(1).as(new ObservableConverter>() { + @Override + public Flowable apply(Observable v) { + return v.toFlowable(BackpressureStrategy.MISSING); + } + }) + .test() + .assertResult(1); } @Test diff --git a/src/test/java/io/reactivex/parallel/ParallelFlowableTest.java b/src/test/java/io/reactivex/parallel/ParallelFlowableTest.java index 4cda73adbc..577d4be1cd 100644 --- a/src/test/java/io/reactivex/parallel/ParallelFlowableTest.java +++ b/src/test/java/io/reactivex/parallel/ParallelFlowableTest.java @@ -1100,6 +1100,20 @@ public Flowable apply(ParallelFlowable pf) throws Exception { .assertResult(1, 2, 3, 4, 5); } + @Test + public void as() { + Flowable.range(1, 5) + .parallel() + .as(new ParallelFlowableConverter>() { + @Override + public Flowable apply(ParallelFlowable pf) { + return pf.sequential(); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + @Test(expected = TestException.class) public void toThrows() { Flowable.range(1, 5) @@ -1112,6 +1126,18 @@ public Flowable apply(ParallelFlowable pf) throws Exception { }); } + @Test(expected = TestException.class) + public void asThrows() { + Flowable.range(1, 5) + .parallel() + .as(new ParallelFlowableConverter>() { + @Override + public Flowable apply(ParallelFlowable pf) { + throw new TestException(); + } + }); + } + @Test public void compose() { Flowable.range(1, 5) diff --git a/src/test/java/io/reactivex/single/SingleNullTests.java b/src/test/java/io/reactivex/single/SingleNullTests.java index 405054243c..374d7ee313 100644 --- a/src/test/java/io/reactivex/single/SingleNullTests.java +++ b/src/test/java/io/reactivex/single/SingleNullTests.java @@ -844,6 +844,11 @@ public void toNull() { just1.to(null); } + @Test(expected = NullPointerException.class) + public void asNull() { + just1.as(null); + } + @Test(expected = NullPointerException.class) public void zipWithNull() { just1.zipWith(null, new BiFunction() { diff --git a/src/test/java/io/reactivex/single/SingleTest.java b/src/test/java/io/reactivex/single/SingleTest.java index 3fc650d276..ac9df2fafb 100644 --- a/src/test/java/io/reactivex/single/SingleTest.java +++ b/src/test/java/io/reactivex/single/SingleTest.java @@ -543,6 +543,18 @@ public Integer apply(Single v) throws Exception { }).intValue()); } + @Test + public void as() { + Single.just(1).as(new SingleConverter>() { + @Override + public Flowable apply(Single v) { + return v.toFlowable(); + } + }) + .test() + .assertResult(1); + } + @Test(expected = NullPointerException.class) public void fromObservableNull() { Single.fromObservable(null); From 85ceeb57683c4c7ba3ad570cf764771e1a585aa3 Mon Sep 17 00:00:00 2001 From: Jake Wharton Date: Tue, 21 Nov 2017 16:19:02 -0500 Subject: [PATCH 042/417] Restore license to correct text. (#5735) This section is a template on how to apply the header and not something that actually should have been changed. --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 7f8ced0d1f..d645695673 100644 --- a/LICENSE +++ b/LICENSE @@ -187,7 +187,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2012 Netflix, Inc. + Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. From fd4377f62dcaf2baa35e3b5fe4c9ddd2bda6bdb3 Mon Sep 17 00:00:00 2001 From: YongJun Kim Date: Wed, 22 Nov 2017 17:36:45 +0900 Subject: [PATCH 043/417] Improved code formatting for README.md (#5737) --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 44470d2ad9..e9c6d500a3 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ Flowable.just("Hello world") RxJava 2 features several base classes you can discover operators on: - - `io.reactivex.Flowable` : 0..N flows, supporting Reactive-Streams and backpressure + - `io.reactivex.Flowable`: 0..N flows, supporting Reactive-Streams and backpressure - `io.reactivex.Observable`: 0..N flows, no backpressure - `io.reactivex.Single`: a flow of exactly 1 item or an error - `io.reactivex.Completable`: a flow without items but only a completion or error signal @@ -133,7 +133,7 @@ Flowable.range(1, 10) .subscribeOn(Schedulers.computation()) .map(w -> w * w) ) -.blockingSubscribe(System.out::println); + .blockingSubscribe(System.out::println); ``` Practically, paralellism in RxJava means running independent flows and merging their results back into a single flow. The operator `flatMap` does this by first mapping each number from 1 to 10 into its own individual `Flowable`, runs them and merges the computed squares. @@ -142,11 +142,11 @@ Starting from 2.0.5, there is an *experimental* operator `parallel()` and type ` ```java Flowable.range(1, 10) -.parallel() -.runOn(Schedulers.computation()) -.map(v -> v * v) -.sequential() -.blockingSubscribe(System.out::println); + .parallel() + .runOn(Schedulers.computation()) + .map(v -> v * v) + .sequential() + .blockingSubscribe(System.out::println); ``` `flatMap` is a powerful operator and helps in a lot of situations. For example, given a service that returns a `Flowable`, we'd like to call another service with values emitted by the first service: @@ -158,8 +158,8 @@ inventorySource.flatMap(inventoryItem -> erp.getDemandAsync(inventoryItem.getId()) .map(demand -> System.out.println("Item " + inventoryItem.getName() + " has demand " + demand)); -) -.subscribe(); + ) + .subscribe(); ``` Note, however, that `flatMap` doesn't guarantee any order and the end result from the inner flows may end up interleaved. There are alternative operators: From ed5cd8bb69bf07bcec9c3e0107aae28d66d8e7a8 Mon Sep 17 00:00:00 2001 From: Dave Moten Date: Wed, 22 Nov 2017 23:13:41 +1100 Subject: [PATCH 044/417] correct javadoc for ConnectableFlowable, GroupedFlowable, FlowableAutoConnect (#5738) --- .../flowables/ConnectableFlowable.java | 32 +++++++++---------- .../reactivex/flowables/GroupedFlowable.java | 6 ++-- .../flowable/FlowableAutoConnect.java | 4 +-- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/main/java/io/reactivex/flowables/ConnectableFlowable.java b/src/main/java/io/reactivex/flowables/ConnectableFlowable.java index 51dad2c11d..c10b07b8e5 100644 --- a/src/main/java/io/reactivex/flowables/ConnectableFlowable.java +++ b/src/main/java/io/reactivex/flowables/ConnectableFlowable.java @@ -25,22 +25,22 @@ import io.reactivex.plugins.RxJavaPlugins; /** - * A {@code ConnectableObservable} resembles an ordinary {@link Flowable}, except that it does not begin + * A {@code ConnectableFlowable} resembles an ordinary {@link Flowable}, except that it does not begin * emitting items when it is subscribed to, but only when its {@link #connect} method is called. In this way you - * can wait for all intended {@link Subscriber}s to {@link Flowable#subscribe} to the {@code Observable} - * before the {@code Observable} begins emitting items. + * can wait for all intended {@link Subscriber}s to {@link Flowable#subscribe} to the {@code Flowable} + * before the {@code Flowable} begins emitting items. *

                * * * @see RxJava Wiki: * Connectable Observable Operators * @param - * the type of items emitted by the {@code ConnectableObservable} + * the type of items emitted by the {@code ConnectableFlowable} */ public abstract class ConnectableFlowable extends Flowable { /** - * Instructs the {@code ConnectableObservable} to begin emitting the items from its underlying + * Instructs the {@code ConnectableFlowable} to begin emitting the items from its underlying * {@link Flowable} to its {@link Subscriber}s. * * @param connection @@ -51,7 +51,7 @@ public abstract class ConnectableFlowable extends Flowable { public abstract void connect(@NonNull Consumer connection); /** - * Instructs the {@code ConnectableObservable} to begin emitting the items from its underlying + * Instructs the {@code ConnectableFlowable} to begin emitting the items from its underlying * {@link Flowable} to its {@link Subscriber}s. *

                * To disconnect from a synchronous source, use the {@link #connect(io.reactivex.functions.Consumer)} method. @@ -66,8 +66,8 @@ public final Disposable connect() { } /** - * Returns an {@code Observable} that stays connected to this {@code ConnectableObservable} as long as there - * is at least one subscription to this {@code ConnectableObservable}. + * Returns a {@code Flowable} that stays connected to this {@code ConnectableFlowable} as long as there + * is at least one subscription to this {@code ConnectableFlowable}. * * @return a {@link Flowable} * @see ReactiveX documentation: RefCount @@ -78,10 +78,10 @@ public Flowable refCount() { } /** - * Returns an Observable that automatically connects to this ConnectableObservable + * Returns a Flowable that automatically connects to this ConnectableFlowable * when the first Subscriber subscribes. * - * @return an Observable that automatically connects to this ConnectableObservable + * @return a Flowable that automatically connects to this ConnectableFlowable * when the first Subscriber subscribes */ @NonNull @@ -89,13 +89,13 @@ public Flowable autoConnect() { return autoConnect(1); } /** - * Returns an Observable that automatically connects to this ConnectableObservable + * Returns a Flowable that automatically connects to this ConnectableFlowable * when the specified number of Subscribers subscribe to it. * * @param numberOfSubscribers the number of subscribers to await before calling connect - * on the ConnectableObservable. A non-positive value indicates + * on the ConnectableFlowable. A non-positive value indicates * an immediate connection. - * @return an Observable that automatically connects to this ConnectableObservable + * @return a Flowable that automatically connects to this ConnectableFlowable * when the specified number of Subscribers subscribe to it */ @NonNull @@ -104,16 +104,16 @@ public Flowable autoConnect(int numberOfSubscribers) { } /** - * Returns an Observable that automatically connects to this ConnectableObservable + * Returns a Flowable that automatically connects to this ConnectableFlowable * when the specified number of Subscribers subscribe to it and calls the * specified callback with the Subscription associated with the established connection. * * @param numberOfSubscribers the number of subscribers to await before calling connect - * on the ConnectableObservable. A non-positive value indicates + * on the ConnectableFlowable. A non-positive value indicates * an immediate connection. * @param connection the callback Consumer that will receive the Subscription representing the * established connection - * @return an Observable that automatically connects to this ConnectableObservable + * @return a Flowable that automatically connects to this ConnectableFlowable * when the specified number of Subscribers subscribe to it and calls the * specified callback with the Subscription associated with the established connection */ diff --git a/src/main/java/io/reactivex/flowables/GroupedFlowable.java b/src/main/java/io/reactivex/flowables/GroupedFlowable.java index 42a51aa03e..d640f4e0e5 100644 --- a/src/main/java/io/reactivex/flowables/GroupedFlowable.java +++ b/src/main/java/io/reactivex/flowables/GroupedFlowable.java @@ -20,7 +20,7 @@ *

                * Note: A {@link GroupedFlowable} will cache the items it is to emit until such time as it * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those - * {@code GroupedObservable}s that do not concern you. Instead, you can signal to them that they + * {@code GroupedFlowable}s that do not concern you. Instead, you can signal to them that they * may discard their buffers by applying an operator like {@link Flowable#take take}{@code (0)} to them. * * @param @@ -43,9 +43,9 @@ protected GroupedFlowable(@Nullable K key) { } /** - * Returns the key that identifies the group of items emitted by this {@code GroupedObservable}. + * Returns the key that identifies the group of items emitted by this {@code GroupedFlowable}. * - * @return the key that the items emitted by this {@code GroupedObservable} were grouped by + * @return the key that the items emitted by this {@code GroupedFlowable} were grouped by */ @Nullable public K getKey() { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAutoConnect.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAutoConnect.java index 65cd6bb6b5..619d551588 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAutoConnect.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAutoConnect.java @@ -23,8 +23,8 @@ import io.reactivex.functions.Consumer; /** - * Wraps a ConnectableObservable and calls its connect() method once - * the specified number of Subscribers have subscribed. + * Wraps a {@link ConnectableFlowable} and calls its {@code connect()} method once + * the specified number of {@link Subscriber}s have subscribed. * * @param the value type of the chain */ From e25be7c048f874814e1f940fa5dcd62724cc95bd Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 24 Nov 2017 08:37:46 +0100 Subject: [PATCH 045/417] 2.x: marbles for Observable all, fromPublisher, zipArray (#5740) --- src/main/java/io/reactivex/Observable.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index bfa3a19e4e..f6f1082a92 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -1898,6 +1898,8 @@ public static Observable fromIterable(Iterable source) { /** * Converts an arbitrary Reactive-Streams Publisher into an Observable. *

                + * + *

                * The {@link Publisher} must follow the * Reactive-Streams specification. * Violating the specification may result in undefined behavior. @@ -4628,7 +4630,7 @@ public static Observable zip( * {@code Function} passed to the method would trigger a {@code ClassCastException}. * *

                - * + * *

                *
                Scheduler:
                *
                {@code zipArray} does not operate by default on a particular {@link Scheduler}.
                @@ -4729,7 +4731,7 @@ public static Observable zipIterable(Iterable - * + * *
                *
                Scheduler:
                *
                {@code all} does not operate by default on a particular {@link Scheduler}.
                From 9564121e09616df909c2d23c4bba62734217bdd6 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Sat, 25 Nov 2017 18:38:02 +0100 Subject: [PATCH 046/417] Check isDisposed before emitting in SingleFromCallable (#5743) Previously SingleFromCallable did not check if the subscriber was unsubscribed before emitting onSuccess or onError. This fixes that behavior and adds tests to SingleFromCallable, CompletableFromCallable, and MaybeFromCallable. Fixes #5742 --- .../operators/single/SingleFromCallable.java | 33 ++- .../CompletableFromCallableTest.java | 65 +++++ .../maybe/MaybeFromCallableTest.java | 58 +++++ .../single/SingleFromCallableTest.java | 228 +++++++++++++++++- 4 files changed, 373 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFromCallable.java b/src/main/java/io/reactivex/internal/operators/single/SingleFromCallable.java index 588e4bc3c1..80c265f6c9 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFromCallable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFromCallable.java @@ -16,8 +16,12 @@ import java.util.concurrent.Callable; import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.Exceptions; import io.reactivex.internal.disposables.EmptyDisposable; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.plugins.RxJavaPlugins; public final class SingleFromCallable extends Single { @@ -28,20 +32,29 @@ public SingleFromCallable(Callable callable) { } @Override - protected void subscribeActual(SingleObserver s) { + protected void subscribeActual(SingleObserver observer) { + Disposable d = Disposables.empty(); + observer.onSubscribe(d); + + if (d.isDisposed()) { + return; + } + T value; - s.onSubscribe(EmptyDisposable.INSTANCE); try { - T v = callable.call(); - if (v != null) { - s.onSuccess(v); + value = ObjectHelper.requireNonNull(callable.call(), "The callable returned a null value"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + if (!d.isDisposed()) { + observer.onError(ex); } else { - s.onError(new NullPointerException("The callable returned a null value")); + RxJavaPlugins.onError(ex); } - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - s.onError(e); + return; } - } + if (!d.isDisposed()) { + observer.onSuccess(value); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java index 64142918bc..5d68b8b59e 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java @@ -15,10 +15,22 @@ import io.reactivex.Completable; import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; + +import io.reactivex.Observable; +import io.reactivex.Observer; +import io.reactivex.TestHelper; +import io.reactivex.disposables.Disposable; +import io.reactivex.observers.TestObserver; +import io.reactivex.schedulers.Schedulers; import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; public class CompletableFromCallableTest { @Test(expected = NullPointerException.class) @@ -100,4 +112,57 @@ public Object call() throws Exception { .test() .assertFailure(UnsupportedOperationException.class); } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotDeliverResultIfSubscriberUnsubscribedBeforeEmission() throws Exception { + Callable func = mock(Callable.class); + + final CountDownLatch funcLatch = new CountDownLatch(1); + final CountDownLatch observerLatch = new CountDownLatch(1); + + when(func.call()).thenAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + observerLatch.countDown(); + + try { + funcLatch.await(); + } catch (InterruptedException e) { + // It's okay, unsubscription causes Thread interruption + + // Restoring interruption status of the Thread + Thread.currentThread().interrupt(); + } + + return "should_not_be_delivered"; + } + }); + + Completable fromCallableObservable = Completable.fromCallable(func); + + Observer observer = TestHelper.mockObserver(); + + TestObserver outer = new TestObserver(observer); + + fromCallableObservable + .subscribeOn(Schedulers.computation()) + .subscribe(outer); + + // Wait until func will be invoked + observerLatch.await(); + + // Unsubscribing before emission + outer.cancel(); + + // Emitting result + funcLatch.countDown(); + + // func must be invoked + verify(func).call(); + + // Observer must not be notified at all + verify(observer).onSubscribe(any(Disposable.class)); + verifyNoMoreInteractions(observer); + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCallableTest.java index 0b8d1df77d..7a56347a32 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCallableTest.java @@ -14,17 +14,22 @@ package io.reactivex.internal.operators.maybe; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; +import io.reactivex.disposables.Disposable; import org.junit.Test; import io.reactivex.*; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; public class MaybeFromCallableTest { @Test(expected = NullPointerException.class) @@ -158,4 +163,57 @@ public Integer call() throws Exception { RxJavaPlugins.reset(); } } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotDeliverResultIfSubscriberUnsubscribedBeforeEmission() throws Exception { + Callable func = mock(Callable.class); + + final CountDownLatch funcLatch = new CountDownLatch(1); + final CountDownLatch observerLatch = new CountDownLatch(1); + + when(func.call()).thenAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + observerLatch.countDown(); + + try { + funcLatch.await(); + } catch (InterruptedException e) { + // It's okay, unsubscription causes Thread interruption + + // Restoring interruption status of the Thread + Thread.currentThread().interrupt(); + } + + return "should_not_be_delivered"; + } + }); + + Maybe fromCallableObservable = Maybe.fromCallable(func); + + Observer observer = TestHelper.mockObserver(); + + TestObserver outer = new TestObserver(observer); + + fromCallableObservable + .subscribeOn(Schedulers.computation()) + .subscribe(outer); + + // Wait until func will be invoked + observerLatch.await(); + + // Unsubscribing before emission + outer.cancel(); + + // Emitting result + funcLatch.countDown(); + + // func must be invoked + verify(func).call(); + + // Observer must not be notified at all + verify(observer).onSubscribe(any(Disposable.class)); + verifyNoMoreInteractions(observer); + } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java index 6c753fafbf..ebd0445358 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java @@ -13,11 +13,31 @@ package io.reactivex.internal.operators.single; +import io.reactivex.Observer; import io.reactivex.Single; -import java.util.concurrent.Callable; +import io.reactivex.SingleObserver; +import io.reactivex.TestHelper; +import io.reactivex.disposables.Disposable; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; public class SingleFromCallableTest { + @Test public void fromCallableValue() { Single.fromCallable(new Callable() { @@ -50,4 +70,210 @@ public void fromCallableNull() { .test() .assertFailureAndMessage(NullPointerException.class, "The callable returned a null value"); } + + @Test + public void fromCallableTwice() { + final AtomicInteger atomicInteger = new AtomicInteger(); + + Callable callable = new Callable() { + @Override + public Integer call() throws Exception { + return atomicInteger.incrementAndGet(); + } + }; + + Single.fromCallable(callable) + .test() + .assertResult(1); + + assertEquals(1, atomicInteger.get()); + + Single.fromCallable(callable) + .test() + .assertResult(2); + + assertEquals(2, atomicInteger.get()); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotInvokeFuncUntilSubscription() throws Exception { + Callable func = mock(Callable.class); + + when(func.call()).thenReturn(new Object()); + + Single fromCallableSingle = Single.fromCallable(func); + + verifyZeroInteractions(func); + + fromCallableSingle.subscribe(); + + verify(func).call(); + } + + + @Test + public void noErrorLoss() throws Exception { + List errors = TestHelper.trackPluginErrors(); + try { + final CountDownLatch cdl1 = new CountDownLatch(1); + final CountDownLatch cdl2 = new CountDownLatch(1); + + TestObserver to = Single.fromCallable(new Callable() { + @Override + public Integer call() throws Exception { + cdl1.countDown(); + cdl2.await(5, TimeUnit.SECONDS); + return 1; + } + }).subscribeOn(Schedulers.single()).test(); + + assertTrue(cdl1.await(5, TimeUnit.SECONDS)); + + to.cancel(); + + int timeout = 10; + + while (timeout-- > 0 && errors.isEmpty()) { + Thread.sleep(100); + } + + TestHelper.assertUndeliverable(errors, 0, InterruptedException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotDeliverResultIfSubscriberUnsubscribedBeforeEmission() throws Exception { + Callable func = mock(Callable.class); + + final CountDownLatch funcLatch = new CountDownLatch(1); + final CountDownLatch observerLatch = new CountDownLatch(1); + + when(func.call()).thenAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + observerLatch.countDown(); + + try { + funcLatch.await(); + } catch (InterruptedException e) { + // It's okay, unsubscription causes Thread interruption + + // Restoring interruption status of the Thread + Thread.currentThread().interrupt(); + } + + return "should_not_be_delivered"; + } + }); + + Single fromCallableObservable = Single.fromCallable(func); + + Observer observer = TestHelper.mockObserver(); + + TestObserver outer = new TestObserver(observer); + + fromCallableObservable + .subscribeOn(Schedulers.computation()) + .subscribe(outer); + + // Wait until func will be invoked + observerLatch.await(); + + // Unsubscribing before emission + outer.cancel(); + + // Emitting result + funcLatch.countDown(); + + // func must be invoked + verify(func).call(); + + // Observer must not be notified at all + verify(observer).onSubscribe(any(Disposable.class)); + verifyNoMoreInteractions(observer); + } + + @Test + public void shouldAllowToThrowCheckedException() { + final Exception checkedException = new Exception("test exception"); + + Single fromCallableObservable = Single.fromCallable(new Callable() { + @Override + public Object call() throws Exception { + throw checkedException; + } + }); + + SingleObserver observer = TestHelper.mockSingleObserver(); + + fromCallableObservable.subscribe(observer); + + verify(observer).onSubscribe(any(Disposable.class)); + verify(observer).onError(checkedException); + verifyNoMoreInteractions(observer); + } + + @Test + public void disposedOnArrival() { + final int[] count = { 0 }; + Single.fromCallable(new Callable() { + @Override + public Object call() throws Exception { + count[0]++; + return 1; + } + }) + .test(true) + .assertEmpty(); + + assertEquals(0, count[0]); + } + + @Test + public void disposedOnCall() { + final TestObserver to = new TestObserver(); + + Single.fromCallable(new Callable() { + @Override + public Integer call() throws Exception { + to.cancel(); + return 1; + } + }) + .subscribe(to); + + to.assertEmpty(); + } + + @Test + public void toObservableTake() { + Single.fromCallable(new Callable() { + @Override + public Object call() throws Exception { + return 1; + } + }) + .toObservable() + .take(1) + .test() + .assertResult(1); + } + + @Test + public void toObservableAndBack() { + Single.fromCallable(new Callable() { + @Override + public Integer call() throws Exception { + return 1; + } + }) + .toObservable() + .singleOrError() + .test() + .assertResult(1); + } } From c9af67b62a1b7b55c3f28b52fb230cc7e378b0d6 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 27 Nov 2017 09:46:47 +0100 Subject: [PATCH 047/417] Release 2.1.7 --- CHANGES.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 1eb4a6a13f..5a88033962 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,32 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.7 - November 27, 2017 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.7%7C)) + +#### API changes + +- [Pull 5729](https://github.com/ReactiveX/RxJava/pull/5729): Implement `as()` operator on the 6 base classes - similar to `to()` but dedicated functional interface for each base class instead of just `Function`. + +#### Documentation changes + +- [Pull 5706](https://github.com/ReactiveX/RxJava/pull/5706): Remove mentions of Main thread from `Schedulers.single()` JavaDoc. +- [Pull 5709](https://github.com/ReactiveX/RxJava/pull/5709): Improve JavaDocs of `flatMapSingle` and `flatMapMaybe`. +- [Pull 5713](https://github.com/ReactiveX/RxJava/pull/5713): Add `BaseTestConsumer` `values()` and `errors()` thread-safety clarifications. +- [Pull 5717](https://github.com/ReactiveX/RxJava/pull/5717): Add period to custom scheduler use sentences in `Schedulers`. +- [Pull 5718](https://github.com/ReactiveX/RxJava/pull/5718): Add a sentence to documentation of `take()` operator about the thread `onComplete` may get signaled. +- [Pull 5738](https://github.com/ReactiveX/RxJava/pull/5738): Correct JavaDoc for `ConnectableFlowable`, `GroupedFlowable`, `FlowableAutoConnect`. +- [Pull 5740](https://github.com/ReactiveX/RxJava/pull/5740): Marbles for `Observable` `all`, `fromPublisher`, `zipArray`. + +#### Bugfixes + +- [Pull 5695](https://github.com/ReactiveX/RxJava/pull/5695): Fix `Completable.concat` to use replace (don't dispose old). +- [Pull 5715](https://github.com/ReactiveX/RxJava/pull/5715): Distinguish between sync and async dispose in `ScheduledRunnable`. +- [Pull 5743](https://github.com/ReactiveX/RxJava/pull/5743): Check `isDisposed` before emitting in `SingleFromCallable`. + +#### Other + +- [Pull 5723](https://github.com/ReactiveX/RxJava/pull/5723): Remove duplicate nullity check line in `toMap`. + ### Version 2.1.6 - October 27, 2017 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.6%7C)) #### API changes From d2fe631f3f05dd12eac2b8e53d6525e9acb474a3 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 27 Nov 2017 23:12:43 +0100 Subject: [PATCH 048/417] 2.x: API to get distinct Workers from some Schedulers (#5741) --- .../operators/parallel/ParallelRunOn.java | 54 +++++-- .../schedulers/ComputationScheduler.java | 36 ++++- .../SchedulerMultiWorkerSupport.java | 52 ++++++ .../SchedulerMultiWorkerSupportTest.java | 149 ++++++++++++++++++ 4 files changed, 272 insertions(+), 19 deletions(-) create mode 100644 src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java create mode 100644 src/test/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupportTest.java diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelRunOn.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelRunOn.java index 3281a20b9d..bf52698359 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelRunOn.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelRunOn.java @@ -22,6 +22,8 @@ import io.reactivex.exceptions.MissingBackpressureException; import io.reactivex.internal.fuseable.ConditionalSubscriber; import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.internal.schedulers.SchedulerMultiWorkerSupport; +import io.reactivex.internal.schedulers.SchedulerMultiWorkerSupport.WorkerCallback; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.BackpressureHelper; import io.reactivex.parallel.ParallelFlowable; @@ -47,7 +49,7 @@ public ParallelRunOn(ParallelFlowable parent, } @Override - public void subscribe(Subscriber[] subscribers) { + public void subscribe(final Subscriber[] subscribers) { if (!validate(subscribers)) { return; } @@ -55,26 +57,50 @@ public void subscribe(Subscriber[] subscribers) { int n = subscribers.length; @SuppressWarnings("unchecked") - Subscriber[] parents = new Subscriber[n]; + final Subscriber[] parents = new Subscriber[n]; + + if (scheduler instanceof SchedulerMultiWorkerSupport) { + SchedulerMultiWorkerSupport multiworker = (SchedulerMultiWorkerSupport) scheduler; + multiworker.createWorkers(n, new MultiWorkerCallback(subscribers, parents)); + } else { + for (int i = 0; i < n; i++) { + createSubscriber(i, subscribers, parents, scheduler.createWorker()); + } + } + source.subscribe(parents); + } - int prefetch = this.prefetch; + void createSubscriber(int i, Subscriber[] subscribers, + Subscriber[] parents, Scheduler.Worker worker) { - for (int i = 0; i < n; i++) { - Subscriber a = subscribers[i]; + Subscriber a = subscribers[i]; - Worker w = scheduler.createWorker(); - SpscArrayQueue q = new SpscArrayQueue(prefetch); + SpscArrayQueue q = new SpscArrayQueue(prefetch); - if (a instanceof ConditionalSubscriber) { - parents[i] = new RunOnConditionalSubscriber((ConditionalSubscriber)a, prefetch, q, w); - } else { - parents[i] = new RunOnSubscriber(a, prefetch, q, w); - } + if (a instanceof ConditionalSubscriber) { + parents[i] = new RunOnConditionalSubscriber((ConditionalSubscriber)a, prefetch, q, worker); + } else { + parents[i] = new RunOnSubscriber(a, prefetch, q, worker); } - - source.subscribe(parents); } + final class MultiWorkerCallback implements WorkerCallback { + + final Subscriber[] subscribers; + + final Subscriber[] parents; + + MultiWorkerCallback(Subscriber[] subscribers, + Subscriber[] parents) { + this.subscribers = subscribers; + this.parents = parents; + } + + @Override + public void onWorker(int i, Worker w) { + createSubscriber(i, subscribers, parents, w); + } + } @Override public int parallelism() { diff --git a/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java b/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java index f2a4dcf7d3..dda22b9255 100644 --- a/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java @@ -15,19 +15,20 @@ */ package io.reactivex.internal.schedulers; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicReference; + import io.reactivex.Scheduler; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.*; import io.reactivex.internal.disposables.*; - -import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicReference; +import io.reactivex.internal.functions.ObjectHelper; /** * Holds a fixed pool of worker threads and assigns them * to requested Scheduler.Workers in a round-robin fashion. */ -public final class ComputationScheduler extends Scheduler { +public final class ComputationScheduler extends Scheduler implements SchedulerMultiWorkerSupport { /** This will indicate no pool is active. */ static final FixedSchedulerPool NONE; /** Manages a fixed number of workers. */ @@ -67,7 +68,7 @@ static int cap(int cpuCount, int paramThreads) { return paramThreads <= 0 || paramThreads > cpuCount ? cpuCount : paramThreads; } - static final class FixedSchedulerPool { + static final class FixedSchedulerPool implements SchedulerMultiWorkerSupport { final int cores; final PoolWorker[] eventLoops; @@ -96,6 +97,25 @@ public void shutdown() { w.dispose(); } } + + @Override + public void createWorkers(int number, WorkerCallback callback) { + int c = cores; + if (c == 0) { + for (int i = 0; i < number; i++) { + callback.onWorker(i, SHUTDOWN_WORKER); + } + } else { + int index = (int)n % c; + for (int i = 0; i < number; i++) { + callback.onWorker(i, new EventLoopWorker(eventLoops[index])); + if (++index == c) { + index = 0; + } + } + n = index; + } + } } /** @@ -125,6 +145,12 @@ public Worker createWorker() { return new EventLoopWorker(pool.get().getEventLoop()); } + @Override + public void createWorkers(int number, WorkerCallback callback) { + ObjectHelper.verifyPositive(number, "number > 0 required"); + pool.get().createWorkers(number, callback); + } + @NonNull @Override public Disposable scheduleDirect(@NonNull Runnable run, long delay, TimeUnit unit) { diff --git a/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java b/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java new file mode 100644 index 0000000000..d2c211a815 --- /dev/null +++ b/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.schedulers; + +import io.reactivex.Scheduler; +import io.reactivex.annotations.*; + +/** + * Allows retrieving multiple workers from the implementing + * {@link io.reactivex.Scheduler} in a way that when asking for + * at most the parallelism level of the Scheduler, those + * {@link io.reactivex.Scheduler.Worker} instances will be running + * with different backing threads. + * + * @since 2.1.7 - experimental + */ +@Experimental +public interface SchedulerMultiWorkerSupport { + + /** + * Creates the given number of {@link io.reactivex.Scheduler.Worker} instances + * that are possibly backed by distinct threads + * and calls the specified {@code Consumer} with them. + * @param number the number of workers to create, positive + * @param callback the callback to send worker instances to + */ + void createWorkers(int number, @NonNull WorkerCallback callback); + + /** + * The callback interface for the {@link SchedulerMultiWorkerSupport#createWorkers(int, WorkerCallback)} + * method. + */ + interface WorkerCallback { + /** + * Called with the Worker index and instance. + * @param index the worker index, zero-based + * @param worker the worker instance + */ + void onWorker(int index, @NonNull Scheduler.Worker worker); + } +} diff --git a/src/test/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupportTest.java b/src/test/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupportTest.java new file mode 100644 index 0000000000..d77dd8786e --- /dev/null +++ b/src/test/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupportTest.java @@ -0,0 +1,149 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.schedulers; + +import static org.junit.Assert.*; + +import java.util.*; +import java.util.concurrent.*; + +import org.junit.Test; + +import io.reactivex.Scheduler.Worker; +import io.reactivex.TestHelper; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.internal.schedulers.SchedulerMultiWorkerSupport.WorkerCallback; +import io.reactivex.schedulers.Schedulers; + +public class SchedulerMultiWorkerSupportTest { + + final int max = ComputationScheduler.MAX_THREADS; + + @Test + public void moreThanMaxWorkers() { + final List list = new ArrayList(); + + SchedulerMultiWorkerSupport mws = (SchedulerMultiWorkerSupport)Schedulers.computation(); + + mws.createWorkers(max * 2, new WorkerCallback() { + @Override + public void onWorker(int i, Worker w) { + list.add(w); + } + }); + + assertEquals(max * 2, list.size()); + } + + @Test + public void getShutdownWorkers() { + final List list = new ArrayList(); + + ComputationScheduler.NONE.createWorkers(max * 2, new WorkerCallback() { + @Override + public void onWorker(int i, Worker w) { + list.add(w); + } + }); + + assertEquals(max * 2, list.size()); + + for (Worker w : list) { + assertEquals(ComputationScheduler.SHUTDOWN_WORKER, w); + } + } + + @Test + public void distinctThreads() throws Exception { + for (int i = 0; i < 1000; i++) { + + final CompositeDisposable composite = new CompositeDisposable(); + + try { + final CountDownLatch cdl = new CountDownLatch(max * 2); + + final Set threads1 = Collections.synchronizedSet(new HashSet()); + + final Set threads2 = Collections.synchronizedSet(new HashSet()); + + Runnable parallel1 = new Runnable() { + @Override + public void run() { + final List list1 = new ArrayList(); + + SchedulerMultiWorkerSupport mws = (SchedulerMultiWorkerSupport)Schedulers.computation(); + + mws.createWorkers(max, new WorkerCallback() { + @Override + public void onWorker(int i, Worker w) { + list1.add(w); + composite.add(w); + } + }); + + Runnable run = new Runnable() { + @Override + public void run() { + threads1.add(Thread.currentThread().getName()); + cdl.countDown(); + } + }; + + for (Worker w : list1) { + w.schedule(run); + } + } + }; + + Runnable parallel2 = new Runnable() { + @Override + public void run() { + final List list2 = new ArrayList(); + + SchedulerMultiWorkerSupport mws = (SchedulerMultiWorkerSupport)Schedulers.computation(); + + mws.createWorkers(max, new WorkerCallback() { + @Override + public void onWorker(int i, Worker w) { + list2.add(w); + composite.add(w); + } + }); + + Runnable run = new Runnable() { + @Override + public void run() { + threads2.add(Thread.currentThread().getName()); + cdl.countDown(); + } + }; + + for (Worker w : list2) { + w.schedule(run); + } + } + }; + + TestHelper.race(parallel1, parallel2); + + assertTrue(cdl.await(5, TimeUnit.SECONDS)); + + assertEquals(threads1.toString(), max, threads1.size()); + assertEquals(threads2.toString(), max, threads2.size()); + } finally { + composite.dispose(); + } + } + } +} From 5f1542be404517a6deda109dd4493cdf5197a3f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Karnok?= Date: Mon, 27 Nov 2017 23:31:46 +0100 Subject: [PATCH 049/417] 2.x: SchedulerMultiWorkerSupport version fix to 2.1.8 - exp --- .../internal/schedulers/SchedulerMultiWorkerSupport.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java b/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java index d2c211a815..31f7ed2a33 100644 --- a/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java +++ b/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java @@ -23,7 +23,7 @@ * {@link io.reactivex.Scheduler.Worker} instances will be running * with different backing threads. * - * @since 2.1.7 - experimental + * @since 2.1.8 - experimental */ @Experimental public interface SchedulerMultiWorkerSupport { From 860e39ea2de222ef65992bcc5a6b04e752c2e08f Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 30 Nov 2017 00:14:00 +0100 Subject: [PATCH 050/417] 2.x: improve wording and links in package-infos + remove unused imports (#5746) * 2.x: improve wording and links in package-infos * Remove unused imports --- src/main/java/io/reactivex/flowables/package-info.java | 5 +++-- .../internal/operators/single/SingleFromCallable.java | 1 - src/main/java/io/reactivex/observables/package-info.java | 5 +++-- src/main/java/io/reactivex/package-info.java | 4 +++- src/main/java/io/reactivex/parallel/package-info.java | 4 ++-- src/main/java/io/reactivex/plugins/package-info.java | 4 ++-- .../operators/completable/CompletableFromCallableTest.java | 1 - 7 files changed, 13 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/reactivex/flowables/package-info.java b/src/main/java/io/reactivex/flowables/package-info.java index 6f229e7e37..66f3f48b62 100644 --- a/src/main/java/io/reactivex/flowables/package-info.java +++ b/src/main/java/io/reactivex/flowables/package-info.java @@ -15,7 +15,8 @@ */ /** - * Classes supporting the Flowable base reactive class: connectable and grouped - * flowables. + * Classes supporting the Flowable base reactive class: + * {@link io.reactivex.flowables.ConnectableFlowable} and + * {@link io.reactivex.flowables.GroupedFlowable}. */ package io.reactivex.flowables; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFromCallable.java b/src/main/java/io/reactivex/internal/operators/single/SingleFromCallable.java index 80c265f6c9..2b5ff36a98 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFromCallable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFromCallable.java @@ -19,7 +19,6 @@ import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.Exceptions; -import io.reactivex.internal.disposables.EmptyDisposable; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.plugins.RxJavaPlugins; diff --git a/src/main/java/io/reactivex/observables/package-info.java b/src/main/java/io/reactivex/observables/package-info.java index d5fce46cc2..959200b525 100644 --- a/src/main/java/io/reactivex/observables/package-info.java +++ b/src/main/java/io/reactivex/observables/package-info.java @@ -15,7 +15,8 @@ */ /** - * Classes supporting the Observable base reactive class: connectable and grouped - * observables. + * Classes supporting the Observable base reactive class: + * {@link io.reactivex.observable.ConnectableObservable} and + * {@link io.reactivex.observable.GroupedObservable}. */ package io.reactivex.observables; diff --git a/src/main/java/io/reactivex/package-info.java b/src/main/java/io/reactivex/package-info.java index 0df7f0aaf5..7d78294b6d 100644 --- a/src/main/java/io/reactivex/package-info.java +++ b/src/main/java/io/reactivex/package-info.java @@ -14,7 +14,9 @@ * limitations under the License. */ /** - * Base reactive classes: Flowable, Observable, Single, Maybe and Completable; base reactive consumers; + * Base reactive classes: {@link io.reactivex.Flowable}, {@link io.reactivex.Observable}, + * {@link io.reactivex.Single}, {@link io.reactivex.Maybe} and + * {@link io.reactivex.Completable}; base reactive consumers; * other common base interfaces. * *

                A library that enables subscribing to and composing asynchronous events and diff --git a/src/main/java/io/reactivex/parallel/package-info.java b/src/main/java/io/reactivex/parallel/package-info.java index 3e4105ea51..e7ee2576eb 100644 --- a/src/main/java/io/reactivex/parallel/package-info.java +++ b/src/main/java/io/reactivex/parallel/package-info.java @@ -15,7 +15,7 @@ */ /** - * Base type for the parallel type offering a sub-DSL for working with Flowable items - * in parallel. + * Contains the base type {@link io.reactivex.parallel.ParallelFlowable}, + * a sub-DSL for working with {@link io.reactivex.Flowable} sequences in parallel. */ package io.reactivex.parallel; \ No newline at end of file diff --git a/src/main/java/io/reactivex/plugins/package-info.java b/src/main/java/io/reactivex/plugins/package-info.java index ad90c82534..3031129387 100644 --- a/src/main/java/io/reactivex/plugins/package-info.java +++ b/src/main/java/io/reactivex/plugins/package-info.java @@ -15,7 +15,7 @@ */ /** - * Callback types and a central plugin handler class to hook into the lifecycle - * of the base reactive types and schedulers. + * Contains the central plugin handler {@link io.reactivex.plugins.RxJavaPlugins} + * class to hook into the lifecycle of the base reactive types and schedulers. */ package io.reactivex.plugins; diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java index 5d68b8b59e..cdd987c8aa 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java @@ -18,7 +18,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; -import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.TestHelper; import io.reactivex.disposables.Disposable; From d20b17e7741d9e77d8d45059e0d96823cacc8118 Mon Sep 17 00:00:00 2001 From: "Artem Zinnatullin :slowpoke" Date: Thu, 30 Nov 2017 00:35:07 -0800 Subject: [PATCH 051/417] 2.x: Fix TrampolineScheduler not calling RxJavaPlugins.onSchedule(), add tests for all schedulers. (#5747) --- .../schedulers/TrampolineScheduler.java | 4 +- .../schedulers/AbstractSchedulerTests.java | 72 +++++++++++++++++++ 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/internal/schedulers/TrampolineScheduler.java b/src/main/java/io/reactivex/internal/schedulers/TrampolineScheduler.java index 2f9a595f6d..20421072e5 100644 --- a/src/main/java/io/reactivex/internal/schedulers/TrampolineScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/TrampolineScheduler.java @@ -49,7 +49,7 @@ public Worker createWorker() { @NonNull @Override public Disposable scheduleDirect(@NonNull Runnable run) { - run.run(); + RxJavaPlugins.onSchedule(run).run(); return EmptyDisposable.INSTANCE; } @@ -58,7 +58,7 @@ public Disposable scheduleDirect(@NonNull Runnable run) { public Disposable scheduleDirect(@NonNull Runnable run, long delay, TimeUnit unit) { try { unit.sleep(delay); - run.run(); + RxJavaPlugins.onSchedule(run).run(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); RxJavaPlugins.onError(ex); diff --git a/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java b/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java index 74c2ecdb0d..b81036a7e0 100644 --- a/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java +++ b/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java @@ -20,6 +20,8 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.plugins.RxJavaPlugins; import org.junit.Test; import org.mockito.InOrder; import org.mockito.invocation.InvocationOnMock; @@ -41,6 +43,7 @@ public abstract class AbstractSchedulerTests { /** * The scheduler to test. + * * @return the Scheduler instance */ protected abstract Scheduler getScheduler(); @@ -576,6 +579,7 @@ public void schedulePeriodicallyDirectZeroPeriod() throws Exception { try { sd.replace(s.schedulePeriodicallyDirect(new Runnable() { int count; + @Override public void run() { if (++count == 10) { @@ -610,6 +614,7 @@ public void schedulePeriodicallyZeroPeriod() throws Exception { try { sd.replace(w.schedulePeriodically(new Runnable() { int count; + @Override public void run() { if (++count == 10) { @@ -626,4 +631,71 @@ public void run() { } } } + + private void assertRunnableDecorated(Runnable scheduleCall) throws InterruptedException { + try { + final CountDownLatch decoratedCalled = new CountDownLatch(1); + + RxJavaPlugins.setScheduleHandler(new Function() { + @Override + public Runnable apply(final Runnable actual) throws Exception { + return new Runnable() { + @Override + public void run() { + decoratedCalled.countDown(); + actual.run(); + } + }; + } + }); + + scheduleCall.run(); + + assertTrue(decoratedCalled.await(5, TimeUnit.SECONDS)); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test(timeout = 6000) + public void scheduleDirectDecoratesRunnable() throws InterruptedException { + assertRunnableDecorated(new Runnable() { + @Override + public void run() { + getScheduler().scheduleDirect(Functions.EMPTY_RUNNABLE); + } + }); + } + + @Test(timeout = 6000) + public void scheduleDirectWithDelayDecoratesRunnable() throws InterruptedException { + assertRunnableDecorated(new Runnable() { + @Override + public void run() { + getScheduler().scheduleDirect(Functions.EMPTY_RUNNABLE, 1, TimeUnit.MILLISECONDS); + } + }); + } + + @Test(timeout = 6000) + public void schedulePeriodicallyDirectDecoratesRunnable() throws InterruptedException { + final Scheduler scheduler = getScheduler(); + if (scheduler instanceof TrampolineScheduler) { + // Can't properly stop a trampolined periodic task. + return; + } + + final AtomicReference disposable = new AtomicReference(); + + try { + assertRunnableDecorated(new Runnable() { + @Override + public void run() { + disposable.set(scheduler.schedulePeriodicallyDirect(Functions.EMPTY_RUNNABLE, 1, 10000, TimeUnit.MILLISECONDS)); + } + }); + } finally { + disposable.get().dispose(); + } + } } From 30905fc4264d8aa3d7e8db0acab4c39cf8e7de7b Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 30 Nov 2017 09:49:08 +0100 Subject: [PATCH 052/417] 2.x: add/update Observable marbles 11/28 (#5745) --- src/main/java/io/reactivex/Observable.java | 26 ++++++++++++++++------ 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index f6f1082a92..fac04781e7 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -4827,6 +4827,8 @@ public final R as(@NonNull ObservableConverter converter) { /** * Returns the first item emitted by this {@code Observable}, or throws * {@code NoSuchElementException} if it emits no items. + *

                + * *

                *
                Scheduler:
                *
                {@code blockingFirst} does not operate by default on a particular {@link Scheduler}.
                @@ -4852,6 +4854,8 @@ public final T blockingFirst() { /** * Returns the first item emitted by this {@code Observable}, or a default value if it emits no * items. + *

                + * *

                *
                Scheduler:
                *
                {@code blockingFirst} does not operate by default on a particular {@link Scheduler}.
                @@ -5124,7 +5128,7 @@ public final T blockingSingle(T defaultItem) { *

                * If the {@code Observable} may emit more than one item, use {@code Observable.toList().toFuture()}. *

                - * + * *

                *
                Scheduler:
                *
                {@code toFuture} does not operate by default on a particular {@link Scheduler}.
                @@ -5141,6 +5145,8 @@ public final Future toFuture() { /** * Runs the source observable to a terminal event, ignoring any values and rethrowing any exception. + *

                + * *

                *
                Scheduler:
                *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                @@ -5155,6 +5161,8 @@ public final void blockingSubscribe() { /** * Subscribes to the source and calls the given callbacks on the current thread. *

                + * + *

                * If the Observable emits an error, it is wrapped into an * {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} * and routed to the RxJavaPlugins.onError handler. @@ -5172,6 +5180,8 @@ public final void blockingSubscribe(Consumer onNext) { /** * Subscribes to the source and calls the given callbacks on the current thread. + *

                + * *

                *
                Scheduler:
                *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                @@ -5188,6 +5198,8 @@ public final void blockingSubscribe(Consumer onNext, Consumeron the current thread. + *

                + * *

                *
                Scheduler:
                *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                @@ -5991,7 +6003,7 @@ public final Single collect(Callable initialValueSupplier, B * Collects items emitted by the source ObservableSource into a single mutable data structure and returns * a Single that emits this structure. *

                - * + * *

                * This is a simplified version of {@code reduce} that does not need to return the state on each pass. *

                @@ -7053,7 +7065,7 @@ public final Observable doFinally(Action onFinally) { * If the action throws a runtime exception, that exception is rethrown by the {@code dispose()} call, * sometimes as a {@code CompositeException} if there were multiple exceptions along the way. *

                - * + * *

                *
                Scheduler:
                *
                {@code doOnDispose} does not operate by default on a particular {@link Scheduler}.
                @@ -7074,7 +7086,7 @@ public final Observable doOnDispose(Action onDispose) { /** * Modifies the source ObservableSource so that it invokes an action when it calls {@code onComplete}. *

                - * + * *

                *
                Scheduler:
                *
                {@code doOnComplete} does not operate by default on a particular {@link Scheduler}.
                @@ -7177,7 +7189,7 @@ public final Observable doOnEach(final Observer observer) { * In case the {@code onError} action throws, the downstream will receive a composite exception containing * the original exception and the exception thrown by {@code onError}. *

                - * + * *

                *
                Scheduler:
                *
                {@code doOnError} does not operate by default on a particular {@link Scheduler}.
                @@ -7198,7 +7210,7 @@ public final Observable doOnError(Consumer onError) { * Calls the appropriate onXXX method (shared between all Observer) for the lifecycle events of * the sequence (subscription, cancellation, requesting). *

                - * + * *

                *
                Scheduler:
                *
                {@code doOnLifecycle} does not operate by default on a particular {@link Scheduler}.
                @@ -7222,7 +7234,7 @@ public final Observable doOnLifecycle(final Consumer onSu /** * Modifies the source ObservableSource so that it invokes an action when it calls {@code onNext}. *

                - * + * *

                *
                Scheduler:
                *
                {@code doOnNext} does not operate by default on a particular {@link Scheduler}.
                From 4d2e8212ac97f0c6c380802cec92764e8d8bbde1 Mon Sep 17 00:00:00 2001 From: lukaszguz Date: Mon, 4 Dec 2017 13:12:12 +0100 Subject: [PATCH 053/417] 2.x: RxJavaPlugins unwrapRunnable (#5734) * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable-javadoc * 2.x: RxJavaPlugins unwrapRunnable-Enhancement and test coverage * 2.x: RxJavaPlugins unwrapRunnable-Enhancement and test coverage * 2.x: RxJavaPlugins unwrapRunnable-Enhancement and test coverage * 2.x: RxJavaPlugins unwrapRunnable-Enhancement and test coverage * 2.x: RxJavaPlugins unwrapRunnable-Enhancement and test coverage * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable * 2.x: RxJavaPlugins unwrapRunnable --- src/main/java/io/reactivex/Scheduler.java | 36 ++++++++--- .../schedulers/AbstractDirectTask.java | 8 ++- .../schedulers/ExecutorScheduler.java | 12 +++- .../SchedulerRunnableIntrospection.java | 35 +++++++++++ .../schedulers/AbstractSchedulerTests.java | 46 +++++++++++++- .../schedulers/ExecutorSchedulerTest.java | 18 ++++++ .../reactivex/schedulers/SchedulerTest.java | 62 +++++++++++++++++++ 7 files changed, 203 insertions(+), 14 deletions(-) create mode 100644 src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java diff --git a/src/main/java/io/reactivex/Scheduler.java b/src/main/java/io/reactivex/Scheduler.java index 136d20d842..724974cbbb 100644 --- a/src/main/java/io/reactivex/Scheduler.java +++ b/src/main/java/io/reactivex/Scheduler.java @@ -13,8 +13,6 @@ package io.reactivex; -import java.util.concurrent.TimeUnit; - import io.reactivex.annotations.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; @@ -23,6 +21,9 @@ import io.reactivex.internal.schedulers.*; import io.reactivex.internal.util.ExceptionHelper; import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.SchedulerRunnableIntrospection; + +import java.util.concurrent.TimeUnit; /** * A {@code Scheduler} is an object that specifies an API for scheduling @@ -197,7 +198,7 @@ public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initial *

                * Limit the amount concurrency two at a time without creating a new fix * size thread pool: - * + * *

                      * Scheduler limitScheduler = Schedulers.computation().when(workers -> {
                      *  // use merge max concurrent to limit the number of concurrent
                @@ -215,7 +216,7 @@ public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initial
                      * {@link Flowable#zip(org.reactivestreams.Publisher, org.reactivestreams.Publisher, io.reactivex.functions.BiFunction)} where
                      * subscribing to the first {@link Flowable} could deadlock the
                      * subscription to the second.
                -     * 
                +     *
                      * 
                      * Scheduler limitScheduler = Schedulers.computation().when(workers -> {
                      *  // use merge max concurrent to limit the number of concurrent
                @@ -223,12 +224,12 @@ public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initial
                      *  return Completable.merge(Flowable.merge(workers, 2));
                      * });
                      * 
                - * + * * Slowing down the rate to no more than than 1 a second. This suffers from * the same problem as the one above I could find an {@link Flowable} * operator that limits the rate without dropping the values (aka leaky * bucket algorithm). - * + * *
                      * Scheduler slowScheduler = Schedulers.computation().when(workers -> {
                      *  // use concatenate to make each worker happen one at a time.
                @@ -238,7 +239,7 @@ public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initial
                      *  }));
                      * });
                      * 
                - * + * *

                History: 2.0.1 - experimental * @param a Scheduler and a Subscription * @param combine the function that takes a two-level nested Flowable sequence of a Completable and returns @@ -347,7 +348,7 @@ public long now(@NonNull TimeUnit unit) { * Holds state and logic to calculate when the next delayed invocation * of this task has to happen (accounting for clock drifts). */ - final class PeriodicTask implements Runnable { + final class PeriodicTask implements Runnable, SchedulerRunnableIntrospection { @NonNull final Runnable decoratedRun; @NonNull @@ -393,11 +394,16 @@ public void run() { sd.replace(schedule(this, delay, TimeUnit.NANOSECONDS)); } } + + @Override + public Runnable getWrappedRunnable() { + return this.decoratedRun; + } } } static class PeriodicDirectTask - implements Runnable, Disposable { + implements Disposable, Runnable, SchedulerRunnableIntrospection { final Runnable run; @NonNull final Worker worker; @@ -432,9 +438,14 @@ public void dispose() { public boolean isDisposed() { return disposed; } + + @Override + public Runnable getWrappedRunnable() { + return run; + } } - static final class DisposeTask implements Runnable, Disposable { + static final class DisposeTask implements Disposable, Runnable, SchedulerRunnableIntrospection { final Runnable decoratedRun; final Worker w; @@ -469,5 +480,10 @@ public void dispose() { public boolean isDisposed() { return w.isDisposed(); } + + @Override + public Runnable getWrappedRunnable() { + return this.decoratedRun; + } } } diff --git a/src/main/java/io/reactivex/internal/schedulers/AbstractDirectTask.java b/src/main/java/io/reactivex/internal/schedulers/AbstractDirectTask.java index cd278fe590..2bf3c454f4 100644 --- a/src/main/java/io/reactivex/internal/schedulers/AbstractDirectTask.java +++ b/src/main/java/io/reactivex/internal/schedulers/AbstractDirectTask.java @@ -21,6 +21,7 @@ import io.reactivex.disposables.Disposable; import io.reactivex.internal.functions.Functions; +import io.reactivex.schedulers.SchedulerRunnableIntrospection; /** * Base functionality for direct tasks that manage a runnable and cancellation/completion. @@ -28,7 +29,7 @@ */ abstract class AbstractDirectTask extends AtomicReference> -implements Disposable { +implements Disposable, SchedulerRunnableIntrospection { private static final long serialVersionUID = 1811839108042568751L; @@ -77,4 +78,9 @@ public final void setFuture(Future future) { } } } + + @Override + public Runnable getWrappedRunnable() { + return runnable; + } } diff --git a/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java b/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java index e050fed1f7..b18e18d16d 100644 --- a/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java @@ -20,10 +20,11 @@ import io.reactivex.annotations.NonNull; import io.reactivex.disposables.*; import io.reactivex.internal.disposables.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.internal.queue.MpscLinkedQueue; import io.reactivex.internal.schedulers.ExecutorScheduler.ExecutorWorker.BooleanRunnable; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.*; /** * Wraps an Executor and provides the Scheduler API over it. @@ -290,7 +291,8 @@ public void run() { } } - static final class DelayedRunnable extends AtomicReference implements Runnable, Disposable { + static final class DelayedRunnable extends AtomicReference + implements Runnable, Disposable, SchedulerRunnableIntrospection { private static final long serialVersionUID = -4101336210206799084L; @@ -330,6 +332,12 @@ public void dispose() { direct.dispose(); } } + + @Override + public Runnable getWrappedRunnable() { + Runnable r = get(); + return r != null ? r : Functions.EMPTY_RUNNABLE; + } } final class DelayedDispose implements Runnable { diff --git a/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java b/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java new file mode 100644 index 0000000000..4e558c8343 --- /dev/null +++ b/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.schedulers; + +import io.reactivex.annotations.*; +import io.reactivex.functions.Function; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Interface to wrap an action inside internal scheduler's task. + * + * You can check if runnable implements this interface and unwrap original runnable. + * For example inside of the {@link RxJavaPlugins#setScheduleHandler(Function)} + * + * @since 2.1.7 - experimental + */ +@Experimental +public interface SchedulerRunnableIntrospection { + + /** + * Returns the wrapped action. + * + * @return the wrapped action. Cannot be null. + */ + @NonNull + Runnable getWrappedRunnable(); +} diff --git a/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java b/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java index b81036a7e0..8d78e3756f 100644 --- a/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java +++ b/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java @@ -698,4 +698,48 @@ public void run() { disposable.get().dispose(); } } -} + + @Test(timeout = 5000) + public void unwrapDefaultPeriodicTask() throws InterruptedException { + Scheduler s = getScheduler(); + if (s instanceof TrampolineScheduler) { + // TrampolineScheduler always return EmptyDisposable + return; + } + + + final CountDownLatch cdl = new CountDownLatch(1); + Runnable countDownRunnable = new Runnable() { + @Override + public void run() { + cdl.countDown(); + } + }; + Disposable disposable = s.schedulePeriodicallyDirect(countDownRunnable, 100, 100, TimeUnit.MILLISECONDS); + SchedulerRunnableIntrospection wrapper = (SchedulerRunnableIntrospection) disposable; + + assertSame(countDownRunnable, wrapper.getWrappedRunnable()); + assertTrue(cdl.await(5, TimeUnit.SECONDS)); + disposable.dispose(); + } + + @Test + public void unwrapScheduleDirectTask() { + Scheduler scheduler = getScheduler(); + if (scheduler instanceof TrampolineScheduler) { + // TrampolineScheduler always return EmptyDisposable + return; + } + final CountDownLatch cdl = new CountDownLatch(1); + Runnable countDownRunnable = new Runnable() { + @Override + public void run() { + cdl.countDown(); + } + }; + Disposable disposable = scheduler.scheduleDirect(countDownRunnable, 100, TimeUnit.MILLISECONDS); + SchedulerRunnableIntrospection wrapper = (SchedulerRunnableIntrospection) disposable; + assertSame(countDownRunnable, wrapper.getWrappedRunnable()); + disposable.dispose(); + } +} \ No newline at end of file diff --git a/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java b/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java index c0a19efa5e..4e53fbcf42 100644 --- a/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java @@ -561,4 +561,22 @@ public void runnableDisposedAsyncTimed2() throws Exception { executorScheduler.shutdownNow(); } } + + @Test + public void unwrapScheduleDirectTaskAfterDispose() { + Scheduler scheduler = getScheduler(); + final CountDownLatch cdl = new CountDownLatch(1); + Runnable countDownRunnable = new Runnable() { + @Override + public void run() { + cdl.countDown(); + } + }; + Disposable disposable = scheduler.scheduleDirect(countDownRunnable, 100, TimeUnit.MILLISECONDS); + SchedulerRunnableIntrospection wrapper = (SchedulerRunnableIntrospection) disposable; + assertSame(countDownRunnable, wrapper.getWrappedRunnable()); + disposable.dispose(); + + assertSame(Functions.EMPTY_RUNNABLE, wrapper.getWrappedRunnable()); + } } diff --git a/src/test/java/io/reactivex/schedulers/SchedulerTest.java b/src/test/java/io/reactivex/schedulers/SchedulerTest.java index 2845cf3a91..714482e5cb 100644 --- a/src/test/java/io/reactivex/schedulers/SchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/SchedulerTest.java @@ -307,4 +307,66 @@ public void customScheduleDirectDisposed() { assertTrue(d.isDisposed()); } + + @Test + public void unwrapDefaultPeriodicTask() { + TestScheduler scheduler = new TestScheduler(); + + Runnable runnable = new Runnable() { + @Override + public void run() { + } + }; + SchedulerRunnableIntrospection wrapper = (SchedulerRunnableIntrospection) scheduler.schedulePeriodicallyDirect(runnable, 100, 100, TimeUnit.MILLISECONDS); + + assertSame(runnable, wrapper.getWrappedRunnable()); + } + + @Test + public void unwrapScheduleDirectTask() { + TestScheduler scheduler = new TestScheduler(); + + Runnable runnable = new Runnable() { + @Override + public void run() { + } + }; + SchedulerRunnableIntrospection wrapper = (SchedulerRunnableIntrospection) scheduler.scheduleDirect(runnable, 100, TimeUnit.MILLISECONDS); + assertSame(runnable, wrapper.getWrappedRunnable()); + } + + @Test + public void unwrapWorkerPeriodicTask() { + final Runnable runnable = new Runnable() { + @Override + public void run() { + } + }; + + Scheduler scheduler = new Scheduler() { + @Override + public Worker createWorker() { + return new Worker() { + @Override + public Disposable schedule(Runnable run, long delay, TimeUnit unit) { + SchedulerRunnableIntrospection outerWrapper = (SchedulerRunnableIntrospection) run; + SchedulerRunnableIntrospection innerWrapper = (SchedulerRunnableIntrospection) outerWrapper.getWrappedRunnable(); + assertSame(runnable, innerWrapper.getWrappedRunnable()); + return (Disposable) innerWrapper; + } + + @Override + public void dispose() { + } + + @Override + public boolean isDisposed() { + return false; + } + }; + } + }; + + scheduler.schedulePeriodicallyDirect(runnable, 100, 100, TimeUnit.MILLISECONDS); + } } From 53d5a235f63ca143c11571cd538ad927c0f8f3ad Mon Sep 17 00:00:00 2001 From: akarnokd Date: Tue, 5 Dec 2017 16:17:55 +0100 Subject: [PATCH 054/417] 2.x: fix javadoc link in observables/package-info --- src/main/java/io/reactivex/observables/package-info.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/observables/package-info.java b/src/main/java/io/reactivex/observables/package-info.java index 959200b525..1cfff8c889 100644 --- a/src/main/java/io/reactivex/observables/package-info.java +++ b/src/main/java/io/reactivex/observables/package-info.java @@ -16,7 +16,7 @@ /** * Classes supporting the Observable base reactive class: - * {@link io.reactivex.observable.ConnectableObservable} and - * {@link io.reactivex.observable.GroupedObservable}. + * {@link io.reactivex.observables.ConnectableObservable} and + * {@link io.reactivex.observables.GroupedObservable}. */ package io.reactivex.observables; From 0bab46d4a974fd0514fc2dc97414d259d1e0689e Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 7 Dec 2017 09:37:03 +0100 Subject: [PATCH 055/417] 2.x: Add marbles for Observable (12/06) (#5755) --- src/main/java/io/reactivex/Observable.java | 26 ++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index fac04781e7..bae61e9cf0 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -6121,7 +6121,8 @@ public final Observable concatMap(Function + * *

                *
                Scheduler:
                *
                {@code concatMapDelayError} does not operate by default on a particular {@link Scheduler}.
                @@ -6142,7 +6143,8 @@ public final Observable concatMapDelayError(Function + * *
                *
                Scheduler:
                *
                {@code concatMapDelayError} does not operate by default on a particular {@link Scheduler}.
                @@ -6181,6 +6183,8 @@ public final Observable concatMapDelayError(Function + * *
                *
                Scheduler:
                *
                This method does not operate by default on a particular {@link Scheduler}.
                @@ -6204,6 +6208,8 @@ public final Observable concatMapEager(Function + * *
                *
                Scheduler:
                *
                This method does not operate by default on a particular {@link Scheduler}.
                @@ -6233,6 +6239,8 @@ public final Observable concatMapEager(Function + * *
                *
                Scheduler:
                *
                This method does not operate by default on a particular {@link Scheduler}.
                @@ -6260,6 +6268,8 @@ public final Observable concatMapEagerDelayError(Function + * *
                *
                Scheduler:
                *
                This method does not operate by default on a particular {@link Scheduler}.
                @@ -6290,6 +6300,8 @@ public final Observable concatMapEagerDelayError(Function + * *
                *
                Scheduler:
                *
                {@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.
                @@ -6310,6 +6322,8 @@ public final Completable concatMapCompletable(Function + * *
                *
                Scheduler:
                *
                {@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.
                @@ -6336,6 +6350,8 @@ public final Completable concatMapCompletable(Function + * * *
                *
                Scheduler:
                @@ -6361,6 +6377,8 @@ public final Observable concatMapIterable(final Function + * * *
                *
                Scheduler:
                @@ -6989,6 +7007,8 @@ public final Observable distinctUntilChanged(BiPredicateNote that the {@code onAfterNext} action is shared between subscriptions and as such * should be thread-safe. + *

                + * *

                *
                Scheduler:
                *
                {@code doAfterNext} does not operate by default on a particular {@link Scheduler}.
                @@ -7038,6 +7058,8 @@ public final Observable doAfterTerminate(Action onFinally) { * is executed once per subscription. *

                Note that the {@code onFinally} action is shared between subscriptions and as such * should be thread-safe. + *

                + * *

                *
                Scheduler:
                *
                {@code doFinally} does not operate by default on a particular {@link Scheduler}.
                From 564c3dc45cbf4e9663eb22e8878ee31054c8e6f4 Mon Sep 17 00:00:00 2001 From: "Artem Zinnatullin :slowpoke" Date: Thu, 7 Dec 2017 00:52:35 -0800 Subject: [PATCH 056/417] 2.x: Check runnable == null in *Scheduler.schedule*(). (#5748) * 2.x: Check runnable == null in *Scheduler.schedule*(). * "run is null". * sudo "run is null". --- .../io/reactivex/plugins/RxJavaPlugins.java | 2 ++ .../reactivex/plugins/RxJavaPluginsTest.java | 5 --- .../schedulers/AbstractSchedulerTests.java | 32 ++++++++++++++++++- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/plugins/RxJavaPlugins.java b/src/main/java/io/reactivex/plugins/RxJavaPlugins.java index 5ab0192342..5c2f0ec5ad 100644 --- a/src/main/java/io/reactivex/plugins/RxJavaPlugins.java +++ b/src/main/java/io/reactivex/plugins/RxJavaPlugins.java @@ -446,6 +446,8 @@ public static Scheduler onNewThreadScheduler(@NonNull Scheduler defaultScheduler */ @NonNull public static Runnable onSchedule(@NonNull Runnable run) { + ObjectHelper.requireNonNull(run, "run is null"); + Function f = onScheduleHandler; if (f == null) { return run; diff --git a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java index a8a998285e..b3cb2b142d 100644 --- a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java +++ b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java @@ -1369,8 +1369,6 @@ public void subscribeActual(CompletableObserver t) { assertNull(RxJavaPlugins.onAssembly((Maybe)null)); - assertNull(RxJavaPlugins.onSchedule(null)); - Maybe myb = new Maybe() { @Override public void subscribeActual(MaybeObserver t) { @@ -1381,10 +1379,7 @@ public void subscribeActual(MaybeObserver t) { assertSame(myb, RxJavaPlugins.onAssembly(myb)); - assertNull(RxJavaPlugins.onSchedule(null)); - Runnable action = Functions.EMPTY_RUNNABLE; - assertSame(action, RxJavaPlugins.onSchedule(action)); class AllSubscriber implements Subscriber, Observer, SingleObserver, CompletableObserver, MaybeObserver { diff --git a/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java b/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java index 8d78e3756f..8d2b56b460 100644 --- a/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java +++ b/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java @@ -742,4 +742,34 @@ public void run() { assertSame(countDownRunnable, wrapper.getWrappedRunnable()); disposable.dispose(); } -} \ No newline at end of file + + @Test + public void scheduleDirectNullRunnable() { + try { + getScheduler().scheduleDirect(null); + fail(); + } catch (NullPointerException npe) { + assertEquals("run is null", npe.getMessage()); + } + } + + @Test + public void scheduleDirectWithDelayNullRunnable() { + try { + getScheduler().scheduleDirect(null, 10, TimeUnit.MILLISECONDS); + fail(); + } catch (NullPointerException npe) { + assertEquals("run is null", npe.getMessage()); + } + } + + @Test + public void schedulePeriodicallyDirectNullRunnable() { + try { + getScheduler().schedulePeriodicallyDirect(null, 5, 10, TimeUnit.MILLISECONDS); + fail(); + } catch (NullPointerException npe) { + assertEquals("run is null", npe.getMessage()); + } + } +} From ec40a5e6c8f0ab39c334a9073692d24b30b414a9 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 7 Dec 2017 10:07:59 +0100 Subject: [PATCH 057/417] 2.x: improve autoConnect() Javadoc + add its marble (#5756) --- .../flowables/ConnectableFlowable.java | 40 +++++++++++++++++-- .../observables/ConnectableObservable.java | 38 ++++++++++++++++-- 2 files changed, 72 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/flowables/ConnectableFlowable.java b/src/main/java/io/reactivex/flowables/ConnectableFlowable.java index c10b07b8e5..9ab9ca1c04 100644 --- a/src/main/java/io/reactivex/flowables/ConnectableFlowable.java +++ b/src/main/java/io/reactivex/flowables/ConnectableFlowable.java @@ -78,19 +78,45 @@ public Flowable refCount() { } /** - * Returns a Flowable that automatically connects to this ConnectableFlowable + * Returns a Flowable that automatically connects (at most once) to this ConnectableFlowable * when the first Subscriber subscribes. + *

                + * + *

                + * The connection happens after the first subscription and happens at most once + * during the lifetime of the returned Flowable. If this ConnectableFlowable + * terminates, the connection is never renewed, no matter how Subscribers come + * and go. Use {@link #refCount()} to renew a connection or dispose an active + * connection when all {@code Subscriber}s have cancelled their {@code Subscription}s. + *

                + * This overload does not allow disconnecting the connection established via + * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload + * to gain access to the {@code Disposable} representing the only connection. * * @return a Flowable that automatically connects to this ConnectableFlowable * when the first Subscriber subscribes + * @see #refCount() + * @see #autoConnect(int, Consumer) */ @NonNull public Flowable autoConnect() { return autoConnect(1); } /** - * Returns a Flowable that automatically connects to this ConnectableFlowable + * Returns a Flowable that automatically connects (at most once) to this ConnectableFlowable * when the specified number of Subscribers subscribe to it. + *

                + * + *

                + * The connection happens after the given number of subscriptions and happens at most once + * during the lifetime of the returned Flowable. If this ConnectableFlowable + * terminates, the connection is never renewed, no matter how Subscribers come + * and go. Use {@link #refCount()} to renew a connection or dispose an active + * connection when all {@code Subscriber}s have cancelled their {@code Subscription}s. + *

                + * This overload does not allow disconnecting the connection established via + * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload + * to gain access to the {@code Disposable} representing the only connection. * * @param numberOfSubscribers the number of subscribers to await before calling connect * on the ConnectableFlowable. A non-positive value indicates @@ -104,9 +130,17 @@ public Flowable autoConnect(int numberOfSubscribers) { } /** - * Returns a Flowable that automatically connects to this ConnectableFlowable + * Returns a Flowable that automatically connects (at most once) to this ConnectableFlowable * when the specified number of Subscribers subscribe to it and calls the * specified callback with the Subscription associated with the established connection. + *

                + * + *

                + * The connection happens after the given number of subscriptions and happens at most once + * during the lifetime of the returned Flowable. If this ConnectableFlowable + * terminates, the connection is never renewed, no matter how Subscribers come + * and go. Use {@link #refCount()} to renew a connection or dispose an active + * connection when all {@code Subscriber}s have cancelled their {@code Subscription}s. * * @param numberOfSubscribers the number of subscribers to await before calling connect * on the ConnectableFlowable. A non-positive value indicates diff --git a/src/main/java/io/reactivex/observables/ConnectableObservable.java b/src/main/java/io/reactivex/observables/ConnectableObservable.java index 31c3e63e9e..62c76ab9a6 100644 --- a/src/main/java/io/reactivex/observables/ConnectableObservable.java +++ b/src/main/java/io/reactivex/observables/ConnectableObservable.java @@ -77,8 +77,20 @@ public Observable refCount() { } /** - * Returns an Observable that automatically connects to this ConnectableObservable + * Returns an Observable that automatically connects (at most once) to this ConnectableObservable * when the first Observer subscribes. + *

                + * + *

                + * The connection happens after the first subscription and happens at most once + * during the lifetime of the returned Observable. If this ConnectableObservable + * terminates, the connection is never renewed, no matter how Observers come + * and go. Use {@link #refCount()} to renew a connection or dispose an active + * connection when all {@code Observers}s have disposed their {@code Disposable}s. + *

                + * This overload does not allow disconnecting the connection established via + * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload + * to gain access to the {@code Disposable} representing the only connection. * * @return an Observable that automatically connects to this ConnectableObservable * when the first Observer subscribes @@ -89,8 +101,20 @@ public Observable autoConnect() { } /** - * Returns an Observable that automatically connects to this ConnectableObservable + * Returns an Observable that automatically connects (at most once) to this ConnectableObservable * when the specified number of Observers subscribe to it. + *

                + * + *

                + * The connection happens after the given number of subscriptions and happens at most once + * during the lifetime of the returned Observable. If this ConnectableObservable + * terminates, the connection is never renewed, no matter how Observers come + * and go. Use {@link #refCount()} to renew a connection or dispose an active + * connection when all {@code Observers}s have disposed their {@code Disposable}s. + *

                + * This overload does not allow disconnecting the connection established via + * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload + * to gain access to the {@code Disposable} representing the only connection. * * @param numberOfSubscribers the number of subscribers to await before calling connect * on the ConnectableObservable. A non-positive value indicates @@ -104,9 +128,17 @@ public Observable autoConnect(int numberOfSubscribers) { } /** - * Returns an Observable that automatically connects to this ConnectableObservable + * Returns an Observable that automatically connects (at most once) to this ConnectableObservable * when the specified number of Subscribers subscribe to it and calls the * specified callback with the Subscription associated with the established connection. + *

                + * + *

                + * The connection happens after the given number of subscriptions and happens at most once + * during the lifetime of the returned Observable. If this ConnectableObservable + * terminates, the connection is never renewed, no matter how Observers come + * and go. Use {@link #refCount()} to renew a connection or dispose an active + * connection when all {@code Observers}s have disposed their {@code Disposable}s. * * @param numberOfSubscribers the number of subscribers to await before calling connect * on the ConnectableObservable. A non-positive value indicates From 34242e14b6c6d5b31c2dfce17e65410dd2f20d8a Mon Sep 17 00:00:00 2001 From: Niklas Baudy Date: Fri, 8 Dec 2017 00:02:47 +0100 Subject: [PATCH 058/417] 2.x: Add retry(times, predicate) to Single & Completable and verify behavior across them and Maybe. (#5753) * 2.x: Add retry(times, predicate) to Single & Completable and verify behavior across them and Maybe. * Adjust ParamValidationCheckerTest for the 2 newly added methods. * Add AtomicInteger for checking the number of subscribe calls. * Fix copy pasta mistake. --- src/main/java/io/reactivex/Completable.java | 22 ++++ src/main/java/io/reactivex/Single.java | 20 +++ .../reactivex/ParamValidationCheckerTest.java | 2 + .../completable/CompletableRetryTest.java | 115 +++++++++++++++++ .../io/reactivex/maybe/MaybeRetryTest.java | 121 ++++++++++++++++++ .../io/reactivex/single/SingleRetryTest.java | 121 ++++++++++++++++++ 6 files changed, 401 insertions(+) create mode 100644 src/test/java/io/reactivex/completable/CompletableRetryTest.java create mode 100644 src/test/java/io/reactivex/maybe/MaybeRetryTest.java create mode 100644 src/test/java/io/reactivex/single/SingleRetryTest.java diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 34008f1a0c..172e3caab6 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1545,6 +1545,28 @@ public final Completable retry(long times) { return fromPublisher(toFlowable().retry(times)); } + /** + * Returns a Completable that when this Completable emits an error, retries at most times + * or until the predicate returns false, whichever happens first and emitting the last error. + *

                + *
                Scheduler:
                + *
                {@code retry} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param times the number of times the returned Completable should retry this Completable + * @param predicate the predicate that is called with the latest throwable and should return + * true to indicate the returned Completable should resubscribe to this Completable. + * @return the new Completable instance + * @throws NullPointerException if predicate is null + * @throws IllegalArgumentException if times is negative + * @since 2.1.8 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final Completable retry(long times, Predicate predicate) { + return fromPublisher(toFlowable().retry(times, predicate)); + } + /** * Returns a Completable that when this Completable emits an error, calls the given predicate with * the latest exception to decide whether to resubscribe to this or not. diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 72ee2872c6..df59da1ff5 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2649,6 +2649,26 @@ public final Single retry(BiPredicate pre return toSingle(toFlowable().retry(predicate)); } + /** + * Repeatedly re-subscribe at most times or until the predicate returns false, whichever happens first + * if it fails with an onError. + *
                + *
                Scheduler:
                + *
                {@code retry} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param times the number of times to resubscribe if the current Single fails + * @param predicate the predicate called with the failure Throwable + * and should return true if a resubscription should happen + * @return the new Single instance + * @since 2.1.8 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final Single retry(long times, Predicate predicate) { + return toSingle(toFlowable().retry(times, predicate)); + } + /** * Re-subscribe to the current Single if the given predicate returns true when the Single fails * with an onError. diff --git a/src/test/java/io/reactivex/ParamValidationCheckerTest.java b/src/test/java/io/reactivex/ParamValidationCheckerTest.java index 5ad5afbd96..d129d14aa4 100644 --- a/src/test/java/io/reactivex/ParamValidationCheckerTest.java +++ b/src/test/java/io/reactivex/ParamValidationCheckerTest.java @@ -258,6 +258,7 @@ public void checkParallelFlowable() { // zero retry is allowed addOverride(new ParamOverride(Completable.class, 0, ParamMode.NON_NEGATIVE, "retry", Long.TYPE)); + addOverride(new ParamOverride(Completable.class, 0, ParamMode.NON_NEGATIVE, "retry", Long.TYPE, Predicate.class)); // negative time is considered as zero time addOverride(new ParamOverride(Completable.class, 0, ParamMode.ANY, "blockingGet", Long.TYPE, TimeUnit.class)); @@ -323,6 +324,7 @@ public void checkParallelFlowable() { // zero retry is allowed addOverride(new ParamOverride(Single.class, 0, ParamMode.NON_NEGATIVE, "retry", Long.TYPE)); + addOverride(new ParamOverride(Single.class, 0, ParamMode.NON_NEGATIVE, "retry", Long.TYPE, Predicate.class)); // negative time is considered as zero time addOverride(new ParamOverride(Single.class, 0, ParamMode.ANY, "delaySubscription", Long.TYPE, TimeUnit.class)); diff --git a/src/test/java/io/reactivex/completable/CompletableRetryTest.java b/src/test/java/io/reactivex/completable/CompletableRetryTest.java new file mode 100644 index 0000000000..23619078bd --- /dev/null +++ b/src/test/java/io/reactivex/completable/CompletableRetryTest.java @@ -0,0 +1,115 @@ +/** + * Copyright (c) 2017-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.completable; + +import io.reactivex.Completable; +import io.reactivex.functions.Action; +import io.reactivex.functions.Predicate; +import io.reactivex.internal.functions.Functions; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CompletableRetryTest { + @Test + public void retryTimesPredicateWithMatchingPredicate() { + final AtomicInteger atomicInteger = new AtomicInteger(3); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Completable.fromAction(new Action() { + @Override public void run() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + + throw new IllegalArgumentException(); + } + }) + .retry(Integer.MAX_VALUE, new Predicate() { + @Override public boolean test(final Throwable throwable) throws Exception { + return !(throwable instanceof IllegalArgumentException); + } + }) + .test() + .assertFailure(IllegalArgumentException.class); + + assertEquals(3, numberOfSubscribeCalls.get()); + } + + @Test + public void retryTimesPredicateWithMatchingRetryAmount() { + final AtomicInteger atomicInteger = new AtomicInteger(3); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Completable.fromAction(new Action() { + @Override public void run() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + } + }) + .retry(2, Functions.alwaysTrue()) + .test() + .assertResult(); + + assertEquals(3, numberOfSubscribeCalls.get()); + } + + @Test + public void retryTimesPredicateWithNotMatchingRetryAmount() { + final AtomicInteger atomicInteger = new AtomicInteger(3); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Completable.fromAction(new Action() { + @Override public void run() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + } + }) + .retry(1, Functions.alwaysTrue()) + .test() + .assertFailure(RuntimeException.class); + + assertEquals(2, numberOfSubscribeCalls.get()); + } + + @Test + public void retryTimesPredicateWithZeroRetries() { + final AtomicInteger atomicInteger = new AtomicInteger(2); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Completable.fromAction(new Action() { + @Override public void run() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + } + }) + .retry(0, Functions.alwaysTrue()) + .test() + .assertFailure(RuntimeException.class); + + assertEquals(1, numberOfSubscribeCalls.get()); + } +} diff --git a/src/test/java/io/reactivex/maybe/MaybeRetryTest.java b/src/test/java/io/reactivex/maybe/MaybeRetryTest.java new file mode 100644 index 0000000000..0749da742d --- /dev/null +++ b/src/test/java/io/reactivex/maybe/MaybeRetryTest.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) 2017-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.maybe; + +import io.reactivex.Maybe; +import io.reactivex.functions.Predicate; +import io.reactivex.internal.functions.Functions; +import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class MaybeRetryTest { + @Test + public void retryTimesPredicateWithMatchingPredicate() { + final AtomicInteger atomicInteger = new AtomicInteger(3); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Maybe.fromCallable(new Callable() { + @Override public Boolean call() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + + throw new IllegalArgumentException(); + } + }) + .retry(Integer.MAX_VALUE, new Predicate() { + @Override public boolean test(final Throwable throwable) throws Exception { + return !(throwable instanceof IllegalArgumentException); + } + }) + .test() + .assertFailure(IllegalArgumentException.class); + + assertEquals(3, numberOfSubscribeCalls.get()); + } + + @Test + public void retryTimesPredicateWithMatchingRetryAmount() { + final AtomicInteger atomicInteger = new AtomicInteger(3); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Maybe.fromCallable(new Callable() { + @Override public Boolean call() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + + return true; + } + }) + .retry(2, Functions.alwaysTrue()) + .test() + .assertResult(true); + + assertEquals(3, numberOfSubscribeCalls.get()); + } + + @Test + public void retryTimesPredicateWithNotMatchingRetryAmount() { + final AtomicInteger atomicInteger = new AtomicInteger(3); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Maybe.fromCallable(new Callable() { + @Override public Boolean call() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + + return true; + } + }) + .retry(1, Functions.alwaysTrue()) + .test() + .assertFailure(RuntimeException.class); + + assertEquals(2, numberOfSubscribeCalls.get()); + } + + @Test + public void retryTimesPredicateWithZeroRetries() { + final AtomicInteger atomicInteger = new AtomicInteger(2); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Maybe.fromCallable(new Callable() { + @Override public Boolean call() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + + return true; + } + }) + .retry(0, Functions.alwaysTrue()) + .test() + .assertFailure(RuntimeException.class); + + assertEquals(1, numberOfSubscribeCalls.get()); + } +} diff --git a/src/test/java/io/reactivex/single/SingleRetryTest.java b/src/test/java/io/reactivex/single/SingleRetryTest.java new file mode 100644 index 0000000000..c37f877f03 --- /dev/null +++ b/src/test/java/io/reactivex/single/SingleRetryTest.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) 2017-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.single; + +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.internal.functions.Functions; +import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SingleRetryTest { + @Test + public void retryTimesPredicateWithMatchingPredicate() { + final AtomicInteger atomicInteger = new AtomicInteger(3); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Single.fromCallable(new Callable() { + @Override public Boolean call() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + + throw new IllegalArgumentException(); + } + }) + .retry(Integer.MAX_VALUE, new Predicate() { + @Override public boolean test(final Throwable throwable) throws Exception { + return !(throwable instanceof IllegalArgumentException); + } + }) + .test() + .assertFailure(IllegalArgumentException.class); + + assertEquals(3, numberOfSubscribeCalls.get()); + } + + @Test + public void retryTimesPredicateWithMatchingRetryAmount() { + final AtomicInteger atomicInteger = new AtomicInteger(3); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Single.fromCallable(new Callable() { + @Override public Boolean call() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + + return true; + } + }) + .retry(2, Functions.alwaysTrue()) + .test() + .assertResult(true); + + assertEquals(3, numberOfSubscribeCalls.get()); + } + + @Test + public void retryTimesPredicateWithNotMatchingRetryAmount() { + final AtomicInteger atomicInteger = new AtomicInteger(3); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Single.fromCallable(new Callable() { + @Override public Boolean call() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + + return true; + } + }) + .retry(1, Functions.alwaysTrue()) + .test() + .assertFailure(RuntimeException.class); + + assertEquals(2, numberOfSubscribeCalls.get()); + } + + @Test + public void retryTimesPredicateWithZeroRetries() { + final AtomicInteger atomicInteger = new AtomicInteger(2); + final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); + + Single.fromCallable(new Callable() { + @Override public Boolean call() throws Exception { + numberOfSubscribeCalls.incrementAndGet(); + + if (atomicInteger.decrementAndGet() != 0) { + throw new RuntimeException(); + } + + return true; + } + }) + .retry(0, Functions.alwaysTrue()) + .test() + .assertFailure(RuntimeException.class); + + assertEquals(1, numberOfSubscribeCalls.get()); + } +} From b338ffe9f469896187e401caee2e9a9a8fffe28d Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 10 Dec 2017 19:51:18 +0100 Subject: [PATCH 059/417] 2.x: add a couple of @see to Completable (#5758) * 2.x: add a couple of @see to Completable * Enable @see in JavadocWording verifier --- src/main/java/io/reactivex/Completable.java | 8 +++++ .../java/io/reactivex/JavadocWording.java | 36 +++++++++++++------ 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 172e3caab6..1aafe50fb1 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1055,6 +1055,10 @@ public final Completable compose(CompletableTransformer transformer) { * @param other the other Completable, not null * @return the new Completable which subscribes to this and then the other Completable * @throws NullPointerException if other is null + * @see #andThen(MaybeSource) + * @see #andThen(ObservableSource) + * @see #andThen(SingleSource) + * @see #andThen(Publisher) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -1130,6 +1134,7 @@ public final Completable delay(final long delay, final TimeUnit unit, final Sche * @param onComplete the callback to call when this emits an onComplete event * @return the new Completable instance * @throws NullPointerException if onComplete is null + * @see #doFinally(Action) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -1167,6 +1172,7 @@ public final Completable doOnDispose(Action onDispose) { * @param onError the error callback * @return the new Completable instance * @throws NullPointerException if onError is null + * @see #doFinally(Action) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -1254,6 +1260,7 @@ public final Completable doOnSubscribe(Consumer onSubscribe) *
                * @param onTerminate the callback to call just before this Completable terminates * @return the new Completable instance + * @see #doFinally(Action) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -1272,6 +1279,7 @@ public final Completable doOnTerminate(final Action onTerminate) { *
                * @param onAfterTerminate the callback to call after this Completable terminates * @return the new Completable instance + * @see #doFinally(Action) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) diff --git a/src/test/java/io/reactivex/JavadocWording.java b/src/test/java/io/reactivex/JavadocWording.java index f8c881ee78..3d53fad38f 100644 --- a/src/test/java/io/reactivex/JavadocWording.java +++ b/src/test/java/io/reactivex/JavadocWording.java @@ -14,6 +14,7 @@ package io.reactivex; import java.util.List; +import java.util.regex.Pattern; import static org.junit.Assert.*; import org.junit.Test; @@ -695,8 +696,11 @@ public void completableDocRefersToCompletableTypes() throws Exception { int idx = m.javadoc.indexOf("Flowable", jdx); if (idx >= 0) { if (!m.signature.contains("Flowable")) { - e.append("java.lang.RuntimeException: Completable doc mentions Flowable but not in the signature\r\n at io.reactivex.") - .append("Completable (Completable.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + Pattern p = Pattern.compile("@see\\s+#[A-Za-z0-9 _.,()]*Flowable"); + if (!p.matcher(m.javadoc).find()) { + e.append("java.lang.RuntimeException: Completable doc mentions Flowable but not in the signature\r\n at io.reactivex.") + .append("Completable (Completable.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + } } jdx = idx + 6; } else { @@ -708,8 +712,11 @@ public void completableDocRefersToCompletableTypes() throws Exception { int idx = m.javadoc.indexOf("Single", jdx); if (idx >= 0) { if (!m.signature.contains("Single")) { - e.append("java.lang.RuntimeException: Completable doc mentions Single but not in the signature\r\n at io.reactivex.") - .append("Completable (Completable.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + Pattern p = Pattern.compile("@see\\s+#[A-Za-z0-9 _.,()]*Single"); + if (!p.matcher(m.javadoc).find()) { + e.append("java.lang.RuntimeException: Completable doc mentions Single but not in the signature\r\n at io.reactivex.") + .append("Completable (Completable.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + } } jdx = idx + 6; } else { @@ -721,8 +728,11 @@ public void completableDocRefersToCompletableTypes() throws Exception { int idx = m.javadoc.indexOf("SingleSource", jdx); if (idx >= 0) { if (!m.signature.contains("SingleSource")) { - e.append("java.lang.RuntimeException: Completable doc mentions SingleSource but not in the signature\r\n at io.reactivex.") - .append("Completable (Completable.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + Pattern p = Pattern.compile("@see\\s+#[A-Za-z0-9 _.,()]*SingleSource"); + if (!p.matcher(m.javadoc).find()) { + e.append("java.lang.RuntimeException: Completable doc mentions SingleSource but not in the signature\r\n at io.reactivex.") + .append("Completable (Completable.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + } } jdx = idx + 6; } else { @@ -734,8 +744,11 @@ public void completableDocRefersToCompletableTypes() throws Exception { int idx = m.javadoc.indexOf(" Observable", jdx); if (idx >= 0) { if (!m.signature.contains("Observable")) { - e.append("java.lang.RuntimeException: Completable doc mentions Observable but not in the signature\r\n at io.reactivex.") - .append("Completable (Completable.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + Pattern p = Pattern.compile("@see\\s+#[A-Za-z0-9 _.,()]*Observable"); + if (!p.matcher(m.javadoc).find()) { + e.append("java.lang.RuntimeException: Completable doc mentions Observable but not in the signature\r\n at io.reactivex.") + .append("Completable (Completable.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + } } jdx = idx + 6; } else { @@ -747,8 +760,11 @@ public void completableDocRefersToCompletableTypes() throws Exception { int idx = m.javadoc.indexOf("ObservableSource", jdx); if (idx >= 0) { if (!m.signature.contains("ObservableSource")) { - e.append("java.lang.RuntimeException: Completable doc mentions ObservableSource but not in the signature\r\n at io.reactivex.") - .append("Completable (Completable.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + Pattern p = Pattern.compile("@see\\s+#[A-Za-z0-9 _.,()]*ObservableSource"); + if (!p.matcher(m.javadoc).find()) { + e.append("java.lang.RuntimeException: Completable doc mentions ObservableSource but not in the signature\r\n at io.reactivex.") + .append("Completable (Completable.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); + } } jdx = idx + 6; } else { From 9f2beac79ca7b95ae2cc90c7c6a1d79f5318b7f9 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 13 Dec 2017 00:04:04 +0100 Subject: [PATCH 060/417] 2.x: marble additions and updates (12/11) (#5759) --- src/main/java/io/reactivex/Observable.java | 26 +++++++++++----------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index bae61e9cf0..83b807371b 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7300,7 +7300,7 @@ public final Observable doOnSubscribe(Consumer onSubscrib * Modifies the source ObservableSource so that it invokes an action when it calls {@code onComplete} or * {@code onError}. *

                - * + * *

                * This differs from {@code doAfterTerminate} in that this happens before the {@code onComplete} or * {@code onError} notification. @@ -7328,7 +7328,7 @@ public final Observable doOnTerminate(final Action onTerminate) { * Returns a Maybe that emits the single item at a specified index in a sequence of emissions from * this Observable or completes if this Observable signals fewer elements than index. *

                - * + * *

                *
                Scheduler:
                *
                {@code elementAt} does not operate by default on a particular {@link Scheduler}.
                @@ -7355,7 +7355,7 @@ public final Maybe elementAt(long index) { * Returns a Single that emits the item found at a specified index in a sequence of emissions from * this Observable, or a default item if that index is out of range. *

                - * + * *

                *
                Scheduler:
                *
                {@code elementAt} does not operate by default on a particular {@link Scheduler}.
                @@ -7385,7 +7385,7 @@ public final Single elementAt(long index, T defaultItem) { * Returns a Single that emits the item found at a specified index in a sequence of emissions from this Observable * or signals a {@link NoSuchElementException} if this Observable signals fewer elements than index. *

                - * + * *

                *
                Scheduler:
                *
                {@code elementAtOrError} does not operate by default on a particular {@link Scheduler}.
                @@ -7435,7 +7435,7 @@ public final Observable filter(Predicate predicate) { * Returns a Maybe that emits only the very first item emitted by the source ObservableSource, or * completes if the source ObservableSource is empty. *

                - * + * *

                *
                Scheduler:
                *
                {@code firstElement} does not operate by default on a particular {@link Scheduler}.
                @@ -7475,7 +7475,7 @@ public final Single first(T defaultItem) { * Returns a Single that emits only the very first item emitted by this Observable or * signals a {@link NoSuchElementException} if this Observable is empty. *

                - * + * *

                *
                Scheduler:
                *
                {@code firstOrError} does not operate by default on a particular {@link Scheduler}.
                @@ -7521,7 +7521,7 @@ public final Observable flatMap(Function - * + * *
                *
                Scheduler:
                *
                {@code flatMap} does not operate by default on a particular {@link Scheduler}.
                @@ -7550,8 +7550,8 @@ public final Observable flatMap(Function --> - * + *

                + * *

                *
                Scheduler:
                *
                {@code flatMap} does not operate by default on a particular {@link Scheduler}.
                @@ -7583,8 +7583,8 @@ public final Observable flatMap(Function --> - * + *

                + * *

                *
                Scheduler:
                *
                {@code flatMap} does not operate by default on a particular {@link Scheduler}.
                @@ -7707,8 +7707,8 @@ public final Observable flatMap( * by the source ObservableSource, where that function returns an ObservableSource, and then merging those resulting * ObservableSources and emitting the results of this merger, while limiting the maximum number of concurrent * subscriptions to these ObservableSources. - * - * + *

                + * *

                *
                Scheduler:
                *
                {@code flatMap} does not operate by default on a particular {@link Scheduler}.
                From 39e159f20c09865dcd44281c02806259f37f4b3d Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 15 Dec 2017 09:26:30 +0100 Subject: [PATCH 061/417] 2.x: fix timed exact buffer calling cancel unnecessarily (#5761) --- .../flowable/FlowableBufferTimed.java | 2 +- .../observable/ObservableBufferTimed.java | 2 +- .../internal/util/QueueDrainHelper.java | 12 +++- .../flowable/FlowableBufferTest.java | 60 ++++++++++++++++++ .../observable/ObservableBufferTest.java | 61 +++++++++++++++++++ 5 files changed, 132 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java index f6320ced12..2597a6d140 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java @@ -166,7 +166,7 @@ public void onComplete() { queue.offer(b); done = true; if (enter()) { - QueueDrainHelper.drainMaxLoop(queue, actual, false, this, this); + QueueDrainHelper.drainMaxLoop(queue, actual, false, null, this); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java index d521ebae80..2bc4bfbec9 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java @@ -161,7 +161,7 @@ public void onComplete() { queue.offer(b); done = true; if (enter()) { - QueueDrainHelper.drainLoop(queue, actual, false, this, this); + QueueDrainHelper.drainLoop(queue, actual, false, null, this); } } DisposableHelper.dispose(timer); diff --git a/src/main/java/io/reactivex/internal/util/QueueDrainHelper.java b/src/main/java/io/reactivex/internal/util/QueueDrainHelper.java index 2964812c4d..25126b3327 100644 --- a/src/main/java/io/reactivex/internal/util/QueueDrainHelper.java +++ b/src/main/java/io/reactivex/internal/util/QueueDrainHelper.java @@ -168,7 +168,9 @@ public static boolean checkTerminated(boolean d, boolean empty, if (d) { if (delayError) { if (empty) { - disposable.dispose(); + if (disposable != null) { + disposable.dispose(); + } Throwable err = qd.error(); if (err != null) { s.onError(err); @@ -181,12 +183,16 @@ public static boolean checkTerminated(boolean d, boolean empty, Throwable err = qd.error(); if (err != null) { q.clear(); - disposable.dispose(); + if (disposable != null) { + disposable.dispose(); + } s.onError(err); return true; } else if (empty) { - disposable.dispose(); + if (disposable != null) { + disposable.dispose(); + } s.onComplete(); return true; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index d2ebe2ca11..bd18c0187d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -2014,4 +2014,64 @@ public void run() { assertEquals("Round: " + i, 5, items); } } + + @SuppressWarnings("unchecked") + @Test + public void noCompletionCancelExact() { + final AtomicInteger counter = new AtomicInteger(); + + Flowable.empty() + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }) + .buffer(5, TimeUnit.SECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(Collections.emptyList()); + + assertEquals(0, counter.get()); + } + + @SuppressWarnings("unchecked") + @Test + public void noCompletionCancelSkip() { + final AtomicInteger counter = new AtomicInteger(); + + Flowable.empty() + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }) + .buffer(5, 10, TimeUnit.SECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(Collections.emptyList()); + + assertEquals(0, counter.get()); + } + + @SuppressWarnings("unchecked") + @Test + public void noCompletionCancelOverlap() { + final AtomicInteger counter = new AtomicInteger(); + + Flowable.empty() + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }) + .buffer(10, 5, TimeUnit.SECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(Collections.emptyList()); + + assertEquals(0, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index d7b6046e42..93a9e2fb74 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -19,6 +19,7 @@ import java.util.*; import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.*; import org.mockito.*; @@ -1439,4 +1440,64 @@ public void run() { assertEquals("Round: " + i, 5, items); } } + + @SuppressWarnings("unchecked") + @Test + public void noCompletionCancelExact() { + final AtomicInteger counter = new AtomicInteger(); + + Observable.empty() + .doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }) + .buffer(5, TimeUnit.SECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(Collections.emptyList()); + + assertEquals(0, counter.get()); + } + + @SuppressWarnings("unchecked") + @Test + public void noCompletionCancelSkip() { + final AtomicInteger counter = new AtomicInteger(); + + Observable.empty() + .doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }) + .buffer(5, 10, TimeUnit.SECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(Collections.emptyList()); + + assertEquals(0, counter.get()); + } + + @SuppressWarnings("unchecked") + @Test + public void noCompletionCancelOverlap() { + final AtomicInteger counter = new AtomicInteger(); + + Observable.empty() + .doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }) + .buffer(10, 5, TimeUnit.SECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(Collections.emptyList()); + + assertEquals(0, counter.get()); + } } From 7ba9a3e04aeee3ab691002997e82e55fec40e495 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 15 Dec 2017 11:13:49 +0100 Subject: [PATCH 062/417] 2.x: Subject NPE fixes, add UnicastProcessor TCK (#5760) * 2.x: add Subject/Processor refCount(), Subject NPE fixes * Fix wording * Move RefCountProcessor into tests * Improve style --- .../reactivex/processors/AsyncProcessor.java | 23 +- .../processors/BehaviorProcessor.java | 10 +- .../processors/FlowableProcessor.java | 27 ++- .../processors/PublishProcessor.java | 10 +- .../reactivex/processors/ReplayProcessor.java | 11 +- .../processors/UnicastProcessor.java | 13 +- .../io/reactivex/subjects/AsyncSubject.java | 22 +- .../reactivex/subjects/BehaviorSubject.java | 10 +- .../subjects/CompletableSubject.java | 7 +- .../io/reactivex/subjects/MaybeSubject.java | 10 +- .../io/reactivex/subjects/PublishSubject.java | 11 +- .../io/reactivex/subjects/ReplaySubject.java | 9 +- .../io/reactivex/subjects/SingleSubject.java | 10 +- .../io/reactivex/subjects/UnicastSubject.java | 9 +- .../processors/AsyncProcessorTest.java | 2 +- .../processors/BehaviorProcessorTest.java | 2 +- .../DelayedFlowableProcessorTest.java | 53 ----- .../processors/FlowableProcessorTest.java | 30 ++- .../processors/UnicastProcessorTest.java | 2 +- .../reactivex/subjects/AsyncSubjectTest.java | 59 +---- .../subjects/BehaviorSubjectTest.java | 67 +----- .../subjects/CompletableSubjectTest.java | 11 +- .../reactivex/subjects/MaybeSubjectTest.java | 22 -- .../subjects/PublishSubjectTest.java | 55 +---- .../reactivex/subjects/ReplaySubjectTest.java | 31 +-- .../reactivex/subjects/SingleSubjectTest.java | 22 +- .../io/reactivex/subjects/SubjectTest.java | 51 ++++ .../subjects/UnicastSubjectTest.java | 65 +----- .../io/reactivex/tck/RefCountProcessor.java | 219 ++++++++++++++++++ .../tck/UnicastProcessorTckTest.java | 64 +++++ 30 files changed, 464 insertions(+), 473 deletions(-) delete mode 100644 src/test/java/io/reactivex/processors/DelayedFlowableProcessorTest.java create mode 100644 src/test/java/io/reactivex/subjects/SubjectTest.java create mode 100644 src/test/java/io/reactivex/tck/RefCountProcessor.java create mode 100644 src/test/java/io/reactivex/tck/UnicastProcessorTckTest.java diff --git a/src/main/java/io/reactivex/processors/AsyncProcessor.java b/src/main/java/io/reactivex/processors/AsyncProcessor.java index 4aa6ec549c..c728d9eb1b 100644 --- a/src/main/java/io/reactivex/processors/AsyncProcessor.java +++ b/src/main/java/io/reactivex/processors/AsyncProcessor.java @@ -15,10 +15,12 @@ import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; +import org.reactivestreams.*; + import io.reactivex.annotations.*; +import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.subscriptions.DeferredScalarSubscription; import io.reactivex.plugins.RxJavaPlugins; -import org.reactivestreams.*; /** * Processor that emits the very last value followed by a completion event or the received error @@ -77,32 +79,17 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); if (subscribers.get() == TERMINATED) { return; } - if (t == null) { - nullOnNext(); - return; - } value = t; } - @SuppressWarnings("unchecked") - void nullOnNext() { - value = null; - Throwable ex = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - error = ex; - for (AsyncSubscription as : subscribers.getAndSet(TERMINATED)) { - as.onError(ex); - } - } - @SuppressWarnings("unchecked") @Override public void onError(Throwable t) { - if (t == null) { - t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (subscribers.get() == TERMINATED) { RxJavaPlugins.onError(t); return; diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index eb9d3196e7..e161727bb3 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -175,10 +175,8 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { - if (t == null) { - onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); - return; - } + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); + if (terminalEvent.get() != null) { return; } @@ -191,9 +189,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - if (t == null) { - t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (!terminalEvent.compareAndSet(null, t)) { RxJavaPlugins.onError(t); return; diff --git a/src/main/java/io/reactivex/processors/FlowableProcessor.java b/src/main/java/io/reactivex/processors/FlowableProcessor.java index e5fe4ad838..8135afa784 100644 --- a/src/main/java/io/reactivex/processors/FlowableProcessor.java +++ b/src/main/java/io/reactivex/processors/FlowableProcessor.java @@ -13,10 +13,11 @@ package io.reactivex.processors; -import io.reactivex.*; -import io.reactivex.annotations.NonNull; import org.reactivestreams.Processor; +import io.reactivex.*; +import io.reactivex.annotations.*; + /** * Represents a Subscriber and a Flowable (Publisher) at the same time, allowing * multicasting events from a single source to multiple child Subscribers. @@ -28,45 +29,47 @@ public abstract class FlowableProcessor extends Flowable implements Processor, FlowableSubscriber { /** - * Returns true if the subject has subscribers. + * Returns true if the FlowableProcessor has subscribers. *

                The method is thread-safe. - * @return true if the subject has subscribers + * @return true if the FlowableProcessor has subscribers */ public abstract boolean hasSubscribers(); /** - * Returns true if the subject has reached a terminal state through an error event. + * Returns true if the FlowableProcessor has reached a terminal state through an error event. *

                The method is thread-safe. - * @return true if the subject has reached a terminal state through an error event + * @return true if the FlowableProcessor has reached a terminal state through an error event * @see #getThrowable() * @see #hasComplete() */ public abstract boolean hasThrowable(); /** - * Returns true if the subject has reached a terminal state through a complete event. + * Returns true if the FlowableProcessor has reached a terminal state through a complete event. *

                The method is thread-safe. - * @return true if the subject has reached a terminal state through a complete event + * @return true if the FlowableProcessor has reached a terminal state through a complete event * @see #hasThrowable() */ public abstract boolean hasComplete(); /** - * Returns the error that caused the Subject to terminate or null if the Subject + * Returns the error that caused the FlowableProcessor to terminate or null if the FlowableProcessor * hasn't terminated yet. *

                The method is thread-safe. - * @return the error that caused the Subject to terminate or null if the Subject + * @return the error that caused the FlowableProcessor to terminate or null if the FlowableProcessor * hasn't terminated yet */ + @Nullable public abstract Throwable getThrowable(); /** - * Wraps this Subject and serializes the calls to the onSubscribe, onNext, onError and + * Wraps this FlowableProcessor and serializes the calls to the onSubscribe, onNext, onError and * onComplete methods, making them thread-safe. *

                The method is thread-safe. - * @return the wrapped and serialized subject + * @return the wrapped and serialized FlowableProcessor */ @NonNull + @CheckReturnValue public final FlowableProcessor toSerialized() { if (this instanceof SerializedProcessor) { return this; diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index b9341ce961..88781c45eb 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -18,6 +18,7 @@ import io.reactivex.annotations.*; import io.reactivex.exceptions.MissingBackpressureException; +import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.BackpressureHelper; import io.reactivex.plugins.RxJavaPlugins; @@ -186,13 +187,10 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); if (subscribers.get() == TERMINATED) { return; } - if (t == null) { - onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); - return; - } for (PublishSubscription s : subscribers.get()) { s.onNext(t); } @@ -201,13 +199,11 @@ public void onNext(T t) { @SuppressWarnings("unchecked") @Override public void onError(Throwable t) { + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (subscribers.get() == TERMINATED) { RxJavaPlugins.onError(t); return; } - if (t == null) { - t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } error = t; for (PublishSubscription s : subscribers.getAndSet(TERMINATED)) { diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index 8021170a45..d4aeba6ebb 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -267,10 +267,8 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { - if (t == null) { - onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); - return; - } + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); + if (done) { return; } @@ -286,9 +284,8 @@ public void onNext(T t) { @SuppressWarnings("unchecked") @Override public void onError(Throwable t) { - if (t == null) { - t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); + if (done) { RxJavaPlugins.onError(t); return; diff --git a/src/main/java/io/reactivex/processors/UnicastProcessor.java b/src/main/java/io/reactivex/processors/UnicastProcessor.java index 8334aa07c5..5c4717c5aa 100644 --- a/src/main/java/io/reactivex/processors/UnicastProcessor.java +++ b/src/main/java/io/reactivex/processors/UnicastProcessor.java @@ -339,12 +339,9 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { - if (done || cancelled) { - return; - } + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - if (t == null) { - onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); + if (done || cancelled) { return; } @@ -354,15 +351,13 @@ public void onNext(T t) { @Override public void onError(Throwable t) { + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); + if (done || cancelled) { RxJavaPlugins.onError(t); return; } - if (t == null) { - t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } - error = t; done = true; diff --git a/src/main/java/io/reactivex/subjects/AsyncSubject.java b/src/main/java/io/reactivex/subjects/AsyncSubject.java index 9b9cf0d423..0561144387 100644 --- a/src/main/java/io/reactivex/subjects/AsyncSubject.java +++ b/src/main/java/io/reactivex/subjects/AsyncSubject.java @@ -13,12 +13,13 @@ package io.reactivex.subjects; -import io.reactivex.annotations.CheckReturnValue; import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; import io.reactivex.Observer; +import io.reactivex.annotations.CheckReturnValue; import io.reactivex.disposables.Disposable; +import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.observers.DeferredScalarDisposable; import io.reactivex.plugins.RxJavaPlugins; @@ -75,32 +76,17 @@ public void onSubscribe(Disposable s) { @Override public void onNext(T t) { + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); if (subscribers.get() == TERMINATED) { return; } - if (t == null) { - nullOnNext(); - return; - } value = t; } - @SuppressWarnings("unchecked") - void nullOnNext() { - value = null; - Throwable ex = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - error = ex; - for (AsyncDisposable as : subscribers.getAndSet(TERMINATED)) { - as.onError(ex); - } - } - @SuppressWarnings("unchecked") @Override public void onError(Throwable t) { - if (t == null) { - t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (subscribers.get() == TERMINATED) { RxJavaPlugins.onError(t); return; diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java index 8a80cf4a24..85ef6af409 100644 --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java @@ -171,10 +171,8 @@ public void onSubscribe(Disposable s) { @Override public void onNext(T t) { - if (t == null) { - onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); - return; - } + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); + if (terminalEvent.get() != null) { return; } @@ -187,9 +185,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - if (t == null) { - t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (!terminalEvent.compareAndSet(null, t)) { RxJavaPlugins.onError(t); return; diff --git a/src/main/java/io/reactivex/subjects/CompletableSubject.java b/src/main/java/io/reactivex/subjects/CompletableSubject.java index dad98fc11d..2f0e209624 100644 --- a/src/main/java/io/reactivex/subjects/CompletableSubject.java +++ b/src/main/java/io/reactivex/subjects/CompletableSubject.java @@ -16,8 +16,9 @@ import java.util.concurrent.atomic.*; import io.reactivex.*; -import io.reactivex.annotations.*; +import io.reactivex.annotations.CheckReturnValue; import io.reactivex.disposables.Disposable; +import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.plugins.RxJavaPlugins; /** @@ -66,9 +67,7 @@ public void onSubscribe(Disposable d) { @Override public void onError(Throwable e) { - if (e == null) { - e = new NullPointerException("Null errors are not allowed in 2.x"); - } + ObjectHelper.requireNonNull(e, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (once.compareAndSet(false, true)) { this.error = e; for (CompletableDisposable md : observers.getAndSet(TERMINATED)) { diff --git a/src/main/java/io/reactivex/subjects/MaybeSubject.java b/src/main/java/io/reactivex/subjects/MaybeSubject.java index c1cda23955..7f303deefc 100644 --- a/src/main/java/io/reactivex/subjects/MaybeSubject.java +++ b/src/main/java/io/reactivex/subjects/MaybeSubject.java @@ -18,6 +18,7 @@ import io.reactivex.*; import io.reactivex.annotations.*; import io.reactivex.disposables.Disposable; +import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.plugins.RxJavaPlugins; /** @@ -73,10 +74,7 @@ public void onSubscribe(Disposable d) { @SuppressWarnings("unchecked") @Override public void onSuccess(T value) { - if (value == null) { - onError(new NullPointerException("Null values are not allowed in 2.x")); - return; - } + ObjectHelper.requireNonNull(value, "onSuccess called with null. Null values are generally not allowed in 2.x operators and sources."); if (once.compareAndSet(false, true)) { this.value = value; for (MaybeDisposable md : observers.getAndSet(TERMINATED)) { @@ -88,9 +86,7 @@ public void onSuccess(T value) { @SuppressWarnings("unchecked") @Override public void onError(Throwable e) { - if (e == null) { - e = new NullPointerException("Null errors are not allowed in 2.x"); - } + ObjectHelper.requireNonNull(e, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (once.compareAndSet(false, true)) { this.error = e; for (MaybeDisposable md : observers.getAndSet(TERMINATED)) { diff --git a/src/main/java/io/reactivex/subjects/PublishSubject.java b/src/main/java/io/reactivex/subjects/PublishSubject.java index 4608afc432..ad0f66d14c 100644 --- a/src/main/java/io/reactivex/subjects/PublishSubject.java +++ b/src/main/java/io/reactivex/subjects/PublishSubject.java @@ -18,6 +18,7 @@ import io.reactivex.Observer; import io.reactivex.disposables.Disposable; +import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.plugins.RxJavaPlugins; /** @@ -172,13 +173,11 @@ public void onSubscribe(Disposable s) { @Override public void onNext(T t) { + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); + if (subscribers.get() == TERMINATED) { return; } - if (t == null) { - onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); - return; - } for (PublishDisposable s : subscribers.get()) { s.onNext(t); } @@ -187,13 +186,11 @@ public void onNext(T t) { @SuppressWarnings("unchecked") @Override public void onError(Throwable t) { + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (subscribers.get() == TERMINATED) { RxJavaPlugins.onError(t); return; } - if (t == null) { - t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } error = t; for (PublishDisposable s : subscribers.getAndSet(TERMINATED)) { diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java index d5bd4bac51..52d0616884 100644 --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java @@ -252,10 +252,7 @@ public void onSubscribe(Disposable s) { @Override public void onNext(T t) { - if (t == null) { - onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); - return; - } + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); if (done) { return; } @@ -270,9 +267,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - if (t == null) { - t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (done) { RxJavaPlugins.onError(t); return; diff --git a/src/main/java/io/reactivex/subjects/SingleSubject.java b/src/main/java/io/reactivex/subjects/SingleSubject.java index 4c486eac97..d09d1f436c 100644 --- a/src/main/java/io/reactivex/subjects/SingleSubject.java +++ b/src/main/java/io/reactivex/subjects/SingleSubject.java @@ -18,6 +18,7 @@ import io.reactivex.*; import io.reactivex.annotations.*; import io.reactivex.disposables.Disposable; +import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.plugins.RxJavaPlugins; /** @@ -74,10 +75,7 @@ public void onSubscribe(@NonNull Disposable d) { @SuppressWarnings("unchecked") @Override public void onSuccess(@NonNull T value) { - if (value == null) { - onError(new NullPointerException("Null values are not allowed in 2.x")); - return; - } + ObjectHelper.requireNonNull(value, "onSuccess called with null. Null values are generally not allowed in 2.x operators and sources."); if (once.compareAndSet(false, true)) { this.value = value; for (SingleDisposable md : observers.getAndSet(TERMINATED)) { @@ -89,9 +87,7 @@ public void onSuccess(@NonNull T value) { @SuppressWarnings("unchecked") @Override public void onError(@NonNull Throwable e) { - if (e == null) { - e = new NullPointerException("Null errors are not allowed in 2.x"); - } + ObjectHelper.requireNonNull(e, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (once.compareAndSet(false, true)) { this.error = e; for (SingleDisposable md : observers.getAndSet(TERMINATED)) { diff --git a/src/main/java/io/reactivex/subjects/UnicastSubject.java b/src/main/java/io/reactivex/subjects/UnicastSubject.java index 69543bd752..a254eaa853 100644 --- a/src/main/java/io/reactivex/subjects/UnicastSubject.java +++ b/src/main/java/io/reactivex/subjects/UnicastSubject.java @@ -227,26 +227,21 @@ public void onSubscribe(Disposable s) { @Override public void onNext(T t) { + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); if (done || disposed) { return; } - if (t == null) { - onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); - return; - } queue.offer(t); drain(); } @Override public void onError(Throwable t) { + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (done || disposed) { RxJavaPlugins.onError(t); return; } - if (t == null) { - t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } error = t; done = true; diff --git a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java index a3d17873e3..8e564efcbe 100644 --- a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java +++ b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java @@ -35,7 +35,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; -public class AsyncProcessorTest extends DelayedFlowableProcessorTest { +public class AsyncProcessorTest extends FlowableProcessorTest { private final Throwable testException = new Throwable(); diff --git a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java index 1a58aaf004..496c75c8fa 100644 --- a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java +++ b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java @@ -39,7 +39,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; -public class BehaviorProcessorTest extends DelayedFlowableProcessorTest { +public class BehaviorProcessorTest extends FlowableProcessorTest { private final Throwable testException = new Throwable(); diff --git a/src/test/java/io/reactivex/processors/DelayedFlowableProcessorTest.java b/src/test/java/io/reactivex/processors/DelayedFlowableProcessorTest.java deleted file mode 100644 index 484335870d..0000000000 --- a/src/test/java/io/reactivex/processors/DelayedFlowableProcessorTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ - -package io.reactivex.processors; - -import io.reactivex.subscribers.TestSubscriber; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; - -public abstract class DelayedFlowableProcessorTest extends FlowableProcessorTest { - - @Test - public void onNextNullDelayed() { - final FlowableProcessor p = create(); - - TestSubscriber ts = p.test(); - - p.onNext(null); - - - - ts - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onErrorNullDelayed() { - final FlowableProcessor p = create(); - - TestSubscriber ts = p.test(); - - p.onError(null); - assertFalse(p.hasSubscribers()); - - ts - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } -} diff --git a/src/test/java/io/reactivex/processors/FlowableProcessorTest.java b/src/test/java/io/reactivex/processors/FlowableProcessorTest.java index bd37deb282..71946677ed 100644 --- a/src/test/java/io/reactivex/processors/FlowableProcessorTest.java +++ b/src/test/java/io/reactivex/processors/FlowableProcessorTest.java @@ -13,6 +13,8 @@ package io.reactivex.processors; +import static org.junit.Assert.*; + import org.junit.Test; public abstract class FlowableProcessorTest { @@ -21,25 +23,29 @@ public abstract class FlowableProcessorTest { @Test public void onNextNull() { - final FlowableProcessor p = create(); + FlowableProcessor p = create(); - p.onNext(null); + try { + p.onNext(null); + fail("No NullPointerException thrown"); + } catch (NullPointerException ex) { + assertEquals("onNext called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); + } - p.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); + p.test().assertEmpty().cancel(); } @Test public void onErrorNull() { - final FlowableProcessor p = create(); + FlowableProcessor p = create(); - p.onError(null); + try { + p.onError(null); + fail("No NullPointerException thrown"); + } catch (NullPointerException ex) { + assertEquals("onError called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); + } - p.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onError called with null. Null values are generally not allowed in 2.x operators and sources."); + p.test().assertEmpty().cancel(); } } diff --git a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java index fbec729694..5b3ab53ed4 100644 --- a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java @@ -30,7 +30,7 @@ import static org.junit.Assert.*; -public class UnicastProcessorTest extends DelayedFlowableProcessorTest { +public class UnicastProcessorTest extends FlowableProcessorTest { @Override protected FlowableProcessor create() { diff --git a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java index 8332c0cb87..04735b2c68 100644 --- a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java @@ -31,10 +31,15 @@ import io.reactivex.observers.*; import io.reactivex.schedulers.Schedulers; -public class AsyncSubjectTest { +public class AsyncSubjectTest extends SubjectTest { private final Throwable testException = new Throwable(); + @Override + protected Subject create() { + return AsyncSubject.create(); + } + @Test public void testNeverCompleted() { AsyncSubject subject = AsyncSubject.create(); @@ -422,58 +427,6 @@ public void fusionOfflie() { .assertResult(1); } - @Test - public void onNextNull() { - final AsyncSubject s = AsyncSubject.create(); - - s.onNext(null); - - s.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onErrorNull() { - final AsyncSubject s = AsyncSubject.create(); - - s.onError(null); - - s.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onNextNullDelayed() { - final AsyncSubject p = AsyncSubject.create(); - - TestObserver ts = p.test(); - - p.onNext(null); - - ts - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onErrorNullDelayed() { - final AsyncSubject p = AsyncSubject.create(); - - TestObserver ts = p.test(); - - p.onError(null); - - ts - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } - @Test public void onSubscribeAfterDone() { AsyncSubject p = AsyncSubject.create(); diff --git a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java index 62941ef5e0..2e2cc2f05e 100644 --- a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java @@ -32,10 +32,15 @@ import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; -public class BehaviorSubjectTest { +public class BehaviorSubjectTest extends SubjectTest { private final Throwable testException = new Throwable(); + @Override + protected Subject create() { + return BehaviorSubject.create(); + } + @Test public void testThatSubscriberReceivesDefaultValueAndSubsequentEvents() { BehaviorSubject subject = BehaviorSubject.createDefault("default"); @@ -563,66 +568,6 @@ public void testCurrentStateMethodsError() { assertTrue(as.getThrowable() instanceof TestException); } - @Test - public void onNextNull() { - final BehaviorSubject s = BehaviorSubject.create(); - - s.onNext(null); - - s.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onErrorNull() { - final BehaviorSubject s = BehaviorSubject.create(); - - s.onError(null); - - s.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onNextNullDelayed() { - final BehaviorSubject p = BehaviorSubject.create(); - - TestObserver ts = p.test(); - - assertTrue(p.hasObservers()); - - p.onNext(null); - - assertFalse(p.hasObservers()); - - ts - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onErrorNullDelayed() { - final BehaviorSubject p = BehaviorSubject.create(); - - TestObserver ts = p.test(); - - assertTrue(p.hasObservers()); - - p.onError(null); - - assertFalse(p.hasObservers()); - - ts - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } - @Test public void cancelOnArrival() { BehaviorSubject p = BehaviorSubject.create(); diff --git a/src/test/java/io/reactivex/subjects/CompletableSubjectTest.java b/src/test/java/io/reactivex/subjects/CompletableSubjectTest.java index c2c13fd5d3..b569457c16 100644 --- a/src/test/java/io/reactivex/subjects/CompletableSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/CompletableSubjectTest.java @@ -125,11 +125,14 @@ public void complete() { public void nullThrowable() { CompletableSubject cs = CompletableSubject.create(); - TestObserver to = cs.test(); - - cs.onError(null); + try { + cs.onError(null); + fail("No NullPointerException thrown"); + } catch (NullPointerException ex) { + assertEquals("onError called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); + } - to.assertFailure(NullPointerException.class); + cs.test().assertEmpty().cancel();; } @Test diff --git a/src/test/java/io/reactivex/subjects/MaybeSubjectTest.java b/src/test/java/io/reactivex/subjects/MaybeSubjectTest.java index 8d40960d19..c7b8b4f4c5 100644 --- a/src/test/java/io/reactivex/subjects/MaybeSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/MaybeSubjectTest.java @@ -176,28 +176,6 @@ public void complete() { assertEquals(0, ms.observerCount()); } - @Test - public void nullValue() { - MaybeSubject ms = MaybeSubject.create(); - - TestObserver to = ms.test(); - - ms.onSuccess(null); - - to.assertFailure(NullPointerException.class); - } - - @Test - public void nullThrowable() { - MaybeSubject ms = MaybeSubject.create(); - - TestObserver to = ms.test(); - - ms.onError(null); - - to.assertFailure(NullPointerException.class); - } - @Test public void cancelOnArrival() { MaybeSubject.create() diff --git a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java index c7b6d2810d..459f075f96 100644 --- a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java @@ -30,7 +30,12 @@ import io.reactivex.observers.*; import io.reactivex.schedulers.Schedulers; -public class PublishSubjectTest { +public class PublishSubjectTest extends SubjectTest { + + @Override + protected Subject create() { + return PublishSubject.create(); + } @Test public void testCompleted() { @@ -667,30 +672,6 @@ public void subscribeToAfterComplete() { assertFalse(pp2.hasObservers()); } - @Test - public void nullOnNext() { - PublishSubject pp = PublishSubject.create(); - - TestObserver ts = pp.test(); - - assertTrue(pp.hasObservers()); - - pp.onNext(null); - - ts.assertFailure(NullPointerException.class); - } - - @Test - public void nullOnError() { - PublishSubject pp = PublishSubject.create(); - - TestObserver ts = pp.test(); - - pp.onError(null); - - ts.assertFailure(NullPointerException.class); - } - @Test public void subscribedTo() { PublishSubject pp = PublishSubject.create(); @@ -706,28 +687,4 @@ public void subscribedTo() { ts.assertResult(1, 2); } - - @Test - public void onNextNull() { - final PublishSubject s = PublishSubject.create(); - - s.onNext(null); - - s.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onErrorNull() { - final PublishSubject s = PublishSubject.create(); - - s.onError(null); - - s.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } } diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java index 0f5e1032ab..2739b24aae 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java @@ -31,10 +31,15 @@ import io.reactivex.observers.*; import io.reactivex.schedulers.*; -public class ReplaySubjectTest { +public class ReplaySubjectTest extends SubjectTest { private final Throwable testException = new Throwable(); + @Override + protected Subject create() { + return ReplaySubject.create(); + } + @Test public void testCompleted() { ReplaySubject subject = ReplaySubject.create(); @@ -951,30 +956,6 @@ public void peekStateTimeAndSizeValueExpired() { assertNull(rp.getValues(new Integer[2])[0]); } - @Test - public void onNextNull() { - final ReplaySubject s = ReplaySubject.create(); - - s.onNext(null); - - s.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onErrorNull() { - final ReplaySubject s = ReplaySubject.create(); - - s.onError(null); - - s.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } - @Test public void capacityHint() { ReplaySubject rp = ReplaySubject.create(8); diff --git a/src/test/java/io/reactivex/subjects/SingleSubjectTest.java b/src/test/java/io/reactivex/subjects/SingleSubjectTest.java index 1ddf762f51..19d6ab6a64 100644 --- a/src/test/java/io/reactivex/subjects/SingleSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/SingleSubjectTest.java @@ -131,22 +131,28 @@ public void error() { public void nullValue() { SingleSubject ss = SingleSubject.create(); - TestObserver to = ss.test(); - - ss.onSuccess(null); + try { + ss.onSuccess(null); + fail("No NullPointerException thrown"); + } catch (NullPointerException ex) { + assertEquals("onSuccess called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); + } - to.assertFailure(NullPointerException.class); + ss.test().assertEmpty().cancel(); } @Test public void nullThrowable() { SingleSubject ss = SingleSubject.create(); - TestObserver to = ss.test(); - - ss.onError(null); + try { + ss.onError(null); + fail("No NullPointerException thrown"); + } catch (NullPointerException ex) { + assertEquals("onError called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); + } - to.assertFailure(NullPointerException.class); + ss.test().assertEmpty().cancel(); } @Test diff --git a/src/test/java/io/reactivex/subjects/SubjectTest.java b/src/test/java/io/reactivex/subjects/SubjectTest.java new file mode 100644 index 0000000000..a50a17781b --- /dev/null +++ b/src/test/java/io/reactivex/subjects/SubjectTest.java @@ -0,0 +1,51 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.subjects; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public abstract class SubjectTest { + + protected abstract Subject create(); + + @Test + public void onNextNull() { + Subject p = create(); + + try { + p.onNext(null); + fail("No NullPointerException thrown"); + } catch (NullPointerException ex) { + assertEquals("onNext called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); + } + + p.test().assertEmpty().cancel(); + } + + @Test + public void onErrorNull() { + Subject p = create(); + + try { + p.onError(null); + fail("No NullPointerException thrown"); + } catch (NullPointerException ex) { + assertEquals("onError called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); + } + + p.test().assertEmpty().cancel(); + } +} diff --git a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java index 1788638967..12f838ee99 100644 --- a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java @@ -29,7 +29,12 @@ import io.reactivex.schedulers.Schedulers; import static org.mockito.Mockito.mock; -public class UnicastSubjectTest { +public class UnicastSubjectTest extends SubjectTest { + + @Override + protected Subject create() { + return UnicastSubject.create(); + } @Test public void fusionLive() { @@ -216,64 +221,6 @@ public void zeroCapacityHint() { UnicastSubject.create(0); } - @Test - public void onNextNull() { - final UnicastSubject s = UnicastSubject.create(); - - s.onNext(null); - - s.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onErrorNull() { - final UnicastSubject s = UnicastSubject.create(); - - s.onError(null); - - s.test() - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onNextNullDelayed() { - final UnicastSubject p = UnicastSubject.create(); - - TestObserver ts = p.test(); - - p.onNext(null); - - ts - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - } - - @Test - public void onErrorNullDelayed() { - final UnicastSubject p = UnicastSubject.create(); - - assertFalse(p.hasObservers()); - - TestObserver ts = p.test(); - - assertTrue(p.hasObservers()); - - p.onError(null); - - assertFalse(p.hasObservers()); - - ts - .assertNoValues() - .assertError(NullPointerException.class) - .assertErrorMessage("onError called with null. Null values are generally not allowed in 2.x operators and sources."); - } - @Test public void completeCancelRace() { for (int i = 0; i < 500; i++) { diff --git a/src/test/java/io/reactivex/tck/RefCountProcessor.java b/src/test/java/io/reactivex/tck/RefCountProcessor.java new file mode 100644 index 0000000000..43fc5d4064 --- /dev/null +++ b/src/test/java/io/reactivex/tck/RefCountProcessor.java @@ -0,0 +1,219 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.FlowableSubscriber; +import io.reactivex.internal.subscriptions.*; +import io.reactivex.processors.FlowableProcessor; + +/** + * A FlowableProcessor wrapper that disposes the Subscription set via + * onSubscribe if the number of subscribers reaches zero. + * + * @param the upstream and downstream value type + * @since 2.1.8 + */ +/* public */final class RefCountProcessor extends FlowableProcessor implements Subscription { + + final FlowableProcessor actual; + + final AtomicReference upstream; + + final AtomicReference[]> subscribers; + + @SuppressWarnings("rawtypes") + static final RefCountSubscriber[] EMPTY = new RefCountSubscriber[0]; + + @SuppressWarnings("rawtypes") + static final RefCountSubscriber[] TERMINATED = new RefCountSubscriber[0]; + + @SuppressWarnings("unchecked") + RefCountProcessor(FlowableProcessor actual) { + this.actual = actual; + this.upstream = new AtomicReference(); + this.subscribers = new AtomicReference[]>(EMPTY); + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.setOnce(upstream, s)) { + actual.onSubscribe(this); + } + } + + @Override + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public void onError(Throwable t) { + upstream.lazySet(SubscriptionHelper.CANCELLED); + actual.onError(t); + } + + @Override + public void onComplete() { + upstream.lazySet(SubscriptionHelper.CANCELLED); + actual.onComplete(); + } + + @Override + protected void subscribeActual(Subscriber s) { + RefCountSubscriber rcs = new RefCountSubscriber(s, this); + if (!add(rcs)) { + EmptySubscription.error(new IllegalStateException("RefCountProcessor terminated"), s); + return; + } + actual.subscribe(rcs); + } + + @Override + public boolean hasComplete() { + return actual.hasComplete(); + } + + @Override + public boolean hasThrowable() { + return actual.hasThrowable(); + } + + @Override + public Throwable getThrowable() { + return actual.getThrowable(); + } + + @Override + public boolean hasSubscribers() { + return actual.hasSubscribers(); + } + + @Override + public void cancel() { + SubscriptionHelper.cancel(upstream); + } + + @Override + public void request(long n) { + upstream.get().request(n); + } + + boolean add(RefCountSubscriber rcs) { + for (;;) { + RefCountSubscriber[] a = subscribers.get(); + if (a == TERMINATED) { + return false; + } + int n = a.length; + @SuppressWarnings("unchecked") + RefCountSubscriber[] b = new RefCountSubscriber[n + 1]; + System.arraycopy(a, 0, b, 0, n); + b[n] = rcs; + if (subscribers.compareAndSet(a, b)) { + return true; + } + } + } + + @SuppressWarnings("unchecked") + void remove(RefCountSubscriber rcs) { + for (;;) { + RefCountSubscriber[] a = subscribers.get(); + int n = a.length; + if (n == 0) { + break; + } + int j = -1; + + for (int i = 0; i < n; i++) { + if (rcs == a[i]) { + j = i; + break; + } + } + + if (j < 0) { + break; + } + + RefCountSubscriber[] b; + if (n == 1) { + b = TERMINATED; + } else { + b = new RefCountSubscriber[n - 1]; + System.arraycopy(a, 0, b, 0, j); + System.arraycopy(a, j + 1, b, j, n - j - 1); + } + if (subscribers.compareAndSet(a, b)) { + if (b == TERMINATED) { + cancel(); + } + break; + } + } + } + + static final class RefCountSubscriber extends AtomicBoolean implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = -4317488092687530631L; + + final Subscriber actual; + + final RefCountProcessor parent; + + Subscription upstream; + + RefCountSubscriber(Subscriber actual, RefCountProcessor parent) { + this.actual = actual; + this.parent = parent; + } + + @Override + public void request(long n) { + upstream.request(n); + } + + @Override + public void cancel() { + lazySet(true); + upstream.cancel(); + parent.remove(this); + } + + @Override + public void onSubscribe(Subscription s) { + this.upstream = s; + actual.onSubscribe(this); + } + + @Override + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public void onError(Throwable t) { + actual.onError(t); + } + + @Override + public void onComplete() { + actual.onComplete(); + } + } +} diff --git a/src/test/java/io/reactivex/tck/UnicastProcessorTckTest.java b/src/test/java/io/reactivex/tck/UnicastProcessorTckTest.java new file mode 100644 index 0000000000..e6490905ea --- /dev/null +++ b/src/test/java/io/reactivex/tck/UnicastProcessorTckTest.java @@ -0,0 +1,64 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import java.util.concurrent.*; + +import org.reactivestreams.*; +import org.reactivestreams.tck.*; +import org.testng.annotations.Test; + +import io.reactivex.exceptions.TestException; +import io.reactivex.processors.UnicastProcessor; + +@Test +public class UnicastProcessorTckTest extends IdentityProcessorVerification { + + public UnicastProcessorTckTest() { + super(new TestEnvironment(50)); + } + + @Override + public Processor createIdentityProcessor(int bufferSize) { + UnicastProcessor up = UnicastProcessor.create(); + return new RefCountProcessor(up); + } + + @Override + public Publisher createFailedPublisher() { + UnicastProcessor up = UnicastProcessor.create(); + up.onError(new TestException()); + return up; + } + + @Override + public ExecutorService publisherExecutorService() { + return Executors.newCachedThreadPool(); + } + + @Override + public Integer createElement(int element) { + return element; + } + + @Override + public long maxSupportedSubscribers() { + return 1; + } + + @Override + public long maxElementsFromPublisher() { + return 1024; + } +} From e71b49caf865966b3670e0671914d1116b043de8 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 19 Dec 2017 16:38:05 +0100 Subject: [PATCH 063/417] 2.x: Upgrade to Reactive Streams 1.0.2 final (#5771) --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 33c1adae30..8cafd79d9d 100644 --- a/build.gradle +++ b/build.gradle @@ -51,7 +51,7 @@ targetCompatibility = JavaVersion.VERSION_1_6 // --------------------------------------- def junitVersion = "4.12" -def reactiveStreamsVersion = "1.0.1" +def reactiveStreamsVersion = "1.0.2" def mockitoVersion = "2.1.0" def jmhLibVersion = "1.19" def testNgVersion = "6.11" From 30960243f4bb8572cbfa1eeadfbd3f0ea063f1c2 Mon Sep 17 00:00:00 2001 From: Shaishav Gandhi Date: Tue, 19 Dec 2017 09:36:31 -0800 Subject: [PATCH 064/417] Rename interface parameters (#5766) Signed-off-by: shaishavgandhi05 --- src/main/java/io/reactivex/CompletableOnSubscribe.java | 4 ++-- src/main/java/io/reactivex/FlowableOnSubscribe.java | 4 ++-- src/main/java/io/reactivex/MaybeOnSubscribe.java | 4 ++-- src/main/java/io/reactivex/ObservableOnSubscribe.java | 4 ++-- src/main/java/io/reactivex/SingleOnSubscribe.java | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/CompletableOnSubscribe.java b/src/main/java/io/reactivex/CompletableOnSubscribe.java index f4dae79f5d..0610a9b3a6 100644 --- a/src/main/java/io/reactivex/CompletableOnSubscribe.java +++ b/src/main/java/io/reactivex/CompletableOnSubscribe.java @@ -23,9 +23,9 @@ public interface CompletableOnSubscribe { /** * Called for each CompletableObserver that subscribes. - * @param e the safe emitter instance, never null + * @param emitter the safe emitter instance, never null * @throws Exception on error */ - void subscribe(@NonNull CompletableEmitter e) throws Exception; + void subscribe(@NonNull CompletableEmitter emitter) throws Exception; } diff --git a/src/main/java/io/reactivex/FlowableOnSubscribe.java b/src/main/java/io/reactivex/FlowableOnSubscribe.java index 40911eb3cd..b5b7b83a3d 100644 --- a/src/main/java/io/reactivex/FlowableOnSubscribe.java +++ b/src/main/java/io/reactivex/FlowableOnSubscribe.java @@ -25,9 +25,9 @@ public interface FlowableOnSubscribe { /** * Called for each Subscriber that subscribes. - * @param e the safe emitter instance, never null + * @param emitter the safe emitter instance, never null * @throws Exception on error */ - void subscribe(@NonNull FlowableEmitter e) throws Exception; + void subscribe(@NonNull FlowableEmitter emitter) throws Exception; } diff --git a/src/main/java/io/reactivex/MaybeOnSubscribe.java b/src/main/java/io/reactivex/MaybeOnSubscribe.java index 9c03275797..035a001be7 100644 --- a/src/main/java/io/reactivex/MaybeOnSubscribe.java +++ b/src/main/java/io/reactivex/MaybeOnSubscribe.java @@ -25,9 +25,9 @@ public interface MaybeOnSubscribe { /** * Called for each MaybeObserver that subscribes. - * @param e the safe emitter instance, never null + * @param emitter the safe emitter instance, never null * @throws Exception on error */ - void subscribe(@NonNull MaybeEmitter e) throws Exception; + void subscribe(@NonNull MaybeEmitter emitter) throws Exception; } diff --git a/src/main/java/io/reactivex/ObservableOnSubscribe.java b/src/main/java/io/reactivex/ObservableOnSubscribe.java index 6ed97c7779..bce34e1925 100644 --- a/src/main/java/io/reactivex/ObservableOnSubscribe.java +++ b/src/main/java/io/reactivex/ObservableOnSubscribe.java @@ -25,9 +25,9 @@ public interface ObservableOnSubscribe { /** * Called for each Observer that subscribes. - * @param e the safe emitter instance, never null + * @param emitter the safe emitter instance, never null * @throws Exception on error */ - void subscribe(@NonNull ObservableEmitter e) throws Exception; + void subscribe(@NonNull ObservableEmitter emitter) throws Exception; } diff --git a/src/main/java/io/reactivex/SingleOnSubscribe.java b/src/main/java/io/reactivex/SingleOnSubscribe.java index 1f65502729..aa12a0dcd4 100644 --- a/src/main/java/io/reactivex/SingleOnSubscribe.java +++ b/src/main/java/io/reactivex/SingleOnSubscribe.java @@ -25,9 +25,9 @@ public interface SingleOnSubscribe { /** * Called for each SingleObserver that subscribes. - * @param e the safe emitter instance, never null + * @param emitter the safe emitter instance, never null * @throws Exception on error */ - void subscribe(@NonNull SingleEmitter e) throws Exception; + void subscribe(@NonNull SingleEmitter emitter) throws Exception; } From 20a72ca2973ebe1ef160baa9d0ebda369c95d438 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 22 Dec 2017 13:36:56 +0100 Subject: [PATCH 065/417] 2.x: Improve JavaDoc of retryWhen() operators (#5773) * 2.x: Improve JavaDoc of retryWhen() operators * Fix example to use emitter. * Fix factory class name * Fix example termination logic, proper blockingX() --- src/main/java/io/reactivex/Completable.java | 25 ++++++++++++++ src/main/java/io/reactivex/Flowable.java | 36 ++++++++++++++++++--- src/main/java/io/reactivex/Maybe.java | 31 ++++++++++++++++-- src/main/java/io/reactivex/Observable.java | 31 ++++++++++++++++-- src/main/java/io/reactivex/Single.java | 25 ++++++++++++++ 5 files changed, 137 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 1aafe50fb1..6d70d6baca 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1597,6 +1597,31 @@ public final Completable retry(Predicate predicate) { * Returns a Completable which given a Publisher and when this Completable emits an error, delivers * that error through a Flowable and the Publisher should signal a value indicating a retry in response * or a terminal event indicating a termination. + *

                + * Note that the inner {@code Publisher} returned by the handler function should signal + * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received + * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to + * the operator is asynchronous, signalling onNext followed by onComplete immediately may + * result in the sequence to be completed immediately. Similarly, if this inner + * {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is + * active, the sequence is terminated with the same signal immediately. + *

                + * The following example demonstrates how to retry an asynchronous source with a delay: + *

                
                +     * Completable.timer(1, TimeUnit.SECONDS)
                +     *     .doOnSubscribe(s -> System.out.println("subscribing"))
                +     *     .doOnComplete(() -> { throw new RuntimeException(); })
                +     *     .retryWhen(errors -> {
                +     *         AtomicInteger counter = new AtomicInteger();
                +     *         return errors
                +     *                   .takeWhile(e -> counter.getAndIncrement() != 3)
                +     *                   .flatMap(e -> {
                +     *                       System.out.println("delay retry by " + counter.get() + " second(s)");
                +     *                       return Flowable.timer(counter.get(), TimeUnit.SECONDS);
                +     *                   });
                +     *     })
                +     *     .blockingAwait();
                +     * 
                *
                *
                Scheduler:
                *
                {@code retryWhen} does not operate by default on a particular {@link Scheduler}.
                diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index b2da55c6fa..623f7874de 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -11770,19 +11770,19 @@ public final Flowable retryUntil(final BooleanSupplier stop) { * resubscribe to the source Publisher. *

                * - * + *

                * Example: * * This retries 3 times, each time incrementing the number of seconds it waits. * *

                
                -     *  Publisher.create((Subscriber<? super String> s) -> {
                +     *  Flowable.create((FlowableEmitter<? super String> s) -> {
                      *      System.out.println("subscribing");
                      *      s.onError(new RuntimeException("always fails"));
                -     *  }).retryWhen(attempts -> {
                +     *  }, BackpressureStrategy.BUFFER).retryWhen(attempts -> {
                      *      return attempts.zipWith(Flowable.range(1, 3), (n, i) -> i).flatMap(i -> {
                      *          System.out.println("delay retry by " + i + " second(s)");
                -     *          return Publisher.timer(i, TimeUnit.SECONDS);
                +     *          return Flowable.timer(i, TimeUnit.SECONDS);
                      *      });
                      *  }).blockingForEach(System.out::println);
                      * 
                @@ -11798,9 +11798,35 @@ public final Flowable retryUntil(final BooleanSupplier stop) { * delay retry by 3 second(s) * subscribing * } + *

                + * Note that the inner {@code Publisher} returned by the handler function should signal + * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received + * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to + * the operator is asynchronous, signalling onNext followed by onComplete immediately may + * result in the sequence to be completed immediately. Similarly, if this inner + * {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is + * active, the sequence is terminated with the same signal immediately. + *

                + * The following example demonstrates how to retry an asynchronous source with a delay: + *

                
                +     * Flowable.timer(1, TimeUnit.SECONDS)
                +     *     .doOnSubscribe(s -> System.out.println("subscribing"))
                +     *     .map(v -> { throw new RuntimeException(); })
                +     *     .retryWhen(errors -> {
                +     *         AtomicInteger counter = new AtomicInteger();
                +     *         return errors
                +     *                   .takeWhile(e -> counter.getAndIncrement() != 3)
                +     *                   .flatMap(e -> {
                +     *                       System.out.println("delay retry by " + counter.get() + " second(s)");
                +     *                       return Flowable.timer(counter.get(), TimeUnit.SECONDS);
                +     *                   });
                +     *     })
                +     *     .blockingSubscribe(System.out::println, System.out::println);
                +     * 
                *
                *
                Backpressure:
                - *
                The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well. + *
                The operator honors downstream backpressure and expects both the source + * and inner {@code Publisher}s to honor backpressure as well. * If this expectation is violated, the operator may throw an {@code IllegalStateException}.
                *
                Scheduler:
                *
                {@code retryWhen} does not operate by default on a particular {@link Scheduler}.
                diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index c2a88aacb3..6dfbe3d927 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3585,19 +3585,19 @@ public final Maybe retryUntil(final BooleanSupplier stop) { * resubscribe to the source Publisher. *

                * - * + *

                * Example: * * This retries 3 times, each time incrementing the number of seconds it waits. * *

                
                -     *  Flowable.create((FlowableEmitter<? super String> s) -> {
                +     *  Maybe.create((MaybeEmitter<? super String> s) -> {
                      *      System.out.println("subscribing");
                      *      s.onError(new RuntimeException("always fails"));
                      *  }, BackpressureStrategy.BUFFER).retryWhen(attempts -> {
                      *      return attempts.zipWith(Publisher.range(1, 3), (n, i) -> i).flatMap(i -> {
                      *          System.out.println("delay retry by " + i + " second(s)");
                -     *          return Publisher.timer(i, TimeUnit.SECONDS);
                +     *          return Flowable.timer(i, TimeUnit.SECONDS);
                      *      });
                      *  }).blockingForEach(System.out::println);
                      * 
                @@ -3613,6 +3613,31 @@ public final Maybe retryUntil(final BooleanSupplier stop) { * delay retry by 3 second(s) * subscribing * } + *

                + * Note that the inner {@code Publisher} returned by the handler function should signal + * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received + * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to + * the operator is asynchronous, signalling onNext followed by onComplete immediately may + * result in the sequence to be completed immediately. Similarly, if this inner + * {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is + * active, the sequence is terminated with the same signal immediately. + *

                + * The following example demonstrates how to retry an asynchronous source with a delay: + *

                
                +     * Maybe.timer(1, TimeUnit.SECONDS)
                +     *     .doOnSubscribe(s -> System.out.println("subscribing"))
                +     *     .map(v -> { throw new RuntimeException(); })
                +     *     .retryWhen(errors -> {
                +     *         AtomicInteger counter = new AtomicInteger();
                +     *         return errors
                +     *                   .takeWhile(e -> counter.getAndIncrement() != 3)
                +     *                   .flatMap(e -> {
                +     *                       System.out.println("delay retry by " + counter.get() + " second(s)");
                +     *                       return Flowable.timer(counter.get(), TimeUnit.SECONDS);
                +     *                   });
                +     *     })
                +     *     .blockingGet();
                +     * 
                *
                *
                Scheduler:
                *
                {@code retryWhen} does not operate by default on a particular {@link Scheduler}.
                diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 83b807371b..3b1b7f8985 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -9927,19 +9927,19 @@ public final Observable retryUntil(final BooleanSupplier stop) { * resubscribe to the source ObservableSource. *

                * - * + *

                * Example: * * This retries 3 times, each time incrementing the number of seconds it waits. * *

                
                -     *  ObservableSource.create((Observer<? super String> s) -> {
                +     *  Observable.create((ObservableEmitter<? super String> s) -> {
                      *      System.out.println("subscribing");
                      *      s.onError(new RuntimeException("always fails"));
                      *  }).retryWhen(attempts -> {
                      *      return attempts.zipWith(Observable.range(1, 3), (n, i) -> i).flatMap(i -> {
                      *          System.out.println("delay retry by " + i + " second(s)");
                -     *          return ObservableSource.timer(i, TimeUnit.SECONDS);
                +     *          return Observable.timer(i, TimeUnit.SECONDS);
                      *      });
                      *  }).blockingForEach(System.out::println);
                      * 
                @@ -9955,6 +9955,31 @@ public final Observable retryUntil(final BooleanSupplier stop) { * delay retry by 3 second(s) * subscribing * } + *

                + * Note that the inner {@code ObservableSource} returned by the handler function should signal + * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received + * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to + * the operator is asynchronous, signalling onNext followed by onComplete immediately may + * result in the sequence to be completed immediately. Similarly, if this inner + * {@code ObservableSource} signals {@code onError} or {@code onComplete} while the upstream is + * active, the sequence is terminated with the same signal immediately. + *

                + * The following example demonstrates how to retry an asynchronous source with a delay: + *

                
                +     * Observable.timer(1, TimeUnit.SECONDS)
                +     *     .doOnSubscribe(s -> System.out.println("subscribing"))
                +     *     .map(v -> { throw new RuntimeException(); })
                +     *     .retryWhen(errors -> {
                +     *         AtomicInteger counter = new AtomicInteger();
                +     *         return errors
                +     *                   .takeWhile(e -> counter.getAndIncrement() != 3)
                +     *                   .flatMap(e -> {
                +     *                       System.out.println("delay retry by " + counter.get() + " second(s)");
                +     *                       return Observable.timer(counter.get(), TimeUnit.SECONDS);
                +     *                   });
                +     *     })
                +     *     .blockingSubscribe(System.out::println, System.out::println);
                +     * 
                *
                *
                Scheduler:
                *
                {@code retryWhen} does not operate by default on a particular {@link Scheduler}.
                diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index df59da1ff5..ed185920cc 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2692,6 +2692,31 @@ public final Single retry(Predicate predicate) { * function signals a value. *

                * If the Publisher signals an onComplete, the resulting Single will signal a NoSuchElementException. + *

                + * Note that the inner {@code Publisher} returned by the handler function should signal + * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received + * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to + * the operator is asynchronous, signalling onNext followed by onComplete immediately may + * result in the sequence to be completed immediately. Similarly, if this inner + * {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is + * active, the sequence is terminated with the same signal immediately. + *

                + * The following example demonstrates how to retry an asynchronous source with a delay: + *

                
                +     * Single.timer(1, TimeUnit.SECONDS)
                +     *     .doOnSubscribe(s -> System.out.println("subscribing"))
                +     *     .map(v -> { throw new RuntimeException(); })
                +     *     .retryWhen(errors -> {
                +     *         AtomicInteger counter = new AtomicInteger();
                +     *         return errors
                +     *                   .takeWhile(e -> counter.getAndIncrement() != 3)
                +     *                   .flatMap(e -> {
                +     *                       System.out.println("delay retry by " + counter.get() + " second(s)");
                +     *                       return Flowable.timer(counter.get(), TimeUnit.SECONDS);
                +     *                   });
                +     *     })
                +     *     .blockingGet();
                +     * 
                *
                *
                Scheduler:
                *
                {@code retryWhen} does not operate by default on a particular {@link Scheduler}.
                From a1c3ba9c885ac6b069b304f6b18c2bfe37278fdc Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 27 Dec 2017 12:00:49 +0100 Subject: [PATCH 066/417] 2.x: Improve BehaviorProcessor JavaDoc (#5778) * 2.x: Improve BehaviorProcessor JavaDoc * Use > in the first example --- .../processors/BehaviorProcessor.java | 99 +++++++++++++++++-- 1 file changed, 90 insertions(+), 9 deletions(-) diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index e161727bb3..b5a3e20ad8 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -33,6 +33,87 @@ *

                * *

                + * This processor does not have a public constructor by design; a new empty instance of this + * {@code BehaviorSubject} can be created via the {@link #create()} method and + * a new non-empty instance can be created via {@link #createDefault(Object)} (named as such to avoid + * overload resolution conflict with {@code Flowable.create} that creates a Flowable, not a {@code BehaviorProcessor}). + *

                + * In accordance with the Reactive Streams specification (Rule 2.13) + * {@code null}s are not allowed as default initial values in {@link #createDefault(Object)} or as parameters to {@link #onNext(Object)} and + * {@link #onError(Throwable)}. + *

                + * When this {@code BehaviorProcessor} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, the + * last observed item (if any) is cleared and late {@link org.reactivestreams.Subscriber}s only receive + * the respective terminal event. + *

                + * The {@code BehaviorProcessor} does not support clearing its cached value (to appear empty again), however, the + * effect can be achieved by using a special item and making sure {@code Subscriber}s subscribe through a + * filter whose predicate filters out this special item: + *

                
                + * BehaviorProcessor<Integer> processor = BehaviorProcessor.create();
                + *
                + * final Integer EMPTY = Integer.MIN_VALUE;
                + *
                + * Flowable<Integer> flowable = processor.filter(v -> v != EMPTY);
                + *
                + * TestSubscriber<Integer> ts1 = flowable.test();
                + *
                + * processor.onNext(1);
                + * // this will "clear" the cache
                + * processor.onNext(EMPTY);
                + * 
                + * TestSubscriber<Integer> ts2 = flowable.test();
                + * 
                + * processor.onNext(2);
                + * processor.onComplete();
                + * 
                + * // ts1 received both non-empty items
                + * ts1.assertResult(1, 2);
                + * 
                + * // ts2 received only 2 even though the current item was EMPTY
                + * // when it got subscribed
                + * ts2.assertResult(2);
                + * 
                + * // Subscribers coming after the processor was terminated receive
                + * // no items and only the onComplete event in this case.
                + * flowable.test().assertResult();
                + * 
                + *

                + * Even though {@code BehaviorProcessor} implements the {@code Subscriber} interface, calling + * {@code onSubscribe} is not required (Rule 2.12) + * if the processor is used as a standalone source. However, calling {@code onSubscribe} is + * called after the {@code BehaviorProcessor} reached its terminal state will result in the + * given {@code Subscription} being cancelled immediately. + *

                + * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is still required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@code FlowableProcessor}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} + * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively. + *

                + * This {@code BehaviorProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the latest observed value + * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()}, + * {@link #getValues()} or {@link #getValues(Object[])}. + *

                + * Note that this processor signals {@code MissingBackpressureException} if a particular {@code Subscriber} is not + * ready to receive {@code onNext} events. To avoid this exception being signaled, use {@link #offer(Object)} to only + * try to emit an item when all {@code Subscriber}s have requested item(s). + *

                + *
                Backpressure:
                + *
                The {@code BehaviorProcessor} does not coordinate requests of its downstream {@code Subscriber}s and + * expects each individual {@code Subscriber} is ready to receive {@code onNext} items when {@link #onNext(Object)} + * is called. If a {@code Subscriber} is not ready, a {@code MissingBackpressureException} is signalled to it. + * To avoid overflowing the current {@code Subscriber}s, the conditional {@link #offer(Object)} method is available + * that returns true if any of the {@code Subscriber}s is not ready to receive {@code onNext} events. If + * there are no {@code Subscriber}s to the processor, {@code offer()} always succeeds. + * If the {@code BehaviorProcessor} is (optionally) subscribed to another {@code Publisher}, this upstream + * {@code Publisher} is consumed in an unbounded fashion (requesting {@code Long.MAX_VALUE}).
                + *
                Scheduler:
                + *
                {@code BehaviorProcessor} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code Subscriber}s get notified on the thread the respective {@code onXXX} methods were invoked.
                + *
                + *

                * Example usage: *

                 {@code
                 
                @@ -94,7 +175,7 @@ public final class BehaviorProcessor extends FlowableProcessor {
                      * Creates a {@link BehaviorProcessor} without a default item.
                      *
                      * @param 
                -     *            the type of item the Subject will emit
                +     *            the type of item the BehaviorProcessor will emit
                      * @return the constructed {@link BehaviorProcessor}
                      */
                     @CheckReturnValue
                @@ -107,7 +188,7 @@ public static  BehaviorProcessor create() {
                      * {@link Subscriber} that subscribes to it.
                      *
                      * @param 
                -     *            the type of item the Subject will emit
                +     *            the type of item the BehaviorProcessor will emit
                      * @param defaultValue
                      *            the item that will be emitted first to any {@link Subscriber} as long as the
                      *            {@link BehaviorProcessor} has not yet observed any items from its source {@code Observable}
                @@ -266,9 +347,9 @@ public Throwable getThrowable() {
                     }
                 
                     /**
                -     * Returns a single value the Subject currently has or null if no such value exists.
                +     * Returns a single value the BehaviorProcessor currently has or null if no such value exists.
                      * 

                The method is thread-safe. - * @return a single value the Subject currently has or null if no such value exists + * @return a single value the BehaviorProcessor currently has or null if no such value exists */ public T getValue() { Object o = value.get(); @@ -279,9 +360,9 @@ public T getValue() { } /** - * Returns an Object array containing snapshot all values of the Subject. + * Returns an Object array containing snapshot all values of the BehaviorProcessor. *

                The method is thread-safe. - * @return the array containing the snapshot of all values of the Subject + * @return the array containing the snapshot of all values of the BehaviorProcessor */ public Object[] getValues() { @SuppressWarnings("unchecked") @@ -295,7 +376,7 @@ public Object[] getValues() { } /** - * Returns a typed array containing a snapshot of all values of the Subject. + * Returns a typed array containing a snapshot of all values of the BehaviorProcessor. *

                The method follows the conventions of Collection.toArray by setting the array element * after the last value to null (if the capacity permits). *

                The method is thread-safe. @@ -337,9 +418,9 @@ public boolean hasThrowable() { } /** - * Returns true if the subject has any value. + * Returns true if the BehaviorProcessor has any value. *

                The method is thread-safe. - * @return true if the subject has any value + * @return true if the BehaviorProcessor has any value */ public boolean hasValue() { Object o = value.get(); From 7e503f0e8e51ecb92622f2e0e0547d7406a901de Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 27 Dec 2017 12:03:50 +0100 Subject: [PATCH 067/417] Update CHANGES.md --- CHANGES.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 5a88033962..675b42389e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,57 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.8 - December 27, 2017 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.8%7C)) + +**Warning! Behavior change regarding handling illegal calls with `null` in `Processor`s and `Subject`s.** + +The [Reactive Streams specification](https://github.com/reactive-streams/reactive-streams-jvm#user-content-2.13) mandates that calling `onNext` and `onError` with `null` should +result in an immediate `NullPointerException` thrown from these methods. Unfortunately, this requirement was overlooked (it resulted in calls to `onError` with `NullPointerException` which meant the Processor/Subject variants entered their terminal state). + +If, for some reason, the original behavior is required, one has to call `onError` with a `NullPointerException` explicitly: + +```java +PublishSubject ps = PublishSubject.create(); + +TestObserver to = ps.test(); + +// ps.onNext(null); // doesn't work anymore + +ps.onError(new NullPointerException()); + +to.assertFailure(NullPointerException.class); +``` + +#### API changes + +- [Pull 5741](https://github.com/ReactiveX/RxJava/pull/5741): API to get distinct `Worker`s from some `Scheduler`s. +- [Pull 5734](https://github.com/ReactiveX/RxJava/pull/5734): Add `RxJavaPlugins.unwrapRunnable` to help with RxJava-internal wrappers in `Scheduler`s. +- [Pull 5753](https://github.com/ReactiveX/RxJava/pull/5753): Add `retry(times, predicate)` to `Single` & `Completable` and verify behavior across them and `Maybe`. + +#### Documentation changes + +- [Pull 5746](https://github.com/ReactiveX/RxJava/pull/5746): Improve wording and links in `package-info`s + remove unused imports. +- [Pull 5745](https://github.com/ReactiveX/RxJava/pull/5745): Add/update `Observable` marbles 11/28. +- [Commit 53d5a235](https://github.com/ReactiveX/RxJava/commit/53d5a235f63ca143c11571cd538ad927c0f8f3ad): Fix JavaDoc link in observables/package-info. +- [Pull 5755](https://github.com/ReactiveX/RxJava/pull/5755): Add marbles for `Observable` (12/06). +- [Pull 5756](https://github.com/ReactiveX/RxJava/pull/5756): Improve `autoConnect()` JavaDoc + add its marble. +- [Pull 5758](https://github.com/ReactiveX/RxJava/pull/5758): Add a couple of `@see` to `Completable`. +- [Pull 5759](https://github.com/ReactiveX/RxJava/pull/5759): Marble additions and updates (12/11) +- [Pull 5773](https://github.com/ReactiveX/RxJava/pull/5773): Improve JavaDoc of `retryWhen()` operators. +- [Pull 5778](https://github.com/ReactiveX/RxJava/pull/5778): Improve `BehaviorProcessor` JavaDoc. + +#### Bugfixes + +- [Pull 5747](https://github.com/ReactiveX/RxJava/pull/5747): Fix `TrampolineScheduler` not calling `RxJavaPlugins.onSchedule()`, add tests for all schedulers. +- [Pull 5748](https://github.com/ReactiveX/RxJava/pull/5748): Check `runnable == null` in `*Scheduler.schedule*()`. +- [Pull 5761](https://github.com/ReactiveX/RxJava/pull/5761): Fix timed exact `buffer()` calling cancel unnecessarily. +- [Pull 5760](https://github.com/ReactiveX/RxJava/pull/5760): `Subject`/`FlowableProcessor` NPE fixes, add `UnicastProcessor` TCK. + +#### Other + +- [Pull 5771](https://github.com/ReactiveX/RxJava/pull/5771): Upgrade dependency to Reactive Streams 1.0.2 +- [Pull 5766](https://github.com/ReactiveX/RxJava/pull/5766): Rename `XOnSubscribe` parameter name to `emitter` for better IDE auto-completion. + ### Version 2.1.7 - November 27, 2017 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.7%7C)) #### API changes From ba1f40ffcfaed06bd69c1b9a810790cf47178c1f Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 29 Dec 2017 17:22:00 +0100 Subject: [PATCH 068/417] 2.x: Fix JavaDoc wording of onTerminateDetach (#5783) --- src/main/java/io/reactivex/Flowable.java | 2 +- src/main/java/io/reactivex/Observable.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 623f7874de..d20b0aafee 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -10524,7 +10524,7 @@ public final Flowable onExceptionResumeNext(final Publisher next *

                Scheduler:
                *
                {@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.
                *
                - * @return a Flowable which out references to the upstream producer and downstream Subscriber if + * @return a Flowable which nulls out references to the upstream producer and downstream Subscriber if * the sequence is terminated or downstream cancels * @since 2.0 */ diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 3b1b7f8985..ae5942bcd1 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -9012,7 +9012,7 @@ public final Observable onExceptionResumeNext(final ObservableSourceScheduler: *
                {@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.
                *
                - * @return an Observable which out references to the upstream producer and downstream Observer if + * @return an Observable which nulls out references to the upstream producer and downstream Observer if * the sequence is terminated or downstream calls dispose() * @since 2.0 */ From 8b11ea879dd8d1e99a2ba88933a5fe3bdd9a24f6 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 3 Jan 2018 12:16:44 +0100 Subject: [PATCH 069/417] 2.x: Improve BehaviorSubject JavaDoc + related clarifications (#5780) * 2.x: Improve BehaviorSubject JavaDoc + related clarifications * Fix grammar, add wiki link --- .../io/reactivex/plugins/RxJavaPlugins.java | 17 ++++ .../processors/BehaviorProcessor.java | 18 ++++- .../reactivex/subjects/BehaviorSubject.java | 81 +++++++++++++++++++ 3 files changed, 112 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/plugins/RxJavaPlugins.java b/src/main/java/io/reactivex/plugins/RxJavaPlugins.java index 5c2f0ec5ad..1f477d4651 100644 --- a/src/main/java/io/reactivex/plugins/RxJavaPlugins.java +++ b/src/main/java/io/reactivex/plugins/RxJavaPlugins.java @@ -337,7 +337,24 @@ public static Scheduler onComputationScheduler(@NonNull Scheduler defaultSchedul /** * Called when an undeliverable error occurs. + *

                + * Undeliverable errors are those {@code Observer.onError()} invocations that are not allowed to happen on + * the given consumer type ({@code Observer}, {@code Subscriber}, etc.) due to protocol restrictions + * because the consumer has either disposed/cancelled its {@code Disposable}/{@code Subscription} or + * has already terminated with an {@code onError()} or {@code onComplete()} signal. + *

                + * By default, this global error handler prints the stacktrace via {@link Throwable#printStackTrace()} + * and calls {@link java.lang.Thread.UncaughtExceptionHandler#uncaughtException(Thread, Throwable)} + * on the current thread. + *

                + * Note that on some platforms, the platform runtime terminates the current application with an error if such + * uncaught exceptions happen. In this case, it is recommended the application installs a global error + * handler via the {@link #setErrorHandler(Consumer)} plugin method. + * * @param error the error to report + * @see #getErrorHandler() + * @see #setErrorHandler(Consumer) + * @see Error handling Wiki */ public static void onError(@NonNull Throwable error) { Consumer f = errorHandler; diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index b5a3e20ad8..ac1abea4f5 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -34,7 +34,7 @@ * *

                * This processor does not have a public constructor by design; a new empty instance of this - * {@code BehaviorSubject} can be created via the {@link #create()} method and + * {@code BehaviorProcessor} can be created via the {@link #create()} method and * a new non-empty instance can be created via {@link #createDefault(Object)} (named as such to avoid * overload resolution conflict with {@code Flowable.create} that creates a Flowable, not a {@code BehaviorProcessor}). *

                @@ -81,15 +81,15 @@ *

                * Even though {@code BehaviorProcessor} implements the {@code Subscriber} interface, calling * {@code onSubscribe} is not required (Rule 2.12) - * if the processor is used as a standalone source. However, calling {@code onSubscribe} is - * called after the {@code BehaviorProcessor} reached its terminal state will result in the + * if the processor is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code BehaviorProcessor} reached its terminal state will result in the * given {@code Subscription} being cancelled immediately. *

                * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} * is still required to be serialized (called from the same thread or called non-overlappingly from different threads * through external means of serialization). The {@link #toSerialized()} method available to all {@code FlowableProcessor}s * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} - * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively. + * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). *

                * This {@code BehaviorProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the latest observed value @@ -112,6 +112,16 @@ *

                Scheduler:
                *
                {@code BehaviorProcessor} does not operate by default on a particular {@link io.reactivex.Scheduler} and * the {@code Subscriber}s get notified on the thread the respective {@code onXXX} methods were invoked.
                + *
                Error handling:
                + *
                When the {@link #onError(Throwable)} is called, the {@code BehaviorProcessor} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code Subscriber}s. During this emission, + * if one or more {@code Subscriber}s cancel their respective {@code Subscription}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Subscriber}s + * cancel at once). + * If there were no {@code Subscriber}s subscribed to this {@code BehaviorProcessor} when the {@code onError()} + * was called, the global error handler is not invoked. + *
                *
                *

                * Example usage: diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java index 85ef6af409..f7ac689b34 100644 --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java @@ -31,6 +31,87 @@ *

                * *

                + * This subject does not have a public constructor by design; a new empty instance of this + * {@code BehaviorSubject} can be created via the {@link #create()} method and + * a new non-empty instance can be created via {@link #createDefault(Object)} (named as such to avoid + * overload resolution conflict with {@code Observable.create} that creates an Observable, not a {@code BehaviorSubject}). + *

                + * Since the {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, + * {@code null}s are not allowed (Rule 2.13) as + * default initial values in {@link #createDefault(Object)} or as parameters to {@link #onNext(Object)} and + * {@link #onError(Throwable)}. + *

                + * Since a {@code BehaviorSubject} is an {@link io.reactivex.Observable}, it does not support backpressure. + *

                + * When this {@code BehaviorSubject} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, the + * last observed item (if any) is cleared and late {@link io.reactivex.Observer}s only receive + * the respective terminal event. + *

                + * The {@code BehaviorSubject} does not support clearing its cached value (to appear empty again), however, the + * effect can be achieved by using a special item and making sure {@code Observer}s subscribe through a + * filter whose predicate filters out this special item: + *

                
                + * BehaviorSubject<Integer> subject = BehaviorSubject.create();
                + *
                + * final Integer EMPTY = Integer.MIN_VALUE;
                + *
                + * Observable<Integer> observable = subject.filter(v -> v != EMPTY);
                + *
                + * TestObserver<Integer> to1 = observable.test();
                + *
                + * observable.onNext(1);
                + * // this will "clear" the cache
                + * observable.onNext(EMPTY);
                + * 
                + * TestObserver<Integer> to2 = observable.test();
                + * 
                + * subject.onNext(2);
                + * subject.onComplete();
                + * 
                + * // to1 received both non-empty items
                + * to1.assertResult(1, 2);
                + * 
                + * // to2 received only 2 even though the current item was EMPTY
                + * // when it got subscribed
                + * to2.assertResult(2);
                + * 
                + * // Observers coming after the subject was terminated receive
                + * // no items and only the onComplete event in this case.
                + * observable.test().assertResult();
                + * 
                + *

                + * Even though {@code BehaviorSubject} implements the {@code Observer} interface, calling + * {@code onSubscribe} is not required (Rule 2.12) + * if the subject is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code BehaviorSubjecct} reached its terminal state will result in the + * given {@code Disposable} being disposed immediately. + *

                + * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is still required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer} + * consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively). + *

                + * This {@code BehaviorSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read the latest observed value + * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()}, + * {@link #getValues()} or {@link #getValues(Object[])}. + *

                + *
                Scheduler:
                + *
                {@code BehaviorSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code Observer}s get notified on the thread the respective {@code onXXX} methods were invoked.
                + *
                Error handling:
                + *
                When the {@link #onError(Throwable)} is called, the {@code BehaviorSubject} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code Observer}s. During this emission, + * if one or more {@code Observer}s dispose their respective {@code Disposable}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Observer}s + * cancel at once). + * If there were no {@code Observer}s subscribed to this {@code BehaviorSubject} when the {@code onError()} + * was called, the global error handler is not invoked. + *
                + *
                + *

                * Example usage: *

                 {@code
                 
                
                From a694145b6775960520dcd3964d9bcf3540fced24 Mon Sep 17 00:00:00 2001
                From: David Karnok 
                Date: Wed, 3 Jan 2018 12:35:53 +0100
                Subject: [PATCH 070/417] 2.x: Describe merge() error handling. (#5781)
                
                ---
                 src/main/java/io/reactivex/Flowable.java | 14 ++++++++++++++
                 1 file changed, 14 insertions(+)
                
                diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java
                index d20b0aafee..87bf672d96 100644
                --- a/src/main/java/io/reactivex/Flowable.java
                +++ b/src/main/java/io/reactivex/Flowable.java
                @@ -2965,6 +2965,19 @@ public static  Flowable mergeArray(int maxConcurrency, int bufferSize, Pub
                      *  backpressure; if violated, the operator may signal {@code MissingBackpressureException}.
                      *  
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as undeliverable errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code Publisher}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -2973,6 +2986,7 @@ public static Flowable mergeArray(int maxConcurrency, int bufferSize, Pub * @return a Flowable that emits items that are the result of flattening the items emitted by the * Publishers in the Iterable * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(Iterable) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue From 709ccd6c6f0795ed81dda3432568c866911ced10 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 3 Jan 2018 13:01:16 +0100 Subject: [PATCH 071/417] 2.x: Update Maybe doOn{Success,Error,Complete} JavaDoc (#5785) --- src/main/java/io/reactivex/Maybe.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 6dfbe3d927..fb053a7a13 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -41,6 +41,8 @@ * in a sequential fashion following this protocol:
                * {@code onSubscribe (onSuccess | onError | onComplete)?}. *

                + * Note that {@code onSuccess}, {@code onError} and {@code onComplete} are mutually exclusive events; unlike {@code Observable}, + * {@code onSuccess} is never followed by {@code onError} or {@code onComplete}. * @param the value type * @since 2.0 */ @@ -2489,7 +2491,7 @@ public final Maybe doOnDispose(Action onDispose) { /** * Modifies the source Maybe so that it invokes an action when it calls {@code onComplete}. *

                - * + * *

                *
                Scheduler:
                *
                {@code doOnComplete} does not operate by default on a particular {@link Scheduler}.
                @@ -2516,6 +2518,8 @@ public final Maybe doOnComplete(Action onComplete) { /** * Calls the shared consumer with the error sent via onError for each * MaybeObserver that subscribes to the current Maybe. + *

                + * *

                *
                Scheduler:
                *
                {@code doOnError} does not operate by default on a particular {@link Scheduler}.
                @@ -2583,6 +2587,8 @@ public final Maybe doOnSubscribe(Consumer onSubscribe) { /** * Calls the shared consumer with the success value sent via onSuccess for each * MaybeObserver that subscribes to the current Maybe. + *

                + * *

                *
                Scheduler:
                *
                {@code doOnSuccess} does not operate by default on a particular {@link Scheduler}.
                @@ -2653,7 +2659,7 @@ public final Maybe flatMap(Function * *
                @@ -4140,7 +4146,7 @@ public final Maybe timeout(Publisher timeoutIndicator, MaybeSource *
                Scheduler:
                *
                {@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.
                From 6aea3f015ae13878adba889d855871e6d1925158 Mon Sep 17 00:00:00 2001 From: Brian Donovan Date: Fri, 5 Jan 2018 15:10:28 -0500 Subject: [PATCH 072/417] Remove apostrophe to correct grammar. (#5793) In this case we want the 3rd person present form of "let", not the contraction "let us". --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9c6d500a3..f8f495ed04 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ Typically, you can move computations or blocking IO to some other thread via `su RxJava operators don't work with `Thread`s or `ExecutorService`s directly but with so called `Scheduler`s that abstract away sources of concurrency behind an uniform API. RxJava 2 features several standard schedulers accessible via `Schedulers` utility class. These are available on all JVM platforms but some specific platforms, such as Android, have their own typical `Scheduler`s defined: `AndroidSchedulers.mainThread()`, `SwingScheduler.instance()` or `JavaFXSchedulers.gui()`. -The `Thread.sleep(2000);` at the end is no accident. In RxJava the default `Scheduler`s run on daemon threads, which means once the Java main thread exits, they all get stopped and background computations may never happen. Sleeping for some time in this example situations let's you see the output of the flow on the console with time to spare. +The `Thread.sleep(2000);` at the end is no accident. In RxJava the default `Scheduler`s run on daemon threads, which means once the Java main thread exits, they all get stopped and background computations may never happen. Sleeping for some time in this example situations lets you see the output of the flow on the console with time to spare. Flows in RxJava are sequential in nature split into processing stages that may run **concurrently** with each other: From 4fd16ee958f7fbf2ee147bd152f4b119c68afd31 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 5 Jan 2018 23:34:31 +0100 Subject: [PATCH 073/417] 2.x: improve request accounting overhead in retry/repeat (#5790) * 2.x: improve request accounting overhead in retry/repeat * Test repeatUntil cancelled case --- .../operators/flowable/FlowableRepeat.java | 11 +++++++++-- .../flowable/FlowableRepeatUntil.java | 16 ++++++++++++++-- .../flowable/FlowableRetryBiPredicate.java | 13 +++++++++++-- .../flowable/FlowableRetryPredicate.java | 19 ++++++++++++++----- .../flowable/FlowableRepeatTest.java | 13 +++++++++++++ 5 files changed, 61 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java index 1c61800b97..a3f7e15d09 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java @@ -36,7 +36,6 @@ public void subscribeActual(Subscriber s) { rs.subscribeNext(); } - // FIXME update to a fresh Rsc algorithm static final class RepeatSubscriber extends AtomicInteger implements FlowableSubscriber { private static final long serialVersionUID = -7098360935104053232L; @@ -45,6 +44,9 @@ static final class RepeatSubscriber extends AtomicInteger implements Flowable final SubscriptionArbiter sa; final Publisher source; long remaining; + + long produced; + RepeatSubscriber(Subscriber actual, long count, SubscriptionArbiter sa, Publisher source) { this.actual = actual; this.sa = sa; @@ -59,8 +61,8 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { + produced++; actual.onNext(t); - sa.produced(1L); } @Override public void onError(Throwable t) { @@ -90,6 +92,11 @@ void subscribeNext() { if (sa.isCancelled()) { return; } + long p = produced; + if (p != 0L) { + produced = 0L; + sa.produced(p); + } source.subscribe(this); missed = addAndGet(-missed); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java index 4ae29226f0..250502c8b4 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java @@ -38,7 +38,6 @@ public void subscribeActual(Subscriber s) { rs.subscribeNext(); } - // FIXME update to a fresh Rsc algorithm static final class RepeatSubscriber extends AtomicInteger implements FlowableSubscriber { private static final long serialVersionUID = -7098360935104053232L; @@ -47,6 +46,9 @@ static final class RepeatSubscriber extends AtomicInteger implements Flowable final SubscriptionArbiter sa; final Publisher source; final BooleanSupplier stop; + + long produced; + RepeatSubscriber(Subscriber actual, BooleanSupplier until, SubscriptionArbiter sa, Publisher source) { this.actual = actual; this.sa = sa; @@ -61,8 +63,8 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { + produced++; actual.onNext(t); - sa.produced(1L); } @Override public void onError(Throwable t) { @@ -93,6 +95,16 @@ void subscribeNext() { if (getAndIncrement() == 0) { int missed = 1; for (;;) { + if (sa.isCancelled()) { + return; + } + + long p = produced; + if (p != 0L) { + produced = 0L; + sa.produced(p); + } + source.subscribe(this); missed = addAndGet(-missed); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java index b478f408ea..cf94105249 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java @@ -40,7 +40,6 @@ public void subscribeActual(Subscriber s) { rs.subscribeNext(); } - // FIXME update to a fresh Rsc algorithm static final class RetryBiSubscriber extends AtomicInteger implements FlowableSubscriber { private static final long serialVersionUID = -7098360935104053232L; @@ -50,6 +49,9 @@ static final class RetryBiSubscriber extends AtomicInteger implements Flowabl final Publisher source; final BiPredicate predicate; int retries; + + long produced; + RetryBiSubscriber(Subscriber actual, BiPredicate predicate, SubscriptionArbiter sa, Publisher source) { this.actual = actual; @@ -65,8 +67,8 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { + produced++; actual.onNext(t); - sa.produced(1L); } @Override public void onError(Throwable t) { @@ -100,6 +102,13 @@ void subscribeNext() { if (sa.isCancelled()) { return; } + + long p = produced; + if (p != 0L) { + produced = 0L; + sa.produced(p); + } + source.subscribe(this); missed = addAndGet(-missed); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java index 2b2c13f0a1..11c4732274 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java @@ -38,12 +38,11 @@ public void subscribeActual(Subscriber s) { SubscriptionArbiter sa = new SubscriptionArbiter(); s.onSubscribe(sa); - RepeatSubscriber rs = new RepeatSubscriber(s, count, predicate, sa, source); + RetrySubscriber rs = new RetrySubscriber(s, count, predicate, sa, source); rs.subscribeNext(); } - // FIXME update to a fresh Rsc algorithm - static final class RepeatSubscriber extends AtomicInteger implements FlowableSubscriber { + static final class RetrySubscriber extends AtomicInteger implements FlowableSubscriber { private static final long serialVersionUID = -7098360935104053232L; @@ -52,7 +51,10 @@ static final class RepeatSubscriber extends AtomicInteger implements Flowable final Publisher source; final Predicate predicate; long remaining; - RepeatSubscriber(Subscriber actual, long count, + + long produced; + + RetrySubscriber(Subscriber actual, long count, Predicate predicate, SubscriptionArbiter sa, Publisher source) { this.actual = actual; this.sa = sa; @@ -68,8 +70,8 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { + produced++; actual.onNext(t); - sa.produced(1L); } @Override public void onError(Throwable t) { @@ -111,6 +113,13 @@ void subscribeNext() { if (sa.isCancelled()) { return; } + + long p = produced; + if (p != 0L) { + produced = 0L; + sa.produced(p); + } + source.subscribe(this); missed = addAndGet(-missed); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java index 561da1a6d5..2be61592cf 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java @@ -259,6 +259,19 @@ public boolean getAsBoolean() throws Exception { .assertResult(1, 1, 1, 1, 1); } + @Test + public void repeatUntilCancel() { + Flowable.just(1) + .repeatUntil(new BooleanSupplier() { + @Override + public boolean getAsBoolean() throws Exception { + return true; + } + }) + .test(2L, true) + .assertEmpty(); + } + @Test public void repeatLongPredicateInvalid() { try { From d91ee5a632a1c2cd647ffd54330772f5bb26d2d2 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sat, 6 Jan 2018 00:26:29 +0100 Subject: [PATCH 074/417] 2.x: Fix flatMap inner fused poll crash not cancelling the upstream (#5792) * 2.x: Fix flatMap inner fused poll crash not cancelling the upstream * Verify Observable.flatMapIterable --- .../operators/flowable/FlowableFlatMap.java | 21 ++++---- .../flowable/FlowableFlatMapTest.java | 43 +++++++++++++++ .../flowable/FlowableFlattenIterableTest.java | 43 +++++++++++++++ .../observable/ObservableFlatMapTest.java | 44 ++++++++++++++++ .../ObservableFlattenIterableTest.java | 52 ++++++++++++++++++- 5 files changed, 192 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java index 9ffd7df2f2..c815fdf111 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java @@ -85,7 +85,7 @@ static final class MergeSubscriber extends AtomicInteger implements Flowab final AtomicLong requested = new AtomicLong(); - Subscription s; + Subscription upstream; long uniqueId; long lastId; @@ -107,8 +107,8 @@ static final class MergeSubscriber extends AtomicInteger implements Flowab @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; actual.onSubscribe(this); if (!cancelled) { if (maxConcurrency == Integer.MAX_VALUE) { @@ -132,7 +132,7 @@ public void onNext(T t) { p = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); onError(e); return; } @@ -154,7 +154,7 @@ public void onNext(T t) { if (maxConcurrency != Integer.MAX_VALUE && !cancelled && ++scalarEmitted == scalarLimit) { scalarEmitted = 0; - s.request(scalarLimit); + upstream.request(scalarLimit); } } } else { @@ -238,7 +238,7 @@ void tryEmitScalar(U value) { if (maxConcurrency != Integer.MAX_VALUE && !cancelled && ++scalarEmitted == scalarLimit) { scalarEmitted = 0; - s.request(scalarLimit); + upstream.request(scalarLimit); } } else { if (q == null) { @@ -350,7 +350,7 @@ public void request(long n) { public void cancel() { if (!cancelled) { cancelled = true; - s.cancel(); + upstream.cancel(); disposeAll(); if (getAndIncrement() == 0) { SimpleQueue q = queue; @@ -482,6 +482,9 @@ void drainLoop() { Exceptions.throwIfFatal(ex); is.dispose(); errs.addThrowable(ex); + if (!delayErrors) { + upstream.cancel(); + } if (checkTerminate()) { return; } @@ -539,7 +542,7 @@ void drainLoop() { } if (replenishMain != 0L && !cancelled) { - s.request(replenishMain); + upstream.request(replenishMain); } if (innerCompleted) { continue; @@ -594,7 +597,7 @@ void innerError(InnerSubscriber inner, Throwable t) { if (errs.addThrowable(t)) { inner.done = true; if (!delayErrors) { - s.cancel(); + upstream.cancel(); for (InnerSubscriber a : subscribers.getAndSet(CANCELLED)) { a.dispose(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index 6a509ad802..66da69516a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -1033,4 +1033,47 @@ public Object apply(Integer v, Object w) throws Exception { .test() .assertFailureAndMessage(NullPointerException.class, "The mapper returned a null Publisher"); } + + @Test + public void failingFusedInnerCancelsSource() { + final AtomicInteger counter = new AtomicInteger(); + Flowable.range(1, 5) + .doOnNext(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + counter.getAndIncrement(); + } + }) + .flatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.fromIterable(new Iterable() { + @Override + public Iterator iterator() { + return new Iterator() { + @Override + public boolean hasNext() { + return true; + } + + @Override + public Integer next() { + throw new TestException(); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + }); + } + }) + .test() + .assertFailure(TestException.class); + + assertEquals(1, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java index a865475acf..ebfe899488 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java @@ -914,4 +914,47 @@ public void multiShareHidden() { .assertResult(600L); } } + + @Test + public void failingInnerCancelsSource() { + final AtomicInteger counter = new AtomicInteger(); + Flowable.range(1, 5) + .doOnNext(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + counter.getAndIncrement(); + } + }) + .flatMapIterable(new Function>() { + @Override + public Iterable apply(Integer v) + throws Exception { + return new Iterable() { + @Override + public Iterator iterator() { + return new Iterator() { + @Override + public boolean hasNext() { + return true; + } + + @Override + public Integer next() { + throw new TestException(); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + }; + } + }) + .test() + .assertFailure(TestException.class); + + assertEquals(1, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index 64cb2e7e41..1a48d43df0 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -894,4 +894,48 @@ public Object apply(Integer v, Object w) throws Exception { .test() .assertFailureAndMessage(NullPointerException.class, "The mapper returned a null ObservableSource"); } + + + @Test + public void failingFusedInnerCancelsSource() { + final AtomicInteger counter = new AtomicInteger(); + Observable.range(1, 5) + .doOnNext(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + counter.getAndIncrement(); + } + }) + .flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.fromIterable(new Iterable() { + @Override + public Iterator iterator() { + return new Iterator() { + @Override + public boolean hasNext() { + return true; + } + + @Override + public Integer next() { + throw new TestException(); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + }); + } + }) + .test() + .assertFailure(TestException.class); + + assertEquals(1, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlattenIterableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlattenIterableTest.java index 147ede1264..8b870877e4 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlattenIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlattenIterableTest.java @@ -13,12 +13,17 @@ package io.reactivex.internal.operators.observable; -import java.util.Arrays; +import static org.junit.Assert.assertEquals; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import io.reactivex.*; -import io.reactivex.functions.Function; +import io.reactivex.Observable; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.*; import io.reactivex.subjects.PublishSubject; public class ObservableFlattenIterableTest { @@ -47,4 +52,47 @@ public Iterable apply(Object v) throws Exception { } }, false, 1, 1, 10, 20); } + + @Test + public void failingInnerCancelsSource() { + final AtomicInteger counter = new AtomicInteger(); + Observable.range(1, 5) + .doOnNext(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + counter.getAndIncrement(); + } + }) + .flatMapIterable(new Function>() { + @Override + public Iterable apply(Integer v) + throws Exception { + return new Iterable() { + @Override + public Iterator iterator() { + return new Iterator() { + @Override + public boolean hasNext() { + return true; + } + + @Override + public Integer next() { + throw new TestException(); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + }; + } + }) + .test() + .assertFailure(TestException.class); + + assertEquals(1, counter.get()); + } } From bc1c705e5b0966c70aae18a40b9c5f6b328bf1a1 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sat, 6 Jan 2018 15:19:14 +0100 Subject: [PATCH 075/417] 2.x: add error handling section to merge() operator docs (#5786) * 2.x: add error handling section to merge() operator docs * Change to "UndeliverableException errors" --- src/main/java/io/reactivex/Completable.java | 59 ++++++++- src/main/java/io/reactivex/Flowable.java | 128 +++++++++++++++++- src/main/java/io/reactivex/Maybe.java | 104 +++++++++++++++ src/main/java/io/reactivex/Observable.java | 140 ++++++++++++++++++++ src/main/java/io/reactivex/Single.java | 77 ++++++++++- 5 files changed, 503 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 6d70d6baca..c9f891b500 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -451,10 +451,23 @@ public static Completable fromSingle(final SingleSource single) { *
                *
                Scheduler:
                *
                {@code mergeArray} does not operate by default on a particular {@link Scheduler}.
                + *
                If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. + * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Completable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeArrayDelayError(CompletableSource...)} to merge sources and terminate only when all source {@code CompletableSource}s + * have completed or failed with an error. + *
                *
                * @param sources the iterable sequence of sources. * @return the new Completable instance * @throws NullPointerException if sources is null + * @see #mergeArrayDelayError(CompletableSource...) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -475,10 +488,24 @@ public static Completable mergeArray(CompletableSource... sources) { *
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. + * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Completable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code CompletableSource}s + * have completed or failed with an error. + *
                *
                * @param sources the iterable sequence of sources. * @return the new Completable instance * @throws NullPointerException if sources is null + * @see #mergeDelayError(Iterable) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -496,10 +523,23 @@ public static Completable merge(Iterable sources) { * and expects the other {@code Publisher} to honor it as well. *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. + * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Completable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Publisher)} to merge sources and terminate only when all source {@code CompletableSource}s + * have completed or failed with an error. + *
                *
                * @param sources the iterable sequence of sources. * @return the new Completable instance * @throws NullPointerException if sources is null + * @see #mergeDelayError(Publisher) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -517,12 +557,25 @@ public static Completable merge(Publisher sources) * and expects the other {@code Publisher} to honor it as well. *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. + * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Completable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Publisher, int)} to merge sources and terminate only when all source {@code CompletableSource}s + * have completed or failed with an error. + *
                *
                * @param sources the iterable sequence of sources. * @param maxConcurrency the maximum number of concurrent subscriptions * @return the new Completable instance * @throws NullPointerException if sources is null * @throws IllegalArgumentException if maxConcurrency is less than 1 + * @see #mergeDelayError(Publisher, int) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -1253,7 +1306,7 @@ public final Completable doOnSubscribe(Consumer onSubscribe) /** * Returns a Completable instance that calls the given onTerminate callback just before this Completable - * completes normally or with an exception + * completes normally or with an exception. *
                *
                Scheduler:
                *
                {@code doOnTerminate} does not operate by default on a particular {@link Scheduler}.
                @@ -1272,7 +1325,7 @@ public final Completable doOnTerminate(final Action onTerminate) { /** * Returns a Completable instance that calls the given onTerminate callback after this Completable - * completes normally or with an exception + * completes normally or with an exception. *
                *
                Scheduler:
                *
                {@code doAfterTerminate} does not operate by default on a particular {@link Scheduler}.
                @@ -2084,7 +2137,7 @@ public final Single toSingleDefault(final T completionValue) { /** * Returns a Completable which makes sure when a subscriber cancels the subscription, the - * dispose is called on the specified scheduler + * dispose is called on the specified scheduler. *
                *
                Scheduler:
                *
                {@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.
                diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 87bf672d96..2057359697 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -2892,6 +2892,19 @@ public static Flowable just(T item1, T item2, T item3, T item4, T item5, * backpressure; if violated, the operator may signal {@code MissingBackpressureException}. *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Iterable, int, int)} to merge sources and terminate only when all source {@code Publisher}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -2906,6 +2919,7 @@ public static Flowable just(T item1, T item2, T item3, T item4, T item5, * @throws IllegalArgumentException * if {@code maxConcurrency} is less than or equal to 0 * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(Iterable, int, int) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -2929,6 +2943,19 @@ public static Flowable merge(Iterable> s * backpressure; if violated, the operator may signal {@code MissingBackpressureException}. *
                Scheduler:
                *
                {@code mergeArray} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeArrayDelayError(int, int, Publisher[])} to merge sources and terminate only when all source {@code Publisher}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -2943,6 +2970,7 @@ public static Flowable merge(Iterable> s * @throws IllegalArgumentException * if {@code maxConcurrency} is less than or equal to 0 * @see ReactiveX operators documentation: Merge + * @see #mergeArrayDelayError(int, int, Publisher...) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -2972,7 +3000,7 @@ public static Flowable mergeArray(int maxConcurrency, int bufferSize, Pub * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via - * {@link RxJavaPlugins#onError(Throwable)} method as undeliverable errors. Similarly, {@code Throwable}s + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code Publisher}s @@ -3010,6 +3038,19 @@ public static Flowable merge(Iterable> s * backpressure; if violated, the operator may signal {@code MissingBackpressureException}. *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Iterable, int)} to merge sources and terminate only when all source {@code Publisher}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -3022,6 +3063,7 @@ public static Flowable merge(Iterable> s * @throws IllegalArgumentException * if {@code maxConcurrency} is less than or equal to 0 * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(Iterable, int) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -3046,6 +3088,19 @@ public static Flowable merge(Iterable> s * backpressure; if violated, the operator may signal {@code MissingBackpressureException}. *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Publisher)} to merge sources and terminate only when all source {@code Publisher}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -3054,6 +3109,7 @@ public static Flowable merge(Iterable> s * @return a Flowable that emits items that are the result of flattening the Publishers emitted by the * {@code source} Publisher * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(Publisher) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -3077,6 +3133,19 @@ public static Flowable merge(Publisher> * backpressure; if violated, the operator may signal {@code MissingBackpressureException}. *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Publisher, int)} to merge sources and terminate only when all source {@code Publisher}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -3089,6 +3158,7 @@ public static Flowable merge(Publisher> * @throws IllegalArgumentException * if {@code maxConcurrency} is less than or equal to 0 * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(Publisher, int) * @since 1.1.0 */ @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -3112,6 +3182,19 @@ public static Flowable merge(Publisher> * backpressure; if violated, the operator may signal {@code MissingBackpressureException}. *
                Scheduler:
                *
                {@code mergeArray} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeArrayDelayError(Publisher...)} to merge sources and terminate only when all source {@code Publisher}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -3119,6 +3202,7 @@ public static Flowable merge(Publisher> * the array of Publishers * @return a Flowable that emits all of the items emitted by the Publishers in the Array * @see ReactiveX operators documentation: Merge + * @see #mergeArrayDelayError(Publisher...) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -3141,6 +3225,19 @@ public static Flowable mergeArray(Publisher... sources) { * backpressure; if violated, the operator may signal {@code MissingBackpressureException}. *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Publisher, Publisher)} to merge sources and terminate only when all source {@code Publisher}s + * have completed or failed with an error. + *
                * * * @param the common element base type @@ -3150,6 +3247,7 @@ public static Flowable mergeArray(Publisher... sources) { * a Publisher to be merged * @return a Flowable that emits all of the items emitted by the source Publishers * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(Publisher, Publisher) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -3174,6 +3272,19 @@ public static Flowable merge(Publisher source1, Publishermay signal {@code MissingBackpressureException}. *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Publisher, Publisher, Publisher)} to merge sources and terminate only when all source {@code Publisher}s + * have completed or failed with an error. + *
                * * * @param the common element base type @@ -3185,6 +3296,7 @@ public static Flowable merge(Publisher source1, PublisherReactiveX operators documentation: Merge + * @see #mergeDelayError(Publisher, Publisher, Publisher) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -3210,6 +3322,19 @@ public static Flowable merge(Publisher source1, Publishermay signal {@code MissingBackpressureException}. *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Publisher, Publisher, Publisher, Publisher)} to merge sources and terminate only when all source {@code Publisher}s + * have completed or failed with an error. + *
                * * * @param the common element base type @@ -3223,6 +3348,7 @@ public static Flowable merge(Publisher source1, PublisherReactiveX operators documentation: Merge + * @see #mergeDelayError(Publisher, Publisher, Publisher, Publisher) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index fb053a7a13..53c042e0ef 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -777,10 +777,24 @@ public static Maybe just(T item) { *
                The operator honors backpressure from downstream.
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code MaybeSource}s + * have completed or failed with an error. + *
                * * @param the common and resulting value type * @param sources the Iterable sequence of MaybeSource sources * @return the new Flowable instance + * @see #mergeDelayError(Iterable) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @@ -797,10 +811,24 @@ public static Flowable merge(Iterable> *
                The operator honors backpressure from downstream.
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Publisher)} to merge sources and terminate only when all source {@code MaybeSource}s + * have completed or failed with an error. + *
                * * @param the common and resulting value type * @param sources the Flowable sequence of MaybeSource sources * @return the new Flowable instance + * @see #mergeDelayError(Publisher) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @@ -817,11 +845,25 @@ public static Flowable merge(Publisher *
                The operator honors backpressure from downstream.
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Publisher, int)} to merge sources and terminate only when all source {@code MaybeSource}s + * have completed or failed with an error. + *
                * * @param the common and resulting value type * @param sources the Flowable sequence of MaybeSource sources * @param maxConcurrency the maximum number of concurrently running MaybeSources * @return the new Flowable instance + * @see #mergeDelayError(Publisher, int) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @@ -841,6 +883,12 @@ public static Flowable merge(Publisher *
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                The resulting {@code Maybe} emits the outer source's or the inner {@code MaybeSource}'s {@code Throwable} as is. + * Unlike the other {@code merge()} operators, this operator won't and can't produce a {@code CompositeException} because there is + * only one possibility for the outer or the inner {@code MaybeSource} to emit an {@code onError} signal. + * Therefore, there is no need for a {@code mergeDelayError(MaybeSource>)} operator. + *
                *
                * * @param the value type of the sources and the output @@ -870,6 +918,19 @@ public static Maybe merge(MaybeSource> *
                The operator honors backpressure from downstream.
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(MaybeSource, MaybeSource)} to merge sources and terminate only when all source {@code MaybeSource}s + * have completed or failed with an error. + *
                * * * @param the common value type @@ -879,6 +940,7 @@ public static Maybe merge(MaybeSource> * a MaybeSource to be merged * @return a Flowable that emits all of the items emitted by the source MaybeSources * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(MaybeSource, MaybeSource) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @@ -904,6 +966,19 @@ public static Flowable merge( *
                The operator honors backpressure from downstream.
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(MaybeSource, MaybeSource, MaybeSource)} to merge sources and terminate only when all source {@code MaybeSource}s + * have completed or failed with an error. + *
                * * * @param the common value type @@ -915,6 +990,7 @@ public static Flowable merge( * a MaybeSource to be merged * @return a Flowable that emits all of the items emitted by the source MaybeSources * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(MaybeSource, MaybeSource, MaybeSource) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @@ -942,6 +1018,19 @@ public static Flowable merge( *
                The operator honors backpressure from downstream.
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(MaybeSource, MaybeSource, MaybeSource, MaybeSource)} to merge sources and terminate only when all source {@code MaybeSource}s + * have completed or failed with an error. + *
                * * * @param the common value type @@ -955,6 +1044,7 @@ public static Flowable merge( * a MaybeSource to be merged * @return a Flowable that emits all of the items emitted by the source MaybeSources * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(MaybeSource, MaybeSource, MaybeSource, MaybeSource) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @@ -979,10 +1069,24 @@ public static Flowable merge( *
                The operator honors backpressure from downstream.
                *
                Scheduler:
                *
                {@code mergeArray} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeArrayDelayError(MaybeSource...)} to merge sources and terminate only when all source {@code MaybeSource}s + * have completed or failed with an error. + *
                * * @param the common and resulting value type * @param sources the array sequence of MaybeSource sources * @return the new Flowable instance + * @see #mergeArrayDelayError(MaybeSource...) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index ae5942bcd1..fc39bc0de3 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -2635,6 +2635,19 @@ public static Observable just(T item1, T item2, T item3, T item4, T item5 *
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Iterable, int, int)} to merge sources and terminate only when all source {@code ObservableSource}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -2649,6 +2662,7 @@ public static Observable just(T item1, T item2, T item3, T item4, T item5 * @throws IllegalArgumentException * if {@code maxConcurrent} is less than or equal to 0 * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(Iterable, int, int) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -2668,6 +2682,19 @@ public static Observable merge(Iterable *
                Scheduler:
                *
                {@code mergeArray} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeArrayDelayError(int, int, ObservableSource...)} to merge sources and terminate only when all source {@code ObservableSource}s + * have completed or failed with an error. + *
                * * * @param the common element base type @@ -2682,6 +2709,7 @@ public static Observable merge(IterableReactiveX operators documentation: Merge + * @see #mergeArrayDelayError(int, int, ObservableSource...) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -2700,6 +2728,19 @@ public static Observable mergeArray(int maxConcurrency, int bufferSize, O *
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code ObservableSource}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -2708,6 +2749,7 @@ public static Observable mergeArray(int maxConcurrency, int bufferSize, O * @return an Observable that emits items that are the result of flattening the items emitted by the * ObservableSources in the Iterable * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(Iterable) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -2727,6 +2769,19 @@ public static Observable merge(Iterable *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Iterable, int)} to merge sources and terminate only when all source {@code ObservableSource}s + * have completed or failed with an error. + *
                * * * @param the common element base type @@ -2739,6 +2794,7 @@ public static Observable merge(IterableReactiveX operators documentation: Merge + * @see #mergeDelayError(Iterable, int) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -2758,6 +2814,19 @@ public static Observable merge(Iterable *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s + * have completed or failed with an error. + *
                * * * @param the common element base type @@ -2766,6 +2835,7 @@ public static Observable merge(IterableReactiveX operators documentation: Merge + * @see #mergeDelayError(ObservableSource) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -2787,6 +2857,19 @@ public static Observable merge(ObservableSource *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(ObservableSource, int)} to merge sources and terminate only when all source {@code ObservableSource}s + * have completed or failed with an error. + *
                * * * @param the common element base type @@ -2800,6 +2883,7 @@ public static Observable merge(ObservableSourceReactiveX operators documentation: Merge * @since 1.1.0 + * @see #mergeDelayError(ObservableSource, int) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -2820,6 +2904,19 @@ public static Observable merge(ObservableSource *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(ObservableSource, ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s + * have completed or failed with an error. + *
                * * * @param the common element base type @@ -2829,6 +2926,7 @@ public static Observable merge(ObservableSourceReactiveX operators documentation: Merge + * @see #mergeDelayError(ObservableSource, ObservableSource) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -2849,6 +2947,19 @@ public static Observable merge(ObservableSource source1, Obs *
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(ObservableSource, ObservableSource, ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -2860,6 +2971,7 @@ public static Observable merge(ObservableSource source1, Obs * an ObservableSource to be merged * @return an Observable that emits all of the items emitted by the source ObservableSources * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(ObservableSource, ObservableSource, ObservableSource) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -2881,6 +2993,19 @@ public static Observable merge(ObservableSource source1, Obs *
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(ObservableSource, ObservableSource, ObservableSource, ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -2894,6 +3019,7 @@ public static Observable merge(ObservableSource source1, Obs * an ObservableSource to be merged * @return an Observable that emits all of the items emitted by the source ObservableSources * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(ObservableSource, ObservableSource, ObservableSource, ObservableSource) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @@ -2918,6 +3044,19 @@ public static Observable merge( *
                *
                Scheduler:
                *
                {@code mergeArray} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeArrayDelayError(ObservableSource...)} to merge sources and terminate only when all source {@code ObservableSource}s + * have completed or failed with an error. + *
                *
                * * @param the common element base type @@ -2925,6 +3064,7 @@ public static Observable merge( * the array of ObservableSources * @return an Observable that emits all of the items emitted by the ObservableSources in the Array * @see ReactiveX operators documentation: Merge + * @see #mergeArrayDelayError(ObservableSource...) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index ed185920cc..4d55b8dd24 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -664,11 +664,25 @@ public static Single just(final T item) { *
                The returned {@code Flowable} honors the backpressure of the downstream consumer.
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code SingleSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are cancelled. + * If more than one {@code SingleSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code SingleSource}s + * have completed or failed with an error. + *
                * * @param the common and resulting value type * @param sources the Iterable sequence of SingleSource sources * @return the new Flowable instance * @since 2.0 + * @see #mergeDelayError(Iterable) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -685,10 +699,24 @@ public static Flowable merge(Iterable *
                The returned {@code Flowable} honors the backpressure of the downstream consumer.
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code SingleSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are cancelled. + * If more than one {@code SingleSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(Publisher)} to merge sources and terminate only when all source {@code SingleSource}s + * have completed or failed with an error. + *
                * * @param the common and resulting value type * @param sources the Flowable sequence of SingleSource sources * @return the new Flowable instance + * @see #mergeDelayError(Publisher) * @since 2.0 */ @CheckReturnValue @@ -708,6 +736,11 @@ public static Flowable merge(Publisher *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                The resulting {@code Single} emits the outer source's or the inner {@code SingleSource}'s {@code Throwable} as is. + * Unlike the other {@code merge()} operators, this operator won't and can't produce a {@code CompositeException} because there is + * only one possibility for the outer or the inner {@code SingleSource} to emit an {@code onError} signal. + * Therefore, there is no need for a {@code mergeDelayError(SingleSource>)} operator. + *
                * * * @param the value type of the sources and the output @@ -737,6 +770,19 @@ public static Single merge(SingleSourceThe returned {@code Flowable} honors the backpressure of the downstream consumer. *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code SingleSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are cancelled. + * If more than one {@code SingleSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(SingleSource, SingleSource)} to merge sources and terminate only when all source {@code SingleSource}s + * have completed or failed with an error. + *
                * * * @param the common value type @@ -746,6 +792,7 @@ public static Single merge(SingleSourceReactiveX operators documentation: Merge + * @see #mergeDelayError(SingleSource, SingleSource) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -771,6 +818,19 @@ public static Flowable merge( *
                The returned {@code Flowable} honors the backpressure of the downstream consumer.
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code SingleSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are cancelled. + * If more than one {@code SingleSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(SingleSource, SingleSource, SingleSource)} to merge sources and terminate only when all source {@code SingleSource}s + * have completed or failed with an error. + *
                * * * @param the common value type @@ -782,6 +842,7 @@ public static Flowable merge( * a Single to be merged * @return a Flowable that emits all of the items emitted by the source Singles * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(SingleSource, SingleSource, SingleSource) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -809,6 +870,19 @@ public static Flowable merge( *
                The returned {@code Flowable} honors the backpressure of the downstream consumer.
                *
                Scheduler:
                *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If any of the source {@code SingleSource}s signal a {@code Throwable} via {@code onError}, the resulting + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are cancelled. + * If more than one {@code SingleSource} signals an error, the resulting {@code Flowable} may terminate with the + * first one's error or, depending on the concurrency of the sources, may terminate with a + * {@code CompositeException} containing two or more of the various error signals. + * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s + * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * (composite) error will be sent to the same global error handler. + * Use {@link #mergeDelayError(SingleSource, SingleSource, SingleSource)} to merge sources and terminate only when all source {@code SingleSource}s + * have completed or failed with an error. + *
                * * * @param the common value type @@ -822,6 +896,7 @@ public static Flowable merge( * a Single to be merged * @return a Flowable that emits all of the items emitted by the source Singles * @see ReactiveX operators documentation: Merge + * @see #mergeDelayError(SingleSource, SingleSource, SingleSource, SingleSource) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -3217,7 +3292,7 @@ public final Observable toObservable() { /** * Returns a Single which makes sure when a SingleObserver disposes the Disposable, - * that call is propagated up on the specified scheduler + * that call is propagated up on the specified scheduler. *
                *
                Scheduler:
                *
                {@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.
                From 732927c40c49ea8218667704a104454eb8260290 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 8 Jan 2018 13:08:34 +0100 Subject: [PATCH 076/417] 2.x: More marbles 01/08-a (#5795) --- src/main/java/io/reactivex/Observable.java | 30 ++++++++++++++-------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index fc39bc0de3..89262ab287 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7805,8 +7805,8 @@ public final Observable flatMap( * Returns an Observable that applies a function to each item emitted or notification raised by the source * ObservableSource and then flattens the ObservableSources returned from these functions and emits the resulting items, * while limiting the maximum number of concurrent subscriptions to these ObservableSources. - * - * + *

                + * *

                *
                Scheduler:
                *
                {@code flatMap} does not operate by default on a particular {@link Scheduler}.
                @@ -7939,8 +7939,8 @@ public final Observable flatMap(Function --> - * + *

                + * *

                *
                Scheduler:
                *
                {@code flatMap} does not operate by default on a particular {@link Scheduler}.
                @@ -7976,8 +7976,8 @@ public final Observable flatMap(Function --> - * + *

                + * *

                *
                Scheduler:
                *
                {@code flatMap} does not operate by default on a particular {@link Scheduler}.
                @@ -8017,8 +8017,8 @@ public final Observable flatMap(final Function --> - * + *

                + * *

                *
                Scheduler:
                *
                {@code flatMap} does not operate by default on a particular {@link Scheduler}.
                @@ -8050,6 +8050,8 @@ public final Observable flatMap(Function + * *
                *
                Scheduler:
                *
                {@code flatMapCompletable} does not operate by default on a particular {@link Scheduler}.
                @@ -8066,6 +8068,8 @@ public final Completable flatMapCompletable(Function + * *
                *
                Scheduler:
                *
                {@code flatMapCompletable} does not operate by default on a particular {@link Scheduler}.
                @@ -8086,7 +8090,7 @@ public final Completable flatMapCompletable(Function - * + * *
                *
                Scheduler:
                *
                {@code flatMapIterable} does not operate by default on a particular {@link Scheduler}.
                @@ -8112,7 +8116,7 @@ public final Observable flatMapIterable(final Function - * + * *
                *
                Scheduler:
                *
                {@code flatMapIterable} does not operate by default on a particular {@link Scheduler}.
                @@ -8228,6 +8232,8 @@ public final Observable flatMapSingle(Function + * + *

                * Alias to {@link #subscribe(Consumer)} *

                *
                Scheduler:
                @@ -8252,6 +8258,8 @@ public final Disposable forEach(Consumer onNext) { * Subscribes to the {@link ObservableSource} and receives notifications for each element until the * onNext Predicate returns false. *

                + * + *

                * If the Observable emits an error, it is wrapped into an * {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} * and routed to the RxJavaPlugins.onError handler. @@ -8584,6 +8592,8 @@ public final Observable groupJoin( *

                Allows hiding extra features such as {@link io.reactivex.subjects.Subject}'s * {@link Observer} methods or preventing certain identity-based * optimizations (fusion). + *

                + * *

                *
                Scheduler:
                *
                {@code hide} does not operate by default on a particular {@link Scheduler}.
                From 1ed3e5eaadf4f4692b78830e29a016917d331683 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 8 Jan 2018 17:32:57 +0100 Subject: [PATCH 077/417] 2.x: Observable marble fixes 01/08-b (#5797) --- src/main/java/io/reactivex/Observable.java | 41 ++++++++++++---------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 89262ab287..cff3fa3b00 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -8741,7 +8741,7 @@ public final Single last(T defaultItem) { * Returns a Single that emits only the last item emitted by this Observable or * signals a {@link NoSuchElementException} if this Observable is empty. *

                - * + * *

                *
                Scheduler:
                *
                {@code lastOrError} does not operate by default on a particular {@link Scheduler}.
                @@ -9054,7 +9054,7 @@ public final Observable onErrorResumeNext(final ObservableSource * Instructs an ObservableSource to emit an item (returned by a specified function) rather than invoking * {@link Observer#onError onError} if it encounters an error. *

                - * + * *

                * By default, when an ObservableSource encounters an error that prevents it from emitting the expected item to * its {@link Observer}, the ObservableSource invokes its Observer's {@code onError} method, and then quits @@ -9087,7 +9087,7 @@ public final Observable onErrorReturn(Function - * + * *

                * By default, when an ObservableSource encounters an error that prevents it from emitting the expected item to * its {@link Observer}, the ObservableSource invokes its Observer's {@code onError} method, and then quits @@ -9158,6 +9158,8 @@ public final Observable onExceptionResumeNext(final ObservableSource + * *

                *
                Scheduler:
                *
                {@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.
                @@ -9197,7 +9199,7 @@ public final ConnectableObservable publish() { * Returns an Observable that emits the results of invoking a specified selector on items emitted by a * {@link ConnectableObservable} that shares a single subscription to the underlying sequence. *

                - * + * *

                *
                Scheduler:
                *
                {@code publish} does not operate by default on a particular {@link Scheduler}.
                @@ -9256,7 +9258,7 @@ public final Maybe reduce(BiFunction reducer) { * emitted by an ObservableSource into the same function, and so on until all items have been emitted by the * source ObservableSource, emitting the final result from the final call to your function as its sole item. *

                - * + * *

                * This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate," * "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject} method @@ -9311,7 +9313,7 @@ public final Single reduce(R seed, BiFunction reducer) { * and so on until all items have been emitted by the source ObservableSource, emitting the final result * from the final call to your function as its sole item. *

                - * + * *

                * This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate," * "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject} method @@ -9343,7 +9345,7 @@ public final Single reduceWith(Callable seedSupplier, BiFunction - * + * *

                *
                Scheduler:
                *
                {@code repeat} does not operate by default on a particular {@link Scheduler}.
                @@ -9362,7 +9364,7 @@ public final Observable repeat() { * Returns an Observable that repeats the sequence of items emitted by the source ObservableSource at most * {@code count} times. *

                - * + * *

                *
                Scheduler:
                *
                {@code repeat} does not operate by default on a particular {@link Scheduler}.
                @@ -9393,15 +9395,16 @@ public final Observable repeat(long times) { * Returns an Observable that repeats the sequence of items emitted by the source ObservableSource until * the provided stop function returns true. *

                - * + * *

                *
                Scheduler:
                *
                {@code repeatUntil} does not operate by default on a particular {@link Scheduler}.
                *
                * * @param stop - * a boolean supplier that is called when the current Observable completes and unless it returns - * false, the current Observable is resubscribed + * a boolean supplier that is called when the current Observable completes; + * if it returns true, the returned Observable completes; if it returns false, + * the upstream Observable is resubscribed. * @return the new Observable instance * @throws NullPointerException * if {@code stop} is null @@ -9446,7 +9449,7 @@ public final Observable repeatWhen(final Function, * ObservableSource resembles an ordinary ObservableSource, except that it does not begin emitting items when it is * subscribed to, but only when its {@code connect} method is called. *

                - * + * *

                *
                Scheduler:
                *
                This version of {@code replay} does not operate by default on a particular {@link Scheduler}.
                @@ -9735,7 +9738,7 @@ public final Observable replay(final Function, ? ex * an ordinary ObservableSource, except that it does not begin emitting items when it is subscribed to, but only * when its {@code connect} method is called. *

                - * + * *

                *
                Scheduler:
                *
                This version of {@code replay} does not operate by default on a particular {@link Scheduler}.
                @@ -9760,7 +9763,7 @@ public final ConnectableObservable replay(final int bufferSize) { * ObservableSource resembles an ordinary ObservableSource, except that it does not begin emitting items when it is * subscribed to, but only when its {@code connect} method is called. *

                - * + * *

                *
                Scheduler:
                *
                This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}.
                @@ -9789,7 +9792,7 @@ public final ConnectableObservable replay(int bufferSize, long time, TimeUnit * Connectable ObservableSource resembles an ordinary ObservableSource, except that it does not begin emitting items * when it is subscribed to, but only when its {@code connect} method is called. *

                - * + * *

                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                @@ -9825,7 +9828,7 @@ public final ConnectableObservable replay(final int bufferSize, final long ti * an ordinary ObservableSource, except that it does not begin emitting items when it is subscribed to, but only * when its {@code connect} method is called. *

                - * + * *

                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                @@ -9852,7 +9855,7 @@ public final ConnectableObservable replay(final int bufferSize, final Schedul * resembles an ordinary ObservableSource, except that it does not begin emitting items when it is subscribed to, * but only when its {@code connect} method is called. *

                - * + * *

                *
                Scheduler:
                *
                This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}.
                @@ -9878,7 +9881,7 @@ public final ConnectableObservable replay(long time, TimeUnit unit) { * resembles an ordinary ObservableSource, except that it does not begin emitting items when it is subscribed to, * but only when its {@code connect} method is called. *

                - * + * *

                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                @@ -9908,7 +9911,7 @@ public final ConnectableObservable replay(final long time, final TimeUnit uni * {@link Scheduler}. A Connectable ObservableSource resembles an ordinary ObservableSource, except that it does not * begin emitting items when it is subscribed to, but only when its {@code connect} method is called. *

                - * + * *

                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                From 2adb1fa6ecd0d624c52728b1779f276c00ea8375 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 9 Jan 2018 15:46:10 +0100 Subject: [PATCH 078/417] 2.x: Observable.replay(Function, ...) marble fixes (#5798) --- src/main/java/io/reactivex/Observable.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index cff3fa3b00..a9885c11ce 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -9469,7 +9469,7 @@ public final ConnectableObservable replay() { * Returns an Observable that emits items that are the results of invoking a specified selector on the items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource. *

                - * + * *

                *
                Scheduler:
                *
                This version of {@code replay} does not operate by default on a particular {@link Scheduler}.
                @@ -9496,7 +9496,7 @@ public final Observable replay(Function, ? extends * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource, * replaying {@code bufferSize} notifications. *

                - * + * *

                *
                Scheduler:
                *
                This version of {@code replay} does not operate by default on a particular {@link Scheduler}.
                @@ -9527,7 +9527,7 @@ public final Observable replay(Function, ? extends * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource, * replaying no more than {@code bufferSize} items that were emitted within a specified time window. *

                - * + * *

                *
                Scheduler:
                *
                This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}.
                @@ -9561,7 +9561,7 @@ public final Observable replay(Function, ? extends * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource, * replaying no more than {@code bufferSize} items that were emitted within a specified time window. *

                - * + * *

                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                @@ -9604,7 +9604,7 @@ public final Observable replay(Function, ? extends * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource, * replaying a maximum of {@code bufferSize} items. *

                - * + * *

                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                @@ -9639,7 +9639,7 @@ public final Observable replay(final Function, ? ex * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource, * replaying all items that were emitted within a specified time window. *

                - * + * *

                *
                Scheduler:
                *
                This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}.
                @@ -9670,7 +9670,7 @@ public final Observable replay(Function, ? extends * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource, * replaying all items that were emitted within a specified time window. *

                - * + * *

                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                @@ -9705,7 +9705,7 @@ public final Observable replay(Function, ? extends * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource. *

                - * + * *

                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                From f00533c91453daa3ce90b4542c2a3210036d00d5 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 9 Jan 2018 20:18:26 +0100 Subject: [PATCH 079/417] 2.x: Add missing {Maybe|Single}.mergeDelayError variants (#5799) * 2.x: Add missing {Maybe|Single}.mergeDelayError variants * In javadoc, use "a SingleSource to be merged" --- src/main/java/io/reactivex/Maybe.java | 48 ++++- src/main/java/io/reactivex/Single.java | 197 +++++++++++++++++- .../operators/maybe/MaybeMergeTest.java | 101 +++++++++ .../operators/single/SingleMergeTest.java | 69 +++++- 4 files changed, 399 insertions(+), 16 deletions(-) create mode 100644 src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeTest.java diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 53c042e0ef..efa8658982 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -1180,12 +1180,12 @@ public static Flowable mergeDelayError(Iterable - * This behaves like {@link #merge(Publisher)} except that if any of the merged Publishers notify of an + * This behaves like {@link #merge(Publisher)} except that if any of the merged MaybeSources notify of an * error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from propagating that - * error notification until all of the merged Publishers have finished emitting items. + * error notification until all of the merged MaybeSources and the main Publisher have finished emitting items. *

                * *

                @@ -1214,6 +1214,46 @@ public static Flowable mergeDelayError(Publisher + * This behaves like {@link #merge(Publisher, int)} except that if any of the merged MaybeSources notify of an + * error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from propagating that + * error notification until all of the merged MaybeSources and the main Publisher have finished emitting items. + *

                + * + *

                + * Even if multiple merged Publishers send {@code onError} notifications, {@code mergeDelayError} will only + * invoke the {@code onError} method of its Subscribers once. + *

                + *
                Backpressure:
                + *
                The operator honors backpressure from downstream. The outer {@code Publisher} is consumed + * in unbounded mode (i.e., no backpressure is applied to it).
                + *
                Scheduler:
                + *
                {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param the common element base type + * @param sources + * a Publisher that emits MaybeSources + * @param maxConcurrency the maximum number of active inner MaybeSources to be merged at a time + * @return a Flowable that emits all of the items emitted by the Publishers emitted by the + * {@code source} Publisher + * @see ReactiveX operators documentation: Merge + * @since 2.1.9 - experimental + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @BackpressureSupport(BackpressureKind.FULL) + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public static Flowable mergeDelayError(Publisher> sources, int maxConcurrency) { + return Flowable.fromPublisher(sources).flatMap((Function)MaybeToPublisher.instance(), true, maxConcurrency); + } + /** * Flattens two MaybeSources into one Flowable, in a way that allows a Subscriber to receive all * successfully emitted items from each of the source MaybeSources without being interrupted by an error diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 4d55b8dd24..63cee36923 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -787,9 +787,9 @@ public static Single merge(SingleSource the common value type * @param source1 - * a Single to be merged + * a SingleSource to be merged * @param source2 - * a Single to be merged + * a SingleSource to be merged * @return a Flowable that emits all of the items emitted by the source Singles * @see ReactiveX operators documentation: Merge * @see #mergeDelayError(SingleSource, SingleSource) @@ -835,11 +835,11 @@ public static Flowable merge( * * @param the common value type * @param source1 - * a Single to be merged + * a SingleSource to be merged * @param source2 - * a Single to be merged + * a SingleSource to be merged * @param source3 - * a Single to be merged + * a SingleSource to be merged * @return a Flowable that emits all of the items emitted by the source Singles * @see ReactiveX operators documentation: Merge * @see #mergeDelayError(SingleSource, SingleSource, SingleSource) @@ -880,20 +880,20 @@ public static Flowable merge( * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a * (composite) error will be sent to the same global error handler. - * Use {@link #mergeDelayError(SingleSource, SingleSource, SingleSource)} to merge sources and terminate only when all source {@code SingleSource}s + * Use {@link #mergeDelayError(SingleSource, SingleSource, SingleSource, SingleSource)} to merge sources and terminate only when all source {@code SingleSource}s * have completed or failed with an error. * *
                * * @param the common value type * @param source1 - * a Single to be merged + * a SingleSource to be merged * @param source2 - * a Single to be merged + * a SingleSource to be merged * @param source3 - * a Single to be merged + * a SingleSource to be merged * @param source4 - * a Single to be merged + * a SingleSource to be merged * @return a Flowable that emits all of the items emitted by the source Singles * @see ReactiveX operators documentation: Merge * @see #mergeDelayError(SingleSource, SingleSource, SingleSource, SingleSource) @@ -913,6 +913,181 @@ public static Flowable merge( return merge(Flowable.fromArray(source1, source2, source3, source4)); } + + /** + * Merges an Iterable sequence of SingleSource instances into a single Flowable sequence, + * running all SingleSources at once and delaying any error(s) until all sources succeed or fail. + *
                + *
                Backpressure:
                + *
                The returned {@code Flowable} honors the backpressure of the downstream consumer.
                + *
                Scheduler:
                + *
                {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the common and resulting value type + * @param sources the Iterable sequence of SingleSource sources + * @return the new Flowable instance + * @since 2.1.9 - experimental + * @see #merge(Iterable) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public static Flowable mergeDelayError(Iterable> sources) { + return mergeDelayError(Flowable.fromIterable(sources)); + } + + /** + * Merges a Flowable sequence of SingleSource instances into a single Flowable sequence, + * running all SingleSources at once and delaying any error(s) until all sources succeed or fail. + *
                + *
                Backpressure:
                + *
                The returned {@code Flowable} honors the backpressure of the downstream consumer.
                + *
                Scheduler:
                + *
                {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the common and resulting value type + * @param sources the Flowable sequence of SingleSource sources + * @return the new Flowable instance + * @see #merge(Publisher) + * @since 2.1.9 - experimental + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Experimental + public static Flowable mergeDelayError(Publisher> sources) { + ObjectHelper.requireNonNull(sources, "sources is null"); + return RxJavaPlugins.onAssembly(new FlowableFlatMapPublisher(sources, SingleInternalHelper.toFlowable(), true, Integer.MAX_VALUE, Flowable.bufferSize())); + } + + + /** + * Flattens two Singles into a single Flowable, without any transformation, delaying + * any error(s) until all sources succeed or fail. + *

                + * + *

                + * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by + * using the {@code mergeDelayError} method. + *

                + *
                Backpressure:
                + *
                The returned {@code Flowable} honors the backpressure of the downstream consumer.
                + *
                Scheduler:
                + *
                {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param the common value type + * @param source1 + * a SingleSource to be merged + * @param source2 + * a SingleSource to be merged + * @return a Flowable that emits all of the items emitted by the source Singles + * @see ReactiveX operators documentation: Merge + * @see #merge(SingleSource, SingleSource) + * @since 2.1.9 - experimental + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @SuppressWarnings("unchecked") + @Experimental + public static Flowable mergeDelayError( + SingleSource source1, SingleSource source2 + ) { + ObjectHelper.requireNonNull(source1, "source1 is null"); + ObjectHelper.requireNonNull(source2, "source2 is null"); + return mergeDelayError(Flowable.fromArray(source1, source2)); + } + + /** + * Flattens three Singles into a single Flowable, without any transformation, delaying + * any error(s) until all sources succeed or fail. + *

                + * + *

                + * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by using + * the {@code mergeDelayError} method. + *

                + *
                Backpressure:
                + *
                The returned {@code Flowable} honors the backpressure of the downstream consumer.
                + *
                Scheduler:
                + *
                {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param the common value type + * @param source1 + * a SingleSource to be merged + * @param source2 + * a SingleSource to be merged + * @param source3 + * a SingleSource to be merged + * @return a Flowable that emits all of the items emitted by the source Singles + * @see ReactiveX operators documentation: Merge + * @see #merge(SingleSource, SingleSource, SingleSource) + * @since 2.1.9 - experimental + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @SuppressWarnings("unchecked") + @Experimental + public static Flowable mergeDelayError( + SingleSource source1, SingleSource source2, + SingleSource source3 + ) { + ObjectHelper.requireNonNull(source1, "source1 is null"); + ObjectHelper.requireNonNull(source2, "source2 is null"); + ObjectHelper.requireNonNull(source3, "source3 is null"); + return mergeDelayError(Flowable.fromArray(source1, source2, source3)); + } + + /** + * Flattens four Singles into a single Flowable, without any transformation, delaying + * any error(s) until all sources succeed or fail. + *

                + * + *

                + * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by using + * the {@code mergeDelayError} method. + *

                + *
                Backpressure:
                + *
                The returned {@code Flowable} honors the backpressure of the downstream consumer.
                + *
                Scheduler:
                + *
                {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param the common value type + * @param source1 + * a SingleSource to be merged + * @param source2 + * a SingleSource to be merged + * @param source3 + * a SingleSource to be merged + * @param source4 + * a SingleSource to be merged + * @return a Flowable that emits all of the items emitted by the source Singles + * @see ReactiveX operators documentation: Merge + * @see #merge(SingleSource, SingleSource, SingleSource, SingleSource) + * @since 2.1.9 - experimental + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @SuppressWarnings("unchecked") + @Experimental + public static Flowable mergeDelayError( + SingleSource source1, SingleSource source2, + SingleSource source3, SingleSource source4 + ) { + ObjectHelper.requireNonNull(source1, "source1 is null"); + ObjectHelper.requireNonNull(source2, "source2 is null"); + ObjectHelper.requireNonNull(source3, "source3 is null"); + ObjectHelper.requireNonNull(source4, "source4 is null"); + return mergeDelayError(Flowable.fromArray(source1, source2, source3, source4)); + } + /** * Returns a singleton instance of a never-signalling Single (only calls onSubscribe). *
                @@ -2417,7 +2592,7 @@ public final Single contains(final Object value, final BiPredicate * * @param other - * a Single to be merged + * a SingleSource to be merged * @return that emits all of the items emitted by the source Singles * @see ReactiveX operators documentation: Merge */ diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeTest.java new file mode 100644 index 0000000000..0d9d450a05 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeTest.java @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.maybe; + +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.schedulers.Schedulers; + +public class MaybeMergeTest { + + @Test + public void delayErrorWithMaxConcurrency() { + Maybe.mergeDelayError( + Flowable.just(Maybe.just(1), Maybe.just(2), Maybe.just(3)), 1) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void delayErrorWithMaxConcurrencyError() { + Maybe.mergeDelayError( + Flowable.just(Maybe.just(1), Maybe.error(new TestException()), Maybe.just(3)), 1) + .test() + .assertFailure(TestException.class, 1, 3); + } + + @Test + public void delayErrorWithMaxConcurrencyAsync() { + final AtomicInteger count = new AtomicInteger(); + @SuppressWarnings("unchecked") + Maybe[] sources = new Maybe[3]; + for (int i = 0; i < 3; i++) { + final int j = i + 1; + sources[i] = Maybe.fromCallable(new Callable() { + @Override + public Integer call() throws Exception { + return count.incrementAndGet() - j; + } + }) + .subscribeOn(Schedulers.io()); + } + + for (int i = 0; i < 1000; i++) { + count.set(0); + Maybe.mergeDelayError( + Flowable.fromArray(sources), 1) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(0, 0, 0); + } + } + + @Test + public void delayErrorWithMaxConcurrencyAsyncError() { + final AtomicInteger count = new AtomicInteger(); + @SuppressWarnings("unchecked") + Maybe[] sources = new Maybe[3]; + for (int i = 0; i < 3; i++) { + final int j = i + 1; + sources[i] = Maybe.fromCallable(new Callable() { + @Override + public Integer call() throws Exception { + return count.incrementAndGet() - j; + } + }) + .subscribeOn(Schedulers.io()); + } + sources[1] = Maybe.fromCallable(new Callable() { + @Override + public Integer call() throws Exception { + throw new TestException("" + count.incrementAndGet()); + } + }) + .subscribeOn(Schedulers.io()); + + for (int i = 0; i < 1000; i++) { + count.set(0); + Maybe.mergeDelayError( + Flowable.fromArray(sources), 1) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertFailureAndMessage(TestException.class, "2", 0, 0); + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleMergeTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleMergeTest.java index 8fdbff7ff1..bf1a100ac9 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleMergeTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.assertTrue; -import java.util.List; +import java.util.*; import org.junit.Test; @@ -70,4 +70,71 @@ public void mergeErrors() { RxJavaPlugins.reset(); } } + + @SuppressWarnings("unchecked") + @Test + public void mergeDelayErrorIterable() { + Single.mergeDelayError(Arrays.asList( + Single.just(1), + Single.error(new TestException()), + Single.just(2)) + ) + .test() + .assertFailure(TestException.class, 1, 2); + } + + @Test + public void mergeDelayErrorPublisher() { + Single.mergeDelayError(Flowable.just( + Single.just(1), + Single.error(new TestException()), + Single.just(2)) + ) + .test() + .assertFailure(TestException.class, 1, 2); + } + + @Test + public void mergeDelayError2() { + Single.mergeDelayError( + Single.just(1), + Single.error(new TestException()) + ) + .test() + .assertFailure(TestException.class, 1); + } + + @Test + public void mergeDelayError2ErrorFirst() { + Single.mergeDelayError( + Single.error(new TestException()), + Single.just(1) + ) + .test() + .assertFailure(TestException.class, 1); + } + + @Test + public void mergeDelayError3() { + Single.mergeDelayError( + Single.just(1), + Single.error(new TestException()), + Single.just(2) + ) + .test() + .assertFailure(TestException.class, 1, 2); + } + + + @Test + public void mergeDelayError4() { + Single.mergeDelayError( + Single.just(1), + Single.error(new TestException()), + Single.just(2), + Single.just(3) + ) + .test() + .assertFailure(TestException.class, 1, 2, 3); + } } From 7194f3ecac0523f1eec53a092d8dbf466c2e8c94 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 10 Jan 2018 09:27:14 +0100 Subject: [PATCH 080/417] 2.x: Improved XSubject JavaDocs (#5802) * 2.x: Improved XSubject JavaDocs * Remove "still" --- .../processors/BehaviorProcessor.java | 2 +- .../io/reactivex/subjects/AsyncSubject.java | 80 +++++++++++- .../reactivex/subjects/BehaviorSubject.java | 9 +- .../subjects/CompletableSubject.java | 59 ++++++++- .../io/reactivex/subjects/MaybeSubject.java | 83 +++++++++++- .../io/reactivex/subjects/PublishSubject.java | 52 +++++++- .../io/reactivex/subjects/ReplaySubject.java | 70 +++++++++- .../io/reactivex/subjects/SingleSubject.java | 67 +++++++++- .../java/io/reactivex/subjects/Subject.java | 8 +- .../io/reactivex/subjects/UnicastSubject.java | 122 ++++++++++++++++-- .../io/reactivex/subjects/package-info.java | 41 +++++- 11 files changed, 548 insertions(+), 45 deletions(-) diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index ac1abea4f5..edd5c620ef 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -86,7 +86,7 @@ * given {@code Subscription} being cancelled immediately. *

                * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} - * is still required to be serialized (called from the same thread or called non-overlappingly from different threads + * is required to be serialized (called from the same thread or called non-overlappingly from different threads * through external means of serialization). The {@link #toSerialized()} method available to all {@code FlowableProcessor}s * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). diff --git a/src/main/java/io/reactivex/subjects/AsyncSubject.java b/src/main/java/io/reactivex/subjects/AsyncSubject.java index 0561144387..581ec9e8c9 100644 --- a/src/main/java/io/reactivex/subjects/AsyncSubject.java +++ b/src/main/java/io/reactivex/subjects/AsyncSubject.java @@ -24,14 +24,86 @@ import io.reactivex.plugins.RxJavaPlugins; /** - * An Subject that emits the very last value followed by a completion event or the received error to Observers. - * - *

                The implementation of onXXX methods are technically thread-safe but non-serialized calls + * A Subject that emits the very last value followed by a completion event or the received error to Observers. + *

                + * This subject does not have a public constructor by design; a new empty instance of this + * {@code AsyncSubject} can be created via the {@link #create()} method. + *

                + * Since a {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, + * {@code null}s are not allowed (Rule 2.13) + * as parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the subject's state is not changed. + *

                + * Since an {@code AsyncSubject} is an {@link io.reactivex.Observable}, it does not support backpressure. + *

                + * When this {@code AsyncSubject} is terminated via {@link #onError(Throwable)}, the + * last observed item (if any) is cleared and late {@link io.reactivex.Observer}s only receive + * the {@code onError} event. + *

                + * The {@code AsyncSubject} caches the latest item internally and it emits this item only when {@code onComplete} is called. + * Therefore, it is not recommended to use this {@code Subject} with infinite or never-completing sources. + *

                + * Even though {@code AsyncSubject} implements the {@code Observer} interface, calling + * {@code onSubscribe} is not required (Rule 2.12) + * if the subject is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code AsyncSubject} reached its terminal state will result in the + * given {@code Disposable} being disposed immediately. + *

                + * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer} + * consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively). + * The implementation of onXXX methods are technically thread-safe but non-serialized calls * to them may lead to undefined state in the currently subscribed Observers. + *

                + * This {@code AsyncSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read the very last observed value - + * after this {@code AsyncSubject} has been completed - in a non-blocking and thread-safe + * manner via {@link #hasValue()}, {@link #getValue()}, {@link #getValues()} or {@link #getValues(Object[])}. + *

                + *
                Scheduler:
                + *
                {@code AsyncSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code Observer}s get notified on the thread where the terminating {@code onError} or {@code onComplete} + * methods were invoked.
                + *
                Error handling:
                + *
                When the {@link #onError(Throwable)} is called, the {@code AsyncSubject} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code Observer}s. During this emission, + * if one or more {@code Observer}s dispose their respective {@code Disposable}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Observer}s + * cancel at once). + * If there were no {@code Observer}s subscribed to this {@code AsyncSubject} when the {@code onError()} + * was called, the global error handler is not invoked. + *
                + *
                + *

                + * Example usage: + *

                
                + * AsyncSubject<Object> subject = AsyncSubject.create();
                + * 
                + * TestObserver<Object> to1 = subject.test();
                + * 
                + * to1.assertEmpty();
                + * 
                + * subject.onNext(1);
                + * 
                + * // AsyncSubject only emits when onComplete was called.
                + * to1.assertEmpty();
                  *
                + * subject.onNext(2);
                + * subject.onComplete();
                + * 
                + * // onComplete triggers the emission of the last cached item and the onComplete event.
                + * to1.assertResult(2);
                + * 
                + * TestObserver<Object> to2 = subject.test();
                + * 
                + * // late Observers receive the last cached item too
                + * to2.assertResult(2);
                + * 
                * @param the value type */ - public final class AsyncSubject extends Subject { @SuppressWarnings("rawtypes") diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java index f7ac689b34..42878adee2 100644 --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java @@ -36,10 +36,11 @@ * a new non-empty instance can be created via {@link #createDefault(Object)} (named as such to avoid * overload resolution conflict with {@code Observable.create} that creates an Observable, not a {@code BehaviorSubject}). *

                - * Since the {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, + * Since a {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, * {@code null}s are not allowed (Rule 2.13) as * default initial values in {@link #createDefault(Object)} or as parameters to {@link #onNext(Object)} and - * {@link #onError(Throwable)}. + * {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the subject's state is not changed. *

                * Since a {@code BehaviorSubject} is an {@link io.reactivex.Observable}, it does not support backpressure. *

                @@ -83,11 +84,11 @@ * Even though {@code BehaviorSubject} implements the {@code Observer} interface, calling * {@code onSubscribe} is not required (Rule 2.12) * if the subject is used as a standalone source. However, calling {@code onSubscribe} - * after the {@code BehaviorSubjecct} reached its terminal state will result in the + * after the {@code BehaviorSubject} reached its terminal state will result in the * given {@code Disposable} being disposed immediately. *

                * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} - * is still required to be serialized (called from the same thread or called non-overlappingly from different threads + * is required to be serialized (called from the same thread or called non-overlappingly from different threads * through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer} * consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively). diff --git a/src/main/java/io/reactivex/subjects/CompletableSubject.java b/src/main/java/io/reactivex/subjects/CompletableSubject.java index 2f0e209624..c1862a6f51 100644 --- a/src/main/java/io/reactivex/subjects/CompletableSubject.java +++ b/src/main/java/io/reactivex/subjects/CompletableSubject.java @@ -24,12 +24,61 @@ /** * Represents a hot Completable-like source and consumer of events similar to Subjects. *

                - * All methods are thread safe. Calling onComplete multiple - * times has no effect. Calling onError multiple times relays the Throwable to - * the RxJavaPlugins' error handler. + * This subject does not have a public constructor by design; a new non-terminated instance of this + * {@code CompletableSubject} can be created via the {@link #create()} method. *

                - * The CompletableSubject doesn't store the Disposables coming through onSubscribe but - * disposes them once the other onXXX methods were called (terminal state reached). + * Since the {@code CompletableSubject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, + * {@code null}s are not allowed (Rule 2.13) + * as parameters to {@link #onError(Throwable)}. + *

                + * Even though {@code CompletableSubject} implements the {@code CompletableObserver} interface, calling + * {@code onSubscribe} is not required (Rule 2.12) + * if the subject is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code CompletableSubject} reached its terminal state will result in the + * given {@code Disposable} being disposed immediately. + *

                + * All methods are thread safe. Calling {@link #onComplete()} multiple + * times has no effect. Calling {@link #onError(Throwable)} multiple times relays the {@code Throwable} to + * the {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} global error handler. + *

                + * This {@code CompletableSubject} supports the standard state-peeking methods {@link #hasComplete()}, + * {@link #hasThrowable()}, {@link #getThrowable()} and {@link #hasObservers()}. + *

                + *
                Scheduler:
                + *
                {@code CompletableSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code CompletableObserver}s get notified on the thread where the terminating {@code onError} or {@code onComplete} + * methods were invoked.
                + *
                Error handling:
                + *
                When the {@link #onError(Throwable)} is called, the {@code CompletableSubject} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code CompletableObserver}s. During this emission, + * if one or more {@code CompletableObserver}s dispose their respective {@code Disposable}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code CompletableObserver}s + * cancel at once). + * If there were no {@code CompletableObserver}s subscribed to this {@code CompletableSubject} when the {@code onError()} + * was called, the global error handler is not invoked. + *
                + *
                + *

                + * Example usage: + *

                
                + * CompletableSubject subject = CompletableSubject.create();
                + * 
                + * TestObserver<Void> to1 = subject.test();
                + *
                + * // a fresh CompletableSubject is empty
                + * to1.assertEmpty();
                + * 
                + * subject.onComplete();
                + *
                + * // a CompletableSubject is always void of items
                + * to1.assertResult();
                + *
                + * TestObserver<Void> to2 = subject.test()
                + *
                + * // late CompletableObservers receive the terminal event
                + * to2.assertResult();
                + * 
                *

                History: 2.0.5 - experimental * @since 2.1 */ diff --git a/src/main/java/io/reactivex/subjects/MaybeSubject.java b/src/main/java/io/reactivex/subjects/MaybeSubject.java index 7f303deefc..d6f84254f2 100644 --- a/src/main/java/io/reactivex/subjects/MaybeSubject.java +++ b/src/main/java/io/reactivex/subjects/MaybeSubject.java @@ -24,12 +24,85 @@ /** * Represents a hot Maybe-like source and consumer of events similar to Subjects. *

                - * All methods are thread safe. Calling onSuccess or onComplete multiple - * times has no effect. Calling onError multiple times relays the Throwable to - * the RxJavaPlugins' error handler. + * This subject does not have a public constructor by design; a new non-terminated instance of this + * {@code MaybeSubject} can be created via the {@link #create()} method. *

                - * The MaybeSubject doesn't store the Disposables coming through onSubscribe but - * disposes them once the other onXXX methods were called (terminal state reached). + * Since the {@code MaybeSubject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, + * {@code null}s are not allowed (Rule 2.13) + * as parameters to {@link #onSuccess(Object)} and {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the subject's state is not changed. + *

                + * Since a {@code MaybeSubject} is a {@link io.reactivex.Maybe}, calling {@code onSuccess}, {@code onError} + * or {@code onComplete} will move this {@code MaybeSubject} into its terminal state atomically. + *

                + * All methods are thread safe. Calling {@link #onSuccess(Object)} or {@link #onComplete()} multiple + * times has no effect. Calling {@link #onError(Throwable)} multiple times relays the {@code Throwable} to + * the {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} global error handler. + *

                + * Even though {@code MaybeSubject} implements the {@code MaybeObserver} interface, calling + * {@code onSubscribe} is not required (Rule 2.12) + * if the subject is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code MaybeSubject} reached its terminal state will result in the + * given {@code Disposable} being disposed immediately. + *

                + * This {@code MaybeSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read any success item in a non-blocking + * and thread-safe manner via {@link #hasValue()} and {@link #getValue()}. + *

                + * The {@code MaybeSubject} does not support clearing its cached {@code onSuccess} value. + *

                + *
                Scheduler:
                + *
                {@code MaybeSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code MaybeObserver}s get notified on the thread where the terminating {@code onSuccess}, {@code onError} or {@code onComplete} + * methods were invoked.
                + *
                Error handling:
                + *
                When the {@link #onError(Throwable)} is called, the {@code MaybeSubject} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code MaybeObserver}s. During this emission, + * if one or more {@code MaybeObserver}s dispose their respective {@code Disposable}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code MaybeObserver}s + * cancel at once). + * If there were no {@code MaybeObserver}s subscribed to this {@code MaybeSubject} when the {@code onError()} + * was called, the global error handler is not invoked. + *
                + *
                + *

                + * Example usage: + *

                
                + * MaybeSubject<Integer> subject1 = MaybeSubject.create();
                + * 
                + * TestObserver<Integer> to1 = subject1.test();
                + * 
                + * // MaybeSubjects are empty by default
                + * to1.assertEmpty();
                + * 
                + * subject1.onSuccess(1);
                + * 
                + * // onSuccess is a terminal event with MaybeSubjects
                + * // TestObserver converts onSuccess into onNext + onComplete
                + * to1.assertResult(1);
                + *
                + * TestObserver<Integer> to2 = subject1.test();
                + * 
                + * // late Observers receive the terminal signal (onSuccess) too
                + * to2.assertResult(1);
                + *
                + * // -----------------------------------------------------
                + *
                + * MaybeSubject<Integer> subject2 = MaybeSubject.create();
                + *
                + * TestObserver<Integer> to3 = subject2.test();
                + * 
                + * subject2.onComplete();
                + * 
                + * // a completed MaybeSubject completes its MaybeObservers
                + * to3.assertResult();
                + *
                + * TestObserver<Integer> to4 = subject1.test();
                + * 
                + * // late Observers receive the terminal signal (onComplete) too
                + * to4.assertResult();
                + * 
                *

                History: 2.0.5 - experimental * @param the value type received and emitted * @since 2.1 diff --git a/src/main/java/io/reactivex/subjects/PublishSubject.java b/src/main/java/io/reactivex/subjects/PublishSubject.java index ad0f66d14c..957b2a0ac6 100644 --- a/src/main/java/io/reactivex/subjects/PublishSubject.java +++ b/src/main/java/io/reactivex/subjects/PublishSubject.java @@ -22,11 +22,57 @@ import io.reactivex.plugins.RxJavaPlugins; /** - * Subject that, once an {@link Observer} has subscribed, emits all subsequently observed items to the - * subscriber. + * A Subject that emits (multicasts) items to currently subscribed {@link Observer}s and terminal events to current + * or late {@code Observer}s. *

                * *

                + * This subject does not have a public constructor by design; a new empty instance of this + * {@code PublishSubject} can be created via the {@link #create()} method. + *

                + * Since a {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, + * {@code null}s are not allowed (Rule 2.13) as + * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the subject's state is not changed. + *

                + * Since a {@code PublishSubject} is an {@link io.reactivex.Observable}, it does not support backpressure. + *

                + * When this {@code PublishSubject} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, + * late {@link io.reactivex.Observer}s only receive the respective terminal event. + *

                + * Unlike a {@link BehaviorSubject}, a {@code PublishSubject} doesn't retain/cache items, therefore, a new + * {@code Observer} won't receive any past items. + *

                + * Even though {@code PublishSubject} implements the {@code Observer} interface, calling + * {@code onSubscribe} is not required (Rule 2.12) + * if the subject is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code PublishSubject} reached its terminal state will result in the + * given {@code Disposable} being disposed immediately. + *

                + * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer} + * consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively). + *

                + * This {@code PublishSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasObservers()}. + *

                + *
                Scheduler:
                + *
                {@code PublishSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code Observer}s get notified on the thread the respective {@code onXXX} methods were invoked.
                + *
                Error handling:
                + *
                When the {@link #onError(Throwable)} is called, the {@code PublishSubject} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code Observer}s. During this emission, + * if one or more {@code Observer}s dispose their respective {@code Disposable}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Observer}s + * cancel at once). + * If there were no {@code Observer}s subscribed to this {@code PublishSubject} when the {@code onError()} + * was called, the global error handler is not invoked. + *
                + *
                + *

                * Example usage: *

                 {@code
                 
                @@ -40,6 +86,8 @@
                   subject.onNext("three");
                   subject.onComplete();
                 
                +  // late Observers only receive the terminal event
                +  subject.test().assertEmpty();
                   } 
                * * @param diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java index 52d0616884..d23756b785 100644 --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java @@ -27,14 +27,80 @@ import io.reactivex.plugins.RxJavaPlugins; /** - * Replays events to Observers. + * Replays events (in a configurable bounded or unbounded manner) to current and late {@link Observer}s. *

                * *

                + * This subject does not have a public constructor by design; a new empty instance of this + * {@code ReplaySubject} can be created via the following {@code create} methods that + * allow specifying the retention policy for items: + *

                  + *
                • {@link #create()} - creates an empty, unbounded {@code ReplaySubject} that + * caches all items and the terminal event it receives.
                • + *
                • {@link #create(int)} - creates an empty, unbounded {@code ReplaySubject} + * with a hint about how many total items one expects to retain.
                • + *
                • {@link #createWithSize(int)} - creates an empty, size-bound {@code ReplaySubject} + * that retains at most the given number of the latest item it receives.
                • + *
                • {@link #createWithTime(long, TimeUnit, Scheduler)} - creates an empty, time-bound + * {@code ReplaySubject} that retains items no older than the specified time amount.
                • + *
                • {@link #createWithTimeAndSize(long, TimeUnit, Scheduler, int)} - creates an empty, + * time- and size-bound {@code ReplaySubject} that retains at most the given number + * items that are also not older than the specified time amount.
                • + *
                + *

                + * Since a {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, + * {@code null}s are not allowed (Rule 2.13) as + * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the subject's state is not changed. + *

                + * Since a {@code ReplaySubject} is an {@link io.reactivex.Observable}, it does not support backpressure. + *

                + * When this {@code ReplaySubject} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, + * late {@link io.reactivex.Observer}s will receive the retained/cached items first (if any) followed by the respective + * terminal event. If the {@code ReplaySubject} has a time-bound, the age of the retained/cached items are still considered + * when replaying and thus it may result in no items being emitted before the terminal event. + *

                + * Once an {@code Observer} has subscribed, it will receive items continuously from that point on. Bounds only affect how + * many past items a new {@code Observer} will receive before it catches up with the live event feed. + *

                + * Even though {@code ReplaySubject} implements the {@code Observer} interface, calling + * {@code onSubscribe} is not required (Rule 2.12) + * if the subject is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code ReplaySubject} reached its terminal state will result in the + * given {@code Disposable} being disposed immediately. + *

                + * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer} + * consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively). + *

                + * This {@code ReplaySubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read the retained/cached items + * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()}, + * {@link #getValues()} or {@link #getValues(Object[])}. + *

                + *
                Scheduler:
                + *
                {@code ReplaySubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code Observer}s get notified on the thread the respective {@code onXXX} methods were invoked. + * Time-bound {@code ReplaySubject}s use the given {@code Scheduler} in their {@code create} methods + * as time source to timestamp of items received for the age checks.
                + *
                Error handling:
                + *
                When the {@link #onError(Throwable)} is called, the {@code ReplaySubject} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code Observer}s. During this emission, + * if one or more {@code Observer}s dispose their respective {@code Disposable}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Observer}s + * cancel at once). + * If there were no {@code Observer}s subscribed to this {@code ReplaySubject} when the {@code onError()} + * was called, the global error handler is not invoked. + *
                + *
                + *

                * Example usage: *

                 {@code
                 
                -  ReplaySubject subject = new ReplaySubject<>();
                +  ReplaySubject subject = ReplaySubject.create();
                   subject.onNext("one");
                   subject.onNext("two");
                   subject.onNext("three");
                diff --git a/src/main/java/io/reactivex/subjects/SingleSubject.java b/src/main/java/io/reactivex/subjects/SingleSubject.java
                index d09d1f436c..d3b4cf63c3 100644
                --- a/src/main/java/io/reactivex/subjects/SingleSubject.java
                +++ b/src/main/java/io/reactivex/subjects/SingleSubject.java
                @@ -24,12 +24,69 @@
                 /**
                  * Represents a hot Single-like source and consumer of events similar to Subjects.
                  * 

                - * All methods are thread safe. Calling onSuccess multiple - * times has no effect. Calling onError multiple times relays the Throwable to - * the RxJavaPlugins' error handler. + * This subject does not have a public constructor by design; a new non-terminated instance of this + * {@code SingleSubject} can be created via the {@link #create()} method. *

                - * The SingleSubject doesn't store the Disposables coming through onSubscribe but - * disposes them once the other onXXX methods were called (terminal state reached). + * Since the {@code SingleSubject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, + * {@code null}s are not allowed (Rule 2.13) + * as parameters to {@link #onSuccess(Object)} and {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the subject's state is not changed. + *

                + * Since a {@code SingleSubject} is a {@link io.reactivex.Maybe}, calling {@code onSuccess}, {@code onError} + * or {@code onComplete} will move this {@code SingleSubject} into its terminal state atomically. + *

                + * All methods are thread safe. Calling {@link #onSuccess(Object)} multiple + * times has no effect. Calling {@link #onError(Throwable)} multiple times relays the {@code Throwable} to + * the {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} global error handler. + *

                + * Even though {@code SingleSubject} implements the {@code SingleObserver} interface, calling + * {@code onSubscribe} is not required (Rule 2.12) + * if the subject is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code SingleSubject} reached its terminal state will result in the + * given {@code Disposable} being disposed immediately. + *

                + * This {@code SingleSubject} supports the standard state-peeking methods {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read any success item in a non-blocking + * and thread-safe manner via {@link #hasValue()} and {@link #getValue()}. + *

                + * The {@code SingleSubject} does not support clearing its cached {@code onSuccess} value. + *

                + *
                Scheduler:
                + *
                {@code SingleSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code SingleObserver}s get notified on the thread where the terminating {@code onSuccess}, {@code onError} + * or {@code onComplete} methods were invoked.
                + *
                Error handling:
                + *
                When the {@link #onError(Throwable)} is called, the {@code SingleSubject} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code SingleObserver}s. During this emission, + * if one or more {@code SingleObserver}s dispose their respective {@code Disposable}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code SingleObserver}s + * cancel at once). + * If there were no {@code SingleObserver}s subscribed to this {@code SingleSubject} when the {@code onError()} + * was called, the global error handler is not invoked. + *
                + *
                + *

                + * Example usage: + *

                
                + * SingleSubject<Integer> subject1 = SingleSubject.create();
                + * 
                + * TestObserver<Integer> to1 = subject1.test();
                + * 
                + * // SingleSubjects are empty by default
                + * to1.assertEmpty();
                + * 
                + * subject1.onSuccess(1);
                + * 
                + * // onSuccess is a terminal event with SingleSubjects
                + * // TestObserver converts onSuccess into onNext + onComplete
                + * to1.assertResult(1);
                + *
                + * TestObserver<Integer> to2 = subject1.test();
                + * 
                + * // late Observers receive the terminal signal (onSuccess) too
                + * to2.assertResult(1);
                + * 
                *

                History: 2.0.5 - experimental * @param the value type received and emitted * @since 2.1 diff --git a/src/main/java/io/reactivex/subjects/Subject.java b/src/main/java/io/reactivex/subjects/Subject.java index 6bd105be85..4a57a4a77d 100644 --- a/src/main/java/io/reactivex/subjects/Subject.java +++ b/src/main/java/io/reactivex/subjects/Subject.java @@ -17,9 +17,11 @@ import io.reactivex.annotations.*; /** - * Represents an Observer and an Observable at the same time, allowing - * multicasting events from a single source to multiple child Subscribers. - *

                All methods except the onSubscribe, onNext, onError and onComplete are thread-safe. + * Represents an {@link Observer} and an {@link Observable} at the same time, allowing + * multicasting events from a single source to multiple child {@code Observer}s. + *

                + * All methods except the {@link #onSubscribe(io.reactivex.disposables.Disposable)}, {@link #onNext(Object)}, + * {@link #onError(Throwable)} and {@link #onComplete()} are thread-safe. * Use {@link #toSerialized()} to make these methods thread-safe as well. * * @param the item value type diff --git a/src/main/java/io/reactivex/subjects/UnicastSubject.java b/src/main/java/io/reactivex/subjects/UnicastSubject.java index a254eaa853..2f5d77f6ba 100644 --- a/src/main/java/io/reactivex/subjects/UnicastSubject.java +++ b/src/main/java/io/reactivex/subjects/UnicastSubject.java @@ -16,9 +16,10 @@ import io.reactivex.annotations.Experimental; import io.reactivex.annotations.Nullable; import io.reactivex.plugins.RxJavaPlugins; + import java.util.concurrent.atomic.*; -import io.reactivex.Observer; +import io.reactivex.*; import io.reactivex.annotations.CheckReturnValue; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.EmptyDisposable; @@ -28,19 +29,116 @@ import io.reactivex.internal.queue.SpscLinkedArrayQueue; /** - * Subject that allows only a single Subscriber to subscribe to it during its lifetime. - * - *

                This subject buffers notifications and replays them to the Subscriber as requested. - * - *

                This subject holds an unbounded internal buffer. - * - *

                If more than one Subscriber attempts to subscribe to this Subject, they - * will receive an IllegalStateException if this Subject hasn't terminated yet, - * or the Subscribers receive the terminal event (error or completion) if this - * Subject has terminated. + * A Subject that queues up events until a single {@link Observer} subscribes to it, replays + * those events to it until the {@code Observer} catches up and then switches to relaying events live to + * this single {@code Observer} until this {@code UnicastSubject} terminates or the {@code Observer} unsubscribes. *

                * - * + *

                + * Note that {@code UnicastSubject} holds an unbounded internal buffer. + *

                + * This subject does not have a public constructor by design; a new empty instance of this + * {@code UnicastSubject} can be created via the following {@code create} methods that + * allow specifying the retention policy for items: + *

                  + *
                • {@link #create()} - creates an empty, unbounded {@code UnicastSubject} that + * caches all items and the terminal event it receives.
                • + *
                • {@link #create(int)} - creates an empty, unbounded {@code UnicastSubject} + * with a hint about how many total items one expects to retain.
                • + *
                • {@link #create(boolean)} - creates an empty, unbounded {@code UnicastSubject} that + * optionally delays an error it receives and replays it after the regular items have been emitted.
                • + *
                • {@link #create(int, Runnable)} - creates an empty, unbounded {@code UnicastSubject} + * with a hint about how many total items one expects to retain and a callback that will be + * called exactly once when the {@code UnicastSubject} gets terminated or the single {@code Observer} unsubscribes.
                • + *
                • {@link #create(int, Runnable, boolean)} - creates an empty, unbounded {@code UnicastSubject} + * with a hint about how many total items one expects to retain and a callback that will be + * called exactly once when the {@code UnicastSubject} gets terminated or the single {@code Observer} unsubscribes + * and optionally delays an error it receives and replays it after the regular items have been emitted.
                • + *
                + *

                + * If more than one {@code Observer} attempts to subscribe to this {@code UnicastSubject}, they + * will receive an {@code IllegalStateException} indicating the single-use-only nature of this {@code UnicastSubject}, + * even if the {@code UnicastSubject} already terminated with an error. + *

                + * Since a {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, + * {@code null}s are not allowed (Rule 2.13) as + * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the subject's state is not changed. + *

                + * Since a {@code UnicastSubject} is an {@link io.reactivex.Observable}, it does not support backpressure. + *

                + * When this {@code UnicastSubject} is terminated via {@link #onError(Throwable)} the current or late single {@code Observer} + * may receive the {@code Throwable} before any available items could be emitted. To make sure an onError event is delivered + * to the {@code Observer} after the normal items, create a {@code UnicastSubject} with the {@link #create(boolean)} or + * {@link #create(int, Runnable, boolean)} factory methods. + *

                + * Even though {@code UnicastSubject} implements the {@code Observer} interface, calling + * {@code onSubscribe} is not required (Rule 2.12) + * if the subject is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code UnicastSubject} reached its terminal state will result in the + * given {@code Disposable} being disposed immediately. + *

                + * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer} + * consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively). + *

                + * This {@code UnicastSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasObservers()}. + *

                + *
                Scheduler:
                + *
                {@code UnicastSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code Observer}s get notified on the thread the respective {@code onXXX} methods were invoked.
                + *
                Error handling:
                + *
                When the {@link #onError(Throwable)} is called, the {@code UnicastSubject} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code Observer}s. During this emission, + * if one or more {@code Observer}s dispose their respective {@code Disposable}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Observer}s + * cancel at once). + * If there were no {@code Observer}s subscribed to this {@code UnicastSubject} when the {@code onError()} + * was called, the global error handler is not invoked. + *
                + *
                + *

                + * Example usage: + *

                
                + * UnicastSubject<Integer> subject = UnicastSubject.create();
                + * 
                + * TestObserver<Integer> to1 = subject.test();
                + * 
                + * // fresh UnicastSubjects are empty
                + * to1.assertEmpty();
                + * 
                + * TestObserver<Integer> to2 = subject.test();
                + * 
                + * // A UnicastSubject only allows one Observer during its lifetime
                + * to2.assertFailure(IllegalStateException.class);
                + * 
                + * subject.onNext(1);
                + * to1.assertValue(1);
                + * 
                + * subject.onNext(2);
                + * to1.assertValues(1, 2);
                + * 
                + * subject.onComplete();
                + * to1.assertResult(1, 2);
                + * 
                + * // ----------------------------------------------------
                + * 
                + * UnicastSubject<Integer> subject2 = UnicastSubject.create();
                + * 
                + * // a UnicastSubject caches events util its single Observer subscribes
                + * subject.onNext(1);
                + * subject.onNext(2);
                + * subject.onComplete();
                + * 
                + * TestObserver<Integer> to3 = subject2.test();
                + * 
                + * // the cached events are emitted in order
                + * to3.assertResult(1, 2);
                + * 
                * @param the value type received and emitted by this Subject subclass * @since 2.0 */ diff --git a/src/main/java/io/reactivex/subjects/package-info.java b/src/main/java/io/reactivex/subjects/package-info.java index e209f5db24..8bd3b06ac2 100644 --- a/src/main/java/io/reactivex/subjects/package-info.java +++ b/src/main/java/io/reactivex/subjects/package-info.java @@ -15,7 +15,44 @@ */ /** - * Classes extending the Observable base reactive class and implementing - * the Observer interface at the same time (aka hot Observables). + * Classes representing so-called hot sources, aka subjects, that implement a base reactive class and + * the respective consumer type at once to allow forms of multicasting events to multiple + * consumers as well as consuming another base reactive type of their kind. + *

                + * Available subject classes with their respective base classes and consumer interfaces: + *
                + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
                Subject typeBase classConsumer interface
                {@link io.reactivex.subjects.Subject Subject} + *
                   {@link io.reactivex.subjects.AsyncSubject AsyncSubject} + *
                   {@link io.reactivex.subjects.BehaviorSubject BehaviorSubject} + *
                   {@link io.reactivex.subjects.PublishSubject PublishSubject} + *
                   {@link io.reactivex.subjects.ReplaySubject ReplaySubject} + *
                   {@link io.reactivex.subjects.UnicastSubject UnicastSubjectSubject} + *
                {@link io.reactivex.Observable Observable}{@link io.reactivex.Observer Observer}
                {@link io.reactivex.subjects.SingleSubject SingleSubject}{@link io.reactivex.Single Single}{@link io.reactivex.SingleObserver SingleObserver}
                {@link io.reactivex.subjects.MaybeSubject MaybeSubject}{@link io.reactivex.Maybe Maybe}{@link io.reactivex.MaybeObserver MaybeObserver}
                {@link io.reactivex.subjects.CompletableSubject CompletableSubject}{@link io.reactivex.Completable Completable}{@link io.reactivex.CompletableObserver CompletableObserver}
                + *

                + * The backpressure-aware variants of the {@code Subject} class are called + * {@link org.reactivestreams.Processor}s and reside in the {@code io.reactivex.processors} package. + * @see io.reactivex.processors */ package io.reactivex.subjects; From 31ab140360f8bd7b6d94ae2f40d1ba665f6fac01 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 10 Jan 2018 15:00:05 +0100 Subject: [PATCH 081/417] 2.x: More Observable marbles, 01/10-a (#5804) --- src/main/java/io/reactivex/Observable.java | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index a9885c11ce..dd3c5535ba 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -9962,7 +9962,7 @@ public final Observable retry() { * Returns an Observable that mirrors the source ObservableSource, resubscribing to it if it calls {@code onError} * and the predicate returns true for that specific exception and retry count. *

                - * + * *

                *
                Scheduler:
                *
                {@code retry} does not operate by default on a particular {@link Scheduler}.
                @@ -9987,7 +9987,7 @@ public final Observable retry(BiPredicate * Returns an Observable that mirrors the source ObservableSource, resubscribing to it if it calls {@code onError} * up to a specified number of retries. *

                - * + * *

                * If the source ObservableSource calls {@link Observer#onError}, this method will resubscribe to the source * ObservableSource for a maximum of {@code count} resubscriptions rather than propagating the @@ -10016,7 +10016,7 @@ public final Observable retry(long times) { /** * Retries at most times or until the predicate returns false, whichever happens first. *

                - * + * *

                *
                Scheduler:
                *
                {@code retry} does not operate by default on a particular {@link Scheduler}.
                @@ -10039,7 +10039,7 @@ public final Observable retry(long times, Predicate predic /** * Retries the current Observable if the predicate returns true. *

                - * + * *

                *
                Scheduler:
                *
                {@code retry} does not operate by default on a particular {@link Scheduler}.
                @@ -10057,7 +10057,8 @@ public final Observable retry(Predicate predicate) { /** * Retries until the given stop function returns true. *

                - * *

                + * + *
                *
                Scheduler:
                *
                {@code retryUntil} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -10498,7 +10499,7 @@ public final Observable serialize() { *

                * This is an alias for {@link #publish()}.{@link ConnectableObservable#refCount()}. *

                - * + * *

                *
                Scheduler:
                *
                {@code share} does not operate by default on a particular {@link Scheduler}.
                @@ -11366,7 +11367,7 @@ public final Observable switchMap(Function - * + * *
                *
                Scheduler:
                *
                {@code switchMapSingle} does not operate by default on a particular {@link Scheduler}.
                @@ -11397,7 +11398,7 @@ public final Observable switchMapSingle(@NonNull Function - * + * *
                *
                Scheduler:
                *
                {@code switchMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.
                From aa3133091dc425cae54aae3002abdbba52dae675 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 10 Jan 2018 18:15:57 +0100 Subject: [PATCH 082/417] 2.x: Final planned Observable marble additions/fixes (#5805) --- src/main/java/io/reactivex/Observable.java | 40 ++++++++++++++++++---- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index dd3c5535ba..6c9a6f986f 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -12657,7 +12657,7 @@ public final Single> toList(final int capacityHint) { * Returns a Single that emits a single item, a list composed of all the items emitted by the * finite source ObservableSource. *

                - * + * *

                * Normally, an ObservableSource that returns multiple items will do so by invoking its {@link Observer}'s * {@link Observer#onNext onNext} method for each such item. You can change this behavior, instructing the @@ -12910,6 +12910,30 @@ public final Single>> toMultimap( /** * Converts the current Observable into a Flowable by applying the specified backpressure strategy. + *

                + * Marble diagrams for the various backpressure strategies are as follows: + *

                  + *
                • {@link BackpressureStrategy#BUFFER} + *

                  + * + *

                • + *
                • {@link BackpressureStrategy#DROP} + *

                  + * + *

                • + *
                • {@link BackpressureStrategy#LATEST} + *

                  + * + *

                • + *
                • {@link BackpressureStrategy#ERROR} + *

                  + * + *

                • + *
                • {@link BackpressureStrategy#MISSING} + *

                  + * + *

                • + *
                *
                *
                Backpressure:
                *
                The operator applies the chosen backpressure strategy of {@link BackpressureStrategy} enum.
                @@ -13046,6 +13070,8 @@ public final Single> toSortedList(int capacityHint) { /** * Modifies the source ObservableSource so that subscribers will dispose it on a specified * {@link Scheduler}. + *

                + * *

                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                @@ -13908,6 +13934,8 @@ public final Observable zipWith(Iterable other, BiFunction + * + *

                * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling @@ -13919,8 +13947,6 @@ public final Observable zipWith(Iterable other, BiFunctionTo work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. - * - * *

                *
                Scheduler:
                *
                {@code zipWith} does not operate by default on a particular {@link Scheduler}.
                @@ -13951,6 +13977,8 @@ public final Observable zipWith(ObservableSource other, * Returns an Observable that emits items that are the result of applying a specified function to pairs of * values, one each from the source ObservableSource and another specified ObservableSource. *

                + * + *

                * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling @@ -13962,8 +13990,6 @@ public final Observable zipWith(ObservableSource other, *
                To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. - * - * *

                *
                Scheduler:
                *
                {@code zipWith} does not operate by default on a particular {@link Scheduler}.
                @@ -13996,6 +14022,8 @@ public final Observable zipWith(ObservableSource other, * Returns an Observable that emits items that are the result of applying a specified function to pairs of * values, one each from the source ObservableSource and another specified ObservableSource. *

                + * + *

                * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling @@ -14007,8 +14035,6 @@ public final Observable zipWith(ObservableSource other, *
                To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. - * - * *

                *
                Scheduler:
                *
                {@code zipWith} does not operate by default on a particular {@link Scheduler}.
                From eb426fd01df975f65fdbca9e5effa88d5e0200e7 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 19 Jan 2018 10:36:38 +0100 Subject: [PATCH 083/417] 2.x: Fix buffer(open, close) not disposing indicators properly (#5811) * 2.x: Fix buffer(open, close) not disposing indicators properly * Unify boundary error methods, fix cleanup, fix last buffer orders * Fix nits. --- .../flowable/FlowableBufferBoundary.java | 433 +++++++++++------- .../observable/ObservableBufferBoundary.java | 387 ++++++++++------ .../flowable/FlowableBufferTest.java | 364 ++++++++++++++- .../observable/ObservableBufferTest.java | 300 +++++++++++- 4 files changed, 1173 insertions(+), 311 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java index e375d5f720..acf35be0cd 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java @@ -15,22 +15,19 @@ import java.util.*; import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.*; import org.reactivestreams.*; -import io.reactivex.Flowable; +import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.fuseable.SimplePlainQueue; -import io.reactivex.internal.queue.MpscLinkedQueue; -import io.reactivex.internal.subscribers.QueueDrainSubscriber; +import io.reactivex.internal.queue.SpscLinkedArrayQueue; import io.reactivex.internal.subscriptions.SubscriptionHelper; -import io.reactivex.internal.util.QueueDrainHelper; +import io.reactivex.internal.util.*; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.subscribers.*; public final class FlowableBufferBoundary, Open, Close> extends AbstractFlowableWithUpstream { @@ -48,48 +45,72 @@ public FlowableBufferBoundary(Flowable source, Publisher buff @Override protected void subscribeActual(Subscriber s) { - source.subscribe(new BufferBoundarySubscriber( - new SerializedSubscriber(s), - bufferOpen, bufferClose, bufferSupplier - )); + BufferBoundarySubscriber parent = + new BufferBoundarySubscriber( + s, bufferOpen, bufferClose, bufferSupplier + ); + s.onSubscribe(parent); + source.subscribe(parent); } - static final class BufferBoundarySubscriber, Open, Close> - extends QueueDrainSubscriber implements Subscription, Disposable { + static final class BufferBoundarySubscriber, Open, Close> + extends AtomicInteger implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = -8466418554264089604L; + + final Subscriber actual; + + final Callable bufferSupplier; + final Publisher bufferOpen; + final Function> bufferClose; - final Callable bufferSupplier; - final CompositeDisposable resources; - Subscription s; + final CompositeDisposable subscribers; + + final AtomicLong requested; + + final AtomicReference upstream; - final List buffers; + final AtomicThrowable errors; - final AtomicInteger windows = new AtomicInteger(); + volatile boolean done; - BufferBoundarySubscriber(Subscriber actual, + final SpscLinkedArrayQueue queue; + + volatile boolean cancelled; + + long index; + + Map buffers; + + long emitted; + + BufferBoundarySubscriber(Subscriber actual, Publisher bufferOpen, Function> bufferClose, - Callable bufferSupplier) { - super(actual, new MpscLinkedQueue()); + Callable bufferSupplier + ) { + this.actual = actual; + this.bufferSupplier = bufferSupplier; this.bufferOpen = bufferOpen; this.bufferClose = bufferClose; - this.bufferSupplier = bufferSupplier; - this.buffers = new LinkedList(); - this.resources = new CompositeDisposable(); + this.queue = new SpscLinkedArrayQueue(bufferSize()); + this.subscribers = new CompositeDisposable(); + this.requested = new AtomicLong(); + this.upstream = new AtomicReference(); + this.buffers = new LinkedHashMap(); + this.errors = new AtomicThrowable(); } + @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - - BufferOpenSubscriber bos = new BufferOpenSubscriber(this); - resources.add(bos); + if (SubscriptionHelper.setOnce(this.upstream, s)) { - actual.onSubscribe(this); + BufferOpenSubscriber open = new BufferOpenSubscriber(this); + subscribers.add(open); - windows.lazySet(1); - bufferOpen.subscribe(bos); + bufferOpen.subscribe(open); s.request(Long.MAX_VALUE); } @@ -98,7 +119,11 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { synchronized (this) { - for (U b : buffers) { + Map bufs = buffers; + if (bufs == null) { + return; + } + for (C b : bufs.values()) { b.add(t); } } @@ -106,206 +131,294 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - cancel(); - cancelled = true; - synchronized (this) { - buffers.clear(); + if (errors.addThrowable(t)) { + subscribers.dispose(); + synchronized (this) { + buffers = null; + } + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); } - actual.onError(t); } @Override public void onComplete() { - if (windows.decrementAndGet() == 0) { - complete(); - } - } - - void complete() { - List list; + subscribers.dispose(); synchronized (this) { - list = new ArrayList(buffers); - buffers.clear(); - } - - SimplePlainQueue q = queue; - for (U u : list) { - q.offer(u); + Map bufs = buffers; + if (bufs == null) { + return; + } + for (C b : bufs.values()) { + queue.offer(b); + } + buffers = null; } done = true; - if (enter()) { - QueueDrainHelper.drainMaxLoop(q, actual, false, this, this); - } + drain(); } @Override public void request(long n) { - requested(n); - } - - @Override - public void dispose() { - resources.dispose(); - } - - @Override - public boolean isDisposed() { - return resources.isDisposed(); + BackpressureHelper.add(requested, n); + drain(); } @Override public void cancel() { - if (!cancelled) { + if (SubscriptionHelper.cancel(upstream)) { cancelled = true; - dispose(); + subscribers.dispose(); + synchronized (this) { + buffers = null; + } + if (getAndIncrement() != 0) { + queue.clear(); + } } } - @Override - public boolean accept(Subscriber a, U v) { - a.onNext(v); - return true; - } - - void open(Open window) { - if (cancelled) { + void open(Open token) { + Publisher p; + C buf; + try { + buf = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null Collection"); + p = ObjectHelper.requireNonNull(bufferClose.apply(token), "The bufferClose returned a null Publisher"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + SubscriptionHelper.cancel(upstream); + onError(ex); return; } - U b; - - try { - b = ObjectHelper.requireNonNull(bufferSupplier.call(), "The buffer supplied is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - onError(e); - return; + long idx = index; + index = idx + 1; + synchronized (this) { + Map bufs = buffers; + if (bufs == null) { + return; + } + bufs.put(idx, buf); } - Publisher p; + BufferCloseSubscriber bc = new BufferCloseSubscriber(this, idx); + subscribers.add(bc); + p.subscribe(bc); + } - try { - p = ObjectHelper.requireNonNull(bufferClose.apply(window), "The buffer closing publisher is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - onError(e); - return; + void openComplete(BufferOpenSubscriber os) { + subscribers.delete(os); + if (subscribers.size() == 0) { + SubscriptionHelper.cancel(upstream); + done = true; + drain(); } + } - if (cancelled) { - return; + void close(BufferCloseSubscriber closer, long idx) { + subscribers.delete(closer); + boolean makeDone = false; + if (subscribers.size() == 0) { + makeDone = true; + SubscriptionHelper.cancel(upstream); } - synchronized (this) { - if (cancelled) { + Map bufs = buffers; + if (bufs == null) { return; } - buffers.add(b); + queue.offer(buffers.remove(idx)); } + if (makeDone) { + done = true; + } + drain(); + } - BufferCloseSubscriber bcs = new BufferCloseSubscriber(b, this); - resources.add(bcs); + void boundaryError(Disposable subscriber, Throwable ex) { + SubscriptionHelper.cancel(upstream); + subscribers.delete(subscriber); + onError(ex); + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } - windows.getAndIncrement(); + int missed = 1; + long e = emitted; + Subscriber a = actual; + SpscLinkedArrayQueue q = queue; + + for (;;) { + long r = requested.get(); + + while (e != r) { + if (cancelled) { + q.clear(); + return; + } + + boolean d = done; + if (d && errors.get() != null) { + q.clear(); + Throwable ex = errors.terminate(); + a.onError(ex); + return; + } + + C v = q.poll(); + boolean empty = v == null; + + if (d && empty) { + a.onComplete(); + return; + } + + if (empty) { + break; + } + + a.onNext(v); + e++; + } - p.subscribe(bcs); - } + if (e == r) { + if (cancelled) { + q.clear(); + return; + } + + if (done) { + if (errors.get() != null) { + q.clear(); + Throwable ex = errors.terminate(); + a.onError(ex); + return; + } else if (q.isEmpty()) { + a.onComplete(); + return; + } + } + } - void openFinished(Disposable d) { - if (resources.remove(d)) { - if (windows.decrementAndGet() == 0) { - complete(); + emitted = e; + missed = addAndGet(-missed); + if (missed == 0) { + break; } } } - void close(U b, Disposable d) { + static final class BufferOpenSubscriber + extends AtomicReference + implements FlowableSubscriber, Disposable { - boolean e; - synchronized (this) { - e = buffers.remove(b); - } + private static final long serialVersionUID = -8498650778633225126L; + + final BufferBoundarySubscriber parent; - if (e) { - fastPathOrderedEmitMax(b, false, this); + BufferOpenSubscriber(BufferBoundarySubscriber parent) { + this.parent = parent; } - if (resources.remove(d)) { - if (windows.decrementAndGet() == 0) { - complete(); + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.setOnce(this, s)) { + s.request(Long.MAX_VALUE); } } - } - } - static final class BufferOpenSubscriber, Open, Close> - extends DisposableSubscriber { - final BufferBoundarySubscriber parent; + @Override + public void onNext(Open t) { + parent.open(t); + } - boolean done; + @Override + public void onError(Throwable t) { + lazySet(SubscriptionHelper.CANCELLED); + parent.boundaryError(this, t); + } - BufferOpenSubscriber(BufferBoundarySubscriber parent) { - this.parent = parent; - } - @Override - public void onNext(Open t) { - if (done) { - return; + @Override + public void onComplete() { + lazySet(SubscriptionHelper.CANCELLED); + parent.openComplete(this); } - parent.open(t); - } - @Override - public void onError(Throwable t) { - if (done) { - RxJavaPlugins.onError(t); - return; + @Override + public void dispose() { + SubscriptionHelper.cancel(this); } - done = true; - parent.onError(t); - } - @Override - public void onComplete() { - if (done) { - return; + @Override + public boolean isDisposed() { + return get() == SubscriptionHelper.CANCELLED; } - done = true; - parent.openFinished(this); } } - static final class BufferCloseSubscriber, Open, Close> - extends DisposableSubscriber { - final BufferBoundarySubscriber parent; - final U value; - boolean done; - BufferCloseSubscriber(U value, BufferBoundarySubscriber parent) { + static final class BufferCloseSubscriber> + extends AtomicReference + implements FlowableSubscriber, Disposable { + + private static final long serialVersionUID = -8498650778633225126L; + + final BufferBoundarySubscriber parent; + + final long index; + + BufferCloseSubscriber(BufferBoundarySubscriber parent, long index) { this.parent = parent; - this.value = value; + this.index = index; } @Override - public void onNext(Close t) { - onComplete(); + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.setOnce(this, s)) { + s.request(Long.MAX_VALUE); + } + } + + @Override + public void onNext(Object t) { + Subscription s = get(); + if (s != SubscriptionHelper.CANCELLED) { + lazySet(SubscriptionHelper.CANCELLED); + s.cancel(); + parent.close(this, index); + } } @Override public void onError(Throwable t) { - if (done) { + if (get() != SubscriptionHelper.CANCELLED) { + lazySet(SubscriptionHelper.CANCELLED); + parent.boundaryError(this, t); + } else { RxJavaPlugins.onError(t); - return; } - parent.onError(t); } @Override public void onComplete() { - if (done) { - return; + if (get() != SubscriptionHelper.CANCELLED) { + lazySet(SubscriptionHelper.CANCELLED); + parent.close(this, index); } - done = true; - parent.close(value, this); + } + + @Override + public void dispose() { + SubscriptionHelper.cancel(this); + } + + @Override + public boolean isDisposed() { + return get() == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundary.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundary.java index a9051e474a..b88bce3477 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundary.java @@ -15,7 +15,7 @@ import java.util.*; import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.*; import io.reactivex.ObservableSource; import io.reactivex.Observer; @@ -24,11 +24,8 @@ import io.reactivex.functions.Function; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.fuseable.SimplePlainQueue; -import io.reactivex.internal.observers.QueueDrainObserver; -import io.reactivex.internal.queue.MpscLinkedQueue; -import io.reactivex.internal.util.QueueDrainHelper; -import io.reactivex.observers.*; +import io.reactivex.internal.queue.SpscLinkedArrayQueue; +import io.reactivex.internal.util.AtomicThrowable; import io.reactivex.plugins.RxJavaPlugins; public final class ObservableBufferBoundary, Open, Close> @@ -47,55 +44,78 @@ public ObservableBufferBoundary(ObservableSource source, ObservableSource t) { - source.subscribe(new BufferBoundaryObserver( - new SerializedObserver(t), - bufferOpen, bufferClose, bufferSupplier - )); + BufferBoundaryObserver parent = + new BufferBoundaryObserver( + t, bufferOpen, bufferClose, bufferSupplier + ); + t.onSubscribe(parent); + source.subscribe(parent); } - static final class BufferBoundaryObserver, Open, Close> - extends QueueDrainObserver implements Disposable { + static final class BufferBoundaryObserver, Open, Close> + extends AtomicInteger implements Observer, Disposable { + + private static final long serialVersionUID = -8466418554264089604L; + + final Observer actual; + + final Callable bufferSupplier; + final ObservableSource bufferOpen; + final Function> bufferClose; - final Callable bufferSupplier; - final CompositeDisposable resources; - Disposable s; + final CompositeDisposable observers; + + final AtomicReference upstream; - final List buffers; + final AtomicThrowable errors; - final AtomicInteger windows = new AtomicInteger(); + volatile boolean done; - BufferBoundaryObserver(Observer actual, + final SpscLinkedArrayQueue queue; + + volatile boolean cancelled; + + long index; + + Map buffers; + + BufferBoundaryObserver(Observer actual, ObservableSource bufferOpen, Function> bufferClose, - Callable bufferSupplier) { - super(actual, new MpscLinkedQueue()); + Callable bufferSupplier + ) { + this.actual = actual; + this.bufferSupplier = bufferSupplier; this.bufferOpen = bufferOpen; this.bufferClose = bufferClose; - this.bufferSupplier = bufferSupplier; - this.buffers = new LinkedList(); - this.resources = new CompositeDisposable(); + this.queue = new SpscLinkedArrayQueue(bufferSize()); + this.observers = new CompositeDisposable(); + this.upstream = new AtomicReference(); + this.buffers = new LinkedHashMap(); + this.errors = new AtomicThrowable(); } + @Override public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - - BufferOpenObserver bos = new BufferOpenObserver(this); - resources.add(bos); + if (DisposableHelper.setOnce(this.upstream, s)) { - actual.onSubscribe(this); + BufferOpenObserver open = new BufferOpenObserver(this); + observers.add(open); - windows.lazySet(1); - bufferOpen.subscribe(bos); + bufferOpen.subscribe(open); } } @Override public void onNext(T t) { synchronized (this) { - for (U b : buffers) { + Map bufs = buffers; + if (bufs == null) { + return; + } + for (C b : bufs.values()) { b.add(t); } } @@ -103,194 +123,265 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - dispose(); - cancelled = true; - synchronized (this) { - buffers.clear(); + if (errors.addThrowable(t)) { + observers.dispose(); + synchronized (this) { + buffers = null; + } + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); } - actual.onError(t); } @Override public void onComplete() { - if (windows.decrementAndGet() == 0) { - complete(); - } - } - - void complete() { - List list; + observers.dispose(); synchronized (this) { - list = new ArrayList(buffers); - buffers.clear(); - } - - SimplePlainQueue q = queue; - for (U u : list) { - q.offer(u); + Map bufs = buffers; + if (bufs == null) { + return; + } + for (C b : bufs.values()) { + queue.offer(b); + } + buffers = null; } done = true; - if (enter()) { - QueueDrainHelper.drainLoop(q, actual, false, this, this); - } + drain(); } @Override public void dispose() { - if (!cancelled) { + if (DisposableHelper.dispose(upstream)) { cancelled = true; - resources.dispose(); + observers.dispose(); + synchronized (this) { + buffers = null; + } + if (getAndIncrement() != 0) { + queue.clear(); + } } } - @Override public boolean isDisposed() { - return cancelled; - } - @Override - public void accept(Observer a, U v) { - a.onNext(v); + public boolean isDisposed() { + return DisposableHelper.isDisposed(upstream.get()); } - void open(Open window) { - if (cancelled) { + void open(Open token) { + ObservableSource p; + C buf; + try { + buf = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null Collection"); + p = ObjectHelper.requireNonNull(bufferClose.apply(token), "The bufferClose returned a null ObservableSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + DisposableHelper.dispose(upstream); + onError(ex); return; } - U b; - - try { - b = ObjectHelper.requireNonNull(bufferSupplier.call(), "The buffer supplied is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - onError(e); - return; + long idx = index; + index = idx + 1; + synchronized (this) { + Map bufs = buffers; + if (bufs == null) { + return; + } + bufs.put(idx, buf); } - ObservableSource p; + BufferCloseObserver bc = new BufferCloseObserver(this, idx); + observers.add(bc); + p.subscribe(bc); + } - try { - p = ObjectHelper.requireNonNull(bufferClose.apply(window), "The buffer closing Observable is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - onError(e); - return; + void openComplete(BufferOpenObserver os) { + observers.delete(os); + if (observers.size() == 0) { + DisposableHelper.dispose(upstream); + done = true; + drain(); } + } - if (cancelled) { - return; + void close(BufferCloseObserver closer, long idx) { + observers.delete(closer); + boolean makeDone = false; + if (observers.size() == 0) { + makeDone = true; + DisposableHelper.dispose(upstream); } - synchronized (this) { - if (cancelled) { + Map bufs = buffers; + if (bufs == null) { return; } - buffers.add(b); + queue.offer(buffers.remove(idx)); } + if (makeDone) { + done = true; + } + drain(); + } - BufferCloseObserver bcs = new BufferCloseObserver(b, this); - resources.add(bcs); + void boundaryError(Disposable observer, Throwable ex) { + DisposableHelper.dispose(upstream); + observers.delete(observer); + onError(ex); + } - windows.getAndIncrement(); + void drain() { + if (getAndIncrement() != 0) { + return; + } - p.subscribe(bcs); - } + int missed = 1; + Observer a = actual; + SpscLinkedArrayQueue q = queue; + + for (;;) { + for (;;) { + if (cancelled) { + q.clear(); + return; + } + + boolean d = done; + if (d && errors.get() != null) { + q.clear(); + Throwable ex = errors.terminate(); + a.onError(ex); + return; + } + + C v = q.poll(); + boolean empty = v == null; + + if (d && empty) { + a.onComplete(); + return; + } + + if (empty) { + break; + } + + a.onNext(v); + } - void openFinished(Disposable d) { - if (resources.remove(d)) { - if (windows.decrementAndGet() == 0) { - complete(); + missed = addAndGet(-missed); + if (missed == 0) { + break; } } } - void close(U b, Disposable d) { + static final class BufferOpenObserver + extends AtomicReference + implements Observer, Disposable { - boolean e; - synchronized (this) { - e = buffers.remove(b); + private static final long serialVersionUID = -8498650778633225126L; + + final BufferBoundaryObserver parent; + + BufferOpenObserver(BufferBoundaryObserver parent) { + this.parent = parent; } - if (e) { - fastPathOrderedEmit(b, false, this); + @Override + public void onSubscribe(Disposable s) { + DisposableHelper.setOnce(this, s); } - if (resources.remove(d)) { - if (windows.decrementAndGet() == 0) { - complete(); - } + @Override + public void onNext(Open t) { + parent.open(t); + } + + @Override + public void onError(Throwable t) { + lazySet(DisposableHelper.DISPOSED); + parent.boundaryError(this, t); + } + + @Override + public void onComplete() { + lazySet(DisposableHelper.DISPOSED); + parent.openComplete(this); + } + + @Override + public void dispose() { + DisposableHelper.dispose(this); + } + + @Override + public boolean isDisposed() { + return get() == DisposableHelper.DISPOSED; } } } - static final class BufferOpenObserver, Open, Close> - extends DisposableObserver { - final BufferBoundaryObserver parent; + static final class BufferCloseObserver> + extends AtomicReference + implements Observer, Disposable { + + private static final long serialVersionUID = -8498650778633225126L; + + final BufferBoundaryObserver parent; - boolean done; + final long index; - BufferOpenObserver(BufferBoundaryObserver parent) { + BufferCloseObserver(BufferBoundaryObserver parent, long index) { this.parent = parent; + this.index = index; } + @Override - public void onNext(Open t) { - if (done) { - return; + public void onSubscribe(Disposable s) { + DisposableHelper.setOnce(this, s); + } + + @Override + public void onNext(Object t) { + Disposable s = get(); + if (s != DisposableHelper.DISPOSED) { + lazySet(DisposableHelper.DISPOSED); + s.dispose(); + parent.close(this, index); } - parent.open(t); } @Override public void onError(Throwable t) { - if (done) { + if (get() != DisposableHelper.DISPOSED) { + lazySet(DisposableHelper.DISPOSED); + parent.boundaryError(this, t); + } else { RxJavaPlugins.onError(t); - return; } - done = true; - parent.onError(t); } @Override public void onComplete() { - if (done) { - return; + if (get() != DisposableHelper.DISPOSED) { + lazySet(DisposableHelper.DISPOSED); + parent.close(this, index); } - done = true; - parent.openFinished(this); - } - } - - static final class BufferCloseObserver, Open, Close> - extends DisposableObserver { - final BufferBoundaryObserver parent; - final U value; - boolean done; - BufferCloseObserver(U value, BufferBoundaryObserver parent) { - this.parent = parent; - this.value = value; } @Override - public void onNext(Close t) { - onComplete(); - } - - @Override - public void onError(Throwable t) { - if (done) { - RxJavaPlugins.onError(t); - return; - } - parent.onError(t); + public void dispose() { + DisposableHelper.dispose(this); } @Override - public void onComplete() { - if (done) { - return; - } - done = true; - parent.close(value, this); + public boolean isDisposed() { + return get() == DisposableHelper.DISPOSED; } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index bd18c0187d..06a4553f1c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -17,6 +17,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +import java.io.IOException; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; @@ -26,7 +27,8 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.exceptions.TestException; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; @@ -2074,4 +2076,364 @@ public void run() throws Exception { assertEquals(0, counter.get()); } + + @Test + @SuppressWarnings("unchecked") + public void boundaryOpenCloseDisposedOnComplete() { + PublishProcessor source = PublishProcessor.create(); + + PublishProcessor openIndicator = PublishProcessor.create(); + + PublishProcessor closeIndicator = PublishProcessor.create(); + + TestSubscriber> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .test(); + + assertTrue(source.hasSubscribers()); + assertTrue(openIndicator.hasSubscribers()); + assertFalse(closeIndicator.hasSubscribers()); + + openIndicator.onNext(1); + + assertTrue(openIndicator.hasSubscribers()); + assertTrue(closeIndicator.hasSubscribers()); + + source.onComplete(); + + ts.assertResult(Collections.emptyList()); + + assertFalse(openIndicator.hasSubscribers()); + assertFalse(closeIndicator.hasSubscribers()); + } + + @Test + public void bufferedCanCompleteIfOpenNeverCompletesDropping() { + Flowable.range(1, 50) + .zipWith(Flowable.interval(5, TimeUnit.MILLISECONDS), + new BiFunction() { + @Override + public Integer apply(Integer integer, Long aLong) { + return integer; + } + }) + .buffer(Flowable.interval(0,200, TimeUnit.MILLISECONDS), + new Function>() { + @Override + public Publisher apply(Long a) { + return Flowable.just(a).delay(100, TimeUnit.MILLISECONDS); + } + }) + .test() + .assertSubscribed() + .awaitDone(3, TimeUnit.SECONDS) + .assertComplete(); + } + + @Test + public void bufferedCanCompleteIfOpenNeverCompletesOverlapping() { + Flowable.range(1, 50) + .zipWith(Flowable.interval(5, TimeUnit.MILLISECONDS), + new BiFunction() { + @Override + public Integer apply(Integer integer, Long aLong) { + return integer; + } + }) + .buffer(Flowable.interval(0,100, TimeUnit.MILLISECONDS), + new Function>() { + @Override + public Publisher apply(Long a) { + return Flowable.just(a).delay(200, TimeUnit.MILLISECONDS); + } + }) + .test() + .assertSubscribed() + .awaitDone(3, TimeUnit.SECONDS) + .assertComplete(); + } + + @Test + @SuppressWarnings("unchecked") + public void openClosemainError() { + Flowable.error(new TestException()) + .buffer(Flowable.never(), Functions.justFunction(Flowable.never())) + .test() + .assertFailure(TestException.class); + } + + @Test + @SuppressWarnings("unchecked") + public void openClosebadSource() { + List errors = TestHelper.trackPluginErrors(); + try { + new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + BooleanSubscription bs1 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); + + s.onSubscribe(bs1); + + assertFalse(bs1.isCancelled()); + assertFalse(bs2.isCancelled()); + + s.onSubscribe(bs2); + + assertFalse(bs1.isCancelled()); + assertTrue(bs2.isCancelled()); + + s.onError(new IOException()); + s.onComplete(); + s.onNext(1); + s.onError(new TestException()); + } + } + .buffer(Flowable.never(), Functions.justFunction(Flowable.never())) + .test() + .assertFailure(IOException.class); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseOpenCompletes() { + PublishProcessor source = PublishProcessor.create(); + + PublishProcessor openIndicator = PublishProcessor.create(); + + PublishProcessor closeIndicator = PublishProcessor.create(); + + TestSubscriber> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .test(); + + openIndicator.onNext(1); + + assertTrue(closeIndicator.hasSubscribers()); + + openIndicator.onComplete(); + + assertTrue(source.hasSubscribers()); + assertTrue(closeIndicator.hasSubscribers()); + + closeIndicator.onComplete(); + + assertFalse(source.hasSubscribers()); + + ts.assertResult(Collections.emptyList()); + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseOpenCompletesNoBuffers() { + PublishProcessor source = PublishProcessor.create(); + + PublishProcessor openIndicator = PublishProcessor.create(); + + PublishProcessor closeIndicator = PublishProcessor.create(); + + TestSubscriber> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .test(); + + openIndicator.onNext(1); + + assertTrue(closeIndicator.hasSubscribers()); + + closeIndicator.onComplete(); + + assertTrue(source.hasSubscribers()); + assertTrue(openIndicator.hasSubscribers()); + + openIndicator.onComplete(); + + assertFalse(source.hasSubscribers()); + + ts.assertResult(Collections.emptyList()); + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseTake() { + PublishProcessor source = PublishProcessor.create(); + + PublishProcessor openIndicator = PublishProcessor.create(); + + PublishProcessor closeIndicator = PublishProcessor.create(); + + TestSubscriber> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .take(1) + .test(2); + + openIndicator.onNext(1); + closeIndicator.onComplete(); + + assertFalse(source.hasSubscribers()); + assertFalse(openIndicator.hasSubscribers()); + assertFalse(closeIndicator.hasSubscribers()); + + ts.assertResult(Collections.emptyList()); + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseLimit() { + PublishProcessor source = PublishProcessor.create(); + + PublishProcessor openIndicator = PublishProcessor.create(); + + PublishProcessor closeIndicator = PublishProcessor.create(); + + TestSubscriber> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .limit(1) + .test(2); + + openIndicator.onNext(1); + closeIndicator.onComplete(); + + assertFalse(source.hasSubscribers()); + assertFalse(openIndicator.hasSubscribers()); + assertFalse(closeIndicator.hasSubscribers()); + + ts.assertResult(Collections.emptyList()); + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseEmptyBackpressure() { + PublishProcessor source = PublishProcessor.create(); + + PublishProcessor openIndicator = PublishProcessor.create(); + + PublishProcessor closeIndicator = PublishProcessor.create(); + + TestSubscriber> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .test(0); + + source.onComplete(); + + assertFalse(openIndicator.hasSubscribers()); + assertFalse(closeIndicator.hasSubscribers()); + + ts.assertResult(); + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseErrorBackpressure() { + PublishProcessor source = PublishProcessor.create(); + + PublishProcessor openIndicator = PublishProcessor.create(); + + PublishProcessor closeIndicator = PublishProcessor.create(); + + TestSubscriber> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .test(0); + + source.onError(new TestException()); + + assertFalse(openIndicator.hasSubscribers()); + assertFalse(closeIndicator.hasSubscribers()); + + ts.assertFailure(TestException.class); + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseBadOpen() { + List errors = TestHelper.trackPluginErrors(); + try { + Flowable.never() + .buffer(new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + + assertFalse(((Disposable)s).isDisposed()); + + BooleanSubscription bs1 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); + + s.onSubscribe(bs1); + + assertFalse(bs1.isCancelled()); + assertFalse(bs2.isCancelled()); + + s.onSubscribe(bs2); + + assertFalse(bs1.isCancelled()); + assertTrue(bs2.isCancelled()); + + s.onError(new IOException()); + + assertTrue(((Disposable)s).isDisposed()); + + s.onComplete(); + s.onNext(1); + s.onError(new TestException()); + } + }, Functions.justFunction(Flowable.never())) + .test() + .assertFailure(IOException.class); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseBadClose() { + List errors = TestHelper.trackPluginErrors(); + try { + Flowable.never() + .buffer(Flowable.just(1).concatWith(Flowable.never()), + Functions.justFunction(new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + + assertFalse(((Disposable)s).isDisposed()); + + BooleanSubscription bs1 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); + + s.onSubscribe(bs1); + + assertFalse(bs1.isCancelled()); + assertFalse(bs2.isCancelled()); + + s.onSubscribe(bs2); + + assertFalse(bs1.isCancelled()); + assertTrue(bs2.isCancelled()); + + s.onError(new IOException()); + + assertTrue(((Disposable)s).isDisposed()); + + s.onComplete(); + s.onNext(1); + s.onError(new TestException()); + } + })) + .test() + .assertFailure(IOException.class); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 93a9e2fb74..6c633581ea 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -17,6 +17,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +import java.io.IOException; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; @@ -27,11 +28,12 @@ import io.reactivex.*; import io.reactivex.Observable; import io.reactivex.Observer; -import io.reactivex.disposables.Disposables; -import io.reactivex.exceptions.TestException; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.observers.*; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; import io.reactivex.subjects.PublishSubject; @@ -1500,4 +1502,298 @@ public void run() throws Exception { assertEquals(0, counter.get()); } + + @Test + @SuppressWarnings("unchecked") + public void boundaryOpenCloseDisposedOnComplete() { + PublishSubject source = PublishSubject.create(); + + PublishSubject openIndicator = PublishSubject.create(); + + PublishSubject closeIndicator = PublishSubject.create(); + + TestObserver> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .test(); + + assertTrue(source.hasObservers()); + assertTrue(openIndicator.hasObservers()); + assertFalse(closeIndicator.hasObservers()); + + openIndicator.onNext(1); + + assertTrue(openIndicator.hasObservers()); + assertTrue(closeIndicator.hasObservers()); + + source.onComplete(); + + ts.assertResult(Collections.emptyList()); + + assertFalse(openIndicator.hasObservers()); + assertFalse(closeIndicator.hasObservers()); + } + + @Test + public void bufferedCanCompleteIfOpenNeverCompletesDropping() { + Observable.range(1, 50) + .zipWith(Observable.interval(5, TimeUnit.MILLISECONDS), + new BiFunction() { + @Override + public Integer apply(Integer integer, Long aLong) { + return integer; + } + }) + .buffer(Observable.interval(0,200, TimeUnit.MILLISECONDS), + new Function>() { + @Override + public Observable apply(Long a) { + return Observable.just(a).delay(100, TimeUnit.MILLISECONDS); + } + }) + .test() + .assertSubscribed() + .awaitDone(3, TimeUnit.SECONDS) + .assertComplete(); + } + + @Test + public void bufferedCanCompleteIfOpenNeverCompletesOverlapping() { + Observable.range(1, 50) + .zipWith(Observable.interval(5, TimeUnit.MILLISECONDS), + new BiFunction() { + @Override + public Integer apply(Integer integer, Long aLong) { + return integer; + } + }) + .buffer(Observable.interval(0,100, TimeUnit.MILLISECONDS), + new Function>() { + @Override + public Observable apply(Long a) { + return Observable.just(a).delay(200, TimeUnit.MILLISECONDS); + } + }) + .test() + .assertSubscribed() + .awaitDone(3, TimeUnit.SECONDS) + .assertComplete(); + } + + @Test + @SuppressWarnings("unchecked") + public void openClosemainError() { + Observable.error(new TestException()) + .buffer(Observable.never(), Functions.justFunction(Observable.never())) + .test() + .assertFailure(TestException.class); + } + + @Test + @SuppressWarnings("unchecked") + public void openClosebadSource() { + List errors = TestHelper.trackPluginErrors(); + try { + new Observable() { + @Override + protected void subscribeActual(Observer s) { + Disposable bs1 = Disposables.empty(); + Disposable bs2 = Disposables.empty(); + + s.onSubscribe(bs1); + + assertFalse(bs1.isDisposed()); + assertFalse(bs2.isDisposed()); + + s.onSubscribe(bs2); + + assertFalse(bs1.isDisposed()); + assertTrue(bs2.isDisposed()); + + s.onError(new IOException()); + s.onComplete(); + s.onNext(1); + s.onError(new TestException()); + } + } + .buffer(Observable.never(), Functions.justFunction(Observable.never())) + .test() + .assertFailure(IOException.class); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseOpenCompletes() { + PublishSubject source = PublishSubject.create(); + + PublishSubject openIndicator = PublishSubject.create(); + + PublishSubject closeIndicator = PublishSubject.create(); + + TestObserver> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .test(); + + openIndicator.onNext(1); + + assertTrue(closeIndicator.hasObservers()); + + openIndicator.onComplete(); + + assertTrue(source.hasObservers()); + assertTrue(closeIndicator.hasObservers()); + + closeIndicator.onComplete(); + + assertFalse(source.hasObservers()); + + ts.assertResult(Collections.emptyList()); + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseOpenCompletesNoBuffers() { + PublishSubject source = PublishSubject.create(); + + PublishSubject openIndicator = PublishSubject.create(); + + PublishSubject closeIndicator = PublishSubject.create(); + + TestObserver> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .test(); + + openIndicator.onNext(1); + + assertTrue(closeIndicator.hasObservers()); + + closeIndicator.onComplete(); + + assertTrue(source.hasObservers()); + assertTrue(openIndicator.hasObservers()); + + openIndicator.onComplete(); + + assertFalse(source.hasObservers()); + + ts.assertResult(Collections.emptyList()); + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseTake() { + PublishSubject source = PublishSubject.create(); + + PublishSubject openIndicator = PublishSubject.create(); + + PublishSubject closeIndicator = PublishSubject.create(); + + TestObserver> ts = source + .buffer(openIndicator, Functions.justFunction(closeIndicator)) + .take(1) + .test(); + + openIndicator.onNext(1); + closeIndicator.onComplete(); + + assertFalse(source.hasObservers()); + assertFalse(openIndicator.hasObservers()); + assertFalse(closeIndicator.hasObservers()); + + ts.assertResult(Collections.emptyList()); + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseBadOpen() { + List errors = TestHelper.trackPluginErrors(); + try { + Observable.never() + .buffer(new Observable() { + @Override + protected void subscribeActual(Observer s) { + + assertFalse(((Disposable)s).isDisposed()); + + Disposable bs1 = Disposables.empty(); + Disposable bs2 = Disposables.empty(); + + s.onSubscribe(bs1); + + assertFalse(bs1.isDisposed()); + assertFalse(bs2.isDisposed()); + + s.onSubscribe(bs2); + + assertFalse(bs1.isDisposed()); + assertTrue(bs2.isDisposed()); + + s.onError(new IOException()); + + assertTrue(((Disposable)s).isDisposed()); + + s.onComplete(); + s.onNext(1); + s.onError(new TestException()); + } + }, Functions.justFunction(Observable.never())) + .test() + .assertFailure(IOException.class); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + @SuppressWarnings("unchecked") + public void openCloseBadClose() { + List errors = TestHelper.trackPluginErrors(); + try { + Observable.never() + .buffer(Observable.just(1).concatWith(Observable.never()), + Functions.justFunction(new Observable() { + @Override + protected void subscribeActual(Observer s) { + + assertFalse(((Disposable)s).isDisposed()); + + Disposable bs1 = Disposables.empty(); + Disposable bs2 = Disposables.empty(); + + s.onSubscribe(bs1); + + assertFalse(bs1.isDisposed()); + assertFalse(bs2.isDisposed()); + + s.onSubscribe(bs2); + + assertFalse(bs1.isDisposed()); + assertTrue(bs2.isDisposed()); + + s.onError(new IOException()); + + assertTrue(((Disposable)s).isDisposed()); + + s.onComplete(); + s.onNext(1); + s.onError(new TestException()); + } + })) + .test() + .assertFailure(IOException.class); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } From bcc419cc92a0162549cd9e31c2f49ac7ab0d84cf Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 22 Jan 2018 10:06:23 +0100 Subject: [PATCH 084/417] 2.x: Add Subject and Processor marbles (#5816) --- .../reactivex/processors/AsyncProcessor.java | 6 +++-- .../processors/PublishProcessor.java | 2 +- .../reactivex/processors/ReplayProcessor.java | 27 +++++++++++++++++-- .../io/reactivex/subjects/AsyncSubject.java | 2 ++ .../subjects/CompletableSubject.java | 2 ++ .../io/reactivex/subjects/MaybeSubject.java | 2 ++ .../io/reactivex/subjects/PublishSubject.java | 2 +- .../io/reactivex/subjects/ReplaySubject.java | 27 ++++++++++++++----- .../io/reactivex/subjects/SingleSubject.java | 2 ++ 9 files changed, 59 insertions(+), 13 deletions(-) diff --git a/src/main/java/io/reactivex/processors/AsyncProcessor.java b/src/main/java/io/reactivex/processors/AsyncProcessor.java index c728d9eb1b..57ad766e5a 100644 --- a/src/main/java/io/reactivex/processors/AsyncProcessor.java +++ b/src/main/java/io/reactivex/processors/AsyncProcessor.java @@ -25,8 +25,10 @@ /** * Processor that emits the very last value followed by a completion event or the received error * to {@link Subscriber}s. - * - *

                The implementation of onXXX methods are technically thread-safe but non-serialized calls + *

                + * + *

                + * The implementation of onXXX methods are technically thread-safe but non-serialized calls * to them may lead to undefined state in the currently subscribed Subscribers. * * @param the value type diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index 88781c45eb..92af846040 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -27,7 +27,7 @@ * Processor that multicasts all subsequently observed items to its current {@link Subscriber}s. * *

                - * + * * *

                The processor does not coordinate backpressure for its subscribers and implements a weaker onSubscribe which * calls requests Long.MAX_VALUE from the incoming Subscriptions. This makes it possible to subscribe the PublishProcessor diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index d4aeba6ebb..ac6a6c240d 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -30,8 +30,31 @@ /** * Replays events to Subscribers. *

                - * - * + * The {@code ReplayProcessor} supports the following item retainment strategies: + *

                  + *
                • {@link #create()} and {@link #create(int)}: retains and replays all events to current and + * future {@code Subscriber}s. + *

                  + * + *

                  + * + *

                • + *
                • {@link #createWithSize(int)}: retains at most the given number of items and replays only these + * latest items to new {@code Subscriber}s. + *

                  + * + *

                • + *
                • {@link #createWithTime(long, TimeUnit, Scheduler)}: retains items no older than the specified time + * and replays them to new {@code Subscriber}s (which could mean all items age out). + *

                  + * + *

                • + *
                • {@link #createWithTimeAndSize(long, TimeUnit, Scheduler, int)}: retaims no more than the given number of items + * which are also no older than the specified time and replays them to new {@code Subscriber}s (which could mean all items age out). + *

                  + * + *

                • + *
                *

                * The ReplayProcessor can be created in bounded and unbounded mode. It can be bounded by * size (maximum number of elements retained at most) and/or time (maximum age of elements replayed). diff --git a/src/main/java/io/reactivex/subjects/AsyncSubject.java b/src/main/java/io/reactivex/subjects/AsyncSubject.java index 581ec9e8c9..e447ee08ac 100644 --- a/src/main/java/io/reactivex/subjects/AsyncSubject.java +++ b/src/main/java/io/reactivex/subjects/AsyncSubject.java @@ -26,6 +26,8 @@ /** * A Subject that emits the very last value followed by a completion event or the received error to Observers. *

                + * + *

                * This subject does not have a public constructor by design; a new empty instance of this * {@code AsyncSubject} can be created via the {@link #create()} method. *

                diff --git a/src/main/java/io/reactivex/subjects/CompletableSubject.java b/src/main/java/io/reactivex/subjects/CompletableSubject.java index c1862a6f51..69e25be91d 100644 --- a/src/main/java/io/reactivex/subjects/CompletableSubject.java +++ b/src/main/java/io/reactivex/subjects/CompletableSubject.java @@ -24,6 +24,8 @@ /** * Represents a hot Completable-like source and consumer of events similar to Subjects. *

                + * + *

                * This subject does not have a public constructor by design; a new non-terminated instance of this * {@code CompletableSubject} can be created via the {@link #create()} method. *

                diff --git a/src/main/java/io/reactivex/subjects/MaybeSubject.java b/src/main/java/io/reactivex/subjects/MaybeSubject.java index d6f84254f2..629e63312b 100644 --- a/src/main/java/io/reactivex/subjects/MaybeSubject.java +++ b/src/main/java/io/reactivex/subjects/MaybeSubject.java @@ -24,6 +24,8 @@ /** * Represents a hot Maybe-like source and consumer of events similar to Subjects. *

                + * + *

                * This subject does not have a public constructor by design; a new non-terminated instance of this * {@code MaybeSubject} can be created via the {@link #create()} method. *

                diff --git a/src/main/java/io/reactivex/subjects/PublishSubject.java b/src/main/java/io/reactivex/subjects/PublishSubject.java index 957b2a0ac6..6a13ffdd2a 100644 --- a/src/main/java/io/reactivex/subjects/PublishSubject.java +++ b/src/main/java/io/reactivex/subjects/PublishSubject.java @@ -25,7 +25,7 @@ * A Subject that emits (multicasts) items to currently subscribed {@link Observer}s and terminal events to current * or late {@code Observer}s. *

                - * + * *

                * This subject does not have a public constructor by design; a new empty instance of this * {@code PublishSubject} can be created via the {@link #create()} method. diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java index d23756b785..2cdc5cb04a 100644 --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java @@ -29,23 +29,36 @@ /** * Replays events (in a configurable bounded or unbounded manner) to current and late {@link Observer}s. *

                - * - *

                * This subject does not have a public constructor by design; a new empty instance of this * {@code ReplaySubject} can be created via the following {@code create} methods that * allow specifying the retention policy for items: *

                  *
                • {@link #create()} - creates an empty, unbounded {@code ReplaySubject} that - * caches all items and the terminal event it receives.
                • + * caches all items and the terminal event it receives. + *

                  + * + *

                  + * + * *

                • {@link #create(int)} - creates an empty, unbounded {@code ReplaySubject} - * with a hint about how many total items one expects to retain.
                • + * with a hint about how many total items one expects to retain. + * *
                • {@link #createWithSize(int)} - creates an empty, size-bound {@code ReplaySubject} - * that retains at most the given number of the latest item it receives.
                • + * that retains at most the given number of the latest item it receives. + *

                  + * + * *

                • {@link #createWithTime(long, TimeUnit, Scheduler)} - creates an empty, time-bound - * {@code ReplaySubject} that retains items no older than the specified time amount.
                • + * {@code ReplaySubject} that retains items no older than the specified time amount. + *

                  + * + * *

                • {@link #createWithTimeAndSize(long, TimeUnit, Scheduler, int)} - creates an empty, * time- and size-bound {@code ReplaySubject} that retains at most the given number - * items that are also not older than the specified time amount.
                • + * items that are also not older than the specified time amount. + *

                  + * + * *

                *

                * Since a {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification, diff --git a/src/main/java/io/reactivex/subjects/SingleSubject.java b/src/main/java/io/reactivex/subjects/SingleSubject.java index d3b4cf63c3..f904662004 100644 --- a/src/main/java/io/reactivex/subjects/SingleSubject.java +++ b/src/main/java/io/reactivex/subjects/SingleSubject.java @@ -24,6 +24,8 @@ /** * Represents a hot Single-like source and consumer of events similar to Subjects. *

                + * + *

                * This subject does not have a public constructor by design; a new non-terminated instance of this * {@code SingleSubject} can be created via the {@link #create()} method. *

                From 173156d3f99e4d49fb262796058ca240deff5675 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 24 Jan 2018 09:24:22 +0100 Subject: [PATCH 085/417] Release 2.1.9 --- CHANGES.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 675b42389e..ca54235019 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,37 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.9 - January 24, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.9%7C)) + +#### API changes + +- [Pull 5799](https://github.com/ReactiveX/RxJava/pull/5799): Add missing `{Maybe|Single}.mergeDelayError` variants. + +#### Performance improvements + +- [Pull 5790](https://github.com/ReactiveX/RxJava/pull/5790): Improve request accounting overhead in `Flowable` `retry`/`repeat`. + +#### Documentation changes + +- [Pull 5783](https://github.com/ReactiveX/RxJava/pull/5783): Fix JavaDoc wording of `onTerminateDetach`. +- [Pull 5780](https://github.com/ReactiveX/RxJava/pull/5780): Improve `BehaviorSubject` JavaDoc + related clarifications. +- [Pull 5781](https://github.com/ReactiveX/RxJava/pull/5781): Describe `merge()` error handling. +- [Pull 5785](https://github.com/ReactiveX/RxJava/pull/5785): Update `Maybe doOn{Success,Error,Complete}` JavaDoc. +- [Pull 5786](https://github.com/ReactiveX/RxJava/pull/5786): Add error handling section to `merge()` operator JavaDocs. +- [Pull 5802](https://github.com/ReactiveX/RxJava/pull/5802): Improved `XSubject` JavaDocs. +- Marble diagram fixes to `Observable`: + - [Pull 5795](https://github.com/ReactiveX/RxJava/pull/5795): More marbles 01/08-a. + - [Pull 5797](https://github.com/ReactiveX/RxJava/pull/5797): `Observable` marble fixes 01/08-b. + - [Pull 5798](https://github.com/ReactiveX/RxJava/pull/5798): `Observable.replay(Function, ...)` marble fixes. + - [Pull 5804](https://github.com/ReactiveX/RxJava/pull/5804): More `Observable` marbles, 01/10-a. + - [Pull 5805](https://github.com/ReactiveX/RxJava/pull/5805): Final planned `Observable` marble additions/fixes. + - [Pull 5816](https://github.com/ReactiveX/RxJava/pull/5816): Add `Subject` and `Processor` marbles. + +#### Bugfixes + +- [Pull 5792](https://github.com/ReactiveX/RxJava/pull/5792): Fix `flatMap` inner fused poll crash not cancelling the upstream. +- [Pull 5811](https://github.com/ReactiveX/RxJava/pull/5811): Fix `buffer(open, close)` not disposing indicators properly. + ### Version 2.1.8 - December 27, 2017 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.8%7C)) **Warning! Behavior change regarding handling illegal calls with `null` in `Processor`s and `Subject`s.** From 3f6e59519fdbc859f9acb2697d9e26cc96f3f2dc Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 28 Jan 2018 14:31:37 +0100 Subject: [PATCH 086/417] 2.x: Improve the wording of the share() JavaDocs (#5824) * 2.x: Improve the wording of the share() JavaDocs * Fix typo. --- src/main/java/io/reactivex/Flowable.java | 4 ++-- src/main/java/io/reactivex/Observable.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 2057359697..d4c18160c2 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -12373,11 +12373,11 @@ public final Flowable serialize() { } /** - * Returns a new {@link Publisher} that multicasts (shares) the original {@link Publisher}. As long as + * Returns a new {@link Publisher} that multicasts (and shares a single subscription to) the original {@link Publisher}. As long as * there is at least one {@link Subscriber} this {@link Publisher} will be subscribed and emitting data. * When all subscribers have cancelled it will cancel the source {@link Publisher}. *

                - * This is an alias for {@link #publish()}.{@link ConnectableFlowable#refCount()}. + * This is an alias for {@link #publish()}.{@link ConnectableFlowable#refCount() refCount()}. *

                * *

                diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 6c9a6f986f..e6a54fc1bb 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -10493,11 +10493,11 @@ public final Observable serialize() { } /** - * Returns a new {@link ObservableSource} that multicasts (shares) the original {@link ObservableSource}. As long as + * Returns a new {@link ObservableSource} that multicasts (and shares a single subscription to) the original {@link ObservableSource}. As long as * there is at least one {@link Observer} this {@link ObservableSource} will be subscribed and emitting data. * When all subscribers have disposed it will dispose the source {@link ObservableSource}. *

                - * This is an alias for {@link #publish()}.{@link ConnectableObservable#refCount()}. + * This is an alias for {@link #publish()}.{@link ConnectableObservable#refCount() refCount()}. *

                * *

                From b8380e21f6dcacfedefec273587e093e0026ed7a Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 31 Jan 2018 00:18:24 +0100 Subject: [PATCH 087/417] 2.x: Fix O.blockingIterable(int) & add O.blockingLatest marbles (#5826) --- src/main/java/io/reactivex/Observable.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index e6a54fc1bb..f2255018e8 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -5078,7 +5078,7 @@ public final Iterable blockingIterable() { /** * Converts this {@code Observable} into an {@link Iterable}. *

                - * + * *

                *
                Scheduler:
                *
                {@code blockingIterable} does not operate by default on a particular {@link Scheduler}.
                @@ -5151,6 +5151,8 @@ public final T blockingLast(T defaultItem) { * Returns an {@link Iterable} that returns the latest item emitted by this {@code Observable}, * waiting if necessary for one to become available. *

                + * + *

                * If this {@code Observable} produces items faster than {@code Iterator.next} takes them, * {@code onNext} events might be skipped, but {@code onError} or {@code onComplete} events are not. *

                From 421b9a4e18de53671af2935873579873ee8b9fee Mon Sep 17 00:00:00 2001 From: btilbrook-nextfaze Date: Wed, 31 Jan 2018 20:04:50 +1030 Subject: [PATCH 088/417] 2.x: Document size-bounded replay emission retention caveat (#5827) (#5828) --- src/main/java/io/reactivex/Flowable.java | 24 +++++++++++++++++++ src/main/java/io/reactivex/Observable.java | 24 +++++++++++++++++++ .../reactivex/processors/ReplayProcessor.java | 4 ++++ .../io/reactivex/subjects/ReplaySubject.java | 3 +++ 4 files changed, 55 insertions(+) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index d4c18160c2..7c861b8d92 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -11234,6 +11234,9 @@ public final Flowable replay(Function, ? extends Publ * emitted by a {@link ConnectableFlowable} that shares a single subscription to the source Publisher, * replaying {@code bufferSize} notifications. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Backpressure:
                @@ -11270,6 +11273,9 @@ public final Flowable replay(Function, ? extends Publ * emitted by a {@link ConnectableFlowable} that shares a single subscription to the source Publisher, * replaying no more than {@code bufferSize} items that were emitted within a specified time window. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Backpressure:
                @@ -11309,6 +11315,9 @@ public final Flowable replay(Function, ? extends Publ * emitted by a {@link ConnectableFlowable} that shares a single subscription to the source Publisher, * replaying no more than {@code bufferSize} items that were emitted within a specified time window. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Backpressure:
                @@ -11357,6 +11366,9 @@ public final Flowable replay(Function, ? extends Publ * emitted by a {@link ConnectableFlowable} that shares a single subscription to the source Publisher, * replaying a maximum of {@code bufferSize} items. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Backpressure:
                @@ -11512,6 +11524,9 @@ public final Flowable replay(final Function, ? extend * an ordinary Publisher, except that it does not begin emitting items when it is subscribed to, but only * when its {@code connect} method is called. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Backpressure:
                @@ -11542,6 +11557,9 @@ public final ConnectableFlowable replay(final int bufferSize) { * Publisher resembles an ordinary Publisher, except that it does not begin emitting items when it is * subscribed to, but only when its {@code connect} method is called. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Backpressure:
                @@ -11576,6 +11594,9 @@ public final ConnectableFlowable replay(int bufferSize, long time, TimeUnit u * Connectable Publisher resembles an ordinary Publisher, except that it does not begin emitting items * when it is subscribed to, but only when its {@code connect} method is called. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Backpressure:
                @@ -11618,6 +11639,9 @@ public final ConnectableFlowable replay(final int bufferSize, final long time * an ordinary Publisher, except that it does not begin emitting items when it is subscribed to, but only * when its {@code connect} method is called. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Backpressure:
                diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index f2255018e8..e4fd63fd8d 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -9498,6 +9498,9 @@ public final Observable replay(Function, ? extends * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource, * replaying {@code bufferSize} notifications. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Scheduler:
                @@ -9529,6 +9532,9 @@ public final Observable replay(Function, ? extends * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource, * replaying no more than {@code bufferSize} items that were emitted within a specified time window. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Scheduler:
                @@ -9563,6 +9569,9 @@ public final Observable replay(Function, ? extends * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource, * replaying no more than {@code bufferSize} items that were emitted within a specified time window. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Scheduler:
                @@ -9606,6 +9615,9 @@ public final Observable replay(Function, ? extends * emitted by a {@link ConnectableObservable} that shares a single subscription to the source ObservableSource, * replaying a maximum of {@code bufferSize} items. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Scheduler:
                @@ -9740,6 +9752,9 @@ public final Observable replay(final Function, ? ex * an ordinary ObservableSource, except that it does not begin emitting items when it is subscribed to, but only * when its {@code connect} method is called. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Scheduler:
                @@ -9765,6 +9780,9 @@ public final ConnectableObservable replay(final int bufferSize) { * ObservableSource resembles an ordinary ObservableSource, except that it does not begin emitting items when it is * subscribed to, but only when its {@code connect} method is called. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Scheduler:
                @@ -9794,6 +9812,9 @@ public final ConnectableObservable replay(int bufferSize, long time, TimeUnit * Connectable ObservableSource resembles an ordinary ObservableSource, except that it does not begin emitting items * when it is subscribed to, but only when its {@code connect} method is called. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Scheduler:
                @@ -9830,6 +9851,9 @@ public final ConnectableObservable replay(final int bufferSize, final long ti * an ordinary ObservableSource, except that it does not begin emitting items when it is subscribed to, but only * when its {@code connect} method is called. *

                + * Note that due to concurrency requirements, {@code replay(bufferSize)} may hold strong references to more than + * {@code bufferSize} source emissions. + *

                * *

                *
                Scheduler:
                diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index ac6a6c240d..cdfcb0a3af 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -66,6 +66,10 @@ * if an individual item gets delayed due to backpressure. * *

                + * Due to concurrency requirements, a size-bounded {@code ReplayProcessor} may hold strong references to more source + * emissions than specified. + * + *

                * Example usage: *

                 {@code
                 
                diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java
                index 2cdc5cb04a..fe89540733 100644
                --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java
                +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java
                @@ -92,6 +92,9 @@
                  * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read the retained/cached items
                  * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()},
                  * {@link #getValues()} or {@link #getValues(Object[])}.
                + * 

                + * Note that due to concurrency requirements, a size-bounded {@code ReplaySubject} may hold strong references to more + * source emissions than specified. *

                *
                Scheduler:
                *
                {@code ReplaySubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and From 1fbc44fb81ec65f624cc98a318217dc031cf6d4e Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 1 Feb 2018 07:36:51 +0100 Subject: [PATCH 089/417] 2.x: Reword the just() operator and reference other typical alternatives (#5830) * 2.x: Reword the just() operator and reference other typical alternatives * Fix a/an --- src/main/java/io/reactivex/Flowable.java | 18 +++++++++++------- src/main/java/io/reactivex/Observable.java | 18 +++++++++++------- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 7c861b8d92..4e9c2d2ee0 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -2458,17 +2458,17 @@ public static Flowable intervalRange(long start, long count, long initialD } /** - * Returns a Flowable that emits a single item and then completes. + * Returns a Flowable that signals the given (constant reference) item and then completes. *

                * *

                - * To convert any object into a Publisher that emits that object, pass that object into the {@code just} - * method. + * Note that the item is taken and re-emitted as is and not computed by any means by {@code just}. Use {@link #fromCallable(Callable)} + * to generate a single item on demand (when {@code Subscriber}s subscribe to it). + *

                + * See the multi-parameter overloads of {@code just} to emit more than one (constant reference) items one after the other. + * Use {@link #fromArray(Object...)} to emit an arbitrary number of items that are known upfront. *

                - * This is similar to the {@link #fromArray(java.lang.Object[])} method, except that {@code from} will convert - * an {@link Iterable} object into a Publisher that emits each of the items in the Iterable, one at a - * time, while the {@code just} method converts an Iterable into a Publisher that emits the entire - * Iterable as a single item. + * To emit the items of an {@link Iterable} sequence (such as a {@link java.util.List}), use {@link #fromIterable(Iterable)}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream.
                @@ -2482,6 +2482,10 @@ public static Flowable intervalRange(long start, long count, long initialD * the type of that item * @return a Flowable that emits {@code value} as a single item and then completes * @see ReactiveX operators documentation: Just + * @see #just(Object, Object) + * @see #fromCallable(Callable) + * @see #fromArray(Object...) + * @see #fromIterable(Iterable) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index e4fd63fd8d..e15da78bfd 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -2234,17 +2234,17 @@ public static Observable intervalRange(long start, long count, long initia } /** - * Returns an Observable that emits a single item and then completes. + * Returns an Observable that signals the given (constant reference) item and then completes. *

                * *

                - * To convert any object into an ObservableSource that emits that object, pass that object into the {@code just} - * method. + * Note that the item is taken and re-emitted as is and not computed by any means by {@code just}. Use {@link #fromCallable(Callable)} + * to generate a single item on demand (when {@code Observer}s subscribe to it). + *

                + * See the multi-parameter overloads of {@code just} to emit more than one (constant reference) items one after the other. + * Use {@link #fromArray(Object...)} to emit an arbitrary number of items that are known upfront. *

                - * This is similar to the {@link #fromArray(java.lang.Object[])} method, except that {@code from} will convert - * an {@link Iterable} object into an ObservableSource that emits each of the items in the Iterable, one at a - * time, while the {@code just} method converts an Iterable into an ObservableSource that emits the entire - * Iterable as a single item. + * To emit the items of an {@link Iterable} sequence (such as a {@link java.util.List}), use {@link #fromIterable(Iterable)}. *

                *
                Scheduler:
                *
                {@code just} does not operate by default on a particular {@link Scheduler}.
                @@ -2256,6 +2256,10 @@ public static Observable intervalRange(long start, long count, long initia * the type of that item * @return an Observable that emits {@code value} as a single item and then completes * @see ReactiveX operators documentation: Just + * @see #just(Object, Object) + * @see #fromCallable(Callable) + * @see #fromArray(Object...) + * @see #fromIterable(Iterable) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) From e76a4765c62907d2d78fc2c89ddc7b6632c74661 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 2 Feb 2018 10:56:24 +0100 Subject: [PATCH 090/417] 2.x: Fix Observable.switchMap main onError not disposing the current inner source (#5833) * 2.x: Fix Obs.switchMap main onError not disposing the current inner src * Fix error-error race test --- .../observable/ObservableSwitchMap.java | 8 +- .../flowable/FlowableSwitchTest.java | 21 ++++ .../observable/ObservableSwitchTest.java | 97 ++++++++++++++++++- 3 files changed, 119 insertions(+), 7 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java index bf7fbaf225..f12ef78945 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java @@ -131,15 +131,15 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - if (done || !errors.addThrowable(t)) { + if (!done && errors.addThrowable(t)) { if (!delayErrors) { disposeInner(); } + done = true; + drain(); + } else { RxJavaPlugins.onError(t); - return; } - done = true; - drain(); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java index 2bad160a63..7b18b2ffdc 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java @@ -1153,4 +1153,25 @@ public Object apply(Integer v) throws Exception { .test() .assertFailure(TestException.class); } + + @Test + public void innerCancelledOnMainError() { + final PublishProcessor main = PublishProcessor.create(); + final PublishProcessor inner = PublishProcessor.create(); + + TestSubscriber to = main.switchMap(Functions.justFunction(inner)) + .test(); + + assertTrue(main.hasSubscribers()); + + main.onNext(1); + + assertTrue(inner.hasSubscribers()); + + main.onError(new TestException()); + + assertFalse(inner.hasSubscribers()); + + to.assertFailure(TestException.class); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java index cb6587f589..c934600ca6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java @@ -18,7 +18,7 @@ import java.util.List; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.*; import org.junit.*; import org.mockito.InOrder; @@ -768,7 +768,7 @@ public void run() { @Test public void outerInnerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < 5000; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -786,6 +786,8 @@ public ObservableSource apply(Integer v) throws Exception { }) .test(); + ps1.onNext(1); + final TestException ex1 = new TestException(); Runnable r1 = new Runnable() { @@ -807,7 +809,7 @@ public void run() { TestHelper.race(r1, r2); for (Throwable e : errors) { - assertTrue(e.toString(), e instanceof TestException); + assertTrue(e.getCause().toString(), e.getCause() instanceof TestException); } } finally { RxJavaPlugins.reset(); @@ -963,4 +965,93 @@ public void onNext(Integer t) { to.assertFailure(TestException.class, 1); } + + @Test + public void innerDisposedOnMainError() { + final PublishSubject main = PublishSubject.create(); + final PublishSubject inner = PublishSubject.create(); + + TestObserver to = main.switchMap(Functions.justFunction(inner)) + .test(); + + assertTrue(main.hasObservers()); + + main.onNext(1); + + assertTrue(inner.hasObservers()); + + main.onError(new TestException()); + + assertFalse(inner.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void outerInnerErrorRaceIgnoreDispose() { + for (int i = 0; i < 5000; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + + final AtomicReference> obs1 = new AtomicReference>(); + final Observable ps1 = new Observable() { + @Override + protected void subscribeActual( + Observer observer) { + obs1.set(observer); + } + }; + final AtomicReference> obs2 = new AtomicReference>(); + final Observable ps2 = new Observable() { + @Override + protected void subscribeActual( + Observer observer) { + obs2.set(observer); + } + }; + + ps1.switchMap(new Function>() { + @Override + public ObservableSource apply(Integer v) throws Exception { + if (v == 1) { + return ps2; + } + return Observable.never(); + } + }) + .test(); + + obs1.get().onSubscribe(Disposables.empty()); + obs1.get().onNext(1); + + obs2.get().onSubscribe(Disposables.empty()); + + final TestException ex1 = new TestException(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + obs1.get().onError(ex1); + } + }; + + final TestException ex2 = new TestException(); + + Runnable r2 = new Runnable() { + @Override + public void run() { + obs2.get().onError(ex2); + } + }; + + TestHelper.race(r1, r2); + + for (Throwable e : errors) { + assertTrue(e.toString(), e.getCause() instanceof TestException); + } + } finally { + RxJavaPlugins.reset(); + } + } + } } From d8f6153568913d21916d6f3130247a01d63e6b7e Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 2 Feb 2018 16:09:30 +0100 Subject: [PATCH 091/417] 2.x: Fix copy-paste errors in SingleSubject JavaDoc (#5834) --- src/main/java/io/reactivex/subjects/SingleSubject.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/subjects/SingleSubject.java b/src/main/java/io/reactivex/subjects/SingleSubject.java index f904662004..ff07b75845 100644 --- a/src/main/java/io/reactivex/subjects/SingleSubject.java +++ b/src/main/java/io/reactivex/subjects/SingleSubject.java @@ -34,8 +34,8 @@ * as parameters to {@link #onSuccess(Object)} and {@link #onError(Throwable)}. Such calls will result in a * {@link NullPointerException} being thrown and the subject's state is not changed. *

                - * Since a {@code SingleSubject} is a {@link io.reactivex.Maybe}, calling {@code onSuccess}, {@code onError} - * or {@code onComplete} will move this {@code SingleSubject} into its terminal state atomically. + * Since a {@code SingleSubject} is a {@link io.reactivex.Single}, calling {@code onSuccess} or {@code onError} + * will move this {@code SingleSubject} into its terminal state atomically. *

                * All methods are thread safe. Calling {@link #onSuccess(Object)} multiple * times has no effect. Calling {@link #onError(Throwable)} multiple times relays the {@code Throwable} to @@ -55,8 +55,8 @@ *

                *
                Scheduler:
                *
                {@code SingleSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and - * the {@code SingleObserver}s get notified on the thread where the terminating {@code onSuccess}, {@code onError} - * or {@code onComplete} methods were invoked.
                + * the {@code SingleObserver}s get notified on the thread where the terminating {@code onSuccess} or {@code onError} + * methods were invoked.
                *
                Error handling:
                *
                When the {@link #onError(Throwable)} is called, the {@code SingleSubject} enters into a terminal state * and emits the same {@code Throwable} instance to the last set of {@code SingleObserver}s. During this emission, From 7e9eb4f8b13ccc9c5e4dacf4bd6d639509daa337 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 2 Feb 2018 16:09:48 +0100 Subject: [PATCH 092/417] Add JavaDoc links to the base reactive classes to Getting started (#5836) --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index f8f495ed04..fabb826636 100644 --- a/README.md +++ b/README.md @@ -68,11 +68,11 @@ Flowable.just("Hello world") RxJava 2 features several base classes you can discover operators on: - - `io.reactivex.Flowable`: 0..N flows, supporting Reactive-Streams and backpressure - - `io.reactivex.Observable`: 0..N flows, no backpressure - - `io.reactivex.Single`: a flow of exactly 1 item or an error - - `io.reactivex.Completable`: a flow without items but only a completion or error signal - - `io.reactivex.Maybe`: a flow with no items, exactly one item or an error + - [`io.reactivex.Flowable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html): 0..N flows, supporting Reactive-Streams and backpressure + - [`io.reactivex.Observable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html): 0..N flows, no backpressure + - [`io.reactivex.Single`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Single.html): a flow of exactly 1 item or an error + - [`io.reactivex.Completable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Completable.html): a flow without items but only a completion or error signal + - [`io.reactivex.Maybe`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Maybe.html): a flow with no items, exactly one item or an error One of the common use cases for RxJava is to run some computation, network request on a background thread and show the results (or error) on the UI thread: From 68f94f09a5f5aa14e4371b0525cdb5ebced9a6ee Mon Sep 17 00:00:00 2001 From: Ilnar Karimov Date: Sat, 3 Feb 2018 17:17:31 +0300 Subject: [PATCH 093/417] Added nullability annotation for completable assembly (#5838) --- src/main/java/io/reactivex/plugins/RxJavaPlugins.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/io/reactivex/plugins/RxJavaPlugins.java b/src/main/java/io/reactivex/plugins/RxJavaPlugins.java index 1f477d4651..339036c134 100644 --- a/src/main/java/io/reactivex/plugins/RxJavaPlugins.java +++ b/src/main/java/io/reactivex/plugins/RxJavaPlugins.java @@ -86,6 +86,7 @@ public final class RxJavaPlugins { @Nullable static volatile Function onSingleAssembly; + @Nullable static volatile Function onCompletableAssembly; @SuppressWarnings("rawtypes") From 363f0381c2fcc9df287d771ffd2826c64c998145 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sat, 3 Feb 2018 17:28:56 +0100 Subject: [PATCH 094/417] 2.x: Detail distinct() & distinctUntilChanged() in JavaDoc (#5837) * 2.x: Detail distinct() & distinctUntilChanged() in JavaDoc * Address feedback --- src/main/java/io/reactivex/Flowable.java | 71 +++++++++++++++++++-- src/main/java/io/reactivex/Observable.java | 74 ++++++++++++++++++++-- 2 files changed, 135 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 4e9c2d2ee0..f87cde880c 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -7669,9 +7669,24 @@ public final Flowable dematerialize() { } /** - * Returns a Flowable that emits all items emitted by the source Publisher that are distinct. + * Returns a Flowable that emits all items emitted by the source Publisher that are distinct + * based on {@link Object#equals(Object)} comparison. *

                * + *

                + * It is recommended the elements' class {@code T} in the flow overrides the default {@code Object.equals()} and {@link Object#hashCode()} to provide + * meaningful comparison between items as the default Java implementation only considers reference equivalence. + *

                + * By default, {@code distinct()} uses an internal {@link java.util.HashSet} per Subscriber to remember + * previously seen items and uses {@link java.util.Set#add(Object)} returning {@code false} as the + * indicator for duplicates. + *

                + * Note that this internal {@code HashSet} may grow unbounded as items won't be removed from it by + * the operator. Therefore, using very long or infinite upstream (with very distinct elements) may lead + * to {@code OutOfMemoryError}. + *

                + * Customizing the retention policy can happen only by providing a custom {@link java.util.Collection} implementation + * to the {@link #distinct(Function, Callable)} overload. *

                *
                Backpressure:
                *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -7683,6 +7698,8 @@ public final Flowable dematerialize() { * @return a Flowable that emits only those items emitted by the source Publisher that are distinct from * each other * @see ReactiveX operators documentation: Distinct + * @see #distinct(Function) + * @see #distinct(Function, Callable) */ @SuppressWarnings({ "rawtypes", "unchecked" }) @CheckReturnValue @@ -7694,9 +7711,24 @@ public final Flowable distinct() { /** * Returns a Flowable that emits all items emitted by the source Publisher that are distinct according - * to a key selector function. + * to a key selector function and based on {@link Object#equals(Object)} comparison of the objects + * returned by the key selector function. *

                * + *

                + * It is recommended the keys' class {@code K} overrides the default {@code Object.equals()} and {@link Object#hashCode()} to provide + * meaningful comparison between the key objects as the default Java implementation only considers reference equivalence. + *

                + * By default, {@code distinct()} uses an internal {@link java.util.HashSet} per Subscriber to remember + * previously seen keys and uses {@link java.util.Set#add(Object)} returning {@code false} as the + * indicator for duplicates. + *

                + * Note that this internal {@code HashSet} may grow unbounded as keys won't be removed from it by + * the operator. Therefore, using very long or infinite upstream (with very distinct keys) may lead + * to {@code OutOfMemoryError}. + *

                + * Customizing the retention policy can happen only by providing a custom {@link java.util.Collection} implementation + * to the {@link #distinct(Function, Callable)} overload. *

                *
                Backpressure:
                *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -7711,6 +7743,7 @@ public final Flowable distinct() { * is distinct from another one or not * @return a Flowable that emits those items emitted by the source Publisher that have distinct keys * @see ReactiveX operators documentation: Distinct + * @see #distinct(Function, Callable) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -7721,9 +7754,13 @@ public final Flowable distinct(Function keySelector) { /** * Returns a Flowable that emits all items emitted by the source Publisher that are distinct according - * to a key selector function. + * to a key selector function and based on {@link Object#equals(Object)} comparison of the objects + * returned by the key selector function. *

                * + *

                + * It is recommended the keys' class {@code K} overrides the default {@code Object.equals()} and {@link Object#hashCode()} to provide + * meaningful comparison between the key objects as the default Java implementation only considers reference equivalence. *

                *
                Backpressure:
                *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -7754,9 +7791,18 @@ public final Flowable distinct(Function keySelector, /** * Returns a Flowable that emits all items emitted by the source Publisher that are distinct from their - * immediate predecessors. + * immediate predecessors based on {@link Object#equals(Object)} comparison. *

                * + *

                + * It is recommended the elements' class {@code T} in the flow overrides the default {@code Object.equals()} to provide + * meaningful comparison between items as the default Java implementation only considers reference equivalence. + * Alternatively, use the {@link #distinctUntilChanged(BiPredicate)} overload and provide a comparison function + * in case the class {@code T} can't be overridden with custom {@code equals()} or the comparison itself + * should happen on different terms or properties of the class {@code T}. + *

                + * Note that the operator always retains the latest item from upstream regardless of the comparison result + * and uses it in the next comparison with the next upstream item. *

                *
                Backpressure:
                *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -7768,6 +7814,7 @@ public final Flowable distinct(Function keySelector, * @return a Flowable that emits those items from the source Publisher that are distinct from their * immediate predecessors * @see ReactiveX operators documentation: Distinct + * @see #distinctUntilChanged(BiPredicate) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -7778,9 +7825,20 @@ public final Flowable distinctUntilChanged() { /** * Returns a Flowable that emits all items emitted by the source Publisher that are distinct from their - * immediate predecessors, according to a key selector function. + * immediate predecessors, according to a key selector function and based on {@link Object#equals(Object)} comparison + * of those objects returned by the key selector function. *

                * + *

                + * It is recommended the keys' class {@code K} overrides the default {@code Object.equals()} to provide + * meaningful comparison between the key objects as the default Java implementation only considers reference equivalence. + * Alternatively, use the {@link #distinctUntilChanged(BiPredicate)} overload and provide a comparison function + * in case the class {@code K} can't be overridden with custom {@code equals()} or the comparison itself + * should happen on different terms or properties of the item class {@code T} (for which the keys can be + * derived via a similar selector). + *

                + * Note that the operator always retains the latest key from upstream regardless of the comparison result + * and uses it in the next comparison with the next key derived from the next upstream item. *

                *
                Backpressure:
                *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -7810,6 +7868,9 @@ public final Flowable distinctUntilChanged(Function keySele * immediate predecessors when compared with each other via the provided comparator function. *

                * + *

                + * Note that the operator always retains the latest item from upstream regardless of the comparison result + * and uses it in the next comparison with the next upstream item. *

                *
                Backpressure:
                *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index e15da78bfd..be140a5a11 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7011,9 +7011,25 @@ public final Observable dematerialize() { } /** - * Returns an Observable that emits all items emitted by the source ObservableSource that are distinct. + * Returns an Observable that emits all items emitted by the source ObservableSource that are distinct + * based on {@link Object#equals(Object)} comparison. *

                * + *

                + * It is recommended the elements' class {@code T} in the flow overrides the default {@code Object.equals()} + * and {@link Object#hashCode()} to provide meaningful comparison between items as the default Java + * implementation only considers reference equivalence. + *

                + * By default, {@code distinct()} uses an internal {@link java.util.HashSet} per Observer to remember + * previously seen items and uses {@link java.util.Set#add(Object)} returning {@code false} as the + * indicator for duplicates. + *

                + * Note that this internal {@code HashSet} may grow unbounded as items won't be removed from it by + * the operator. Therefore, using very long or infinite upstream (with very distinct elements) may lead + * to {@code OutOfMemoryError}. + *

                + * Customizing the retention policy can happen only by providing a custom {@link java.util.Collection} implementation + * to the {@link #distinct(Function, Callable)} overload. *

                *
                Scheduler:
                *
                {@code distinct} does not operate by default on a particular {@link Scheduler}.
                @@ -7022,6 +7038,8 @@ public final Observable dematerialize() { * @return an Observable that emits only those items emitted by the source ObservableSource that are distinct from * each other * @see ReactiveX operators documentation: Distinct + * @see #distinct(Function) + * @see #distinct(Function, Callable) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -7031,9 +7049,25 @@ public final Observable distinct() { /** * Returns an Observable that emits all items emitted by the source ObservableSource that are distinct according - * to a key selector function. + * to a key selector function and based on {@link Object#equals(Object)} comparison of the objects + * returned by the key selector function. *

                * + *

                + * It is recommended the keys' class {@code K} overrides the default {@code Object.equals()} + * and {@link Object#hashCode()} to provide meaningful comparison between the key objects as the default + * Java implementation only considers reference equivalence. + *

                + * By default, {@code distinct()} uses an internal {@link java.util.HashSet} per Observer to remember + * previously seen keys and uses {@link java.util.Set#add(Object)} returning {@code false} as the + * indicator for duplicates. + *

                + * Note that this internal {@code HashSet} may grow unbounded as keys won't be removed from it by + * the operator. Therefore, using very long or infinite upstream (with very distinct keys) may lead + * to {@code OutOfMemoryError}. + *

                + * Customizing the retention policy can happen only by providing a custom {@link java.util.Collection} implementation + * to the {@link #distinct(Function, Callable)} overload. *

                *
                Scheduler:
                *
                {@code distinct} does not operate by default on a particular {@link Scheduler}.
                @@ -7045,6 +7079,7 @@ public final Observable distinct() { * is distinct from another one or not * @return an Observable that emits those items emitted by the source ObservableSource that have distinct keys * @see ReactiveX operators documentation: Distinct + * @see #distinct(Function, Callable) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -7054,9 +7089,14 @@ public final Observable distinct(Function keySelector) { /** * Returns an Observable that emits all items emitted by the source ObservableSource that are distinct according - * to a key selector function. + * to a key selector function and based on {@link Object#equals(Object)} comparison of the objects + * returned by the key selector function. *

                * + *

                + * It is recommended the keys' class {@code K} overrides the default {@code Object.equals()} + * and {@link Object#hashCode()} to provide meaningful comparison between the key objects as + * the default Java implementation only considers reference equivalence. *

                *
                Scheduler:
                *
                {@code distinct} does not operate by default on a particular {@link Scheduler}.
                @@ -7082,9 +7122,18 @@ public final Observable distinct(Function keySelector, Call /** * Returns an Observable that emits all items emitted by the source ObservableSource that are distinct from their - * immediate predecessors. + * immediate predecessors based on {@link Object#equals(Object)} comparison. *

                * + *

                + * It is recommended the elements' class {@code T} in the flow overrides the default {@code Object.equals()} to provide + * meaningful comparison between items as the default Java implementation only considers reference equivalence. + * Alternatively, use the {@link #distinctUntilChanged(BiPredicate)} overload and provide a comparison function + * in case the class {@code T} can't be overridden with custom {@code equals()} or the comparison itself + * should happen on different terms or properties of the class {@code T}. + *

                + * Note that the operator always retains the latest item from upstream regardless of the comparison result + * and uses it in the next comparison with the next upstream item. *

                *
                Scheduler:
                *
                {@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.
                @@ -7093,6 +7142,7 @@ public final Observable distinct(Function keySelector, Call * @return an Observable that emits those items from the source ObservableSource that are distinct from their * immediate predecessors * @see ReactiveX operators documentation: Distinct + * @see #distinctUntilChanged(BiPredicate) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -7102,9 +7152,20 @@ public final Observable distinctUntilChanged() { /** * Returns an Observable that emits all items emitted by the source ObservableSource that are distinct from their - * immediate predecessors, according to a key selector function. + * immediate predecessors, according to a key selector function and based on {@link Object#equals(Object)} comparison + * of those objects returned by the key selector function. *

                * + *

                + * It is recommended the keys' class {@code K} overrides the default {@code Object.equals()} to provide + * meaningful comparison between the key objects as the default Java implementation only considers reference equivalence. + * Alternatively, use the {@link #distinctUntilChanged(BiPredicate)} overload and provide a comparison function + * in case the class {@code K} can't be overridden with custom {@code equals()} or the comparison itself + * should happen on different terms or properties of the item class {@code T} (for which the keys can be + * derived via a similar selector). + *

                + * Note that the operator always retains the latest key from upstream regardless of the comparison result + * and uses it in the next comparison with the next key derived from the next upstream item. *

                *
                Scheduler:
                *
                {@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.
                @@ -7130,6 +7191,9 @@ public final Observable distinctUntilChanged(Function keySe * immediate predecessors when compared with each other via the provided comparator function. *

                * + *

                + * Note that the operator always retains the latest item from upstream regardless of the comparison result + * and uses it in the next comparison with the next upstream item. *

                *
                Scheduler:
                *
                {@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.
                From f7a28703bd533ad235114e27e86cc7ac06ee9dfb Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 8 Feb 2018 23:02:48 +0100 Subject: [PATCH 095/417] 2.x: Improve JavaDoc of XObserver types. (#5841) * 2.x: Improve JavaDoc of XObserver types. * Use "disposing", add missing space * Add more explanation about throwing exceptions. --- .../io/reactivex/CompletableObserver.java | 31 ++++++++++- src/main/java/io/reactivex/MaybeObserver.java | 38 ++++++++++--- src/main/java/io/reactivex/Observer.java | 55 +++++++++++++++++-- .../java/io/reactivex/SingleObserver.java | 35 +++++++++--- 4 files changed, 138 insertions(+), 21 deletions(-) diff --git a/src/main/java/io/reactivex/CompletableObserver.java b/src/main/java/io/reactivex/CompletableObserver.java index 54695d9a41..a33a479128 100644 --- a/src/main/java/io/reactivex/CompletableObserver.java +++ b/src/main/java/io/reactivex/CompletableObserver.java @@ -17,7 +17,36 @@ import io.reactivex.disposables.Disposable; /** - * Represents the subscription API callbacks when subscribing to a Completable instance. + * Provides a mechanism for receiving push-based notification of a valueless completion or an error. + *

                + * When a {@code CompletableObserver} is subscribed to a {@link CompletableSource} through the {@link CompletableSource#subscribe(CompletableObserver)} method, + * the {@code CompletableSource} calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows + * disposing the sequence at any time. A well-behaved + * {@code CompletableSource} will call a {@code CompletableObserver}'s {@link #onError(Throwable)} + * or {@link #onComplete()} method exactly once as they are considered mutually exclusive terminal signals. + *

                + * Calling the {@code CompletableObserver}'s method must happen in a serialized fashion, that is, they must not + * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must + * adhere to the following protocol: + *

                + *

                    onSubscribe (onError | onComplete)?
                + *

                + * Subscribing a {@code CompletableObserver} to multiple {@code CompletableSource}s is not recommended. If such reuse + * happens, it is the duty of the {@code CompletableObserver} implementation to be ready to receive multiple calls to + * its methods and ensure proper concurrent behavior of its business logic. + *

                + * Calling {@link #onSubscribe(Disposable)} or {@link #onError(Throwable)} with a + * {@code null} argument is forbidden. + *

                + * The implementations of the {@code onXXX} methods should avoid throwing runtime exceptions other than the following cases: + *

                  + *
                • If the argument is {@code null}, the methods can throw a {@code NullPointerException}. + * Note though that RxJava prevents {@code null}s to enter into the flow and thus there is generally no + * need to check for nulls in flows assembled from standard sources and intermediate operators. + *
                • + *
                • If there is a fatal error (such as {@code VirtualMachineError}).
                • + *
                + * @since 2.0 */ public interface CompletableObserver { /** diff --git a/src/main/java/io/reactivex/MaybeObserver.java b/src/main/java/io/reactivex/MaybeObserver.java index 42a0ac7bfe..d2f4792245 100644 --- a/src/main/java/io/reactivex/MaybeObserver.java +++ b/src/main/java/io/reactivex/MaybeObserver.java @@ -17,14 +17,38 @@ import io.reactivex.disposables.Disposable; /** - * Provides a mechanism for receiving push-based notifications. + * Provides a mechanism for receiving push-based notification of a single value, an error or completion without any value. *

                - * After a MaybeObserver calls a {@link Maybe}'s {@link Maybe#subscribe subscribe} method, - * first the Maybe calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows - * cancelling the sequence at any time, then the - * {@code Maybe} calls only one of the MaybeObserver's {@link #onSuccess}, {@link #onError} or - * {@link #onComplete} methods to provide notifications. - * + * When a {@code MaybeObserver} is subscribed to a {@link MaybeSource} through the {@link MaybeSource#subscribe(MaybeObserver)} method, + * the {@code MaybeSource} calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows + * disposing the sequence at any time. A well-behaved + * {@code MaybeSource} will call a {@code MaybeObserver}'s {@link #onSuccess(Object)}, {@link #onError(Throwable)} + * or {@link #onComplete()} method exactly once as they are considered mutually exclusive terminal signals. + *

                + * Calling the {@code MaybeObserver}'s method must happen in a serialized fashion, that is, they must not + * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must + * adhere to the following protocol: + *

                + *

                    onSubscribe (onSuccess | onError | onComplete)?
                + *

                + * Note that unlike with the {@code Observable} protocol, {@link #onComplete()} is not called after the success item has been + * signalled via {@link #onSuccess(Object)}. + *

                + * Subscribing a {@code MaybeObserver} to multiple {@code MaybeSource}s is not recommended. If such reuse + * happens, it is the duty of the {@code MaybeObserver} implementation to be ready to receive multiple calls to + * its methods and ensure proper concurrent behavior of its business logic. + *

                + * Calling {@link #onSubscribe(Disposable)}, {@link #onSuccess(Object)} or {@link #onError(Throwable)} with a + * {@code null} argument is forbidden. + *

                + * The implementations of the {@code onXXX} methods should avoid throwing runtime exceptions other than the following cases: + *

                  + *
                • If the argument is {@code null}, the methods can throw a {@code NullPointerException}. + * Note though that RxJava prevents {@code null}s to enter into the flow and thus there is generally no + * need to check for nulls in flows assembled from standard sources and intermediate operators. + *
                • + *
                • If there is a fatal error (such as {@code VirtualMachineError}).
                • + *
                * @see ReactiveX documentation: Observable * @param * the type of item the MaybeObserver expects to observe diff --git a/src/main/java/io/reactivex/Observer.java b/src/main/java/io/reactivex/Observer.java index a383d04a27..cc3e62a573 100644 --- a/src/main/java/io/reactivex/Observer.java +++ b/src/main/java/io/reactivex/Observer.java @@ -19,14 +19,57 @@ /** * Provides a mechanism for receiving push-based notifications. *

                - * After an Observer calls an {@link Observable}'s {@link Observable#subscribe subscribe} method, - * first the Observable calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows - * cancelling the sequence at any time, then the - * {@code Observable} may call the Observer's {@link #onNext} method any number of times + * When an {@code Observer} is subscribed to an {@link ObservableSource} through the {@link ObservableSource#subscribe(Observer)} method, + * the {@code ObservableSource} calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows + * disposing the sequence at any time, then the + * {@code ObservableSource} may call the Observer's {@link #onNext} method any number of times * to provide notifications. A well-behaved - * {@code Observable} will call an Observer's {@link #onComplete} method exactly once or the Observer's + * {@code ObservableSource} will call an {@code Observer}'s {@link #onComplete} method exactly once or the {@code Observer}'s * {@link #onError} method exactly once. - * + *

                + * Calling the {@code Observer}'s method must happen in a serialized fashion, that is, they must not + * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must + * adhere to the following protocol: + *

                + *

                    onSubscribe onNext* (onError | onComplete)?
                + *

                + * Subscribing an {@code Observer} to multiple {@code ObservableSource}s is not recommended. If such reuse + * happens, it is the duty of the {@code Observer} implementation to be ready to receive multiple calls to + * its methods and ensure proper concurrent behavior of its business logic. + *

                + * Calling {@link #onSubscribe(Disposable)}, {@link #onNext(Object)} or {@link #onError(Throwable)} with a + * {@code null} argument is forbidden. + *

                + * The implementations of the {@code onXXX} methods should avoid throwing runtime exceptions other than the following cases + * (see Rule 2.13 of the Reactive Streams specification): + *

                  + *
                • If the argument is {@code null}, the methods can throw a {@code NullPointerException}. + * Note though that RxJava prevents {@code null}s to enter into the flow and thus there is generally no + * need to check for nulls in flows assembled from standard sources and intermediate operators. + *
                • + *
                • If there is a fatal error (such as {@code VirtualMachineError}).
                • + *
                + *

                + * Violating Rule 2.13 results in undefined flow behavior. Generally, the following can happen: + *

                  + *
                • An upstream operator turns it into an {@link #onError} call.
                • + *
                • If the flow is synchronous, the {@link ObservableSource#subscribe(Observer)} throws instead of returning normally.
                • + *
                • If the flow is asynchronous, the exception propagates up to the component ({@link Scheduler} or {@link java.util.concurrent.Executor}) + * providing the asynchronous boundary the code is running and either routes the exception to the global + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} handler or the current thread's + * {@link java.lang.Thread.UncaughtExceptionHandler#uncaughtException(Thread, Throwable)} handler.
                • + *
                + * From the {@code Observable}'s perspective, an {@code Observer} is the end consumer thus it is the {@code Observer}'s + * responsibility to handle the error case and signal it "further down". This means unreliable code in the {@code onXXX} + * methods should be wrapped into `try-catch`es, specifically in {@link #onError(Throwable)} or {@link #onComplete()}, and handled there + * (for example, by logging it or presenting the user with an error dialog). However, if the error would be thrown from + * {@link #onNext(Object)}, Rule 2.13 mandates + * the implementation calls {@link Disposable#dispose()} and signals the exception in a way that is adequate to the target context, + * for example, by calling {@link #onError(Throwable)} on the same {@code Observer} instance. + *

                + * If, for some reason, the {@code Observer} won't follow Rule 2.13, the {@link Observable#safeSubscribe(Observer)} can wrap it + * with the necessary safeguards and route exceptions thrown from {@code onNext} into {@code onError} and route exceptions thrown + * from {@code onError} and {@code onComplete} into the global error handler via {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. * @see ReactiveX documentation: Observable * @param * the type of item the Observer expects to observe diff --git a/src/main/java/io/reactivex/SingleObserver.java b/src/main/java/io/reactivex/SingleObserver.java index eeda4af342..ed8adf58c7 100644 --- a/src/main/java/io/reactivex/SingleObserver.java +++ b/src/main/java/io/reactivex/SingleObserver.java @@ -17,14 +17,35 @@ import io.reactivex.disposables.Disposable; /** - * Provides a mechanism for receiving push-based notifications. + * Provides a mechanism for receiving push-based notification of a single value or an error. *

                - * After a SingleObserver calls a {@link Single}'s {@link Single#subscribe subscribe} method, - * first the Single calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows - * cancelling the sequence at any time, then the - * {@code Single} calls only one of the SingleObserver {@link #onSuccess} and {@link #onError} methods to provide - * notifications. - * + * When a {@code SingleObserver} is subscribed to a {@link SingleSource} through the {@link SingleSource#subscribe(SingleObserver)} method, + * the {@code SingleSource} calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows + * disposing the sequence at any time. A well-behaved + * {@code SingleSource} will call a {@code SingleObserver}'s {@link #onSuccess(Object)} method exactly once or the {@code SingleObserver}'s + * {@link #onError} method exactly once as they are considered mutually exclusive terminal signals. + *

                + * Calling the {@code SingleObserver}'s method must happen in a serialized fashion, that is, they must not + * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must + * adhere to the following protocol: + *

                + *

                    onSubscribe (onSuccess | onError)?
                + *

                + * Subscribing a {@code SingleObserver} to multiple {@code SingleSource}s is not recommended. If such reuse + * happens, it is the duty of the {@code SingleObserver} implementation to be ready to receive multiple calls to + * its methods and ensure proper concurrent behavior of its business logic. + *

                + * Calling {@link #onSubscribe(Disposable)}, {@link #onSuccess(Object)} or {@link #onError(Throwable)} with a + * {@code null} argument is forbidden. + *

                + * The implementations of the {@code onXXX} methods should avoid throwing runtime exceptions other than the following cases: + *

                  + *
                • If the argument is {@code null}, the methods can throw a {@code NullPointerException}. + * Note though that RxJava prevents {@code null}s to enter into the flow and thus there is generally no + * need to check for nulls in flows assembled from standard sources and intermediate operators. + *
                • + *
                • If there is a fatal error (such as {@code VirtualMachineError}).
                • + *
                * @see ReactiveX documentation: Observable * @param * the type of item the SingleObserver expects to observe From 2875fefd28b18c9f54d6b487a976c7bcba7dc98b Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 13 Feb 2018 08:28:00 +0100 Subject: [PATCH 096/417] 2.x: Expand the JavaDocs of the Scheduler API (#5843) * 2.x: Expand the JavaDocs of the Scheduler API * Fix typo and grammar. --- src/main/java/io/reactivex/Scheduler.java | 158 +++++++++++++++--- .../SchedulerRunnableIntrospection.java | 13 +- 2 files changed, 142 insertions(+), 29 deletions(-) diff --git a/src/main/java/io/reactivex/Scheduler.java b/src/main/java/io/reactivex/Scheduler.java index 724974cbbb..44a5b1830f 100644 --- a/src/main/java/io/reactivex/Scheduler.java +++ b/src/main/java/io/reactivex/Scheduler.java @@ -27,14 +27,72 @@ /** * A {@code Scheduler} is an object that specifies an API for scheduling - * units of work with or without delays or periodically. - * You can get common instances of this class in {@link io.reactivex.schedulers.Schedulers}. + * units of work provided in the form of {@link Runnable}s to be + * executed without delay (effectively as soon as possible), after a specified time delay or periodically + * and represents an abstraction over an asynchronous boundary that ensures + * these units of work get executed by some underlying task-execution scheme + * (such as custom Threads, event loop, {@link java.util.concurrent.Executor Executor} or Actor system) + * with some uniform properties and guarantees regardless of the particular underlying + * scheme. + *

                + * You can get various standard, RxJava-specific instances of this class via + * the static methods of the {@link io.reactivex.schedulers.Schedulers} utility class. + *

                + * The so-called {@link Worker}s of a {@code Scheduler} can be created via the {@link #createWorker()} method which allow the scheduling + * of multiple {@link Runnable} tasks in an isolated manner. {@code Runnable} tasks scheduled on a {@code Worker} are guaranteed to be + * executed sequentially and in a non-overlapping fashion. Non-delayed {@code Runnable} tasks are guaranteed to execute in a + * First-In-First-Out order but their execution may be interleaved with delayed tasks. + * In addition, outstanding or running tasks can be cancelled together via + * {@link Worker#dispose()} without affecting any other {@code Worker} instances of the same {@code Scheduler}. + *

                + * Implementations of the {@link #scheduleDirect} and {@link Worker#schedule} methods are encouraged to call the {@link io.reactivex.plugins.RxJavaPlugins#onSchedule(Runnable)} + * method to allow a scheduler hook to manipulate (wrap or replace) the original {@code Runnable} task before it is submitted to the + * underlying task-execution scheme. + *

                + * The default implementations of the {@code scheduleDirect} methods provided by this abstract class + * delegate to the respective {@code schedule} methods in the {@link Worker} instance created via {@link #createWorker()} + * for each individual {@link Runnable} task submitted. Implementors of this class are encouraged to provide + * a more efficient direct scheduling implementation to avoid the time and memory overhead of creating such {@code Worker}s + * for every task. + * This delegation is done via special wrapper instances around the original {@code Runnable} before calling the respective + * {@code Worker.schedule} method. Note that this can lead to multiple {@code RxJavaPlugins.onSchedule} calls and potentially + * multiple hooks applied. Therefore, the default implementations of {@code scheduleDirect} (and the {@link Worker#schedulePeriodically(Runnable, long, long, TimeUnit)}) + * wrap the incoming {@code Runnable} into a class that implements the {@link io.reactivex.schedulers.SchedulerRunnableIntrospection} + * interface which can grant access to the original or hooked {@code Runnable}, thus, a repeated {@code RxJavaPlugins.onSchedule} + * can detect the earlier hook and not apply a new one over again. + *

                + * The default implementation of {@link #now(TimeUnit)} and {@link Worker#now(TimeUnit)} methods to return current + * {@link System#currentTimeMillis()} value in the desired time unit. Custom {@code Scheduler} implementations can override this + * to provide specialized time accounting (such as virtual time to be advanced programmatically). + * Note that operators requiring a {@code Scheduler} may rely on either of the {@code now()} calls provided by + * {@code Scheduler} or {@code Worker} respectively, therefore, it is recommended they represent a logically + * consistent source of the current time. + *

                + * The default implementation of the {@link Worker#schedulePeriodically(Runnable, long, long, TimeUnit)} method uses + * the {@link Worker#schedule(Runnable, long, TimeUnit)} for scheduling the {@code Runnable} task periodically. + * The algorithm calculates the next absolute time when the task should run again and schedules this execution + * based on the relative time between it and {@link Worker#now(TimeUnit)}. However, drifts or changes in the + * system clock could affect this calculation either by scheduling subsequent runs too frequently or too far apart. + * Therefore, the default implementation uses the {@link #clockDriftTolerance()} value (set via + * {@code rx2.scheduler.drift-tolerance} in minutes) to detect a drift in {@link Worker#now(TimeUnit)} and + * re-adjust the absolute/relative time calculation accordingly. + *

                + * The default implementations of {@link #start()} and {@link #shutdown()} do nothing and should be overridden if the + * underlying task-execution scheme supports stopping and restarting itself. + *

                + * If the {@code Scheduler} is shut down or a {@code Worker} is disposed, the {@code schedule} methods + * should return the {@link io.reactivex.disposables.Disposables#disposed()} singleton instance indicating the shut down/disposed + * state to the caller. Since the shutdown or dispose can happen from any thread, the {@code schedule} implementations + * should make best effort to cancel tasks immediately after those tasks have been submitted to the + * underlying task-execution scheme if the shutdown/dispose was detected after this submission. + *

                + * All methods on the {@code Scheduler} and {@code Worker} classes should be thread safe. */ public abstract class Scheduler { /** * The tolerance for a clock drift in nanoseconds where the periodic scheduler will rebase. *

                - * The associated system parameter, {@code rx.scheduler.drift-tolerance}, expects its value in minutes. + * The associated system parameter, {@code rx2.scheduler.drift-tolerance}, expects its value in minutes. */ static final long CLOCK_DRIFT_TOLERANCE_NANOSECONDS; static { @@ -44,7 +102,7 @@ public abstract class Scheduler { /** * Returns the clock drift tolerance in nanoseconds. - *

                Related system property: {@code rx2.scheduler.drift-tolerance} in minutes + *

                Related system property: {@code rx2.scheduler.drift-tolerance} in minutes. * @return the tolerance in nanoseconds * @since 2.0 */ @@ -54,11 +112,13 @@ public static long clockDriftTolerance() { /** - * Retrieves or creates a new {@link Scheduler.Worker} that represents serial execution of actions. + * Retrieves or creates a new {@link Scheduler.Worker} that represents sequential execution of actions. *

                - * When work is completed it should be unsubscribed using {@link Scheduler.Worker#dispose()}. + * When work is completed, the {@code Worker} instance should be released + * by calling {@link Scheduler.Worker#dispose()} to avoid potential resource leaks in the + * underlying task-execution scheme. *

                - * Work on a {@link Scheduler.Worker} is guaranteed to be sequential. + * Work on a {@link Scheduler.Worker} is guaranteed to be sequential and non-overlapping. * * @return a Worker representing a serial queue of actions to be executed */ @@ -78,7 +138,11 @@ public long now(@NonNull TimeUnit unit) { /** * Allows the Scheduler instance to start threads * and accept tasks on them. - *

                Implementations should make sure the call is idempotent and thread-safe. + *

                + * Implementations should make sure the call is idempotent, thread-safe and + * should not throw any {@code RuntimeException} if it doesn't support this + * functionality. + * * @since 2.0 */ public void start() { @@ -86,9 +150,13 @@ public void start() { } /** - * Instructs the Scheduler instance to stop threads - * and stop accepting tasks on any outstanding Workers. - *

                Implementations should make sure the call is idempotent and thread-safe. + * Instructs the Scheduler instance to stop threads, + * stop accepting tasks on any outstanding {@link Worker} instances + * and clean up any associated resources with this Scheduler. + *

                + * Implementations should make sure the call is idempotent, thread-safe and + * should not throw any {@code RuntimeException} if it doesn't support this + * functionality. * @since 2.0 */ public void shutdown() { @@ -96,11 +164,11 @@ public void shutdown() { } /** - * Schedules the given task on this scheduler non-delayed execution. + * Schedules the given task on this Scheduler without any time delay. * *

                * This method is safe to be called from multiple threads but there are no - * ordering guarantees between tasks. + * ordering or non-overlapping guarantees between tasks. * * @param run the task to execute * @@ -113,7 +181,7 @@ public Disposable scheduleDirect(@NonNull Runnable run) { } /** - * Schedules the execution of the given task with the given delay amount. + * Schedules the execution of the given task with the given time delay. * *

                * This method is safe to be called from multiple threads but there are no @@ -139,15 +207,16 @@ public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull Tim } /** - * Schedules a periodic execution of the given task with the given initial delay and period. + * Schedules a periodic execution of the given task with the given initial time delay and repeat period. * *

                * This method is safe to be called from multiple threads but there are no * ordering guarantees between tasks. * *

                - * The periodic execution is at a fixed rate, that is, the first execution will be after the initial - * delay, the second after initialDelay + period, the third after initialDelay + 2 * period, and so on. + * The periodic execution is at a fixed rate, that is, the first execution will be after the + * {@code initialDelay}, the second after {@code initialDelay + period}, the third after + * {@code initialDelay + 2 * period}, and so on. * * @param run the task to schedule * @param initialDelay the initial delay amount, non-positive values indicate non-delayed scheduling @@ -254,13 +323,43 @@ public S when(@NonNull Function + * Disposing the {@link Worker} should cancel all outstanding work and allows resource cleanup. *

                - * Disposing the {@link Worker} cancels all outstanding work and allows resource cleanup. + * The default implementations of {@link #schedule(Runnable)} and {@link #schedulePeriodically(Runnable, long, long, TimeUnit)} + * delegate to the abstract {@link #schedule(Runnable, long, TimeUnit)} method. Its implementation is encouraged to + * track the individual {@code Runnable} tasks while they are waiting to be executed (with or without delay) so that + * {@link #dispose()} can prevent their execution or potentially interrupt them if they are currently running. + *

                + * The default implementation of the {@link #now(TimeUnit)} method returns current + * {@link System#currentTimeMillis()} value in the desired time unit. Custom {@code Worker} implementations can override this + * to provide specialized time accounting (such as virtual time to be advanced programmatically). + * Note that operators requiring a scheduler may rely on either of the {@code now()} calls provided by + * {@code Scheduler} or {@code Worker} respectively, therefore, it is recommended they represent a logically + * consistent source of the current time. + *

                + * The default implementation of the {@link #schedulePeriodically(Runnable, long, long, TimeUnit)} method uses + * the {@link #schedule(Runnable, long, TimeUnit)} for scheduling the {@code Runnable} task periodically. + * The algorithm calculates the next absolute time when the task should run again and schedules this execution + * based on the relative time between it and {@link #now(TimeUnit)}. However, drifts or changes in the + * system clock would affect this calculation either by scheduling subsequent runs too frequently or too far apart. + * Therefore, the default implementation uses the {@link #clockDriftTolerance()} value (set via + * {@code rx2.scheduler.drift-tolerance} in minutes) to detect a drift in {@link #now(TimeUnit)} and + * re-adjust the absolute/relative time calculation accordingly. + *

                + * If the {@code Worker} is disposed, the {@code schedule} methods + * should return the {@link io.reactivex.disposables.Disposables#disposed()} singleton instance indicating the disposed + * state to the caller. Since the {@link #dispose()} call can happen on any thread, the {@code schedule} implementations + * should make best effort to cancel tasks immediately after those tasks have been submitted to the + * underlying task-execution scheme if the dispose was detected after this submission. + *

                + * All methods on the {@code Worker} class should be thread safe. */ public abstract static class Worker implements Disposable { /** - * Schedules a Runnable for execution without delay. + * Schedules a Runnable for execution without any time delay. * *

                The default implementation delegates to {@link #schedule(Runnable, long, TimeUnit)}. * @@ -274,7 +373,8 @@ public Disposable schedule(@NonNull Runnable run) { } /** - * Schedules an Runnable for execution at some point in the future. + * Schedules an Runnable for execution at some point in the future specified by a time delay + * relative to the current time. *

                * Note to implementors: non-positive {@code delayTime} should be regarded as non-delayed schedule, i.e., * as if the {@link #schedule(Runnable)} was called. @@ -282,7 +382,7 @@ public Disposable schedule(@NonNull Runnable run) { * @param run * the Runnable to schedule * @param delay - * time to wait before executing the action; non-positive values indicate an non-delayed + * time to "wait" before executing the action; non-positive values indicate an non-delayed * schedule * @param unit * the time unit of {@code delayTime} @@ -292,12 +392,20 @@ public Disposable schedule(@NonNull Runnable run) { public abstract Disposable schedule(@NonNull Runnable run, long delay, @NonNull TimeUnit unit); /** - * Schedules a cancelable action to be executed periodically. This default implementation schedules - * recursively and waits for actions to complete (instead of potentially executing long-running actions - * concurrently). Each scheduler that can do periodic scheduling in a better way should override this. + * Schedules a periodic execution of the given task with the given initial time delay and repeat period. + *

                + * The default implementation schedules and reschedules the {@code Runnable} task via the + * {@link #schedule(Runnable, long, TimeUnit)} + * method over and over and at a fixed rate, that is, the first execution will be after the + * {@code initialDelay}, the second after {@code initialDelay + period}, the third after + * {@code initialDelay + 2 * period}, and so on. *

                * Note to implementors: non-positive {@code initialTime} and {@code period} should be regarded as * non-delayed scheduling of the first and any subsequent executions. + * In addition, a more specific {@code Worker} implementation should override this method + * if it can perform the periodic task execution with less overhead (such as by avoiding the + * creation of the wrapper and tracker objects upon each periodic invocation of the + * common {@link #schedule(Runnable, long, TimeUnit)} method). * * @param run * the Runnable to execute periodically diff --git a/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java b/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java index 4e558c8343..810fd6f408 100644 --- a/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java +++ b/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java @@ -15,10 +15,15 @@ import io.reactivex.plugins.RxJavaPlugins; /** - * Interface to wrap an action inside internal scheduler's task. - * - * You can check if runnable implements this interface and unwrap original runnable. - * For example inside of the {@link RxJavaPlugins#setScheduleHandler(Function)} + * Interface to indicate the implementor class wraps a {@code Runnable} that can + * be accessed via {@link #getWrappedRunnable()}. + *

                + * You can check if a {@link Runnable} task submitted to a {@link io.reactivex.Scheduler Scheduler} (or its + * {@link io.reactivex.Scheduler.Worker Scheduler.Worker}) implements this interface and unwrap the + * original {@code Runnable} instance. This could help to avoid hooking the same underlying {@code Runnable} + * task in a custom {@link RxJavaPlugins#onSchedule(Runnable)} hook set via + * the {@link RxJavaPlugins#setScheduleHandler(Function)} method multiple times due to internal delegation + * of the default {@code Scheduler.scheduleDirect} or {@code Scheduler.Worker.schedule} methods. * * @since 2.1.7 - experimental */ From f624001648cad934e2f4be0d71be865c0c60a228 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 13 Feb 2018 09:56:23 +0100 Subject: [PATCH 097/417] 2.x: Explain the properties of the XEmitter interfaces in detail (#5844) --- .../java/io/reactivex/CompletableEmitter.java | 31 +++++++++++++++--- .../java/io/reactivex/FlowableEmitter.java | 31 +++++++++++++++--- src/main/java/io/reactivex/MaybeEmitter.java | 32 ++++++++++++++++--- .../java/io/reactivex/ObservableEmitter.java | 32 ++++++++++++++++--- src/main/java/io/reactivex/SingleEmitter.java | 31 +++++++++++++++--- 5 files changed, 135 insertions(+), 22 deletions(-) diff --git a/src/main/java/io/reactivex/CompletableEmitter.java b/src/main/java/io/reactivex/CompletableEmitter.java index 7a9dfac549..7a8d2e1e75 100644 --- a/src/main/java/io/reactivex/CompletableEmitter.java +++ b/src/main/java/io/reactivex/CompletableEmitter.java @@ -21,9 +21,29 @@ * Abstraction over an RxJava {@link CompletableObserver} that allows associating * a resource with it. *

                - * All methods are safe to call from multiple threads. + * All methods are safe to call from multiple threads, but note that there is no guarantee + * whose terminal event will win and get delivered to the downstream. *

                - * Calling onComplete or onError multiple times has no effect. + * Calling {@link #onComplete()} multiple times has no effect. + * Calling {@link #onError(Throwable)} multiple times or after {@code onComplete} will route the + * exception into the global error handler via {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. + *

                + * The emitter allows the registration of a single resource, in the form of a {@link Disposable} + * or {@link Cancellable} via {@link #setDisposable(Disposable)} or {@link #setCancellable(Cancellable)} + * respectively. The emitter implementations will dispose/cancel this instance when the + * downstream cancels the flow or after the event generator logic calls + * {@link #onError(Throwable)}, {@link #onComplete()} or when {@link #tryOnError(Throwable)} succeeds. + *

                + * Only one {@code Disposable} or {@code Cancellable} object can be associated with the emitter at + * a time. Calling either {@code set} method will dispose/cancel any previous object. If there + * is a need for handling multiple resources, one can create a {@link io.reactivex.disposables.CompositeDisposable} + * and associate that with the emitter instead. + *

                + * The {@link Cancellable} is logically equivalent to {@code Disposable} but allows using cleanup logic that can + * throw a checked exception (such as many {@code close()} methods on Java IO components). Since + * the release of resources happens after the terminal events have been delivered or the sequence gets + * cancelled, exceptions throw within {@code Cancellable} are routed to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. */ public interface CompletableEmitter { @@ -53,8 +73,11 @@ public interface CompletableEmitter { void setCancellable(@Nullable Cancellable c); /** - * Returns true if the downstream disposed the sequence. - * @return true if the downstream disposed the sequence + * Returns true if the downstream disposed the sequence or the + * emitter was terminated via {@link #onError(Throwable)}, + * {@link #onComplete} or a successful {@link #tryOnError(Throwable)}. + *

                This method is thread-safe. + * @return true if the downstream disposed the sequence or the emitter was terminated */ boolean isDisposed(); diff --git a/src/main/java/io/reactivex/FlowableEmitter.java b/src/main/java/io/reactivex/FlowableEmitter.java index 9b76cbbad0..f3c1d8e0cb 100644 --- a/src/main/java/io/reactivex/FlowableEmitter.java +++ b/src/main/java/io/reactivex/FlowableEmitter.java @@ -22,10 +22,29 @@ * a resource with it and exposes the current number of downstream * requested amount. *

                - * The onNext, onError and onComplete methods should be called - * in a sequential manner, just like the Subscriber's methods. - * Use {@link #serialize()} if you want to ensure this. + * The {@link #onNext(Object)}, {@link #onError(Throwable)}, {@link #tryOnError(Throwable)} + * and {@link #onComplete()} methods should be called in a sequential manner, just like + * the {@link org.reactivestreams.Subscriber Subscriber}'s methods. + * Use the {@code FlowableEmitter} the {@link #serialize()} method returns instead of the original + * {@code FlowableEmitter} instance provided by the generator routine if you want to ensure this. * The other methods are thread-safe. + *

                + * The emitter allows the registration of a single resource, in the form of a {@link Disposable} + * or {@link Cancellable} via {@link #setDisposable(Disposable)} or {@link #setCancellable(Cancellable)} + * respectively. The emitter implementations will dispose/cancel this instance when the + * downstream cancels the flow or after the event generator logic calls {@link #onError(Throwable)}, + * {@link #onComplete()} or when {@link #tryOnError(Throwable)} succeeds. + *

                + * Only one {@code Disposable} or {@code Cancellable} object can be associated with the emitter at + * a time. Calling either {@code set} method will dispose/cancel any previous object. If there + * is a need for handling multiple resources, one can create a {@link io.reactivex.disposables.CompositeDisposable} + * and associate that with the emitter instead. + *

                + * The {@link Cancellable} is logically equivalent to {@code Disposable} but allows using cleanup logic that can + * throw a checked exception (such as many {@code close()} methods on Java IO components). Since + * the release of resources happens after the terminal events have been delivered or the sequence gets + * cancelled, exceptions throw within {@code Cancellable} are routed to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. * * @param the value type to emit */ @@ -53,9 +72,11 @@ public interface FlowableEmitter extends Emitter { long requested(); /** - * Returns true if the downstream cancelled the sequence. + * Returns true if the downstream cancelled the sequence or the + * emitter was terminated via {@link #onError(Throwable)}, {@link #onComplete} or a + * successful {@link #tryOnError(Throwable)}. *

                This method is thread-safe. - * @return true if the downstream cancelled the sequence + * @return true if the downstream cancelled the sequence or the emitter was terminated */ boolean isCancelled(); diff --git a/src/main/java/io/reactivex/MaybeEmitter.java b/src/main/java/io/reactivex/MaybeEmitter.java index dfe7958d11..c772430730 100644 --- a/src/main/java/io/reactivex/MaybeEmitter.java +++ b/src/main/java/io/reactivex/MaybeEmitter.java @@ -21,9 +21,29 @@ * Abstraction over an RxJava {@link MaybeObserver} that allows associating * a resource with it. *

                - * All methods are safe to call from multiple threads. + * All methods are safe to call from multiple threads, but note that there is no guarantee + * whose terminal event will win and get delivered to the downstream. *

                - * Calling onSuccess, onError or onComplete multiple times has no effect. + * Calling {@link #onSuccess(Object)} or {@link #onComplete()} multiple times has no effect. + * Calling {@link #onError(Throwable)} multiple times or after the other two will route the + * exception into the global error handler via {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. + *

                + * The emitter allows the registration of a single resource, in the form of a {@link Disposable} + * or {@link Cancellable} via {@link #setDisposable(Disposable)} or {@link #setCancellable(Cancellable)} + * respectively. The emitter implementations will dispose/cancel this instance when the + * downstream cancels the flow or after the event generator logic calls {@link #onSuccess(Object)}, + * {@link #onError(Throwable)}, {@link #onComplete()} or when {@link #tryOnError(Throwable)} succeeds. + *

                + * Only one {@code Disposable} or {@code Cancellable} object can be associated with the emitter at + * a time. Calling either {@code set} method will dispose/cancel any previous object. If there + * is a need for handling multiple resources, one can create a {@link io.reactivex.disposables.CompositeDisposable} + * and associate that with the emitter instead. + *

                + * The {@link Cancellable} is logically equivalent to {@code Disposable} but allows using cleanup logic that can + * throw a checked exception (such as many {@code close()} methods on Java IO components). Since + * the release of resources happens after the terminal events have been delivered or the sequence gets + * cancelled, exceptions throw within {@code Cancellable} are routed to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. * * @param the value type to emit */ @@ -61,8 +81,12 @@ public interface MaybeEmitter { void setCancellable(@Nullable Cancellable c); /** - * Returns true if the downstream cancelled the sequence. - * @return true if the downstream cancelled the sequence + * Returns true if the downstream disposed the sequence or the + * emitter was terminated via {@link #onSuccess(Object)}, {@link #onError(Throwable)}, + * {@link #onComplete} or a + * successful {@link #tryOnError(Throwable)}. + *

                This method is thread-safe. + * @return true if the downstream disposed the sequence or the emitter was terminated */ boolean isDisposed(); diff --git a/src/main/java/io/reactivex/ObservableEmitter.java b/src/main/java/io/reactivex/ObservableEmitter.java index bd2aac8eb1..68c81207b6 100644 --- a/src/main/java/io/reactivex/ObservableEmitter.java +++ b/src/main/java/io/reactivex/ObservableEmitter.java @@ -21,10 +21,29 @@ * Abstraction over an RxJava {@link Observer} that allows associating * a resource with it. *

                - * The onNext, onError and onComplete methods should be called - * in a sequential manner, just like the Observer's methods. - * Use {@link #serialize()} if you want to ensure this. + * The {@link #onNext(Object)}, {@link #onError(Throwable)}, {@link #tryOnError(Throwable)} + * and {@link #onComplete()} methods should be called in a sequential manner, just like the + * {@link Observer}'s methods should be. + * Use the {@code ObservableEmitter} the {@link #serialize()} method returns instead of the original + * {@code ObservableEmitter} instance provided by the generator routine if you want to ensure this. * The other methods are thread-safe. + *

                + * The emitter allows the registration of a single resource, in the form of a {@link Disposable} + * or {@link Cancellable} via {@link #setDisposable(Disposable)} or {@link #setCancellable(Cancellable)} + * respectively. The emitter implementations will dispose/cancel this instance when the + * downstream cancels the flow or after the event generator logic calls {@link #onError(Throwable)}, + * {@link #onComplete()} or when {@link #tryOnError(Throwable)} succeeds. + *

                + * Only one {@code Disposable} or {@code Cancellable} object can be associated with the emitter at + * a time. Calling either {@code set} method will dispose/cancel any previous object. If there + * is a need for handling multiple resources, one can create a {@link io.reactivex.disposables.CompositeDisposable} + * and associate that with the emitter instead. + *

                + * The {@link Cancellable} is logically equivalent to {@code Disposable} but allows using cleanup logic that can + * throw a checked exception (such as many {@code close()} methods on Java IO components). Since + * the release of resources happens after the terminal events have been delivered or the sequence gets + * cancelled, exceptions throw within {@code Cancellable} are routed to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. * * @param the value type to emit */ @@ -45,8 +64,11 @@ public interface ObservableEmitter extends Emitter { void setCancellable(@Nullable Cancellable c); /** - * Returns true if the downstream disposed the sequence. - * @return true if the downstream disposed the sequence + * Returns true if the downstream disposed the sequence or the + * emitter was terminated via {@link #onError(Throwable)}, {@link #onComplete} or a + * successful {@link #tryOnError(Throwable)}. + *

                This method is thread-safe. + * @return true if the downstream disposed the sequence or the emitter was terminated */ boolean isDisposed(); diff --git a/src/main/java/io/reactivex/SingleEmitter.java b/src/main/java/io/reactivex/SingleEmitter.java index 6c0da0ce06..c623638ef7 100644 --- a/src/main/java/io/reactivex/SingleEmitter.java +++ b/src/main/java/io/reactivex/SingleEmitter.java @@ -21,9 +21,29 @@ * Abstraction over an RxJava {@link SingleObserver} that allows associating * a resource with it. *

                - * All methods are safe to call from multiple threads. + * All methods are safe to call from multiple threads, but note that there is no guarantee + * whose terminal event will win and get delivered to the downstream. *

                - * Calling onSuccess or onError multiple times has no effect. + * Calling {@link #onSuccess(Object)} multiple times has no effect. + * Calling {@link #onError(Throwable)} multiple times or after {@code onSuccess} will route the + * exception into the global error handler via {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. + *

                + * The emitter allows the registration of a single resource, in the form of a {@link Disposable} + * or {@link Cancellable} via {@link #setDisposable(Disposable)} or {@link #setCancellable(Cancellable)} + * respectively. The emitter implementations will dispose/cancel this instance when the + * downstream cancels the flow or after the event generator logic calls {@link #onSuccess(Object)}, + * {@link #onError(Throwable)}, or when {@link #tryOnError(Throwable)} succeeds. + *

                + * Only one {@code Disposable} or {@code Cancellable} object can be associated with the emitter at + * a time. Calling either {@code set} method will dispose/cancel any previous object. If there + * is a need for handling multiple resources, one can create a {@link io.reactivex.disposables.CompositeDisposable} + * and associate that with the emitter instead. + *

                + * The {@link Cancellable} is logically equivalent to {@code Disposable} but allows using cleanup logic that can + * throw a checked exception (such as many {@code close()} methods on Java IO components). Since + * the release of resources happens after the terminal events have been delivered or the sequence gets + * cancelled, exceptions throw within {@code Cancellable} are routed to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. * * @param the value type to emit */ @@ -56,8 +76,11 @@ public interface SingleEmitter { void setCancellable(@Nullable Cancellable c); /** - * Returns true if the downstream cancelled the sequence. - * @return true if the downstream cancelled the sequence + * Returns true if the downstream disposed the sequence or the + * emitter was terminated via {@link #onSuccess(Object)}, {@link #onError(Throwable)}, + * or a successful {@link #tryOnError(Throwable)}. + *

                This method is thread-safe. + * @return true if the downstream disposed the sequence or the emitter was terminated */ boolean isDisposed(); From ba79413b22b1d02c51c4d1f36486090183f8f700 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 13 Feb 2018 10:19:45 +0100 Subject: [PATCH 098/417] 2.x: Improve the wording of the Maybe.fromCallable JavaDoc (#5848) --- src/main/java/io/reactivex/Maybe.java | 32 ++++++++++++++++++++------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index efa8658982..83b7c92969 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -628,26 +628,42 @@ public static Maybe fromSingle(SingleSource singleSource) { } /** - * Returns a {@link Maybe} that invokes passed function and emits its result for each new MaybeObserver that subscribes - * while considering {@code null} value from the callable as indication for valueless completion. + * Returns a {@link Maybe} that invokes the given {@link Callable} for each individual {@link MaybeObserver} that + * subscribes and emits the resulting non-null item via {@code onSuccess} while + * considering a {@code null} result from the {@code Callable} as indication for valueless completion + * via {@code onComplete}. *

                - * Allows you to defer execution of passed function until MaybeObserver subscribes to the {@link Maybe}. - * It makes passed function "lazy". - * Result of the function invocation will be emitted by the {@link Maybe}. + * This operator allows you to defer the execution of the given {@code Callable} until a {@code MaybeObserver} + * subscribes to the returned {@link Maybe}. In other terms, this source operator evaluates the given + * {@code Callable} "lazily". + *

                + * Note that the {@code null} handling of this operator differs from the similar source operators in the other + * {@link io.reactivex base reactive classes}. Those operators signal a {@code NullPointerException} if the value returned by their + * {@code Callable} is {@code null} while this {@code fromCallable} considers it to indicate the + * returned {@code Maybe} is empty. *

                *
                Scheduler:
                *
                {@code fromCallable} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                Any non-fatal exception thrown by {@link Callable#call()} will be forwarded to {@code onError}, + * except if the {@code MaybeObserver} disposed the subscription in the meantime. In this latter case, + * the exception is forwarded to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} wrapped into a + * {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}. + * Fatal exceptions are rethrown and usually will end up in the executing thread's + * {@link java.lang.Thread.UncaughtExceptionHandler#uncaughtException(Thread, Throwable)} handler.
                *
                * * @param callable - * function which execution should be deferred, it will be invoked when MaybeObserver will subscribe to the {@link Maybe}. + * a {@link Callable} instance whose execution should be deferred and performed for each individual + * {@code MaybeObserver} that subscribes to the returned {@link Maybe}. * @param * the type of the item emitted by the {@link Maybe}. - * @return a {@link Maybe} whose {@link MaybeObserver}s' subscriptions trigger an invocation of the given function. + * @return a new Maybe instance */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - public static Maybe fromCallable(final Callable callable) { + public static Maybe fromCallable(@NonNull final Callable callable) { ObjectHelper.requireNonNull(callable, "callable is null"); return RxJavaPlugins.onAssembly(new MaybeFromCallable(callable)); } From 12c0e3011726b15fc34ebc4dd1a4c67589210898 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 16 Feb 2018 12:37:37 +0100 Subject: [PATCH 099/417] 2.x: Add efficient concatWith(Single|Maybe|Completable) overloads (#5845) * 2.x: Add efficient concatWith(Single|Maybe|Completable) overloads * Correct the concatWith(Completable) TCK file name * Increase coverage * Change local variable names. --- src/main/java/io/reactivex/Flowable.java | 77 ++++++++ src/main/java/io/reactivex/Observable.java | 63 ++++++ .../FlowableConcatWithCompletable.java | 111 +++++++++++ .../flowable/FlowableConcatWithMaybe.java | 104 ++++++++++ .../flowable/FlowableConcatWithSingle.java | 97 ++++++++++ .../ObservableConcatWithCompletable.java | 99 ++++++++++ .../observable/ObservableConcatWithMaybe.java | 105 ++++++++++ .../ObservableConcatWithSingle.java | 101 ++++++++++ .../io/reactivex/InternalWrongNaming.java | 5 +- .../reactivex/flowable/FlowableNullTests.java | 2 +- .../FlowableConcatWithCompletableTest.java | 125 ++++++++++++ .../flowable/FlowableConcatWithMaybeTest.java | 129 +++++++++++++ .../FlowableConcatWithSingleTest.java | 101 ++++++++++ .../ObservableConcatWithCompletableTest.java | 145 ++++++++++++++ .../ObservableConcatWithMaybeTest.java | 179 ++++++++++++++++++ .../ObservableConcatWithSingleTest.java | 151 +++++++++++++++ .../observable/ObservableNullTests.java | 2 +- .../tck/ConcatWithCompletableTckTest.java | 31 +++ .../tck/ConcatWithMaybeEmptyTckTest.java | 31 +++ .../reactivex/tck/ConcatWithMaybeTckTest.java | 31 +++ .../tck/ConcatWithSingleTckTest.java | 31 +++ 21 files changed, 1717 insertions(+), 3 deletions(-) create mode 100644 src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java create mode 100644 src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java create mode 100644 src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java create mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java create mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java create mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletableTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingleTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java create mode 100644 src/test/java/io/reactivex/tck/ConcatWithCompletableTckTest.java create mode 100644 src/test/java/io/reactivex/tck/ConcatWithMaybeEmptyTckTest.java create mode 100644 src/test/java/io/reactivex/tck/ConcatWithMaybeTckTest.java create mode 100644 src/test/java/io/reactivex/tck/ConcatWithSingleTckTest.java diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index f87cde880c..c0e51f365f 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -7170,6 +7170,83 @@ public final Flowable concatWith(Publisher other) { return concat(this, other); } + /** + * Returns a {@code Flowable} that emits the items from this {@code Flowable} followed by the success item or error event + * of the other {@link SingleSource}. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator supports backpressure and makes sure the success item of the other {@code SingleSource} + * is only emitted when there is a demand for it.
                + *
                Scheduler:
                + *
                {@code concatWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param other the SingleSource whose signal should be emitted after this {@code Flowable} completes normally. + * @return the new Flowable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatWith(@NonNull SingleSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new FlowableConcatWithSingle(this, other)); + } + + /** + * Returns a {@code Flowable} that emits the items from this {@code Flowable} followed by the success item or terminal events + * of the other {@link MaybeSource}. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator supports backpressure and makes sure the success item of the other {@code MaybeSource} + * is only emitted when there is a demand for it.
                + *
                Scheduler:
                + *
                {@code concatWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param other the MaybeSource whose signal should be emitted after this Flowable completes normally. + * @return the new Flowable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatWith(@NonNull MaybeSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new FlowableConcatWithMaybe(this, other)); + } + + /** + * Returns a {@code Flowable} that emits items from this {@code Flowable} and when it completes normally, the + * other {@link CompletableSource} is subscribed to and the returned {@code Flowable} emits its terminal events. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator does not interfere with backpressure between the current Flowable and the + * downstream consumer (i.e., acts as pass-through). When the operator switches to the + * {@code Completable}, backpressure is no longer present because {@code Completable} doesn't + * have items to apply backpressure to.
                + *
                Scheduler:
                + *
                {@code concatWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param other the {@code CompletableSource} to subscribe to once the current {@code Flowable} completes normally + * @return the new Flowable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.PASS_THROUGH) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatWith(@NonNull CompletableSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new FlowableConcatWithCompletable(this, other)); + } + /** * Returns a Single that emits a Boolean that indicates whether the source Publisher emitted a * specified item. diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index be140a5a11..f2db8f5e67 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -6573,6 +6573,69 @@ public final Observable concatWith(ObservableSource other) { return concat(this, other); } + /** + * Returns an {@code Observable} that emits the items from this {@code Observable} followed by the success item or error event + * of the other {@link SingleSource}. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param other the SingleSource whose signal should be emitted after this {@code Observable} completes normally. + * @return the new Observable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatWith(@NonNull SingleSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new ObservableConcatWithSingle(this, other)); + } + + /** + * Returns an {@code Observable} that emits the items from this {@code Observable} followed by the success item or terminal events + * of the other {@link MaybeSource}. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param other the MaybeSource whose signal should be emitted after this Observable completes normally. + * @return the new Observable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatWith(@NonNull MaybeSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new ObservableConcatWithMaybe(this, other)); + } + + /** + * Returns an {@code Observable} that emits items from this {@code Observable} and when it completes normally, the + * other {@link CompletableSource} is subscribed to and the returned {@code Observable} emits its terminal events. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param other the {@code CompletableSource} to subscribe to once the current {@code Observable} completes normally + * @return the new Observable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatWith(@NonNull CompletableSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new ObservableConcatWithCompletable(this, other)); + } + /** * Returns a Single that emits a Boolean that indicates whether the source ObservableSource emitted a * specified item. diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java new file mode 100644 index 0000000000..d683d3e788 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java @@ -0,0 +1,111 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import java.util.concurrent.atomic.AtomicReference; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.subscriptions.SubscriptionHelper; + +/** + * Subscribe to a main Flowable first, then when it completes normally, subscribe to a Completable + * and terminate when it terminates. + * @param the element type of the main source and output type + * @since 2.1.10 - experimental + */ +public final class FlowableConcatWithCompletable extends AbstractFlowableWithUpstream { + + final CompletableSource other; + + public FlowableConcatWithCompletable(Flowable source, CompletableSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new ConcatWithSubscriber(s, other)); + } + + static final class ConcatWithSubscriber + extends AtomicReference + implements FlowableSubscriber, CompletableObserver, Subscription { + + private static final long serialVersionUID = -7346385463600070225L; + + final Subscriber actual; + + Subscription upstream; + + CompletableSource other; + + boolean inCompletable; + + ConcatWithSubscriber(Subscriber actual, CompletableSource other) { + this.actual = actual; + this.other = other; + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(upstream, s)) { + this.upstream = s; + actual.onSubscribe(this); + } + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public void onError(Throwable t) { + actual.onError(t); + } + + @Override + public void onComplete() { + if (inCompletable) { + actual.onComplete(); + } else { + inCompletable = true; + upstream = SubscriptionHelper.CANCELLED; + CompletableSource cs = other; + other = null; + cs.subscribe(this); + } + } + + @Override + public void request(long n) { + upstream.request(n); + } + + @Override + public void cancel() { + upstream.cancel(); + DisposableHelper.dispose(this); + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java new file mode 100644 index 0000000000..a3128b6e37 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java @@ -0,0 +1,104 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.subscribers.SinglePostCompleteSubscriber; +import io.reactivex.internal.subscriptions.SubscriptionHelper; + +/** + * Subscribe to a main Flowable first, then when it completes normally, subscribe to a Maybe, + * signal its success value followed by a completion or signal its error or completion signal as is. + * @param the element type of the main source and output type + * @since 2.1.10 - experimental + */ +public final class FlowableConcatWithMaybe extends AbstractFlowableWithUpstream { + + final MaybeSource other; + + public FlowableConcatWithMaybe(Flowable source, MaybeSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new ConcatWithSubscriber(s, other)); + } + + static final class ConcatWithSubscriber + extends SinglePostCompleteSubscriber + implements MaybeObserver { + + private static final long serialVersionUID = -7346385463600070225L; + + final AtomicReference otherDisposable; + + MaybeSource other; + + boolean inMaybe; + + ConcatWithSubscriber(Subscriber actual, MaybeSource other) { + super(actual); + this.other = other; + this.otherDisposable = new AtomicReference(); + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(otherDisposable, d); + } + + @Override + public void onNext(T t) { + produced++; + actual.onNext(t); + } + + @Override + public void onError(Throwable t) { + actual.onError(t); + } + + @Override + public void onSuccess(T t) { + complete(t); + } + + @Override + public void onComplete() { + if (inMaybe) { + actual.onComplete(); + } else { + inMaybe = true; + s = SubscriptionHelper.CANCELLED; + MaybeSource ms = other; + other = null; + ms.subscribe(this); + } + } + + @Override + public void cancel() { + super.cancel(); + DisposableHelper.dispose(otherDisposable); + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java new file mode 100644 index 0000000000..bf86de2003 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java @@ -0,0 +1,97 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.subscribers.SinglePostCompleteSubscriber; +import io.reactivex.internal.subscriptions.SubscriptionHelper; + +/** + * Subscribe to a main Flowable first, then when it completes normally, subscribe to a Single, + * signal its success value followed by a completion or signal its error as is. + * @param the element type of the main source and output type + * @since 2.1.10 - experimental + */ +public final class FlowableConcatWithSingle extends AbstractFlowableWithUpstream { + + final SingleSource other; + + public FlowableConcatWithSingle(Flowable source, SingleSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new ConcatWithSubscriber(s, other)); + } + + static final class ConcatWithSubscriber + extends SinglePostCompleteSubscriber + implements SingleObserver { + + private static final long serialVersionUID = -7346385463600070225L; + + final AtomicReference otherDisposable; + + SingleSource other; + + ConcatWithSubscriber(Subscriber actual, SingleSource other) { + super(actual); + this.other = other; + this.otherDisposable = new AtomicReference(); + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(otherDisposable, d); + } + + @Override + public void onNext(T t) { + produced++; + actual.onNext(t); + } + + @Override + public void onError(Throwable t) { + actual.onError(t); + } + + @Override + public void onSuccess(T t) { + complete(t); + } + + @Override + public void onComplete() { + s = SubscriptionHelper.CANCELLED; + SingleSource ss = other; + other = null; + ss.subscribe(this); + } + + @Override + public void cancel() { + super.cancel(); + DisposableHelper.dispose(otherDisposable); + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java new file mode 100644 index 0000000000..518e2f7b28 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import java.util.concurrent.atomic.AtomicReference; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; + +/** + * Subscribe to a main Observable first, then when it completes normally, subscribe to a Single, + * signal its success value followed by a completion or signal its error as is. + * @param the element type of the main source and output type + * @since 2.1.10 - experimental + */ +public final class ObservableConcatWithCompletable extends AbstractObservableWithUpstream { + + final CompletableSource other; + + public ObservableConcatWithCompletable(Observable source, CompletableSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Observer observer) { + source.subscribe(new ConcatWithObserver(observer, other)); + } + + static final class ConcatWithObserver + extends AtomicReference + implements Observer, CompletableObserver, Disposable { + + private static final long serialVersionUID = -1953724749712440952L; + + final Observer actual; + + CompletableSource other; + + boolean inCompletable; + + ConcatWithObserver(Observer actual, CompletableSource other) { + this.actual = actual; + this.other = other; + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(this, d) && !inCompletable) { + actual.onSubscribe(this); + } + } + + @Override + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public void onError(Throwable e) { + actual.onError(e); + } + + @Override + public void onComplete() { + if (inCompletable) { + actual.onComplete(); + } else { + inCompletable = true; + DisposableHelper.replace(this, null); + CompletableSource cs = other; + other = null; + cs.subscribe(this); + } + } + + @Override + public void dispose() { + DisposableHelper.dispose(this); + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(get()); + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java new file mode 100644 index 0000000000..e8bcbfa766 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java @@ -0,0 +1,105 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import java.util.concurrent.atomic.AtomicReference; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; + +/** + * Subscribe to a main Observable first, then when it completes normally, subscribe to a Maybe, + * signal its success value followed by a completion or signal its error or completion signal as is. + * @param the element type of the main source and output type + * @since 2.1.10 - experimental + */ +public final class ObservableConcatWithMaybe extends AbstractObservableWithUpstream { + + final MaybeSource other; + + public ObservableConcatWithMaybe(Observable source, MaybeSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Observer observer) { + source.subscribe(new ConcatWithObserver(observer, other)); + } + + static final class ConcatWithObserver + extends AtomicReference + implements Observer, MaybeObserver, Disposable { + + private static final long serialVersionUID = -1953724749712440952L; + + final Observer actual; + + MaybeSource other; + + boolean inMaybe; + + ConcatWithObserver(Observer actual, MaybeSource other) { + this.actual = actual; + this.other = other; + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(this, d) && !inMaybe) { + actual.onSubscribe(this); + } + } + + @Override + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public void onSuccess(T t) { + actual.onNext(t); + actual.onComplete(); + } + + @Override + public void onError(Throwable e) { + actual.onError(e); + } + + @Override + public void onComplete() { + if (inMaybe) { + actual.onComplete(); + } else { + inMaybe = true; + DisposableHelper.replace(this, null); + MaybeSource ms = other; + other = null; + ms.subscribe(this); + } + } + + @Override + public void dispose() { + DisposableHelper.dispose(this); + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(get()); + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java new file mode 100644 index 0000000000..516580f507 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import java.util.concurrent.atomic.AtomicReference; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; + +/** + * Subscribe to a main Observable first, then when it completes normally, subscribe to a Single, + * signal its success value followed by a completion or signal its error as is. + * @param the element type of the main source and output type + * @since 2.1.10 - experimental + */ +public final class ObservableConcatWithSingle extends AbstractObservableWithUpstream { + + final SingleSource other; + + public ObservableConcatWithSingle(Observable source, SingleSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Observer observer) { + source.subscribe(new ConcatWithObserver(observer, other)); + } + + static final class ConcatWithObserver + extends AtomicReference + implements Observer, SingleObserver, Disposable { + + private static final long serialVersionUID = -1953724749712440952L; + + final Observer actual; + + SingleSource other; + + boolean inSingle; + + ConcatWithObserver(Observer actual, SingleSource other) { + this.actual = actual; + this.other = other; + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(this, d) && !inSingle) { + actual.onSubscribe(this); + } + } + + @Override + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public void onSuccess(T t) { + actual.onNext(t); + actual.onComplete(); + } + + @Override + public void onError(Throwable e) { + actual.onError(e); + } + + @Override + public void onComplete() { + inSingle = true; + DisposableHelper.replace(this, null); + SingleSource ss = other; + other = null; + ss.subscribe(this); + } + + @Override + public void dispose() { + DisposableHelper.dispose(this); + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(get()); + } + } +} diff --git a/src/test/java/io/reactivex/InternalWrongNaming.java b/src/test/java/io/reactivex/InternalWrongNaming.java index 846a1d08e0..1e4bfc5943 100644 --- a/src/test/java/io/reactivex/InternalWrongNaming.java +++ b/src/test/java/io/reactivex/InternalWrongNaming.java @@ -179,7 +179,10 @@ public void flowableNoObserver() throws Exception { "FlowableFlatMapCompletableCompletable", "FlowableFlatMapSingle", "FlowableFlatMapMaybe", - "FlowableSequenceEqualSingle" + "FlowableSequenceEqualSingle", + "FlowableConcatWithSingle", + "FlowableConcatWithMaybe", + "FlowableConcatWithCompletable" ); } } diff --git a/src/test/java/io/reactivex/flowable/FlowableNullTests.java b/src/test/java/io/reactivex/flowable/FlowableNullTests.java index fdba369d99..67c1d61d8d 100644 --- a/src/test/java/io/reactivex/flowable/FlowableNullTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableNullTests.java @@ -999,7 +999,7 @@ public Iterator iterator() { @Test(expected = NullPointerException.class) public void concatWithNull() { - just1.concatWith(null); + just1.concatWith((Publisher)null); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletableTest.java new file mode 100644 index 0000000000..d186e2fcd4 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletableTest.java @@ -0,0 +1,125 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.reactivestreams.Subscriber; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.subjects.CompletableSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableConcatWithCompletableTest { + + @Test + public void normal() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5) + .concatWith(Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .subscribe(ts); + + ts.assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void mainError() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.error(new TestException()) + .concatWith(Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .subscribe(ts); + + ts.assertFailure(TestException.class); + } + + @Test + public void otherError() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5) + .concatWith(Completable.error(new TestException())) + .subscribe(ts); + + ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); + } + + @Test + public void takeMain() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5) + .concatWith(Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .take(3) + .subscribe(ts); + + ts.assertResult(1, 2, 3); + } + + @Test + public void cancelOther() { + CompletableSubject other = CompletableSubject.create(); + + TestSubscriber ts = Flowable.empty() + .concatWith(other) + .test(); + + assertTrue(other.hasObservers()); + + ts.cancel(); + + assertFalse(other.hasObservers()); + } + + @Test + public void badSource() { + new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + BooleanSubscription bs1 = new BooleanSubscription(); + s.onSubscribe(bs1); + + BooleanSubscription bs2 = new BooleanSubscription(); + s.onSubscribe(bs2); + + assertFalse(bs1.isCancelled()); + assertTrue(bs2.isCancelled()); + + s.onComplete(); + } + }.concatWith(Completable.complete()) + .test() + .assertResult(); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybeTest.java new file mode 100644 index 0000000000..eb1fd62fe2 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybeTest.java @@ -0,0 +1,129 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.subjects.MaybeSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableConcatWithMaybeTest { + + @Test + public void normalEmpty() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5) + .concatWith(Maybe.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .subscribe(ts); + + ts.assertResult(1, 2, 3, 4, 5, 100); + } + + + @Test + public void normalNonEmpty() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5) + .concatWith(Maybe.just(100)) + .subscribe(ts); + + ts.assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void backpressure() { + Flowable.range(1, 5) + .concatWith(Maybe.just(100)) + .test(0) + .assertEmpty() + .requestMore(3) + .assertValues(1, 2, 3) + .requestMore(2) + .assertValues(1, 2, 3, 4, 5) + .requestMore(1) + .assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void mainError() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.error(new TestException()) + .concatWith(Maybe.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .subscribe(ts); + + ts.assertFailure(TestException.class); + } + + @Test + public void otherError() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5) + .concatWith(Maybe.error(new TestException())) + .subscribe(ts); + + ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); + } + + @Test + public void takeMain() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5) + .concatWith(Maybe.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .take(3) + .subscribe(ts); + + ts.assertResult(1, 2, 3); + } + + @Test + public void cancelOther() { + MaybeSubject other = MaybeSubject.create(); + + TestSubscriber ts = Flowable.empty() + .concatWith(other) + .test(); + + assertTrue(other.hasObservers()); + + ts.cancel(); + + assertFalse(other.hasObservers()); + } + +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingleTest.java new file mode 100644 index 0000000000..921f3c163a --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingleTest.java @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.subjects.SingleSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableConcatWithSingleTest { + + @Test + public void normal() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5) + .concatWith(Single.just(100)) + .subscribe(ts); + + ts.assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void backpressure() { + Flowable.range(1, 5) + .concatWith(Single.just(100)) + .test(0) + .assertEmpty() + .requestMore(3) + .assertValues(1, 2, 3) + .requestMore(2) + .assertValues(1, 2, 3, 4, 5) + .requestMore(1) + .assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void mainError() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.error(new TestException()) + .concatWith(Single.just(100)) + .subscribe(ts); + + ts.assertFailure(TestException.class); + } + + @Test + public void otherError() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5) + .concatWith(Single.error(new TestException())) + .subscribe(ts); + + ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); + } + + @Test + public void takeMain() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5) + .concatWith(Single.just(100)) + .take(3) + .subscribe(ts); + + ts.assertResult(1, 2, 3); + } + + @Test + public void cancelOther() { + SingleSubject other = SingleSubject.create(); + + TestSubscriber ts = Flowable.empty() + .concatWith(other) + .test(); + + assertTrue(other.hasObservers()); + + ts.cancel(); + + assertFalse(other.hasObservers()); + } + +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java new file mode 100644 index 0000000000..c2ad3b5ae1 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java @@ -0,0 +1,145 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.observers.TestObserver; +import io.reactivex.subjects.CompletableSubject; + +public class ObservableConcatWithCompletableTest { + + @Test + public void normal() { + final TestObserver ts = new TestObserver(); + + Observable.range(1, 5) + .concatWith(Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .subscribe(ts); + + ts.assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void mainError() { + final TestObserver ts = new TestObserver(); + + Observable.error(new TestException()) + .concatWith(Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .subscribe(ts); + + ts.assertFailure(TestException.class); + } + + @Test + public void otherError() { + final TestObserver ts = new TestObserver(); + + Observable.range(1, 5) + .concatWith(Completable.error(new TestException())) + .subscribe(ts); + + ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); + } + + @Test + public void takeMain() { + final TestObserver ts = new TestObserver(); + + Observable.range(1, 5) + .concatWith(Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .take(3) + .subscribe(ts); + + ts.assertResult(1, 2, 3); + } + + @Test + public void cancelOther() { + CompletableSubject other = CompletableSubject.create(); + + TestObserver ts = Observable.empty() + .concatWith(other) + .test(); + + assertTrue(other.hasObservers()); + + ts.cancel(); + + assertFalse(other.hasObservers()); + } + + @Test + public void badSource() { + new Observable() { + @Override + protected void subscribeActual(Observer s) { + Disposable bs1 = Disposables.empty(); + s.onSubscribe(bs1); + + Disposable bs2 = Disposables.empty(); + s.onSubscribe(bs2); + + assertFalse(bs1.isDisposed()); + assertTrue(bs2.isDisposed()); + + s.onComplete(); + } + }.concatWith(Completable.complete()) + .test() + .assertResult(); + } + + @Test + public void consumerDisposed() { + new Observable() { + @Override + protected void subscribeActual(Observer observer) { + Disposable bs1 = Disposables.empty(); + observer.onSubscribe(bs1); + + assertFalse(((Disposable)observer).isDisposed()); + + observer.onNext(1); + + assertTrue(((Disposable)observer).isDisposed()); + assertTrue(bs1.isDisposed()); + } + }.concatWith(Completable.complete()) + .take(1) + .test() + .assertResult(1); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java new file mode 100644 index 0000000000..586d9315e4 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java @@ -0,0 +1,179 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.observers.TestObserver; +import io.reactivex.subjects.MaybeSubject; + +public class ObservableConcatWithMaybeTest { + + @Test + public void normalEmpty() { + final TestObserver ts = new TestObserver(); + + Observable.range(1, 5) + .concatWith(Maybe.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .subscribe(ts); + + ts.assertResult(1, 2, 3, 4, 5, 100); + } + + + @Test + public void normalNonEmpty() { + final TestObserver ts = new TestObserver(); + + Observable.range(1, 5) + .concatWith(Maybe.just(100)) + .subscribe(ts); + + ts.assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void mainError() { + final TestObserver ts = new TestObserver(); + + Observable.error(new TestException()) + .concatWith(Maybe.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .subscribe(ts); + + ts.assertFailure(TestException.class); + } + + @Test + public void otherError() { + final TestObserver ts = new TestObserver(); + + Observable.range(1, 5) + .concatWith(Maybe.error(new TestException())) + .subscribe(ts); + + ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); + } + + @Test + public void takeMain() { + final TestObserver ts = new TestObserver(); + + Observable.range(1, 5) + .concatWith(Maybe.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + })) + .take(3) + .subscribe(ts); + + ts.assertResult(1, 2, 3); + } + + @Test + public void cancelOther() { + MaybeSubject other = MaybeSubject.create(); + + TestObserver ts = Observable.empty() + .concatWith(other) + .test(); + + assertTrue(other.hasObservers()); + + ts.cancel(); + + assertFalse(other.hasObservers()); + } + + @Test + public void consumerDisposed() { + new Observable() { + @Override + protected void subscribeActual(Observer observer) { + Disposable bs1 = Disposables.empty(); + observer.onSubscribe(bs1); + + assertFalse(((Disposable)observer).isDisposed()); + + observer.onNext(1); + + assertTrue(((Disposable)observer).isDisposed()); + assertTrue(bs1.isDisposed()); + } + }.concatWith(Maybe.just(100)) + .take(1) + .test() + .assertResult(1); + } + + @Test + public void badSource() { + new Observable() { + @Override + protected void subscribeActual(Observer s) { + Disposable bs1 = Disposables.empty(); + s.onSubscribe(bs1); + + Disposable bs2 = Disposables.empty(); + s.onSubscribe(bs2); + + assertFalse(bs1.isDisposed()); + assertTrue(bs2.isDisposed()); + + s.onComplete(); + } + }.concatWith(Maybe.empty()) + .test() + .assertResult(); + } + + @Test + public void badSource2() { + Flowable.empty().concatWith(new Maybe() { + @Override + protected void subscribeActual(MaybeObserver s) { + Disposable bs1 = Disposables.empty(); + s.onSubscribe(bs1); + + Disposable bs2 = Disposables.empty(); + s.onSubscribe(bs2); + + assertFalse(bs1.isDisposed()); + assertTrue(bs2.isDisposed()); + + s.onComplete(); + } + }) + .test() + .assertResult(); + } + +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java new file mode 100644 index 0000000000..5fc06d83e3 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java @@ -0,0 +1,151 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.observers.TestObserver; +import io.reactivex.subjects.SingleSubject; + +public class ObservableConcatWithSingleTest { + + @Test + public void normal() { + final TestObserver ts = new TestObserver(); + + Observable.range(1, 5) + .concatWith(Single.just(100)) + .subscribe(ts); + + ts.assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void mainError() { + final TestObserver ts = new TestObserver(); + + Observable.error(new TestException()) + .concatWith(Single.just(100)) + .subscribe(ts); + + ts.assertFailure(TestException.class); + } + + @Test + public void otherError() { + final TestObserver ts = new TestObserver(); + + Observable.range(1, 5) + .concatWith(Single.error(new TestException())) + .subscribe(ts); + + ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); + } + + @Test + public void takeMain() { + final TestObserver ts = new TestObserver(); + + Observable.range(1, 5) + .concatWith(Single.just(100)) + .take(3) + .subscribe(ts); + + ts.assertResult(1, 2, 3); + } + + @Test + public void cancelOther() { + SingleSubject other = SingleSubject.create(); + + TestObserver ts = Observable.empty() + .concatWith(other) + .test(); + + assertTrue(other.hasObservers()); + + ts.cancel(); + + assertFalse(other.hasObservers()); + } + + @Test + public void consumerDisposed() { + new Observable() { + @Override + protected void subscribeActual(Observer observer) { + Disposable bs1 = Disposables.empty(); + observer.onSubscribe(bs1); + + assertFalse(((Disposable)observer).isDisposed()); + + observer.onNext(1); + + assertTrue(((Disposable)observer).isDisposed()); + assertTrue(bs1.isDisposed()); + } + }.concatWith(Single.just(100)) + .take(1) + .test() + .assertResult(1); + } + + @Test + public void badSource() { + new Observable() { + @Override + protected void subscribeActual(Observer s) { + Disposable bs1 = Disposables.empty(); + s.onSubscribe(bs1); + + Disposable bs2 = Disposables.empty(); + s.onSubscribe(bs2); + + assertFalse(bs1.isDisposed()); + assertTrue(bs2.isDisposed()); + + s.onComplete(); + } + }.concatWith(Single.just(100)) + .test() + .assertResult(100); + } + + @Test + public void badSource2() { + Flowable.empty().concatWith(new Single() { + @Override + protected void subscribeActual(SingleObserver s) { + Disposable bs1 = Disposables.empty(); + s.onSubscribe(bs1); + + Disposable bs2 = Disposables.empty(); + s.onSubscribe(bs2); + + assertFalse(bs1.isDisposed()); + assertTrue(bs2.isDisposed()); + + s.onSuccess(100); + } + }) + .test() + .assertResult(100); + } + +} diff --git a/src/test/java/io/reactivex/observable/ObservableNullTests.java b/src/test/java/io/reactivex/observable/ObservableNullTests.java index 8816bcfe10..55b5846601 100644 --- a/src/test/java/io/reactivex/observable/ObservableNullTests.java +++ b/src/test/java/io/reactivex/observable/ObservableNullTests.java @@ -1088,7 +1088,7 @@ public Iterator iterator() { @Test(expected = NullPointerException.class) public void concatWithNull() { - just1.concatWith(null); + just1.concatWith((ObservableSource)null); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/io/reactivex/tck/ConcatWithCompletableTckTest.java b/src/test/java/io/reactivex/tck/ConcatWithCompletableTckTest.java new file mode 100644 index 0000000000..5a6b12cfeb --- /dev/null +++ b/src/test/java/io/reactivex/tck/ConcatWithCompletableTckTest.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; + +@Test +public class ConcatWithCompletableTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + return + Flowable.range(1, (int)elements) + .concatWith(Completable.complete()) + ; + } +} diff --git a/src/test/java/io/reactivex/tck/ConcatWithMaybeEmptyTckTest.java b/src/test/java/io/reactivex/tck/ConcatWithMaybeEmptyTckTest.java new file mode 100644 index 0000000000..57d3440724 --- /dev/null +++ b/src/test/java/io/reactivex/tck/ConcatWithMaybeEmptyTckTest.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; + +@Test +public class ConcatWithMaybeEmptyTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + return + Flowable.range(1, (int)elements) + .concatWith(Maybe.empty()) + ; + } +} diff --git a/src/test/java/io/reactivex/tck/ConcatWithMaybeTckTest.java b/src/test/java/io/reactivex/tck/ConcatWithMaybeTckTest.java new file mode 100644 index 0000000000..e053a47811 --- /dev/null +++ b/src/test/java/io/reactivex/tck/ConcatWithMaybeTckTest.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; + +@Test +public class ConcatWithMaybeTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + return + Flowable.range(1, Math.max(0, (int)elements - 1)) + .concatWith(Maybe.just((int)elements)) + ; + } +} diff --git a/src/test/java/io/reactivex/tck/ConcatWithSingleTckTest.java b/src/test/java/io/reactivex/tck/ConcatWithSingleTckTest.java new file mode 100644 index 0000000000..b46d344f15 --- /dev/null +++ b/src/test/java/io/reactivex/tck/ConcatWithSingleTckTest.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; + +@Test +public class ConcatWithSingleTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + return + Flowable.range(1, Math.max(0, (int)elements - 1)) + .concatWith(Single.just((int)elements)) + ; + } +} From f74504f5f1516c1e73f82ece9e55d9131285d80e Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 18 Feb 2018 00:18:16 +0100 Subject: [PATCH 100/417] 2.x: Unify race test loop counts and invocations (#5857) --- src/test/java/io/reactivex/TestHelper.java | 17 +++++++ .../disposables/CompositeDisposableTest.java | 49 +++++++++---------- .../disposables/DisposablesTest.java | 6 +-- .../ArrayCompositeDisposableTest.java | 13 +++-- .../CancellableDisposableTest.java | 5 +- .../disposables/DisposableHelperTest.java | 13 +++-- .../ListCompositeDisposableTest.java | 45 +++++++++-------- .../observers/FutureObserverTest.java | 12 ++--- .../observers/FutureSingleObserverTest.java | 13 +++-- .../completable/CompletableAmbTest.java | 9 ++-- .../completable/CompletableCacheTest.java | 4 +- .../completable/CompletableConcatTest.java | 12 ++--- .../CompletableMergeIterableTest.java | 5 +- .../completable/CompletableMergeTest.java | 13 +++-- .../completable/CompletableTimeoutTest.java | 4 +- .../completable/CompletableUsingTest.java | 13 +++-- .../operators/flowable/FlowableAmbTest.java | 12 ++--- .../flowable/FlowableBlockingTest.java | 2 +- .../flowable/FlowableBufferTest.java | 2 +- .../operators/flowable/FlowableCacheTest.java | 4 +- .../flowable/FlowableCombineLatestTest.java | 2 +- .../flowable/FlowableConcatMapEagerTest.java | 10 ++-- .../flowable/FlowableCreateTest.java | 21 ++++---- .../flowable/FlowableFlatMapMaybeTest.java | 2 +- .../flowable/FlowableFlatMapSingleTest.java | 2 +- .../flowable/FlowableFlatMapTest.java | 6 +-- .../flowable/FlowableFromIterableTest.java | 24 ++++----- .../flowable/FlowableGenerateTest.java | 2 +- .../flowable/FlowableGroupJoinTest.java | 9 ++-- .../operators/flowable/FlowableLimitTest.java | 2 +- .../flowable/FlowableObserveOnTest.java | 2 +- .../flowable/FlowablePublishFunctionTest.java | 2 +- .../flowable/FlowablePublishTest.java | 10 ++-- .../flowable/FlowableReplayTest.java | 12 ++--- .../FlowableRetryWithPredicateTest.java | 9 ++-- .../flowable/FlowableSampleTest.java | 6 +-- .../flowable/FlowableScalarXMapTest.java | 5 +- .../flowable/FlowableSequenceEqualTest.java | 8 +-- .../flowable/FlowableSkipLastTimedTest.java | 2 +- .../flowable/FlowableSubscribeOnTest.java | 2 +- .../flowable/FlowableSwitchTest.java | 8 +-- .../flowable/FlowableTakeLastTimedTest.java | 2 +- .../flowable/FlowableTimeoutTests.java | 4 +- .../FlowableTimeoutWithSelectorTest.java | 8 +-- .../operators/flowable/FlowableTimerTest.java | 2 +- .../flowable/FlowableToListTest.java | 6 +-- .../flowable/FlowableWithLatestFromTest.java | 4 +- .../operators/maybe/MaybeAmbTest.java | 6 +-- .../operators/maybe/MaybeCacheTest.java | 9 ++-- .../operators/maybe/MaybeConcatArrayTest.java | 12 ++--- .../maybe/MaybeConcatIterableTest.java | 5 +- .../MaybeFlatMapIterableFlowableTest.java | 8 +-- .../operators/maybe/MaybeMergeArrayTest.java | 7 ++- .../maybe/MaybeSwitchIfEmptySingleTest.java | 17 +++---- .../maybe/MaybeSwitchIfEmptyTest.java | 5 +- .../maybe/MaybeTakeUntilPublisherTest.java | 9 ++-- .../operators/maybe/MaybeTakeUntilTest.java | 9 ++-- .../maybe/MaybeTimeoutPublisherTest.java | 11 ++--- .../operators/maybe/MaybeTimeoutTest.java | 8 +-- .../maybe/MaybeUnsubscribeOnTest.java | 4 +- .../operators/maybe/MaybeUsingTest.java | 13 +++-- .../operators/maybe/MaybeZipArrayTest.java | 7 ++- .../operators/maybe/MaybeZipIterableTest.java | 5 +- .../observable/ObservableAmbTest.java | 12 ++--- .../observable/ObservableBufferTest.java | 2 +- .../observable/ObservableCacheTest.java | 4 +- .../ObservableCombineLatestTest.java | 2 +- .../ObservableConcatMapCompletableTest.java | 22 ++++----- .../ObservableConcatMapEagerTest.java | 8 +-- .../observable/ObservableConcatMapTest.java | 5 +- .../observable/ObservableCreateTest.java | 21 ++++---- .../observable/ObservableFlatMapTest.java | 6 +-- .../observable/ObservableGroupJoinTest.java | 9 ++-- .../observable/ObservablePublishTest.java | 10 ++-- .../observable/ObservableReplayTest.java | 12 ++--- .../ObservableRetryWithPredicateTest.java | 9 ++-- .../observable/ObservableSampleTest.java | 6 +-- .../observable/ObservableScalarXMapTest.java | 5 +- .../ObservableSequenceEqualTest.java | 4 +- .../ObservableSkipLastTimedTest.java | 2 +- .../observable/ObservableSwitchTest.java | 8 +-- .../ObservableTakeLastTimedTest.java | 2 +- .../operators/single/SingleAmbTest.java | 13 +++-- .../operators/single/SingleCacheTest.java | 5 +- .../SingleFlatMapIterableFlowableTest.java | 12 ++--- .../operators/single/SingleTakeUntilTest.java | 8 +-- .../operators/single/SingleTimeoutTest.java | 4 +- .../single/SingleUnsubscribeOnTest.java | 4 +- .../operators/single/SingleUsingTest.java | 9 ++-- .../operators/single/SingleZipArrayTest.java | 5 +- .../single/SingleZipIterableTest.java | 5 +- .../schedulers/AbstractDirectTaskTest.java | 2 +- .../schedulers/ScheduledRunnableTest.java | 12 ++--- .../SchedulerMultiWorkerSupportTest.java | 2 +- .../schedulers/SingleSchedulerTest.java | 2 +- .../subscribers/FutureSubscriberTest.java | 12 ++--- .../SinglePostCompleteSubscriberTest.java | 2 +- .../ArrayCompositeSubscriptionTest.java | 9 ++-- .../DeferredScalarSubscriptionTest.java | 13 +++-- .../subscriptions/SubscriptionHelperTest.java | 17 +++---- .../internal/util/BackpressureHelperTest.java | 9 ++-- .../internal/util/ExceptionHelperTest.java | 8 +-- .../util/HalfSerializerObserverTest.java | 9 ++-- .../util/HalfSerializerSubscriberTest.java | 9 ++-- .../internal/util/QueueDrainHelperTest.java | 2 +- .../java/io/reactivex/maybe/MaybeTest.java | 4 +- .../observers/SerializedObserverTest.java | 20 ++++---- .../reactivex/parallel/ParallelRunOnTest.java | 8 +-- .../parallel/ParallelSortedJoinTest.java | 4 +- .../processors/AsyncProcessorTest.java | 36 ++++++-------- .../processors/BehaviorProcessorTest.java | 16 +++--- .../processors/PublishProcessorTest.java | 12 ++--- .../processors/ReplayProcessorTest.java | 26 +++++----- .../processors/SerializedProcessorTest.java | 33 ++++++------- .../processors/UnicastProcessorTest.java | 28 +++++------ .../reactivex/schedulers/SchedulerTest.java | 4 +- .../reactivex/subjects/AsyncSubjectTest.java | 9 ++-- .../subjects/BehaviorSubjectTest.java | 12 ++--- .../subjects/CompletableSubjectTest.java | 5 +- .../reactivex/subjects/MaybeSubjectTest.java | 5 +- .../subjects/PublishSubjectTest.java | 18 +++---- .../reactivex/subjects/ReplaySubjectTest.java | 12 ++--- .../subjects/SerializedSubjectTest.java | 33 ++++++------- .../reactivex/subjects/SingleSubjectTest.java | 5 +- .../subjects/UnicastSubjectTest.java | 11 ++--- .../subscribers/SerializedSubscriberTest.java | 20 ++++---- 126 files changed, 580 insertions(+), 623 deletions(-) diff --git a/src/test/java/io/reactivex/TestHelper.java b/src/test/java/io/reactivex/TestHelper.java index 9ed96562e8..b0bbf1d9a6 100644 --- a/src/test/java/io/reactivex/TestHelper.java +++ b/src/test/java/io/reactivex/TestHelper.java @@ -50,6 +50,19 @@ */ public enum TestHelper { ; + + /** + * Number of times to loop a {@link #race(Runnable, Runnable)} invocation + * by default. + */ + public static final int RACE_DEFAULT_LOOPS = 2500; + + /** + * Number of times to loop a {@link #race(Runnable, Runnable)} invocation + * in tests with race conditions requiring more runs to check. + */ + public static final int RACE_LONG_LOOPS = 10000; + /** * Mocks a subscriber and prepares it to request Long.MAX_VALUE. * @param the value type @@ -344,6 +357,8 @@ public void onComplete() { *

                The method blocks until both have run to completion. * @param r1 the first runnable * @param r2 the second runnable + * @see #RACE_DEFAULT_LOOPS + * @see #RACE_LONG_LOOPS */ public static void race(final Runnable r1, final Runnable r2) { race(r1, r2, Schedulers.single()); @@ -355,6 +370,8 @@ public static void race(final Runnable r1, final Runnable r2) { * @param r1 the first runnable * @param r2 the second runnable * @param s the scheduler to use + * @see #RACE_DEFAULT_LOOPS + * @see #RACE_LONG_LOOPS */ public static void race(final Runnable r1, final Runnable r2, Scheduler s) { final AtomicInteger count = new AtomicInteger(2); diff --git a/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java b/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java index 55daf27e2a..78e73bf047 100644 --- a/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java +++ b/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java @@ -25,7 +25,6 @@ import io.reactivex.TestHelper; import io.reactivex.exceptions.CompositeException; import io.reactivex.functions.Action; -import io.reactivex.schedulers.Schedulers; public class CompositeDisposableTest { @@ -443,7 +442,7 @@ public void delete() { @Test public void disposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); Runnable run = new Runnable() { @@ -453,13 +452,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void addRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); Runnable run = new Runnable() { @@ -469,13 +468,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void addAllRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); Runnable run = new Runnable() { @@ -485,13 +484,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void removeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -505,13 +504,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void deleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -525,13 +524,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void clearRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -545,13 +544,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void addDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); Runnable run = new Runnable() { @@ -568,13 +567,13 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } @Test public void addAllDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); Runnable run = new Runnable() { @@ -591,13 +590,13 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } @Test public void removeDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -618,13 +617,13 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } @Test public void deleteDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -645,13 +644,13 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } @Test public void clearDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -672,13 +671,13 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } @Test public void sizeDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable cd = new CompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -699,7 +698,7 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } diff --git a/src/test/java/io/reactivex/disposables/DisposablesTest.java b/src/test/java/io/reactivex/disposables/DisposablesTest.java index 3dd90382db..779b85fead 100644 --- a/src/test/java/io/reactivex/disposables/DisposablesTest.java +++ b/src/test/java/io/reactivex/disposables/DisposablesTest.java @@ -14,6 +14,7 @@ package io.reactivex.disposables; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.*; import java.io.IOException; @@ -27,7 +28,6 @@ import io.reactivex.functions.Action; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; public class DisposablesTest { @@ -123,7 +123,7 @@ public void run() throws Exception { @Test public void disposeRace() { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Disposable d = Disposables.empty(); Runnable r = new Runnable() { @@ -133,7 +133,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.io()); + TestHelper.race(r, r); } } diff --git a/src/test/java/io/reactivex/internal/disposables/ArrayCompositeDisposableTest.java b/src/test/java/io/reactivex/internal/disposables/ArrayCompositeDisposableTest.java index 77afd9e6b1..81fb4de489 100644 --- a/src/test/java/io/reactivex/internal/disposables/ArrayCompositeDisposableTest.java +++ b/src/test/java/io/reactivex/internal/disposables/ArrayCompositeDisposableTest.java @@ -19,7 +19,6 @@ import io.reactivex.TestHelper; import io.reactivex.disposables.*; -import io.reactivex.schedulers.Schedulers; public class ArrayCompositeDisposableTest { @@ -70,7 +69,7 @@ public void normal() { @Test public void disposeRace() { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ArrayCompositeDisposable acd = new ArrayCompositeDisposable(2); Runnable r = new Runnable() { @@ -80,13 +79,13 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.io()); + TestHelper.race(r, r); } } @Test public void replaceRace() { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ArrayCompositeDisposable acd = new ArrayCompositeDisposable(2); Runnable r = new Runnable() { @@ -96,13 +95,13 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.io()); + TestHelper.race(r, r); } } @Test public void setRace() { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ArrayCompositeDisposable acd = new ArrayCompositeDisposable(2); Runnable r = new Runnable() { @@ -112,7 +111,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.io()); + TestHelper.race(r, r); } } diff --git a/src/test/java/io/reactivex/internal/disposables/CancellableDisposableTest.java b/src/test/java/io/reactivex/internal/disposables/CancellableDisposableTest.java index aedb7a716b..41e3997243 100644 --- a/src/test/java/io/reactivex/internal/disposables/CancellableDisposableTest.java +++ b/src/test/java/io/reactivex/internal/disposables/CancellableDisposableTest.java @@ -24,7 +24,6 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.Cancellable; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; public class CancellableDisposableTest { @@ -84,7 +83,7 @@ public void cancel() throws Exception { @Test public void disposeRace() { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicInteger count = new AtomicInteger(); Cancellable c = new Cancellable() { @@ -103,7 +102,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.io()); + TestHelper.race(r, r); assertEquals(1, count.get()); } diff --git a/src/test/java/io/reactivex/internal/disposables/DisposableHelperTest.java b/src/test/java/io/reactivex/internal/disposables/DisposableHelperTest.java index 941e082101..b219e44dd1 100644 --- a/src/test/java/io/reactivex/internal/disposables/DisposableHelperTest.java +++ b/src/test/java/io/reactivex/internal/disposables/DisposableHelperTest.java @@ -23,7 +23,6 @@ import io.reactivex.TestHelper; import io.reactivex.disposables.*; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; public class DisposableHelperTest { @Test @@ -53,7 +52,7 @@ public void validationNull() { @Test public void disposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicReference d = new AtomicReference(); Runnable r = new Runnable() { @@ -63,13 +62,13 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.io()); + TestHelper.race(r, r); } } @Test public void setReplace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicReference d = new AtomicReference(); Runnable r = new Runnable() { @@ -79,13 +78,13 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.io()); + TestHelper.race(r, r); } } @Test public void setRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicReference d = new AtomicReference(); Runnable r = new Runnable() { @@ -95,7 +94,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.io()); + TestHelper.race(r, r); } } diff --git a/src/test/java/io/reactivex/internal/disposables/ListCompositeDisposableTest.java b/src/test/java/io/reactivex/internal/disposables/ListCompositeDisposableTest.java index fa6050d952..4d3ed24708 100644 --- a/src/test/java/io/reactivex/internal/disposables/ListCompositeDisposableTest.java +++ b/src/test/java/io/reactivex/internal/disposables/ListCompositeDisposableTest.java @@ -22,7 +22,6 @@ import io.reactivex.TestHelper; import io.reactivex.disposables.*; import io.reactivex.exceptions.*; -import io.reactivex.schedulers.Schedulers; public class ListCompositeDisposableTest { @@ -179,7 +178,7 @@ public void remove() { @Test public void disposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); Runnable run = new Runnable() { @@ -189,13 +188,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void addRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); Runnable run = new Runnable() { @@ -205,13 +204,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void addAllRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); Runnable run = new Runnable() { @@ -221,13 +220,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void removeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -241,13 +240,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void deleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -261,13 +260,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void clearRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -281,13 +280,13 @@ public void run() { } }; - TestHelper.race(run, run, Schedulers.io()); + TestHelper.race(run, run); } } @Test public void addDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); Runnable run = new Runnable() { @@ -304,13 +303,13 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } @Test public void addAllDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); Runnable run = new Runnable() { @@ -327,13 +326,13 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } @Test public void removeDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -354,13 +353,13 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } @Test public void deleteDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -381,13 +380,13 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } @Test public void clearDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ListCompositeDisposable cd = new ListCompositeDisposable(); final Disposable d1 = Disposables.empty(); @@ -408,7 +407,7 @@ public void run() { } }; - TestHelper.race(run, run2, Schedulers.io()); + TestHelper.race(run, run2); } } } diff --git a/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java b/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java index d31c4137fd..917a156f14 100644 --- a/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java @@ -154,7 +154,7 @@ public void onSubscribe() throws Exception { @Test public void cancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FutureSubscriber fo = new FutureSubscriber(); Runnable r = new Runnable() { @@ -164,7 +164,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } @@ -185,7 +185,7 @@ public void run() { public void onErrorCancelRace() { RxJavaPlugins.setErrorHandler(Functions.emptyConsumer()); try { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FutureSubscriber fo = new FutureSubscriber(); final TestException ex = new TestException(); @@ -204,7 +204,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } finally { RxJavaPlugins.reset(); @@ -213,7 +213,7 @@ public void run() { @Test public void onCompleteCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FutureSubscriber fo = new FutureSubscriber(); if (i % 3 == 0) { @@ -238,7 +238,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java b/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java index c463d48386..cd52919537 100644 --- a/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java @@ -22,7 +22,6 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; public class FutureSingleObserverTest { @@ -66,7 +65,7 @@ public void cancel() { @Test public void cancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Future f = Single.never().toFuture(); Runnable r = new Runnable() { @@ -76,7 +75,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } @@ -130,7 +129,7 @@ public void getAwait() throws Exception { @Test public void onSuccessCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final Future f = ps.single(-99).toFuture(); @@ -151,13 +150,13 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void onErrorCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final Future f = ps.single(-99).toFuture(); @@ -178,7 +177,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java index 194ca4f119..dbb9bf79db 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java @@ -24,7 +24,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.*; public class CompletableAmbTest { @@ -70,7 +69,7 @@ public void dispose() { @Test public void innerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp0 = PublishProcessor.create(); @@ -95,7 +94,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); @@ -110,7 +109,7 @@ public void run() { @Test public void nullSourceSuccessRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -134,7 +133,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (!errors.isEmpty()) { TestHelper.assertError(errors, 0, NullPointerException.class); diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableCacheTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableCacheTest.java index b34c8dbef8..0a20999b98 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableCacheTest.java @@ -168,7 +168,7 @@ public void dispose() { @Test public void subscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { PublishSubject ps = PublishSubject.create(); final Completable c = ps.ignoreElements().cache(); @@ -201,7 +201,7 @@ public void run() { @Test public void subscribeDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { PublishSubject ps = PublishSubject.create(); final Completable c = ps.ignoreElements().cache(); diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java index 9c2c080104..a72faf078b 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java @@ -69,7 +69,7 @@ public void dispose() { @Test public void errorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -100,7 +100,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); @@ -203,7 +203,7 @@ public void arrayCancelRace() { Completable[] a = new Completable[1024]; Arrays.fill(a, Completable.complete()); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Completable c = Completable.concatArray(a); @@ -223,7 +223,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @@ -232,7 +232,7 @@ public void iterableCancelRace() { Completable[] a = new Completable[1024]; Arrays.fill(a, Completable.complete()); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Completable c = Completable.concat(Arrays.asList(a)); @@ -252,7 +252,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeIterableTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeIterableTest.java index 934364adf5..fb1b4c709a 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeIterableTest.java @@ -21,14 +21,13 @@ import io.reactivex.exceptions.TestException; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; public class CompletableMergeIterableTest { @Test public void errorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishSubject ps1 = PublishSubject.create(); @@ -52,7 +51,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeTest.java index ba3bdf546f..d386969ad9 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeTest.java @@ -28,7 +28,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class CompletableMergeTest { @Test @@ -192,7 +191,7 @@ public void innerErrorDelayError() { @Test public void mainErrorInnerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp1 = PublishProcessor.create(); @@ -223,7 +222,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); Throwable ex = to.errors().get(0); if (ex instanceof CompositeException) { @@ -247,7 +246,7 @@ public void run() { @Test public void mainErrorInnerErrorDelayedRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); @@ -277,7 +276,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(CompositeException.class); @@ -446,7 +445,7 @@ protected void subscribeActual(CompletableObserver s) { @Test public void mergeArrayInnerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp1 = PublishProcessor.create(); @@ -472,7 +471,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java index 35ec511859..fe6a8478dc 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java @@ -106,7 +106,7 @@ public void mainError() { @Test public void errorTimeoutRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -133,7 +133,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertTerminated(); diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java index f5e790731b..30c1965120 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java @@ -26,7 +26,6 @@ import io.reactivex.functions.*; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; public class CompletableUsingTest { @@ -440,7 +439,7 @@ public void accept(Object d) throws Exception { @Test public void successDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); @@ -477,13 +476,13 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void errorDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); @@ -520,13 +519,13 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void emptyDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); @@ -562,7 +561,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java index f3b7ec2d3e..ba6b837a37 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java @@ -567,7 +567,7 @@ public void singleIterable() { @Test public void onNextRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps1 = PublishProcessor.create(); final PublishProcessor ps2 = PublishProcessor.create(); @@ -587,7 +587,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertSubscribed().assertNoErrors() .assertNotComplete().assertValueCount(1); @@ -596,7 +596,7 @@ public void run() { @Test public void onCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps1 = PublishProcessor.create(); final PublishProcessor ps2 = PublishProcessor.create(); @@ -616,7 +616,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertResult(); } @@ -624,7 +624,7 @@ public void run() { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps1 = PublishProcessor.create(); final PublishProcessor ps2 = PublishProcessor.create(); @@ -648,7 +648,7 @@ public void run() { List errors = TestHelper.trackPluginErrors(); try { - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } finally { RxJavaPlugins.reset(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java index cd4aa269d3..50edb0ac6d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java @@ -345,7 +345,7 @@ protected void subscribeActual(Subscriber observer) { @Test public void blockinsSubscribeCancelAsync() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(); final PublishProcessor pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index 06a4553f1c..471fc5836e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -1978,7 +1978,7 @@ public void skipBackpressure() { @Test public void withTimeAndSizeCapacityRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler scheduler = new TestScheduler(); final PublishProcessor ps = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java index 526b8bcd77..7cec7d4c33 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java @@ -315,7 +315,7 @@ public void disposeOnArrival2() { @Test public void subscribeEmitRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); final Flowable cache = ps.cache(); @@ -341,7 +341,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to .awaitDone(5, TimeUnit.SECONDS) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java index a2ea0152ef..f43a58dedc 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java @@ -1264,7 +1264,7 @@ public Object apply(Object a, Object b) throws Exception { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor ps1 = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java index ee4e982bf7..37cd8bf3d6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java @@ -856,7 +856,7 @@ public Flowable apply(Integer v) throws Exception { @Test public void innerOuterRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor ps1 = PublishProcessor.create(); @@ -887,7 +887,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertSubscribed().assertNoValues().assertNotComplete(); @@ -966,7 +966,7 @@ public Flowable apply(Integer v) throws Exception { @Test public void nextCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps1 = PublishProcessor.create(); final TestSubscriber to = ps1.concatMapEager(new Function>() { @@ -989,7 +989,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertEmpty(); } @@ -1136,7 +1136,7 @@ public Publisher apply(Integer v) throws Exception { @Test public void drainCancelRaceOnEmpty() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestSubscriber ts = new TestSubscriber(0L); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java index 1289087d65..de6e10417c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java @@ -27,7 +27,6 @@ import io.reactivex.functions.Cancellable; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; public class FlowableCreateTest { @@ -480,14 +479,14 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } }, m); List errors = TestHelper.trackPluginErrors(); try { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { source .test() .assertFailure(Throwable.class); @@ -521,11 +520,11 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } }, m); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { source .test() .assertResult(); @@ -589,7 +588,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } }, m) .test() @@ -783,18 +782,18 @@ public void subscribe(FlowableEmitter e) throws Exception { Runnable r1 = new Runnable() { @Override public void run() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { f.onNext(1); } } }; - TestHelper.race(r1, r1, Schedulers.single()); + TestHelper.race(r1, r1); } }, m) - .take(1000) + .take(TestHelper.RACE_DEFAULT_LOOPS) .test() - .assertSubscribed().assertValueCount(1000).assertComplete().assertNoErrors(); + .assertSubscribed().assertValueCount(TestHelper.RACE_DEFAULT_LOOPS).assertComplete().assertNoErrors(); } } @@ -825,7 +824,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } }, m) .test() diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java index 4f5a594abd..26762e7e4d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java @@ -584,7 +584,7 @@ public void errorDelayed() { @Test public void requestCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber to = Flowable.just(1).concatWith(Flowable.never()) .flatMapMaybe(Functions.justFunction(Maybe.just(2))).test(0); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java index 0e39156baa..14a0dfa569 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java @@ -470,7 +470,7 @@ public void errorDelayed() { @Test public void requestCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber to = Flowable.just(1).concatWith(Flowable.never()) .flatMapSingle(Functions.justFunction(Single.just(2))).test(0); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index 66da69516a..9e53cbe70a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -826,7 +826,7 @@ public void onNext(Integer t) { @Test public void innerCompleteCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); final TestSubscriber to = Flowable.merge(Flowable.just(ps)).test(); @@ -930,7 +930,7 @@ public Object apply(Integer v) throws Exception { @Test public void cancelScalarDrainRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -962,7 +962,7 @@ public void run() { @Test public void cancelDrainRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { for (int j = 1; j < 50; j += 5) { List errors = TestHelper.trackPluginErrors(); try { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java index 877222aca3..7a23049928 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java @@ -722,7 +722,7 @@ public void normalConditionalLong2() { @Test public void requestRaceConditional() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(0L); Runnable r = new Runnable() { @@ -736,13 +736,13 @@ public void run() { .filter(Functions.alwaysTrue()) .subscribe(ts); - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } @Test public void requestRaceConditional2() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(0L); Runnable r = new Runnable() { @@ -756,13 +756,13 @@ public void run() { .filter(Functions.alwaysFalse()) .subscribe(ts); - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } @Test public void requestCancelConditionalRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(0L); Runnable r1 = new Runnable() { @@ -783,13 +783,13 @@ public void run() { .filter(Functions.alwaysTrue()) .subscribe(ts); - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void requestCancelConditionalRace2() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(0L); Runnable r1 = new Runnable() { @@ -810,13 +810,13 @@ public void run() { .filter(Functions.alwaysTrue()) .subscribe(ts); - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void requestCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(0L); Runnable r1 = new Runnable() { @@ -836,13 +836,13 @@ public void run() { Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)) .subscribe(ts); - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void requestCancelRace2() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(0L); Runnable r1 = new Runnable() { @@ -862,7 +862,7 @@ public void run() { Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)) .subscribe(ts); - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGenerateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGenerateTest.java index a90d91455a..73a7401588 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGenerateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGenerateTest.java @@ -219,7 +219,7 @@ public void accept(Object s, Emitter e) throws Exception { } }, Functions.emptyConsumer()); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = source.test(0L); Runnable r = new Runnable() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java index 4407dceb07..fb5d55d265 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java @@ -30,7 +30,6 @@ import io.reactivex.internal.functions.Functions; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; public class FlowableGroupJoinTest { @@ -506,7 +505,7 @@ public Flowable apply(Integer r, Flowable l) throws Exception @Test public void innerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps1 = PublishProcessor.create(); final PublishProcessor ps2 = PublishProcessor.create(); @@ -553,7 +552,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertError(Throwable.class).assertSubscribed().assertNotComplete().assertValueCount(1); @@ -578,7 +577,7 @@ public void run() { @Test public void outerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps1 = PublishProcessor.create(); final PublishProcessor ps2 = PublishProcessor.create(); @@ -626,7 +625,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertError(Throwable.class).assertSubscribed().assertNotComplete().assertNoValues(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java index 553085ace2..471b0e818d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java @@ -190,7 +190,7 @@ public void badRequest() { @Test public void requestRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = Flowable.range(1, 10) .limit(5) .test(0L); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java index 77bdf9e8b3..dab9f09e72 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java @@ -1740,7 +1740,7 @@ public void backFusedErrorConditional() { @Test public void backFusedCancelConditional() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); final TestScheduler scheduler = new TestScheduler(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java index c46f1c5aff..c05899bdc3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java @@ -427,7 +427,7 @@ public void inputOutputSubscribeRace2() { @Test public void sourceSubscriptionDelayed() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts1 = new TestSubscriber(0L); Flowable.just(1) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java index 79305861ad..20d074fd4c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java @@ -529,7 +529,7 @@ public void accept(Disposable s) throws Exception { @Test public void addRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableFlowable co = Flowable.empty().publish(); @@ -618,7 +618,7 @@ public void onNext(Integer t) { @Test public void nextCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); @@ -686,7 +686,7 @@ public void noErrorLoss() { @Test public void subscribeDisconnectRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); @@ -768,7 +768,7 @@ public Flowable apply(Flowable v) throws Exception { @Test public void preNextConnect() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableFlowable co = Flowable.empty().publish(); @@ -787,7 +787,7 @@ public void run() { @Test public void connectRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableFlowable co = Flowable.empty().publish(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index 58b5ffedd0..a9c41366ad 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -1305,7 +1305,7 @@ public void source() { @Test public void connectRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableFlowable co = Flowable.range(1, 3).replay(); Runnable r = new Runnable() { @@ -1321,7 +1321,7 @@ public void run() { @Test public void subscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableFlowable co = Flowable.range(1, 3).replay(); final TestSubscriber to1 = new TestSubscriber(); @@ -1347,7 +1347,7 @@ public void run() { @Test public void addRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableFlowable co = Flowable.range(1, 3).replay(); final TestSubscriber to1 = new TestSubscriber(); @@ -1445,7 +1445,7 @@ protected void subscribeActual(Subscriber observer) { @Test public void subscribeOnNextRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); final ConnectableFlowable co = ps.replay(); @@ -1474,7 +1474,7 @@ public void run() { @Test public void unsubscribeOnNextRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); final ConnectableFlowable co = ps.replay(); @@ -1505,7 +1505,7 @@ public void run() { @Test public void unsubscribeReplayRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableFlowable co = Flowable.range(1, 1000).replay(); final TestSubscriber to1 = new TestSubscriber(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java index 5664a973aa..9f94cc267c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java @@ -33,7 +33,6 @@ import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.*; public class FlowableRetryWithPredicateTest { @@ -419,7 +418,7 @@ public void dontRetry() { @Test public void retryDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); final TestSubscriber to = ps.retry(Functions.alwaysTrue()).test(); @@ -440,7 +439,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertEmpty(); } @@ -467,7 +466,7 @@ public boolean test(Integer n, Throwable e) throws Exception { @Test public void retryBiPredicateDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); final TestSubscriber to = ps.retry(new BiPredicate() { @@ -493,7 +492,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertEmpty(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java index 743da3f284..8c15a44130 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java @@ -338,7 +338,7 @@ public void emitLastTimedCustomScheduler() { @Test public void emitLastTimedRunCompleteRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler scheduler = new TestScheduler(); final PublishProcessor pp = PublishProcessor.create(); @@ -386,7 +386,7 @@ public void emitLastOtherEmpty() { @Test public void emitLastOtherRunCompleteRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final PublishProcessor sampler = PublishProcessor.create(); @@ -417,7 +417,7 @@ public void run() { @Test public void emitLastOtherCompleteCompleteRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final PublishProcessor sampler = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableScalarXMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableScalarXMapTest.java index 0f0a4e4486..191f90bbea 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableScalarXMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableScalarXMapTest.java @@ -24,7 +24,6 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; import io.reactivex.internal.subscriptions.*; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; public class FlowableScalarXMapTest { @@ -212,7 +211,7 @@ public void scalarDisposableStateCheck() { @Test public void scalarDisposableRunDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestSubscriber to = new TestSubscriber(); final ScalarSubscription sd = new ScalarSubscription(to, 1); to.onSubscribe(sd); @@ -231,7 +230,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java index 7036ff3d9e..f4dc1441d0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java @@ -312,7 +312,7 @@ public void simpleInequalObservable() { @Test public void onNextCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); final TestObserver to = Flowable.sequenceEqual(Flowable.never(), ps).test(); @@ -339,7 +339,7 @@ public void run() { @Test public void onNextCancelRaceObservable() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); final TestSubscriber to = Flowable.sequenceEqual(Flowable.never(), ps).toFlowable().test(); @@ -414,7 +414,7 @@ protected void subscribeActual(Subscriber s) { } }; - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(); final PublishProcessor pp = PublishProcessor.create(); @@ -518,7 +518,7 @@ protected void subscribeActual(Subscriber s) { } }; - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestObserver ts = new TestObserver(); final PublishProcessor pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java index ac2d820d1d..23d5a7b987 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java @@ -196,7 +196,7 @@ public Flowable apply(Flowable o) throws Exception { @Test public void onNextDisposeRace() { TestScheduler scheduler = new TestScheduler(); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); final TestSubscriber to = ps.skipLast(1, TimeUnit.DAYS, scheduler).test(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOnTest.java index 7798cc88f1..0214825887 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOnTest.java @@ -294,7 +294,7 @@ public void dispose() { @Test public void deferredRequestRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(0L); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java index 7b18b2ffdc..41a13caa60 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java @@ -821,7 +821,7 @@ public void dispose() { @Test public void nextSourceErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -868,7 +868,7 @@ public void run() { @Test public void outerInnerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -917,7 +917,7 @@ public void run() { @Test public void nextCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps1 = PublishProcessor.create(); final TestSubscriber to = ps1.switchMap(new Function>() { @@ -1114,7 +1114,7 @@ protected void subscribeActual(Subscriber s) { @Test public void drainCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(); final PublishProcessor pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java index 88015beffe..f27411ef0e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java @@ -291,7 +291,7 @@ public void observeOn() { @Test public void cancelCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor ps = PublishProcessor.create(); final TestSubscriber to = ps.takeLast(1, TimeUnit.DAYS).test(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java index 296627e2fe..b95a03d7be 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java @@ -523,7 +523,7 @@ public void fallbackErrors() { @Test public void onNextOnTimeoutRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler sch = new TestScheduler(); final PublishProcessor pp = PublishProcessor.create(); @@ -560,7 +560,7 @@ public void run() { @Test public void onNextOnTimeoutRaceFallback() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler sch = new TestScheduler(); final PublishProcessor pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java index 0482ff5e68..bad1090d85 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java @@ -549,7 +549,7 @@ public void selectorFallbackTake() { @Test public void lateOnTimeoutError() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp = PublishProcessor.create(); @@ -603,7 +603,7 @@ public void run() { @Test public void lateOnTimeoutFallbackRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp = PublishProcessor.create(); @@ -658,7 +658,7 @@ public void run() { @Test public void onErrorOnTimeoutRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp = PublishProcessor.create(); @@ -713,7 +713,7 @@ public void run() { @Test public void onECompleteOnTimeoutRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java index 16052e328d..ec18215c00 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java @@ -304,7 +304,7 @@ public void backpressureNotReady() { @Test public void timerCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(); final TestScheduler scheduler = new TestScheduler(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java index 2bb37c2f18..b5b86cf9e2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java @@ -392,7 +392,7 @@ public Collection call() throws Exception { @Test public void onNextCancelRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestObserver> ts = pp.toList().test(); @@ -415,7 +415,7 @@ public void run() { @Test public void onNextCancelRaceFlowable() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestSubscriber> ts = pp.toList().toFlowable().test(); @@ -439,7 +439,7 @@ public void run() { @Test public void onCompleteCancelRaceFlowable() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestSubscriber> ts = pp.toList().toFlowable().test(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java index 01ca2f1edf..0151fbbe90 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java @@ -779,7 +779,7 @@ public Object apply(Integer a, Object b, Object c, Object d) throws Exception { @Test public void otherOnSubscribeRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp0 = PublishProcessor.create(); final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); @@ -822,7 +822,7 @@ public void run() { @Test public void otherCompleteRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp0 = PublishProcessor.create(); final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java index de8120f227..9f3f888ba9 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.maybe; import static org.junit.Assert.*; + import java.util.*; import org.junit.Test; @@ -23,7 +24,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class MaybeAmbTest { @@ -71,7 +71,7 @@ public void dispose() { @SuppressWarnings("unchecked") @Test public void innerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp0 = PublishProcessor.create(); @@ -96,7 +96,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java index 041f3a88a7..652ddf6e0a 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java @@ -24,7 +24,6 @@ import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; public class MaybeCacheTest { @@ -224,7 +223,7 @@ public void run() throws Exception { @Test public void addAddRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { PublishProcessor pp = PublishProcessor.create(); final Maybe source = pp.singleElement().cache(); @@ -236,13 +235,13 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } @Test public void removeRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { PublishProcessor pp = PublishProcessor.create(); final Maybe source = pp.singleElement().cache(); @@ -264,7 +263,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayTest.java index 04773bcedf..29eac9a2a3 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayTest.java @@ -13,17 +13,17 @@ package io.reactivex.internal.operators.maybe; +import static org.junit.Assert.assertEquals; + import java.io.IOException; import java.util.List; -import static org.junit.Assert.*; import org.junit.Test; import io.reactivex.*; import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.TestException; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; public class MaybeConcatArrayTest { @@ -83,7 +83,7 @@ public void backpressureDelayError() { @SuppressWarnings("unchecked") @Test public void requestCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = Maybe.concatArray(Maybe.just(1), Maybe.just(2)) .test(0L); @@ -101,14 +101,14 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @SuppressWarnings("unchecked") @Test public void requestCancelRaceDelayError() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = Maybe.concatArrayDelayError(Maybe.just(1), Maybe.just(2)) .test(0L); @@ -126,7 +126,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatIterableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatIterableTest.java index 4bc41e8af7..545c15225f 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatIterableTest.java @@ -24,7 +24,6 @@ import io.reactivex.functions.Function; import io.reactivex.internal.util.CrashingMappedIterable; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; public class MaybeConcatIterableTest { @@ -61,7 +60,7 @@ public void error() { @SuppressWarnings("unchecked") @Test public void successCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); @@ -84,7 +83,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java index 60b270ec28..bc9617c293 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java @@ -403,7 +403,7 @@ public void requestCreateInnerRace() { final Integer[] a = new Integer[1000]; Arrays.fill(a, 1); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); ps.onNext(1); @@ -436,13 +436,13 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void cancelCreateInnerRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); ps.onNext(1); @@ -470,7 +470,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java index 61dc02da35..2d65eb5b67 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java @@ -18,7 +18,7 @@ import java.util.*; import org.junit.Test; -import org.reactivestreams.*; +import org.reactivestreams.Subscription; import io.reactivex.*; import io.reactivex.disposables.Disposables; @@ -26,7 +26,6 @@ import io.reactivex.internal.fuseable.QueueSubscription; import io.reactivex.internal.operators.maybe.MaybeMergeArray.MergeMaybeObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; import io.reactivex.subscribers.*; @@ -133,7 +132,7 @@ public void errorFused() { @SuppressWarnings("unchecked") @Test public void errorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -159,7 +158,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertFailure(Throwable.class); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java index d21eccb211..cd8db6760f 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java @@ -13,18 +13,15 @@ package io.reactivex.internal.operators.maybe; -import io.reactivex.Maybe; -import io.reactivex.Single; -import io.reactivex.TestHelper; +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; public class MaybeSwitchIfEmptySingleTest { @@ -83,7 +80,7 @@ public Single apply(Maybe f) throws Exception { @Test public void emptyCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestObserver ts = pp.singleElement().switchIfEmpty(Single.just(2)).test(); @@ -102,7 +99,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java index 91ebad9948..2ce1d6b8d7 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java @@ -22,7 +22,6 @@ import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class MaybeSwitchIfEmptyTest { @@ -97,7 +96,7 @@ public Maybe apply(Maybe f) throws Exception { @Test public void emptyCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestObserver ts = pp.singleElement().switchIfEmpty(Maybe.just(2)).test(); @@ -116,7 +115,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisherTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisherTest.java index c1c49886f3..28bc00a1a2 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisherTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisherTest.java @@ -25,7 +25,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class MaybeTakeUntilPublisherTest { @@ -118,7 +117,7 @@ public void otherCompletes() { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); @@ -143,7 +142,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); @@ -160,7 +159,7 @@ public void run() { @Test public void onCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); @@ -179,7 +178,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertResult(); } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilTest.java index 3fd457172b..601c123d9e 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilTest.java @@ -25,7 +25,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class MaybeTakeUntilTest { @@ -146,7 +145,7 @@ public void otherCompletes() { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); @@ -171,7 +170,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); @@ -188,7 +187,7 @@ public void run() { @Test public void onCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); @@ -207,7 +206,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertResult(); } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisherTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisherTest.java index 6fbb5f4359..763af24904 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisherTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisherTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.*; -import java.util.concurrent.*; +import java.util.concurrent.TimeoutException; import org.junit.Test; @@ -25,7 +25,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.*; public class MaybeTimeoutPublisherTest { @@ -157,7 +156,7 @@ public void dispose2() { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestHelper.trackPluginErrors(); try { final PublishProcessor pp1 = PublishProcessor.create(); @@ -180,7 +179,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); } finally { @@ -191,7 +190,7 @@ public void run() { @Test public void onCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); @@ -210,7 +209,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertSubscribed().assertNoValues(); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimeoutTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimeoutTest.java index bf47c09cec..eaa5ef25f6 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimeoutTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimeoutTest.java @@ -276,7 +276,7 @@ public void dispose2() { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestHelper.trackPluginErrors(); try { final PublishProcessor pp1 = PublishProcessor.create(); @@ -299,7 +299,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); } finally { @@ -310,7 +310,7 @@ public void run() { @Test public void onCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); @@ -329,7 +329,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertSubscribed().assertNoValues(); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeUnsubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeUnsubscribeOnTest.java index 92d3528221..813fb2c25d 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeUnsubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeUnsubscribeOnTest.java @@ -103,7 +103,7 @@ public MaybeSource apply(Maybe v) throws Exception { @Test public void disposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { PublishProcessor pp = PublishProcessor.create(); final Disposable[] ds = { null }; @@ -137,7 +137,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java index 535495e35e..28fabf6080 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java @@ -26,7 +26,6 @@ import io.reactivex.functions.*; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; public class MaybeUsingTest { @@ -440,7 +439,7 @@ public void accept(Object d) throws Exception { @Test public void successDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); @@ -477,13 +476,13 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void errorDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); @@ -520,13 +519,13 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void emptyDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); @@ -562,7 +561,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java index be8bac0b87..7fb24e1e27 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.*; -import java.util.*; +import java.util.List; import org.junit.Test; @@ -26,7 +26,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class MaybeZipArrayTest { @@ -114,7 +113,7 @@ public void middleError() { @Test public void innerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp0 = PublishProcessor.create(); @@ -139,7 +138,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipIterableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipIterableTest.java index bd43490bc5..87cf95d328 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipIterableTest.java @@ -27,7 +27,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class MaybeZipIterableTest { @@ -115,7 +114,7 @@ public void middleError() { @SuppressWarnings("unchecked") @Test public void innerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp0 = PublishProcessor.create(); @@ -141,7 +140,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java index fd3d5aafc7..932b40187c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java @@ -271,7 +271,7 @@ public void disposed() { @Test public void onNextRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps1 = PublishSubject.create(); final PublishSubject ps2 = PublishSubject.create(); @@ -291,7 +291,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertSubscribed().assertNoErrors() .assertNotComplete().assertValueCount(1); @@ -300,7 +300,7 @@ public void run() { @Test public void onCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps1 = PublishSubject.create(); final PublishSubject ps2 = PublishSubject.create(); @@ -320,7 +320,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertResult(); } @@ -328,7 +328,7 @@ public void run() { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps1 = PublishSubject.create(); final PublishSubject ps2 = PublishSubject.create(); @@ -352,7 +352,7 @@ public void run() { List errors = TestHelper.trackPluginErrors(); try { - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } finally { RxJavaPlugins.reset(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 6c633581ea..7a435a389c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -1404,7 +1404,7 @@ public void bufferTimedExactBoundedError() { @Test public void withTimeAndSizeCapacityRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler scheduler = new TestScheduler(); final PublishSubject ps = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java index f985211c66..e7d7e35f16 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java @@ -318,7 +318,7 @@ public void take() { @Test public void subscribeEmitRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final Observable cache = ps.cache(); @@ -344,7 +344,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to .awaitDone(5, TimeUnit.SECONDS) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java index 24fde40419..7595a9b893 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java @@ -963,7 +963,7 @@ public Object apply(Object[] a) throws Exception { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishSubject ps1 = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java index bf07d82430..63789a756d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java @@ -12,21 +12,19 @@ */ package io.reactivex.internal.operators.observable; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Test; + import io.reactivex.*; -import io.reactivex.disposables.Disposable; -import io.reactivex.disposables.Disposables; +import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; -import io.reactivex.subjects.PublishSubject; -import io.reactivex.subjects.UnicastSubject; -import org.junit.Test; - -import java.util.List; - -import static org.junit.Assert.assertTrue; +import io.reactivex.subjects.*; public class ObservableConcatMapCompletableTest { @@ -107,7 +105,7 @@ protected void subscribeActual(Observer observer) { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishSubject ps1 = PublishSubject.create(); @@ -136,7 +134,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java index 9823436941..593febc4eb 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java @@ -807,7 +807,7 @@ public Integer call() throws Exception { @Test public void innerOuterRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishSubject ps1 = PublishSubject.create(); @@ -838,7 +838,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertSubscribed().assertNoValues().assertNotComplete(); @@ -862,7 +862,7 @@ public void run() { @Test public void nextCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps1 = PublishSubject.create(); final TestObserver to = ps1.concatMapEager(new Function>() { @@ -885,7 +885,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertEmpty(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java index 9991e65254..ecff867fdb 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java @@ -27,7 +27,6 @@ import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.*; public class ObservableConcatMapTest { @@ -232,7 +231,7 @@ public ObservableSource apply(Integer v) throws Exception { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishSubject ps1 = PublishSubject.create(); @@ -261,7 +260,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCreateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCreateTest.java index ef623e98a4..4933a70fb7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCreateTest.java @@ -26,7 +26,6 @@ import io.reactivex.functions.Cancellable; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; public class ObservableCreateTest { @@ -438,18 +437,18 @@ public void subscribe(ObservableEmitter e) throws Exception { Runnable r1 = new Runnable() { @Override public void run() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { f.onNext(1); } } }; - TestHelper.race(r1, r1, Schedulers.single()); + TestHelper.race(r1, r1); } }) - .take(1000) + .take(TestHelper.RACE_DEFAULT_LOOPS) .test() - .assertSubscribed().assertValueCount(1000).assertComplete().assertNoErrors(); + .assertSubscribed().assertValueCount(TestHelper.RACE_DEFAULT_LOOPS).assertComplete().assertNoErrors(); } @Test @@ -478,7 +477,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } }) .test() @@ -512,7 +511,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } }) .test() @@ -546,14 +545,14 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } }); List errors = TestHelper.trackPluginErrors(); try { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { source .test() .assertFailure(Throwable.class); @@ -585,11 +584,11 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } }); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { source .test() .assertResult(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index 1a48d43df0..1771e1d5f4 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -694,7 +694,7 @@ public void onNext(Integer t) { @Test public void innerCompleteCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final TestObserver to = Observable.merge(Observable.just(ps)).test(); @@ -789,7 +789,7 @@ public Object apply(Integer v) throws Exception { @Test public void cancelScalarDrainRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -821,7 +821,7 @@ public void run() { @Test public void cancelDrainRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { for (int j = 1; j < 50; j += 5) { List errors = TestHelper.trackPluginErrors(); try { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java index c23628c4bb..ac89708573 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java @@ -32,7 +32,6 @@ import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; public class ObservableGroupJoinTest { @@ -507,7 +506,7 @@ public Observable apply(Integer r, Observable l) throws Except @Test public void innerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps1 = PublishSubject.create(); final PublishSubject ps2 = PublishSubject.create(); @@ -554,7 +553,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertError(Throwable.class).assertSubscribed().assertNotComplete().assertValueCount(1); @@ -579,7 +578,7 @@ public void run() { @Test public void outerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps1 = PublishSubject.create(); final PublishSubject ps2 = PublishSubject.create(); @@ -627,7 +626,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertError(Throwable.class).assertSubscribed().assertNotComplete().assertNoValues(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java index 695f9c8e00..e4f04bba95 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java @@ -400,7 +400,7 @@ public void testObserveOn() { @Test public void preNextConnect() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableObservable co = Observable.empty().publish(); @@ -419,7 +419,7 @@ public void run() { @Test public void connectRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableObservable co = Observable.empty().publish(); @@ -470,7 +470,7 @@ public void accept(Disposable s) throws Exception { @Test public void addRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableObservable co = Observable.empty().publish(); @@ -552,7 +552,7 @@ public void onNext(Integer t) { @Test public void nextCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); @@ -620,7 +620,7 @@ public void noErrorLoss() { @Test public void subscribeDisconnectRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java index d6f2a512c3..d8b9c75ef2 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java @@ -1178,7 +1178,7 @@ public void source() { @Test public void connectRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableObservable co = Observable.range(1, 3).replay(); Runnable r = new Runnable() { @@ -1194,7 +1194,7 @@ public void run() { @Test public void subscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableObservable co = Observable.range(1, 3).replay(); final TestObserver to1 = new TestObserver(); @@ -1220,7 +1220,7 @@ public void run() { @Test public void addRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableObservable co = Observable.range(1, 3).replay(); final TestObserver to1 = new TestObserver(); @@ -1318,7 +1318,7 @@ protected void subscribeActual(Observer observer) { @Test public void subscribeOnNextRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final ConnectableObservable co = ps.replay(); @@ -1347,7 +1347,7 @@ public void run() { @Test public void unsubscribeOnNextRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final ConnectableObservable co = ps.replay(); @@ -1378,7 +1378,7 @@ public void run() { @Test public void unsubscribeReplayRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ConnectableObservable co = Observable.range(1, 1000).replay(); final TestObserver to1 = new TestObserver(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java index 785de1a592..1763f74d9f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java @@ -33,7 +33,6 @@ import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.observers.*; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; public class ObservableRetryWithPredicateTest { @@ -390,7 +389,7 @@ public void dontRetry() { @Test public void retryDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final TestObserver to = ps.retry(Functions.alwaysTrue()).test(); @@ -411,7 +410,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertEmpty(); } @@ -438,7 +437,7 @@ public boolean test(Integer n, Throwable e) throws Exception { @Test public void retryBiPredicateDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final TestObserver to = ps.retry(new BiPredicate() { @@ -464,7 +463,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertEmpty(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java index fb86ff92a8..a45881ef83 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java @@ -319,7 +319,7 @@ public void emitLastTimedCustomScheduler() { @Test public void emitLastTimedRunCompleteRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler scheduler = new TestScheduler(); final PublishSubject pp = PublishSubject.create(); @@ -367,7 +367,7 @@ public void emitLastOtherEmpty() { @Test public void emitLastOtherRunCompleteRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject pp = PublishSubject.create(); final PublishSubject sampler = PublishSubject.create(); @@ -398,7 +398,7 @@ public void run() { @Test public void emitLastOtherCompleteCompleteRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject pp = PublishSubject.create(); final PublishSubject sampler = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java index 587cc98fa9..ba401f5124 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java @@ -25,7 +25,6 @@ import io.reactivex.internal.disposables.EmptyDisposable; import io.reactivex.internal.operators.observable.ObservableScalarXMap.ScalarDisposable; import io.reactivex.observers.TestObserver; -import io.reactivex.schedulers.Schedulers; public class ObservableScalarXMapTest { @@ -214,7 +213,7 @@ public void scalarDisposableStateCheck() { @Test public void scalarDisposableRunDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestObserver to = new TestObserver(); final ScalarDisposable sd = new ScalarDisposable(to, 1); to.onSubscribe(sd); @@ -233,7 +232,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java index d4a38f78a4..5a5adb36d1 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java @@ -316,7 +316,7 @@ public void simpleInequalObservable() { @Test public void onNextCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final TestObserver to = Observable.sequenceEqual(Observable.never(), ps).test(); @@ -343,7 +343,7 @@ public void run() { @Test public void onNextCancelRaceObservable() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final TestObserver to = Observable.sequenceEqual(Observable.never(), ps).toObservable().test(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimedTest.java index 7e73421ede..50df641a26 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimedTest.java @@ -195,7 +195,7 @@ public ObservableSource apply(Observable o) throws Exception { @Test public void onNextDisposeRace() { TestScheduler scheduler = new TestScheduler(); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final TestObserver to = ps.skipLast(1, TimeUnit.DAYS, scheduler).test(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java index c934600ca6..034890b1bd 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java @@ -721,7 +721,7 @@ public void dispose() { @Test public void nextSourceErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -768,7 +768,7 @@ public void run() { @Test public void outerInnerErrorRace() { - for (int i = 0; i < 5000; i++) { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -819,7 +819,7 @@ public void run() { @Test public void nextCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps1 = PublishSubject.create(); final TestObserver to = ps1.switchMap(new Function>() { @@ -989,7 +989,7 @@ public void innerDisposedOnMainError() { @Test public void outerInnerErrorRaceIgnoreDispose() { - for (int i = 0; i < 5000; i++) { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java index 75e8948284..bc933f9b02 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java @@ -254,7 +254,7 @@ public void observeOn() { @Test public void cancelCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final TestObserver to = ps.takeLast(1, TimeUnit.DAYS).test(); diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java index feb9abd77d..e07b27129c 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java @@ -24,7 +24,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.*; public class SingleAmbTest { @@ -134,7 +133,7 @@ public void error() { @Test public void nullSourceSuccessRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -159,7 +158,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (!errors.isEmpty()) { TestHelper.assertError(errors, 0, NullPointerException.class); @@ -173,7 +172,7 @@ public void run() { @SuppressWarnings("unchecked") @Test public void multipleErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -199,7 +198,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); @@ -213,7 +212,7 @@ public void run() { @SuppressWarnings("unchecked") @Test public void successErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -240,7 +239,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleCacheTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleCacheTest.java index 47a3cabf28..cd56bb5fe9 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleCacheTest.java @@ -19,7 +19,6 @@ import io.reactivex.disposables.Disposable; import io.reactivex.observers.TestObserver; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class SingleCacheTest { @@ -41,7 +40,7 @@ public void cancelImmediately() { @Test public void addRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { PublishProcessor pp = PublishProcessor.create(); final Single cached = pp.single(-99).cache(); @@ -62,7 +61,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java index 959c3f3ff5..749e326ce6 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java @@ -390,7 +390,7 @@ public void requestCreateInnerRace() { final Integer[] a = new Integer[1000]; Arrays.fill(a, 1); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); ps.onNext(1); @@ -423,13 +423,13 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void cancelCreateInnerRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); ps.onNext(1); @@ -457,7 +457,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @@ -554,7 +554,7 @@ public void requestIteratorRace() { final Integer[] a = new Integer[1000]; Arrays.fill(a, 1); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject ps = PublishSubject.create(); final TestSubscriber ts = ps.singleOrError().flattenAsFlowable(new Function>() { @@ -581,7 +581,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java index a253f2edb7..c9d7ab4467 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java @@ -13,10 +13,11 @@ package io.reactivex.internal.operators.single; +import static org.junit.Assert.assertTrue; + import java.util.List; import java.util.concurrent.CancellationException; -import static org.junit.Assert.*; import org.junit.Test; import io.reactivex.*; @@ -24,7 +25,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class SingleTakeUntilTest { @@ -223,7 +223,7 @@ public void withPublisherDispose() { @Test public void onErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -248,7 +248,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleTimeoutTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleTimeoutTest.java index 132b0076d6..37077a6dd2 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleTimeoutTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleTimeoutTest.java @@ -134,7 +134,7 @@ public void run() throws Exception { @Test public void successTimeoutRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final SingleSubject subj = SingleSubject.create(); SingleSubject fallback = SingleSubject.create(); @@ -172,7 +172,7 @@ public void errorTimeoutRace() { List errors = TestHelper.trackPluginErrors(); try { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final SingleSubject subj = SingleSubject.create(); SingleSubject fallback = SingleSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleUnsubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleUnsubscribeOnTest.java index 733d7d0ccc..5bcf01f1f6 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleUnsubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleUnsubscribeOnTest.java @@ -95,7 +95,7 @@ public SingleSource apply(Single v) throws Exception { @Test public void disposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { PublishProcessor pp = PublishProcessor.create(); final Disposable[] ds = { null }; @@ -124,7 +124,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleUsingTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleUsingTest.java index 5a278fbae0..c0d3229e59 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleUsingTest.java @@ -28,7 +28,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class SingleUsingTest { @@ -220,7 +219,7 @@ public SingleSource apply(Disposable v) throws Exception { @Test public void successDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); Disposable d = Disposables.empty(); @@ -248,7 +247,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); assertTrue(d.isDisposed()); } @@ -295,7 +294,7 @@ protected void subscribeActual(SingleObserver observer) { @Test public void errorDisposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); Disposable d = Disposables.empty(); @@ -323,7 +322,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); assertTrue(d.isDisposed()); } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java index 5c2b17c368..2f7e398c03 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java @@ -26,7 +26,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class SingleZipArrayTest { @@ -114,7 +113,7 @@ public void middleError() { @Test public void innerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp0 = PublishProcessor.create(); @@ -139,7 +138,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleZipIterableTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleZipIterableTest.java index 415aeb1db4..f5ba4954a0 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleZipIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleZipIterableTest.java @@ -27,7 +27,6 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.Schedulers; public class SingleZipIterableTest { @@ -115,7 +114,7 @@ public void middleError() { @SuppressWarnings("unchecked") @Test public void innerErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { final PublishProcessor pp0 = PublishProcessor.create(); @@ -141,7 +140,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); to.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/internal/schedulers/AbstractDirectTaskTest.java b/src/test/java/io/reactivex/internal/schedulers/AbstractDirectTaskTest.java index dd77428cd7..1357f27b5c 100644 --- a/src/test/java/io/reactivex/internal/schedulers/AbstractDirectTaskTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/AbstractDirectTaskTest.java @@ -208,7 +208,7 @@ public boolean cancel(boolean mayInterruptIfRunning) { @Test public void disposeSetFutureRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AbstractDirectTask task = new AbstractDirectTask(Functions.EMPTY_RUNNABLE) { private static final long serialVersionUID = 208585707945686116L; }; diff --git a/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java b/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java index 49d20edf80..add5de3ed0 100644 --- a/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java @@ -59,7 +59,7 @@ public void disposeRun() { @Test public void setFutureCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); @@ -88,7 +88,7 @@ public void run() { @Test public void setFutureRunRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); @@ -117,7 +117,7 @@ public void run() { @Test public void disposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); @@ -137,7 +137,7 @@ public void run() { @Test public void runDispose() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); @@ -260,7 +260,7 @@ public void withFutureDisposed3() { @Test public void runFuture() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); @@ -287,7 +287,7 @@ public void run() { @Test public void syncWorkerCancelRace() { - for (int i = 0; i < 10000; i++) { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { final CompositeDisposable set = new CompositeDisposable(); final AtomicBoolean interrupted = new AtomicBoolean(); final AtomicInteger sync = new AtomicInteger(2); diff --git a/src/test/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupportTest.java b/src/test/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupportTest.java index d77dd8786e..23980da892 100644 --- a/src/test/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupportTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupportTest.java @@ -66,7 +66,7 @@ public void onWorker(int i, Worker w) { @Test public void distinctThreads() throws Exception { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompositeDisposable composite = new CompositeDisposable(); diff --git a/src/test/java/io/reactivex/internal/schedulers/SingleSchedulerTest.java b/src/test/java/io/reactivex/internal/schedulers/SingleSchedulerTest.java index 362b6dd7f1..e7b79d21bd 100644 --- a/src/test/java/io/reactivex/internal/schedulers/SingleSchedulerTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/SingleSchedulerTest.java @@ -68,7 +68,7 @@ public void run() { @Test public void startRace() { final Scheduler s = new SingleScheduler(); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { s.shutdown(); Runnable r1 = new Runnable() { diff --git a/src/test/java/io/reactivex/internal/subscribers/FutureSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/FutureSubscriberTest.java index 85ace65ce0..baef7a9176 100644 --- a/src/test/java/io/reactivex/internal/subscribers/FutureSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/FutureSubscriberTest.java @@ -126,7 +126,7 @@ public void onSubscribe() throws Exception { @Test public void cancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FutureSubscriber fs = new FutureSubscriber(); Runnable r = new Runnable() { @@ -136,7 +136,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } @@ -155,7 +155,7 @@ public void run() { @Test public void onErrorCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FutureSubscriber fs = new FutureSubscriber(); final TestException ex = new TestException(); @@ -174,13 +174,13 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void onCompleteCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FutureSubscriber fs = new FutureSubscriber(); if (i % 3 == 0) { @@ -205,7 +205,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/subscribers/SinglePostCompleteSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/SinglePostCompleteSubscriberTest.java index 6e9d2a9206..825e08d4fe 100644 --- a/src/test/java/io/reactivex/internal/subscribers/SinglePostCompleteSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/SinglePostCompleteSubscriberTest.java @@ -23,7 +23,7 @@ public class SinglePostCompleteSubscriberTest { @Test public void requestCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(0L); final SinglePostCompleteSubscriber spc = new SinglePostCompleteSubscriber(ts) { diff --git a/src/test/java/io/reactivex/internal/subscriptions/ArrayCompositeSubscriptionTest.java b/src/test/java/io/reactivex/internal/subscriptions/ArrayCompositeSubscriptionTest.java index 68997ebe64..6861f9cb0e 100644 --- a/src/test/java/io/reactivex/internal/subscriptions/ArrayCompositeSubscriptionTest.java +++ b/src/test/java/io/reactivex/internal/subscriptions/ArrayCompositeSubscriptionTest.java @@ -18,7 +18,6 @@ import org.junit.Test; import io.reactivex.TestHelper; -import io.reactivex.schedulers.Schedulers; public class ArrayCompositeSubscriptionTest { @@ -94,7 +93,7 @@ public void replace() { @Test public void disposeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ArrayCompositeSubscription ac = new ArrayCompositeSubscription(1000); Runnable r = new Runnable() { @@ -104,13 +103,13 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } @Test public void setReplaceRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ArrayCompositeSubscription ac = new ArrayCompositeSubscription(1); final BooleanSubscription s1 = new BooleanSubscription(); @@ -130,7 +129,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/subscriptions/DeferredScalarSubscriptionTest.java b/src/test/java/io/reactivex/internal/subscriptions/DeferredScalarSubscriptionTest.java index d090760961..6ad325a9d4 100644 --- a/src/test/java/io/reactivex/internal/subscriptions/DeferredScalarSubscriptionTest.java +++ b/src/test/java/io/reactivex/internal/subscriptions/DeferredScalarSubscriptionTest.java @@ -19,7 +19,6 @@ import io.reactivex.TestHelper; import io.reactivex.internal.fuseable.QueueSubscription; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; public class DeferredScalarSubscriptionTest { @@ -54,7 +53,7 @@ public void cancel() { @Test public void completeCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final DeferredScalarSubscription ds = new DeferredScalarSubscription(new TestSubscriber()); Runnable r1 = new Runnable() { @@ -71,13 +70,13 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void requestClearRace() { - for (int i = 0; i < 5000; i++) { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { TestSubscriber ts = new TestSubscriber(0L); final DeferredScalarSubscription ds = new DeferredScalarSubscription(ts); @@ -98,7 +97,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (ts.valueCount() >= 1) { ts.assertValue(1); @@ -108,7 +107,7 @@ public void run() { @Test public void requestCancelRace() { - for (int i = 0; i < 5000; i++) { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { TestSubscriber ts = new TestSubscriber(0L); final DeferredScalarSubscription ds = new DeferredScalarSubscription(ts); @@ -129,7 +128,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (ts.valueCount() >= 1) { ts.assertValue(1); diff --git a/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java b/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java index a84289670f..3b98ee30c7 100644 --- a/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java +++ b/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java @@ -23,7 +23,6 @@ import io.reactivex.TestHelper; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; public class SubscriptionHelperTest { @@ -85,7 +84,7 @@ public void replace() { @Test public void cancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicReference s = new AtomicReference(); Runnable r = new Runnable() { @@ -95,13 +94,13 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } @Test public void setRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicReference s = new AtomicReference(); final BooleanSubscription bs1 = new BooleanSubscription(); @@ -121,7 +120,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); assertTrue(bs1.isCancelled() ^ bs2.isCancelled()); } @@ -129,7 +128,7 @@ public void run() { @Test public void replaceRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicReference s = new AtomicReference(); final BooleanSubscription bs1 = new BooleanSubscription(); @@ -149,7 +148,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); assertFalse(bs1.isCancelled()); assertFalse(bs2.isCancelled()); @@ -192,7 +191,7 @@ public void invalidDeferredRequest() { @Test public void deferredRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicReference s = new AtomicReference(); final AtomicLong r = new AtomicLong(); @@ -224,7 +223,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); assertSame(a, s.get()); assertEquals(1, q.get()); diff --git a/src/test/java/io/reactivex/internal/util/BackpressureHelperTest.java b/src/test/java/io/reactivex/internal/util/BackpressureHelperTest.java index a9796f08c5..fbcff0ab95 100644 --- a/src/test/java/io/reactivex/internal/util/BackpressureHelperTest.java +++ b/src/test/java/io/reactivex/internal/util/BackpressureHelperTest.java @@ -24,7 +24,6 @@ import io.reactivex.TestHelper; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; public class BackpressureHelperTest { @Ignore("BackpressureHelper is an enum") @@ -85,7 +84,7 @@ public void producedMoreCancel() { public void requestProduceRace() { final AtomicLong requested = new AtomicLong(1); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { Runnable r1 = new Runnable() { @Override @@ -101,7 +100,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @@ -109,7 +108,7 @@ public void run() { public void requestCancelProduceRace() { final AtomicLong requested = new AtomicLong(1); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { Runnable r1 = new Runnable() { @Override @@ -125,7 +124,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/internal/util/ExceptionHelperTest.java b/src/test/java/io/reactivex/internal/util/ExceptionHelperTest.java index 618ae20d31..de401c0df7 100644 --- a/src/test/java/io/reactivex/internal/util/ExceptionHelperTest.java +++ b/src/test/java/io/reactivex/internal/util/ExceptionHelperTest.java @@ -13,14 +13,14 @@ package io.reactivex.internal.util; +import static org.junit.Assert.assertTrue; + import java.util.concurrent.atomic.AtomicReference; -import static org.junit.Assert.*; import org.junit.Test; import io.reactivex.TestHelper; import io.reactivex.exceptions.TestException; -import io.reactivex.schedulers.Schedulers; public class ExceptionHelperTest { @Test @@ -30,7 +30,7 @@ public void utilityClass() { @Test public void addRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicReference error = new AtomicReference(); @@ -43,7 +43,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); } } diff --git a/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java b/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java index 2b923b6fb0..a0262cd328 100644 --- a/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java +++ b/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java @@ -23,7 +23,6 @@ import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.observers.TestObserver; -import io.reactivex.schedulers.Schedulers; public class HalfSerializerObserverTest { @@ -203,7 +202,7 @@ public void onComplete() { @Test public void onNextOnCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicInteger wip = new AtomicInteger(); final AtomicThrowable error = new AtomicThrowable(); @@ -225,7 +224,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertComplete().assertNoErrors(); @@ -235,7 +234,7 @@ public void run() { @Test public void onErrorOnCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicInteger wip = new AtomicInteger(); final AtomicThrowable error = new AtomicThrowable(); @@ -260,7 +259,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (ts.completions() != 0) { ts.assertResult(); diff --git a/src/test/java/io/reactivex/internal/util/HalfSerializerSubscriberTest.java b/src/test/java/io/reactivex/internal/util/HalfSerializerSubscriberTest.java index 4a3adf662f..4cfbf4bb91 100644 --- a/src/test/java/io/reactivex/internal/util/HalfSerializerSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/util/HalfSerializerSubscriberTest.java @@ -23,7 +23,6 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.internal.subscriptions.BooleanSubscription; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; public class HalfSerializerSubscriberTest { @@ -209,7 +208,7 @@ public void onComplete() { @Test public void onNextOnCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicInteger wip = new AtomicInteger(); final AtomicThrowable error = new AtomicThrowable(); @@ -231,7 +230,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertComplete().assertNoErrors(); @@ -241,7 +240,7 @@ public void run() { @Test public void onErrorOnCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicInteger wip = new AtomicInteger(); final AtomicThrowable error = new AtomicThrowable(); @@ -266,7 +265,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (ts.completions() != 0) { ts.assertResult(); diff --git a/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java b/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java index e680304893..1c24351a65 100644 --- a/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java +++ b/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java @@ -123,7 +123,7 @@ public boolean getAsBoolean() throws Exception { @Test public void completeRequestRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(); final ArrayDeque queue = new ArrayDeque(); final AtomicLong state = new AtomicLong(); diff --git a/src/test/java/io/reactivex/maybe/MaybeTest.java b/src/test/java/io/reactivex/maybe/MaybeTest.java index c493f956b1..14705243ea 100644 --- a/src/test/java/io/reactivex/maybe/MaybeTest.java +++ b/src/test/java/io/reactivex/maybe/MaybeTest.java @@ -2089,7 +2089,7 @@ public void mergeArrayFused() { @SuppressWarnings("unchecked") @Test public void mergeArrayFusedRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); @@ -2114,7 +2114,7 @@ public void run() { pp2.onNext(1); pp2.onComplete(); } - }, Schedulers.single()); + }); ts .awaitDone(5, TimeUnit.SECONDS) diff --git a/src/test/java/io/reactivex/observers/SerializedObserverTest.java b/src/test/java/io/reactivex/observers/SerializedObserverTest.java index f330ce0b37..0fb3526df9 100644 --- a/src/test/java/io/reactivex/observers/SerializedObserverTest.java +++ b/src/test/java/io/reactivex/observers/SerializedObserverTest.java @@ -1018,7 +1018,7 @@ public void dispose() { @Test public void onCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestObserver ts = new TestObserver(); final SerializedObserver so = new SerializedObserver(ts); @@ -1034,7 +1034,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); ts.awaitDone(5, TimeUnit.SECONDS) .assertResult(); @@ -1044,7 +1044,7 @@ public void run() { @Test public void onNextOnCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestObserver ts = new TestObserver(); final SerializedObserver so = new SerializedObserver(ts); @@ -1067,7 +1067,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.awaitDone(5, TimeUnit.SECONDS) .assertNoErrors() @@ -1080,7 +1080,7 @@ public void run() { @Test public void onNextOnErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestObserver ts = new TestObserver(); final SerializedObserver so = new SerializedObserver(ts); @@ -1105,7 +1105,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.awaitDone(5, TimeUnit.SECONDS) .assertError(ex) @@ -1118,7 +1118,7 @@ public void run() { @Test public void onNextOnErrorRaceDelayError() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestObserver ts = new TestObserver(); final SerializedObserver so = new SerializedObserver(ts, true); @@ -1143,7 +1143,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.awaitDone(5, TimeUnit.SECONDS) .assertError(ex) @@ -1180,7 +1180,7 @@ public void startOnce() { @Test public void onCompleteOnErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -1208,7 +1208,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.awaitDone(5, TimeUnit.SECONDS); diff --git a/src/test/java/io/reactivex/parallel/ParallelRunOnTest.java b/src/test/java/io/reactivex/parallel/ParallelRunOnTest.java index bf0bb0b33b..53023b5790 100644 --- a/src/test/java/io/reactivex/parallel/ParallelRunOnTest.java +++ b/src/test/java/io/reactivex/parallel/ParallelRunOnTest.java @@ -163,7 +163,7 @@ public void emptyConditionalBackpressured() { @Test public void nextCancelRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestSubscriber ts = pp.parallel(1) @@ -192,7 +192,7 @@ public void run() { @SuppressWarnings("unchecked") @Test public void nextCancelRaceBackpressured() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestSubscriber ts = TestSubscriber.create(0L); @@ -221,7 +221,7 @@ public void run() { @Test public void nextCancelRaceConditional() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestSubscriber ts = pp.parallel(1) @@ -251,7 +251,7 @@ public void run() { @SuppressWarnings("unchecked") @Test public void nextCancelRaceBackpressuredConditional() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestSubscriber ts = TestSubscriber.create(0L); diff --git a/src/test/java/io/reactivex/parallel/ParallelSortedJoinTest.java b/src/test/java/io/reactivex/parallel/ParallelSortedJoinTest.java index 99e336d338..aede8c5717 100644 --- a/src/test/java/io/reactivex/parallel/ParallelSortedJoinTest.java +++ b/src/test/java/io/reactivex/parallel/ParallelSortedJoinTest.java @@ -152,7 +152,7 @@ public void asyncDrain() { @Test public void sortCancelRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ReplayProcessor pp = ReplayProcessor.create(); pp.onNext(1); pp.onNext(2); @@ -181,7 +181,7 @@ public void run() { @Test public void sortCancelRace2() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ReplayProcessor pp = ReplayProcessor.create(); pp.onNext(1); pp.onNext(2); diff --git a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java index 8e564efcbe..488b58ac88 100644 --- a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java +++ b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java @@ -13,27 +13,23 @@ package io.reactivex.processors; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.*; +import org.mockito.*; +import org.reactivestreams.Subscriber; + import io.reactivex.TestHelper; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Consumer; import io.reactivex.internal.fuseable.QueueSubscription; import io.reactivex.internal.subscriptions.BooleanSubscription; -import io.reactivex.schedulers.Schedulers; -import io.reactivex.subscribers.SubscriberFusion; -import io.reactivex.subscribers.TestSubscriber; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.InOrder; -import org.mockito.Mockito; -import org.reactivestreams.Subscriber; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; +import io.reactivex.subscribers.*; public class AsyncProcessorTest extends FlowableProcessorTest { @@ -467,7 +463,7 @@ public void cancelUpfront() { public void cancelRace() { AsyncProcessor p = AsyncProcessor.create(); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts1 = p.test(); final TestSubscriber ts2 = p.test(); @@ -485,14 +481,14 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void onErrorCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AsyncProcessor p = AsyncProcessor.create(); final TestSubscriber ts1 = p.test(); @@ -513,7 +509,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (ts1.errorCount() != 0) { ts1.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java index 496c75c8fa..ba52d0c806 100644 --- a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java +++ b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java @@ -636,7 +636,7 @@ public void cancelOnArrival2() { @Test public void addRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorProcessor p = BehaviorProcessor.create(); final TestSubscriber ts = p.test(); @@ -655,14 +655,14 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void subscribeOnNextRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorProcessor p = BehaviorProcessor.createDefault((Object)1); final TestSubscriber[] ts = { null }; @@ -681,7 +681,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (ts[0].valueCount() == 1) { ts[0].assertValue(2).assertNoErrors().assertNotComplete(); @@ -759,7 +759,7 @@ public void run() { @Test public void completeSubscribeRace() throws Exception { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorProcessor p = BehaviorProcessor.create(); final TestSubscriber ts = new TestSubscriber(); @@ -786,7 +786,7 @@ public void run() { @Test public void errorSubscribeRace() throws Exception { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorProcessor p = BehaviorProcessor.create(); final TestSubscriber ts = new TestSubscriber(); @@ -815,7 +815,7 @@ public void run() { @Test(timeout = 10000) public void subscriberCancelOfferRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorProcessor pp = BehaviorProcessor.create(); final TestSubscriber ts = pp.test(1); @@ -824,7 +824,7 @@ public void subscriberCancelOfferRace() { @Override public void run() { for (int i = 0; i < 2; i++) { - while (!pp.offer(i)) ; + while (!pp.offer(i)) { } } } }; diff --git a/src/test/java/io/reactivex/processors/PublishProcessorTest.java b/src/test/java/io/reactivex/processors/PublishProcessorTest.java index 42f43bb1a6..ae0248a8c5 100644 --- a/src/test/java/io/reactivex/processors/PublishProcessorTest.java +++ b/src/test/java/io/reactivex/processors/PublishProcessorTest.java @@ -576,7 +576,7 @@ public void onComplete() { @Test public void terminateRace() throws Exception { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); TestSubscriber ts = pp.test(); @@ -588,7 +588,7 @@ public void run() { } }; - TestHelper.race(task, task, Schedulers.io()); + TestHelper.race(task, task); ts .awaitDone(5, TimeUnit.SECONDS) @@ -599,7 +599,7 @@ public void run() { @Test public void addRemoveRance() throws Exception { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestSubscriber ts = pp.test(); @@ -617,7 +617,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.io()); + TestHelper.race(r1, r2); } } @@ -680,7 +680,7 @@ public void run() { @Test(timeout = 10000) public void subscriberCancelOfferRace() { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); final TestSubscriber ts = pp.test(1); @@ -689,7 +689,7 @@ public void subscriberCancelOfferRace() { @Override public void run() { for (int i = 0; i < 2; i++) { - while (!pp.offer(i)) ; + while (!pp.offer(i)) { } } } }; diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index e42f801f4a..cd8f6de326 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -1060,7 +1060,7 @@ public void capacityHint() { @Test public void subscribeCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber ts = new TestSubscriber(); final ReplayProcessor rp = ReplayProcessor.create(); @@ -1079,7 +1079,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @@ -1097,7 +1097,7 @@ public void subscribeAfterDone() { @Test public void subscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ReplayProcessor rp = ReplayProcessor.create(); Runnable r1 = new Runnable() { @@ -1107,7 +1107,7 @@ public void run() { } }; - TestHelper.race(r1, r1, Schedulers.single()); + TestHelper.race(r1, r1); } } @@ -1126,7 +1126,7 @@ public void cancelUpfront() { @Test public void cancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ReplayProcessor rp = ReplayProcessor.create(); final TestSubscriber ts1 = rp.test(); @@ -1146,7 +1146,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); assertFalse(rp.hasSubscribers()); } @@ -1182,7 +1182,7 @@ public void sizeAndTimeBoundReplayError() { @Test public void replayRequestRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ReplayProcessor rp = ReplayProcessor.createWithTimeAndSize(1, TimeUnit.DAYS, Schedulers.single(), 2); final TestSubscriber ts = rp.test(0L); @@ -1201,7 +1201,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @@ -1315,11 +1315,9 @@ public void timedNoOutdatedData() { source.test().assertResult(); } - int raceLoop = 10000; - @Test public void unboundedRequestCompleteRace() { - for (int i = 0; i < raceLoop; i++) { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { final ReplayProcessor source = ReplayProcessor.create(); final TestSubscriber ts = source.test(0); @@ -1346,7 +1344,7 @@ public void run() { @Test public void sizeRequestCompleteRace() { - for (int i = 0; i < raceLoop; i++) { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { final ReplayProcessor source = ReplayProcessor.createWithSize(10); final TestSubscriber ts = source.test(0); @@ -1373,7 +1371,7 @@ public void run() { @Test public void timedRequestCompleteRace() { - for (int i = 0; i < raceLoop; i++) { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { final ReplayProcessor source = ReplayProcessor.createWithTime(2, TimeUnit.HOURS, Schedulers.single()); final TestSubscriber ts = source.test(0); @@ -1400,7 +1398,7 @@ public void run() { @Test public void timeAndSizeRequestCompleteRace() { - for (int i = 0; i < raceLoop; i++) { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { final ReplayProcessor source = ReplayProcessor.createWithTimeAndSize(2, TimeUnit.HOURS, Schedulers.single(), 100); final TestSubscriber ts = source.test(0); diff --git a/src/test/java/io/reactivex/processors/SerializedProcessorTest.java b/src/test/java/io/reactivex/processors/SerializedProcessorTest.java index db60b5c793..790419220e 100644 --- a/src/test/java/io/reactivex/processors/SerializedProcessorTest.java +++ b/src/test/java/io/reactivex/processors/SerializedProcessorTest.java @@ -23,7 +23,6 @@ import io.reactivex.exceptions.TestException; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; public class SerializedProcessorTest { @@ -432,7 +431,7 @@ public void normal() { @Test public void onNextOnNextRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FlowableProcessor s = PublishProcessor.create().toSerialized(); TestSubscriber ts = s.test(); @@ -451,7 +450,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertSubscribed().assertNoErrors().assertNotComplete() .assertValueSet(Arrays.asList(1, 2)); @@ -460,7 +459,7 @@ public void run() { @Test public void onNextOnErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FlowableProcessor s = PublishProcessor.create().toSerialized(); TestSubscriber ts = s.test(); @@ -481,7 +480,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertError(ex).assertNotComplete(); @@ -493,7 +492,7 @@ public void run() { @Test public void onNextOnCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FlowableProcessor s = PublishProcessor.create().toSerialized(); TestSubscriber ts = s.test(); @@ -512,7 +511,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertComplete().assertNoErrors(); @@ -524,7 +523,7 @@ public void run() { @Test public void onNextOnSubscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FlowableProcessor s = PublishProcessor.create().toSerialized(); TestSubscriber ts = s.test(); @@ -545,7 +544,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertValue(1).assertNotComplete().assertNoErrors(); } @@ -553,7 +552,7 @@ public void run() { @Test public void onCompleteOnSubscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FlowableProcessor s = PublishProcessor.create().toSerialized(); TestSubscriber ts = s.test(); @@ -574,7 +573,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertResult(); } @@ -582,7 +581,7 @@ public void run() { @Test public void onCompleteOnCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FlowableProcessor s = PublishProcessor.create().toSerialized(); TestSubscriber ts = s.test(); @@ -601,7 +600,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertResult(); } @@ -609,7 +608,7 @@ public void run() { @Test public void onErrorOnErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FlowableProcessor s = PublishProcessor.create().toSerialized(); TestSubscriber ts = s.test(); @@ -632,7 +631,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertFailure(TestException.class); @@ -645,7 +644,7 @@ public void run() { @Test public void onSubscribeOnSubscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final FlowableProcessor s = PublishProcessor.create().toSerialized(); TestSubscriber ts = s.test(); @@ -667,7 +666,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertEmpty(); } diff --git a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java index 5b3ab53ed4..fc19064fdd 100644 --- a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java @@ -13,22 +13,20 @@ package io.reactivex.processors; -import io.reactivex.Observable; -import io.reactivex.TestHelper; +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.Test; + +import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; import io.reactivex.internal.fuseable.QueueSubscription; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; -import io.reactivex.subscribers.SubscriberFusion; -import io.reactivex.subscribers.TestSubscriber; -import org.junit.Test; - -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.junit.Assert.*; +import io.reactivex.subscribers.*; public class UnicastProcessorTest extends FlowableProcessorTest { @@ -188,7 +186,7 @@ public void zeroCapacityHint() { @Test public void completeCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final int[] calls = { 0 }; final UnicastProcessor up = UnicastProcessor.create(100, new Runnable() { @Override @@ -213,7 +211,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); assertEquals(1, calls[0]); } @@ -296,7 +294,7 @@ public void multiSubscriber() { @Test public void fusedDrainCancel() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final UnicastProcessor p = UnicastProcessor.create(); final TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); @@ -317,7 +315,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } } diff --git a/src/test/java/io/reactivex/schedulers/SchedulerTest.java b/src/test/java/io/reactivex/schedulers/SchedulerTest.java index 714482e5cb..bee0b3935b 100644 --- a/src/test/java/io/reactivex/schedulers/SchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/SchedulerTest.java @@ -182,7 +182,7 @@ public void run() { public void periodicDirectTaskRace() { final TestScheduler scheduler = new TestScheduler(); - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Disposable d = scheduler.schedulePeriodicallyDirect(Functions.EMPTY_RUNNABLE, 1, 1, TimeUnit.MILLISECONDS); Runnable r1 = new Runnable() { @@ -199,7 +199,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.io()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java index 04735b2c68..b1fbf0efe9 100644 --- a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java @@ -29,7 +29,6 @@ import io.reactivex.functions.Consumer; import io.reactivex.internal.fuseable.QueueSubscription; import io.reactivex.observers.*; -import io.reactivex.schedulers.Schedulers; public class AsyncSubjectTest extends SubjectTest { @@ -464,7 +463,7 @@ public void cancelUpfront() { public void cancelRace() { AsyncSubject p = AsyncSubject.create(); - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestObserver ts1 = p.test(); final TestObserver ts2 = p.test(); @@ -482,14 +481,14 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @Test public void onErrorCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AsyncSubject p = AsyncSubject.create(); final TestObserver ts1 = p.test(); @@ -510,7 +509,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (ts1.errorCount() != 0) { ts1.assertFailure(TestException.class); diff --git a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java index 2e2cc2f05e..cc0b6ae05d 100644 --- a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java @@ -630,7 +630,7 @@ public void cancelOnArrival2() { @Test public void addRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorSubject p = BehaviorSubject.create(); final TestObserver ts = p.test(); @@ -649,14 +649,14 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void subscribeOnNextRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorSubject p = BehaviorSubject.createDefault((Object)1); final TestObserver[] ts = { null }; @@ -675,7 +675,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); if (ts[0].valueCount() == 1) { ts[0].assertValue(2).assertNoErrors().assertNotComplete(); @@ -718,7 +718,7 @@ public void onComplete() { @Test public void completeSubscribeRace() throws Exception { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorSubject p = BehaviorSubject.create(); final TestObserver ts = new TestObserver(); @@ -745,7 +745,7 @@ public void run() { @Test public void errorSubscribeRace() throws Exception { - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorSubject p = BehaviorSubject.create(); final TestObserver ts = new TestObserver(); diff --git a/src/test/java/io/reactivex/subjects/CompletableSubjectTest.java b/src/test/java/io/reactivex/subjects/CompletableSubjectTest.java index b569457c16..56be25b2b3 100644 --- a/src/test/java/io/reactivex/subjects/CompletableSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/CompletableSubjectTest.java @@ -24,7 +24,6 @@ import io.reactivex.disposables.*; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; public class CompletableSubjectTest { @@ -205,7 +204,7 @@ public void onSubscribeDispose() { @Test public void addRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final CompletableSubject cs = CompletableSubject.create(); final TestObserver to = cs.test(); @@ -223,7 +222,7 @@ public void run() { to.cancel(); } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } } diff --git a/src/test/java/io/reactivex/subjects/MaybeSubjectTest.java b/src/test/java/io/reactivex/subjects/MaybeSubjectTest.java index c7b8b4f4c5..b2a62c894b 100644 --- a/src/test/java/io/reactivex/subjects/MaybeSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/MaybeSubjectTest.java @@ -24,7 +24,6 @@ import io.reactivex.disposables.*; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; public class MaybeSubjectTest { @@ -251,7 +250,7 @@ public void onSubscribeDispose() { @Test public void addRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final MaybeSubject ms = MaybeSubject.create(); final TestObserver to = ms.test(); @@ -269,7 +268,7 @@ public void run() { to.cancel(); } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } } diff --git a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java index 459f075f96..bfe9f7c02b 100644 --- a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java @@ -14,6 +14,7 @@ package io.reactivex.subjects; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.ArrayList; @@ -28,7 +29,6 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.observers.*; -import io.reactivex.schedulers.Schedulers; public class PublishSubjectTest extends SubjectTest { @@ -563,7 +563,7 @@ public void onComplete() { @Test public void terminateRace() throws Exception { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject pp = PublishSubject.create(); TestObserver ts = pp.test(); @@ -575,7 +575,7 @@ public void run() { } }; - TestHelper.race(task, task, Schedulers.io()); + TestHelper.race(task, task); ts .awaitDone(5, TimeUnit.SECONDS) @@ -586,7 +586,7 @@ public void run() { @Test public void addRemoveRance() throws Exception { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject pp = PublishSubject.create(); final TestObserver ts = pp.test(); @@ -604,14 +604,14 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.io()); + TestHelper.race(r1, r2); } } @Test public void addTerminateRance() throws Exception { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject pp = PublishSubject.create(); Runnable r1 = new Runnable() { @@ -627,14 +627,14 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.io()); + TestHelper.race(r1, r2); } } @Test public void addCompleteRance() throws Exception { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject pp = PublishSubject.create(); final TestObserver ts = new TestObserver(); @@ -652,7 +652,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.io()); + TestHelper.race(r1, r2); ts.awaitDone(5, TimeUnit.SECONDS) .assertResult(); diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java index 2739b24aae..7331edf615 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java @@ -970,7 +970,7 @@ public void capacityHint() { @Test public void subscribeCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestObserver ts = new TestObserver(); final ReplaySubject rp = ReplaySubject.create(); @@ -989,7 +989,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } @@ -1007,7 +1007,7 @@ public void subscribeAfterDone() { @Test public void subscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ReplaySubject rp = ReplaySubject.create(); Runnable r1 = new Runnable() { @@ -1017,7 +1017,7 @@ public void run() { } }; - TestHelper.race(r1, r1, Schedulers.single()); + TestHelper.race(r1, r1); } } @@ -1036,7 +1036,7 @@ public void cancelUpfront() { @Test public void cancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ReplaySubject rp = ReplaySubject.create(); final TestObserver ts1 = rp.test(); @@ -1056,7 +1056,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); assertFalse(rp.hasObservers()); } diff --git a/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java b/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java index 7328c494ca..523e375ea0 100644 --- a/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java @@ -25,7 +25,6 @@ import io.reactivex.exceptions.TestException; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; public class SerializedSubjectTest { @@ -433,7 +432,7 @@ public void normal() { @Test public void onNextOnNextRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); TestObserver ts = s.test(); @@ -452,7 +451,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertSubscribed().assertNoErrors().assertNotComplete() .assertValueSet(Arrays.asList(1, 2)); @@ -461,7 +460,7 @@ public void run() { @Test public void onNextOnErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); TestObserver ts = s.test(); @@ -482,7 +481,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertError(ex).assertNotComplete(); @@ -494,7 +493,7 @@ public void run() { @Test public void onNextOnCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); TestObserver ts = s.test(); @@ -513,7 +512,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertComplete().assertNoErrors(); @@ -525,7 +524,7 @@ public void run() { @Test public void onNextOnSubscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); TestObserver ts = s.test(); @@ -546,7 +545,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertValue(1).assertNotComplete().assertNoErrors(); } @@ -554,7 +553,7 @@ public void run() { @Test public void onCompleteOnSubscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); TestObserver ts = s.test(); @@ -575,7 +574,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertResult(); } @@ -583,7 +582,7 @@ public void run() { @Test public void onCompleteOnCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); TestObserver ts = s.test(); @@ -602,7 +601,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertResult(); } @@ -610,7 +609,7 @@ public void run() { @Test public void onErrorOnErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); TestObserver ts = s.test(); @@ -633,7 +632,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertFailure(TestException.class); @@ -646,7 +645,7 @@ public void run() { @Test public void onSubscribeOnSubscribeRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); TestObserver ts = s.test(); @@ -668,7 +667,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.assertEmpty(); } diff --git a/src/test/java/io/reactivex/subjects/SingleSubjectTest.java b/src/test/java/io/reactivex/subjects/SingleSubjectTest.java index 19d6ab6a64..cdba1fe5c9 100644 --- a/src/test/java/io/reactivex/subjects/SingleSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/SingleSubjectTest.java @@ -24,7 +24,6 @@ import io.reactivex.disposables.*; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; public class SingleSubjectTest { @@ -225,7 +224,7 @@ public void onSubscribeDispose() { @Test public void addRemoveRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final SingleSubject ss = SingleSubject.create(); final TestObserver to = ss.test(); @@ -243,7 +242,7 @@ public void run() { to.cancel(); } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } } diff --git a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java index 12f838ee99..ec8f678d72 100644 --- a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java @@ -14,6 +14,7 @@ package io.reactivex.subjects; import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @@ -26,8 +27,6 @@ import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; -import static org.mockito.Mockito.mock; public class UnicastSubjectTest extends SubjectTest { @@ -223,7 +222,7 @@ public void zeroCapacityHint() { @Test public void completeCancelRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final int[] calls = { 0 }; final UnicastSubject up = UnicastSubject.create(100, new Runnable() { @Override @@ -248,7 +247,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); assertEquals(1, calls[0]); } @@ -331,7 +330,7 @@ public void multiSubscriber() { @Test public void fusedDrainCancel() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final UnicastSubject p = UnicastSubject.create(); final TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); @@ -352,7 +351,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); } } diff --git a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java index 3ba6a7252e..e70777edc5 100644 --- a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java @@ -1015,7 +1015,7 @@ public void dispose() { @Test public void onCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestSubscriber ts = new TestSubscriber(); final SerializedSubscriber so = new SerializedSubscriber(ts); @@ -1031,7 +1031,7 @@ public void run() { } }; - TestHelper.race(r, r, Schedulers.single()); + TestHelper.race(r, r); ts.awaitDone(5, TimeUnit.SECONDS) .assertResult(); @@ -1041,7 +1041,7 @@ public void run() { @Test public void onNextOnCompleteRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestSubscriber ts = new TestSubscriber(); final SerializedSubscriber so = new SerializedSubscriber(ts); @@ -1064,7 +1064,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.awaitDone(5, TimeUnit.SECONDS) .assertNoErrors() @@ -1077,7 +1077,7 @@ public void run() { @Test public void onNextOnErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestSubscriber ts = new TestSubscriber(); final SerializedSubscriber so = new SerializedSubscriber(ts); @@ -1102,7 +1102,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.awaitDone(5, TimeUnit.SECONDS) .assertError(ex) @@ -1115,7 +1115,7 @@ public void run() { @Test public void onNextOnErrorRaceDelayError() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestSubscriber ts = new TestSubscriber(); final SerializedSubscriber so = new SerializedSubscriber(ts, true); @@ -1140,7 +1140,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.awaitDone(5, TimeUnit.SECONDS) .assertError(ex) @@ -1177,7 +1177,7 @@ public void startOnce() { @Test public void onCompleteOnErrorRace() { - for (int i = 0; i < 500; i++) { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { TestSubscriber ts = new TestSubscriber(); final SerializedSubscriber so = new SerializedSubscriber(ts); @@ -1202,7 +1202,7 @@ public void run() { } }; - TestHelper.race(r1, r2, Schedulers.single()); + TestHelper.race(r1, r2); ts.awaitDone(5, TimeUnit.SECONDS); From 4227a5903f559b56f1f1e6bc1c992e7d9572a68d Mon Sep 17 00:00:00 2001 From: Vladislav Zhukov Date: Sun, 18 Feb 2018 20:30:44 +0300 Subject: [PATCH 101/417] remove unnecessary comment from Observable.timeInterval(TimeUnit) (#5858) --- src/main/java/io/reactivex/Observable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index f2db8f5e67..0f80e17f98 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -12337,7 +12337,7 @@ public final Observable> timeInterval(Scheduler scheduler) { * @see ReactiveX operators documentation: TimeInterval */ @CheckReturnValue - @SchedulerSupport(SchedulerSupport.NONE) // Trampoline scheduler is only used for creating timestamps. + @SchedulerSupport(SchedulerSupport.NONE) public final Observable> timeInterval(TimeUnit unit) { return timeInterval(unit, Schedulers.computation()); } From 7ede8ee2a26f4d842b90e1e331c5812d64911eaa Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 19 Feb 2018 21:18:41 +0100 Subject: [PATCH 102/417] 2.x: Add efficient mergeWith(Single|Maybe|Completable) overloads. (#5847) * 2.x: Add efficient mergeWith(Single|Maybe|Completable) overloads. * Compact tests, use named constants --- src/main/java/io/reactivex/Flowable.java | 85 +++- src/main/java/io/reactivex/Observable.java | 71 +++ .../FlowableMergeWithCompletable.java | 151 +++++++ .../flowable/FlowableMergeWithMaybe.java | 359 ++++++++++++++++ .../flowable/FlowableMergeWithSingle.java | 349 +++++++++++++++ .../ObservableMergeWithCompletable.java | 145 +++++++ .../observable/ObservableMergeWithMaybe.java | 266 ++++++++++++ .../observable/ObservableMergeWithSingle.java | 257 +++++++++++ .../io/reactivex/InternalWrongNaming.java | 5 +- .../reactivex/flowable/FlowableNullTests.java | 2 +- .../FlowableMergeWithCompletableTest.java | 139 ++++++ .../flowable/FlowableMergeWithMaybeTest.java | 404 ++++++++++++++++++ .../flowable/FlowableMergeWithSingleTest.java | 400 +++++++++++++++++ .../ObservableMergeWithCompletableTest.java | 138 ++++++ .../ObservableMergeWithMaybeTest.java | 275 ++++++++++++ .../ObservableMergeWithSingleTest.java | 266 ++++++++++++ .../observable/ObservableNullTests.java | 2 +- .../tck/MergeWithCompletableTckTest.java | 31 ++ .../tck/MergeWithMaybeEmptyTckTest.java | 31 ++ .../reactivex/tck/MergeWithMaybeTckTest.java | 35 ++ .../reactivex/tck/MergeWithSingleTckTest.java | 34 ++ 21 files changed, 3441 insertions(+), 4 deletions(-) create mode 100644 src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java create mode 100644 src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java create mode 100644 src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java create mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java create mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java create mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletableTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingleTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletableTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java create mode 100644 src/test/java/io/reactivex/tck/MergeWithCompletableTckTest.java create mode 100644 src/test/java/io/reactivex/tck/MergeWithMaybeEmptyTckTest.java create mode 100644 src/test/java/io/reactivex/tck/MergeWithMaybeTckTest.java create mode 100644 src/test/java/io/reactivex/tck/MergeWithSingleTckTest.java diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index c0e51f365f..f906f89c20 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -5771,7 +5771,7 @@ public final Future toFuture() { } /** - * Runs the source observable to a terminal event, ignoring any values and rethrowing any exception. + * Runs the source Flowable to a terminal event, ignoring any values and rethrowing any exception. *
                *
                Backpressure:
                *
                The operator consumes the source {@code Flowable} in an unbounded manner @@ -10112,6 +10112,89 @@ public final Flowable mergeWith(Publisher other) { return merge(this, other); } + /** + * Merges the sequence of items of this Flowable with the success value of the other SingleSource. + *

                + * + *

                + * The success value of the other {@code SingleSource} can get interleaved at any point of this + * {@code Flowable} sequence. + *

                + *
                Backpressure:
                + *
                The operator honors backpressure from downstream and ensures the success item from the + * {@code SingleSource} is emitted only when there is a downstream demand.
                + *
                Scheduler:
                + *
                {@code mergeWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param other the {@code SingleSource} whose success value to merge with + * @return the new Flowable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable mergeWith(@NonNull SingleSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new FlowableMergeWithSingle(this, other)); + } + + /** + * Merges the sequence of items of this Flowable with the success value of the other MaybeSource + * or waits both to complete normally if the MaybeSource is empty. + *

                + * + *

                + * The success value of the other {@code MaybeSource} can get interleaved at any point of this + * {@code Flowable} sequence. + *

                + *
                Backpressure:
                + *
                The operator honors backpressure from downstream and ensures the success item from the + * {@code MaybeSource} is emitted only when there is a downstream demand.
                + *
                Scheduler:
                + *
                {@code mergeWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param other the {@code MaybeSource} which provides a success value to merge with or completes + * @return the new Flowable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable mergeWith(@NonNull MaybeSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new FlowableMergeWithMaybe(this, other)); + } + + /** + * Relays the items of this Flowable and completes only when the other CompletableSource completes + * as well. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s backpressure + * behavior.
                + *
                Scheduler:
                + *
                {@code mergeWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param other the {@code CompletableSource} to await for completion + * @return the new Flowable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.PASS_THROUGH) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable mergeWith(@NonNull CompletableSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new FlowableMergeWithCompletable(this, other)); + } + /** * Modifies a Publisher to perform its emissions and notifications on a specified {@link Scheduler}, * asynchronously with a bounded buffer of {@link #bufferSize()} slots. diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 0f80e17f98..ebd48d6537 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -8991,6 +8991,77 @@ public final Observable mergeWith(ObservableSource other) { return merge(this, other); } + /** + * Merges the sequence of items of this Observable with the success value of the other SingleSource. + *

                + * + *

                + * The success value of the other {@code SingleSource} can get interleaved at any point of this + * {@code Observable} sequence. + *

                + *
                Scheduler:
                + *
                {@code mergeWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param other the {@code SingleSource} whose success value to merge with + * @return the new Observable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable mergeWith(@NonNull SingleSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new ObservableMergeWithSingle(this, other)); + } + + /** + * Merges the sequence of items of this Observable with the success value of the other MaybeSource + * or waits both to complete normally if the MaybeSource is empty. + *

                + * + *

                + * The success value of the other {@code MaybeSource} can get interleaved at any point of this + * {@code Observable} sequence. + *

                + *
                Scheduler:
                + *
                {@code mergeWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param other the {@code MaybeSource} which provides a success value to merge with or completes + * @return the new Observable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable mergeWith(@NonNull MaybeSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new ObservableMergeWithMaybe(this, other)); + } + + /** + * Relays the items of this Observable and completes only when the other CompletableSource completes + * as well. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code mergeWith} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param other the {@code CompletableSource} to await for completion + * @return the new Observable instance + * @since 2.1.10 - experimental + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable mergeWith(@NonNull CompletableSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + return RxJavaPlugins.onAssembly(new ObservableMergeWithCompletable(this, other)); + } + /** * Modifies an ObservableSource to perform its emissions and notifications on a specified {@link Scheduler}, * asynchronously with an unbounded buffer with {@link Flowable#bufferSize()} "island size". diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java new file mode 100644 index 0000000000..cfdd0974f3 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java @@ -0,0 +1,151 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.*; + +/** + * Merges a Flowable and a Completable by emitting the items of the Flowable and waiting until + * both the Flowable and Completable complete normally. + * + * @param the element type of the Flowable + * @since 2.1.10 - experimental + */ +public final class FlowableMergeWithCompletable extends AbstractFlowableWithUpstream { + + final CompletableSource other; + + public FlowableMergeWithCompletable(Flowable source, CompletableSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Subscriber observer) { + MergeWithSubscriber parent = new MergeWithSubscriber(observer); + observer.onSubscribe(parent); + source.subscribe(parent); + other.subscribe(parent.otherObserver); + } + + static final class MergeWithSubscriber extends AtomicInteger + implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = -4592979584110982903L; + + final Subscriber actual; + + final AtomicReference mainSubscription; + + final OtherObserver otherObserver; + + final AtomicThrowable error; + + final AtomicLong requested; + + volatile boolean mainDone; + + volatile boolean otherDone; + + MergeWithSubscriber(Subscriber actual) { + this.actual = actual; + this.mainSubscription = new AtomicReference(); + this.otherObserver = new OtherObserver(this); + this.error = new AtomicThrowable(); + this.requested = new AtomicLong(); + } + + @Override + public void onSubscribe(Subscription d) { + SubscriptionHelper.deferredSetOnce(mainSubscription, requested, d); + } + + @Override + public void onNext(T t) { + HalfSerializer.onNext(actual, t, this, error); + } + + @Override + public void onError(Throwable ex) { + SubscriptionHelper.cancel(mainSubscription); + HalfSerializer.onError(actual, ex, this, error); + } + + @Override + public void onComplete() { + mainDone = true; + if (otherDone) { + HalfSerializer.onComplete(actual, this, error); + } + } + + @Override + public void request(long n) { + SubscriptionHelper.deferredRequest(mainSubscription, requested, n); + } + + @Override + public void cancel() { + SubscriptionHelper.cancel(mainSubscription); + DisposableHelper.dispose(otherObserver); + } + + void otherError(Throwable ex) { + SubscriptionHelper.cancel(mainSubscription); + HalfSerializer.onError(actual, ex, this, error); + } + + void otherComplete() { + otherDone = true; + if (mainDone) { + HalfSerializer.onComplete(actual, this, error); + } + } + + static final class OtherObserver extends AtomicReference + implements CompletableObserver { + + private static final long serialVersionUID = -2935427570954647017L; + + final MergeWithSubscriber parent; + + OtherObserver(MergeWithSubscriber parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onError(Throwable e) { + parent.otherError(e); + } + + @Override + public void onComplete() { + parent.otherComplete(); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java new file mode 100644 index 0000000000..68c8e2c8f5 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java @@ -0,0 +1,359 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Merges an Observable and a Maybe by emitting the items of the Observable and the success + * value of the Maybe and waiting until both the Observable and Maybe terminate normally. + * + * @param the element type of the Observable + * @since 2.1.10 - experimental + */ +public final class FlowableMergeWithMaybe extends AbstractFlowableWithUpstream { + + final MaybeSource other; + + public FlowableMergeWithMaybe(Flowable source, MaybeSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Subscriber observer) { + MergeWithObserver parent = new MergeWithObserver(observer); + observer.onSubscribe(parent); + source.subscribe(parent); + other.subscribe(parent.otherObserver); + } + + static final class MergeWithObserver extends AtomicInteger + implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = -4592979584110982903L; + + final Subscriber actual; + + final AtomicReference mainSubscription; + + final OtherObserver otherObserver; + + final AtomicThrowable error; + + final AtomicLong requested; + + final int prefetch; + + final int limit; + + volatile SimplePlainQueue queue; + + T singleItem; + + volatile boolean cancelled; + + volatile boolean mainDone; + + volatile int otherState; + + long emitted; + + int consumed; + + static final int OTHER_STATE_HAS_VALUE = 1; + + static final int OTHER_STATE_CONSUMED_OR_EMPTY = 2; + + MergeWithObserver(Subscriber actual) { + this.actual = actual; + this.mainSubscription = new AtomicReference(); + this.otherObserver = new OtherObserver(this); + this.error = new AtomicThrowable(); + this.requested = new AtomicLong(); + this.prefetch = bufferSize(); + this.limit = prefetch - (prefetch >> 2); + } + + @Override + public void onSubscribe(Subscription d) { + if (SubscriptionHelper.setOnce(mainSubscription, d)) { + d.request(prefetch); + } + } + + @Override + public void onNext(T t) { + if (compareAndSet(0, 1)) { + long e = emitted; + if (requested.get() != e) { + SimplePlainQueue q = queue; + if (q == null || q.isEmpty()) { + + emitted = e + 1; + actual.onNext(t); + + int c = consumed + 1; + if (c == limit) { + consumed = 0; + mainSubscription.get().request(c); + } else { + consumed = c; + } + } else { + q.offer(t); + } + } else { + SimplePlainQueue q = getOrCreateQueue(); + q.offer(t); + } + if (decrementAndGet() == 0) { + return; + } + } else { + SimplePlainQueue q = getOrCreateQueue(); + q.offer(t); + if (getAndIncrement() != 0) { + return; + } + } + drainLoop(); + } + + @Override + public void onError(Throwable ex) { + if (error.addThrowable(ex)) { + SubscriptionHelper.cancel(mainSubscription); + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + @Override + public void onComplete() { + mainDone = true; + drain(); + } + + @Override + public void request(long n) { + BackpressureHelper.add(requested, n); + drain(); + } + + @Override + public void cancel() { + cancelled = true; + SubscriptionHelper.cancel(mainSubscription); + DisposableHelper.dispose(otherObserver); + if (getAndIncrement() == 0) { + queue = null; + singleItem = null; + } + } + + void otherSuccess(T value) { + if (compareAndSet(0, 1)) { + long e = emitted; + if (requested.get() != e) { + + emitted = e + 1; + actual.onNext(value); + otherState = OTHER_STATE_CONSUMED_OR_EMPTY; + } else { + singleItem = value; + otherState = OTHER_STATE_HAS_VALUE; + if (decrementAndGet() == 0) { + return; + } + } + } else { + singleItem = value; + otherState = OTHER_STATE_HAS_VALUE; + if (getAndIncrement() != 0) { + return; + } + } + drainLoop(); + } + + void otherError(Throwable ex) { + if (error.addThrowable(ex)) { + SubscriptionHelper.cancel(mainSubscription); + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + void otherComplete() { + otherState = OTHER_STATE_CONSUMED_OR_EMPTY; + drain(); + } + + SimplePlainQueue getOrCreateQueue() { + SimplePlainQueue q = queue; + if (q == null) { + q = new SpscArrayQueue(bufferSize()); + queue = q; + } + return q; + } + + void drain() { + if (getAndIncrement() == 0) { + drainLoop(); + } + } + + void drainLoop() { + Subscriber actual = this.actual; + int missed = 1; + long e = emitted; + int c = consumed; + int lim = limit; + for (;;) { + + long r = requested.get(); + + while (e != r) { + if (cancelled) { + singleItem = null; + queue = null; + return; + } + + if (error.get() != null) { + singleItem = null; + queue = null; + actual.onError(error.terminate()); + return; + } + + int os = otherState; + if (os == OTHER_STATE_HAS_VALUE) { + T v = singleItem; + singleItem = null; + otherState = OTHER_STATE_CONSUMED_OR_EMPTY; + os = OTHER_STATE_CONSUMED_OR_EMPTY; + actual.onNext(v); + + e++; + continue; + } + + boolean d = mainDone; + SimplePlainQueue q = queue; + T v = q != null ? q.poll() : null; + boolean empty = v == null; + + if (d && empty && os == OTHER_STATE_CONSUMED_OR_EMPTY) { + queue = null; + actual.onComplete(); + return; + } + + if (empty) { + break; + } + + actual.onNext(v); + + e++; + + if (++c == lim) { + c = 0; + mainSubscription.get().request(lim); + } + } + + if (e == r) { + if (cancelled) { + singleItem = null; + queue = null; + return; + } + + if (error.get() != null) { + singleItem = null; + queue = null; + actual.onError(error.terminate()); + return; + } + + boolean d = mainDone; + SimplePlainQueue q = queue; + boolean empty = q == null || q.isEmpty(); + + if (d && empty && otherState == 2) { + queue = null; + actual.onComplete(); + return; + } + } + + emitted = e; + consumed = c; + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class OtherObserver extends AtomicReference + implements MaybeObserver { + + private static final long serialVersionUID = -2935427570954647017L; + + final MergeWithObserver parent; + + OtherObserver(MergeWithObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onSuccess(T t) { + parent.otherSuccess(t); + } + + @Override + public void onError(Throwable e) { + parent.otherError(e); + } + + @Override + public void onComplete() { + parent.otherComplete(); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java new file mode 100644 index 0000000000..b14c5c9b22 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java @@ -0,0 +1,349 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Merges an Observable and a Maybe by emitting the items of the Observable and the success + * value of the Maybe and waiting until both the Observable and Maybe terminate normally. + * + * @param the element type of the Observable + * @since 2.1.10 - experimental + */ +public final class FlowableMergeWithSingle extends AbstractFlowableWithUpstream { + + final SingleSource other; + + public FlowableMergeWithSingle(Flowable source, SingleSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Subscriber observer) { + MergeWithObserver parent = new MergeWithObserver(observer); + observer.onSubscribe(parent); + source.subscribe(parent); + other.subscribe(parent.otherObserver); + } + + static final class MergeWithObserver extends AtomicInteger + implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = -4592979584110982903L; + + final Subscriber actual; + + final AtomicReference mainSubscription; + + final OtherObserver otherObserver; + + final AtomicThrowable error; + + final AtomicLong requested; + + final int prefetch; + + final int limit; + + volatile SimplePlainQueue queue; + + T singleItem; + + volatile boolean cancelled; + + volatile boolean mainDone; + + volatile int otherState; + + long emitted; + + int consumed; + + static final int OTHER_STATE_HAS_VALUE = 1; + + static final int OTHER_STATE_CONSUMED_OR_EMPTY = 2; + + MergeWithObserver(Subscriber actual) { + this.actual = actual; + this.mainSubscription = new AtomicReference(); + this.otherObserver = new OtherObserver(this); + this.error = new AtomicThrowable(); + this.requested = new AtomicLong(); + this.prefetch = bufferSize(); + this.limit = prefetch - (prefetch >> 2); + } + + @Override + public void onSubscribe(Subscription d) { + if (SubscriptionHelper.setOnce(mainSubscription, d)) { + d.request(prefetch); + } + } + + @Override + public void onNext(T t) { + if (compareAndSet(0, 1)) { + long e = emitted; + if (requested.get() != e) { + SimplePlainQueue q = queue; + if (q == null || q.isEmpty()) { + + emitted = e + 1; + actual.onNext(t); + + int c = consumed + 1; + if (c == limit) { + consumed = 0; + mainSubscription.get().request(c); + } else { + consumed = c; + } + } else { + q.offer(t); + } + } else { + SimplePlainQueue q = getOrCreateQueue(); + q.offer(t); + } + if (decrementAndGet() == 0) { + return; + } + } else { + SimplePlainQueue q = getOrCreateQueue(); + q.offer(t); + if (getAndIncrement() != 0) { + return; + } + } + drainLoop(); + } + + @Override + public void onError(Throwable ex) { + if (error.addThrowable(ex)) { + SubscriptionHelper.cancel(mainSubscription); + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + @Override + public void onComplete() { + mainDone = true; + drain(); + } + + @Override + public void request(long n) { + BackpressureHelper.add(requested, n); + drain(); + } + + @Override + public void cancel() { + cancelled = true; + SubscriptionHelper.cancel(mainSubscription); + DisposableHelper.dispose(otherObserver); + if (getAndIncrement() == 0) { + queue = null; + singleItem = null; + } + } + + void otherSuccess(T value) { + if (compareAndSet(0, 1)) { + long e = emitted; + if (requested.get() != e) { + + emitted = e + 1; + actual.onNext(value); + otherState = OTHER_STATE_CONSUMED_OR_EMPTY; + } else { + singleItem = value; + otherState = OTHER_STATE_HAS_VALUE; + if (decrementAndGet() == 0) { + return; + } + } + } else { + singleItem = value; + otherState = OTHER_STATE_HAS_VALUE; + if (getAndIncrement() != 0) { + return; + } + } + drainLoop(); + } + + void otherError(Throwable ex) { + if (error.addThrowable(ex)) { + SubscriptionHelper.cancel(mainSubscription); + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + SimplePlainQueue getOrCreateQueue() { + SimplePlainQueue q = queue; + if (q == null) { + q = new SpscArrayQueue(bufferSize()); + queue = q; + } + return q; + } + + void drain() { + if (getAndIncrement() == 0) { + drainLoop(); + } + } + + void drainLoop() { + Subscriber actual = this.actual; + int missed = 1; + long e = emitted; + int c = consumed; + int lim = limit; + for (;;) { + + long r = requested.get(); + + while (e != r) { + if (cancelled) { + singleItem = null; + queue = null; + return; + } + + if (error.get() != null) { + singleItem = null; + queue = null; + actual.onError(error.terminate()); + return; + } + + int os = otherState; + if (os == OTHER_STATE_HAS_VALUE) { + T v = singleItem; + singleItem = null; + otherState = OTHER_STATE_CONSUMED_OR_EMPTY; + os = OTHER_STATE_CONSUMED_OR_EMPTY; + actual.onNext(v); + + e++; + continue; + } + + boolean d = mainDone; + SimplePlainQueue q = queue; + T v = q != null ? q.poll() : null; + boolean empty = v == null; + + if (d && empty && os == OTHER_STATE_CONSUMED_OR_EMPTY) { + queue = null; + actual.onComplete(); + return; + } + + if (empty) { + break; + } + + actual.onNext(v); + + e++; + + if (++c == lim) { + c = 0; + mainSubscription.get().request(lim); + } + } + + if (e == r) { + if (cancelled) { + singleItem = null; + queue = null; + return; + } + + if (error.get() != null) { + singleItem = null; + queue = null; + actual.onError(error.terminate()); + return; + } + + boolean d = mainDone; + SimplePlainQueue q = queue; + boolean empty = q == null || q.isEmpty(); + + if (d && empty && otherState == 2) { + queue = null; + actual.onComplete(); + return; + } + } + + emitted = e; + consumed = c; + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class OtherObserver extends AtomicReference + implements SingleObserver { + + private static final long serialVersionUID = -2935427570954647017L; + + final MergeWithObserver parent; + + OtherObserver(MergeWithObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onSuccess(T t) { + parent.otherSuccess(t); + } + + @Override + public void onError(Throwable e) { + parent.otherError(e); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java new file mode 100644 index 0000000000..7d0945def8 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java @@ -0,0 +1,145 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.util.*; + +/** + * Merges an Observable and a Completable by emitting the items of the Observable and waiting until + * both the Observable and Completable complete normally. + * + * @param the element type of the Observable + * @since 2.1.10 - experimental + */ +public final class ObservableMergeWithCompletable extends AbstractObservableWithUpstream { + + final CompletableSource other; + + public ObservableMergeWithCompletable(Observable source, CompletableSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Observer observer) { + MergeWithObserver parent = new MergeWithObserver(observer); + observer.onSubscribe(parent); + source.subscribe(parent); + other.subscribe(parent.otherObserver); + } + + static final class MergeWithObserver extends AtomicInteger + implements Observer, Disposable { + + private static final long serialVersionUID = -4592979584110982903L; + + final Observer actual; + + final AtomicReference mainDisposable; + + final OtherObserver otherObserver; + + final AtomicThrowable error; + + volatile boolean mainDone; + + volatile boolean otherDone; + + MergeWithObserver(Observer actual) { + this.actual = actual; + this.mainDisposable = new AtomicReference(); + this.otherObserver = new OtherObserver(this); + this.error = new AtomicThrowable(); + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(mainDisposable, d); + } + + @Override + public void onNext(T t) { + HalfSerializer.onNext(actual, t, this, error); + } + + @Override + public void onError(Throwable ex) { + DisposableHelper.dispose(mainDisposable); + HalfSerializer.onError(actual, ex, this, error); + } + + @Override + public void onComplete() { + mainDone = true; + if (otherDone) { + HalfSerializer.onComplete(actual, this, error); + } + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(mainDisposable.get()); + } + + @Override + public void dispose() { + DisposableHelper.dispose(mainDisposable); + DisposableHelper.dispose(otherObserver); + } + + void otherError(Throwable ex) { + DisposableHelper.dispose(mainDisposable); + HalfSerializer.onError(actual, ex, this, error); + } + + void otherComplete() { + otherDone = true; + if (mainDone) { + HalfSerializer.onComplete(actual, this, error); + } + } + + static final class OtherObserver extends AtomicReference + implements CompletableObserver { + + private static final long serialVersionUID = -2935427570954647017L; + + final MergeWithObserver parent; + + OtherObserver(MergeWithObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onError(Throwable e) { + parent.otherError(e); + } + + @Override + public void onComplete() { + parent.otherComplete(); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java new file mode 100644 index 0000000000..c1714df168 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java @@ -0,0 +1,266 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.queue.SpscLinkedArrayQueue; +import io.reactivex.internal.util.AtomicThrowable; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Merges an Observable and a Maybe by emitting the items of the Observable and the success + * value of the Maybe and waiting until both the Observable and Maybe terminate normally. + * + * @param the element type of the Observable + * @since 2.1.10 - experimental + */ +public final class ObservableMergeWithMaybe extends AbstractObservableWithUpstream { + + final MaybeSource other; + + public ObservableMergeWithMaybe(Observable source, MaybeSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Observer observer) { + MergeWithObserver parent = new MergeWithObserver(observer); + observer.onSubscribe(parent); + source.subscribe(parent); + other.subscribe(parent.otherObserver); + } + + static final class MergeWithObserver extends AtomicInteger + implements Observer, Disposable { + + private static final long serialVersionUID = -4592979584110982903L; + + final Observer actual; + + final AtomicReference mainDisposable; + + final OtherObserver otherObserver; + + final AtomicThrowable error; + + volatile SimplePlainQueue queue; + + T singleItem; + + volatile boolean disposed; + + volatile boolean mainDone; + + volatile int otherState; + + static final int OTHER_STATE_HAS_VALUE = 1; + + static final int OTHER_STATE_CONSUMED_OR_EMPTY = 2; + + MergeWithObserver(Observer actual) { + this.actual = actual; + this.mainDisposable = new AtomicReference(); + this.otherObserver = new OtherObserver(this); + this.error = new AtomicThrowable(); + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(mainDisposable, d); + } + + @Override + public void onNext(T t) { + if (compareAndSet(0, 1)) { + actual.onNext(t); + if (decrementAndGet() == 0) { + return; + } + } else { + SimplePlainQueue q = getOrCreateQueue(); + q.offer(t); + if (getAndIncrement() != 0) { + return; + } + } + drainLoop(); + } + + @Override + public void onError(Throwable ex) { + if (error.addThrowable(ex)) { + DisposableHelper.dispose(mainDisposable); + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + @Override + public void onComplete() { + mainDone = true; + drain(); + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(mainDisposable.get()); + } + + @Override + public void dispose() { + disposed = true; + DisposableHelper.dispose(mainDisposable); + DisposableHelper.dispose(otherObserver); + if (getAndIncrement() == 0) { + queue = null; + singleItem = null; + } + } + + void otherSuccess(T value) { + if (compareAndSet(0, 1)) { + actual.onNext(value); + otherState = OTHER_STATE_CONSUMED_OR_EMPTY; + } else { + singleItem = value; + otherState = OTHER_STATE_HAS_VALUE; + if (getAndIncrement() != 0) { + return; + } + } + drainLoop(); + } + + void otherError(Throwable ex) { + if (error.addThrowable(ex)) { + DisposableHelper.dispose(mainDisposable); + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + void otherComplete() { + otherState = OTHER_STATE_CONSUMED_OR_EMPTY; + drain(); + } + + SimplePlainQueue getOrCreateQueue() { + SimplePlainQueue q = queue; + if (q == null) { + q = new SpscLinkedArrayQueue(bufferSize()); + queue = q; + } + return q; + } + + void drain() { + if (getAndIncrement() == 0) { + drainLoop(); + } + } + + void drainLoop() { + Observer actual = this.actual; + int missed = 1; + for (;;) { + + for (;;) { + if (disposed) { + singleItem = null; + queue = null; + return; + } + + if (error.get() != null) { + singleItem = null; + queue = null; + actual.onError(error.terminate()); + return; + } + + int os = otherState; + if (os == OTHER_STATE_HAS_VALUE) { + T v = singleItem; + singleItem = null; + otherState = OTHER_STATE_CONSUMED_OR_EMPTY; + os = OTHER_STATE_CONSUMED_OR_EMPTY; + actual.onNext(v); + } + + boolean d = mainDone; + SimplePlainQueue q = queue; + T v = q != null ? q.poll() : null; + boolean empty = v == null; + + if (d && empty && os == OTHER_STATE_CONSUMED_OR_EMPTY) { + queue = null; + actual.onComplete(); + return; + } + + if (empty) { + break; + } + + actual.onNext(v); + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class OtherObserver extends AtomicReference + implements MaybeObserver { + + private static final long serialVersionUID = -2935427570954647017L; + + final MergeWithObserver parent; + + OtherObserver(MergeWithObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onSuccess(T t) { + parent.otherSuccess(t); + } + + @Override + public void onError(Throwable e) { + parent.otherError(e); + } + + @Override + public void onComplete() { + parent.otherComplete(); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java new file mode 100644 index 0000000000..458786dff5 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java @@ -0,0 +1,257 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.queue.SpscLinkedArrayQueue; +import io.reactivex.internal.util.AtomicThrowable; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Merges an Observable and a Single by emitting the items of the Observable and the success + * value of the Single and waiting until both the Observable and Single terminate normally. + * + * @param the element type of the Observable + * @since 2.1.10 - experimental + */ +public final class ObservableMergeWithSingle extends AbstractObservableWithUpstream { + + final SingleSource other; + + public ObservableMergeWithSingle(Observable source, SingleSource other) { + super(source); + this.other = other; + } + + @Override + protected void subscribeActual(Observer observer) { + MergeWithObserver parent = new MergeWithObserver(observer); + observer.onSubscribe(parent); + source.subscribe(parent); + other.subscribe(parent.otherObserver); + } + + static final class MergeWithObserver extends AtomicInteger + implements Observer, Disposable { + + private static final long serialVersionUID = -4592979584110982903L; + + final Observer actual; + + final AtomicReference mainDisposable; + + final OtherObserver otherObserver; + + final AtomicThrowable error; + + volatile SimplePlainQueue queue; + + T singleItem; + + volatile boolean disposed; + + volatile boolean mainDone; + + volatile int otherState; + + static final int OTHER_STATE_HAS_VALUE = 1; + + static final int OTHER_STATE_CONSUMED_OR_EMPTY = 2; + + MergeWithObserver(Observer actual) { + this.actual = actual; + this.mainDisposable = new AtomicReference(); + this.otherObserver = new OtherObserver(this); + this.error = new AtomicThrowable(); + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(mainDisposable, d); + } + + @Override + public void onNext(T t) { + if (compareAndSet(0, 1)) { + actual.onNext(t); + if (decrementAndGet() == 0) { + return; + } + } else { + SimplePlainQueue q = getOrCreateQueue(); + q.offer(t); + if (getAndIncrement() != 0) { + return; + } + } + drainLoop(); + } + + @Override + public void onError(Throwable ex) { + if (error.addThrowable(ex)) { + DisposableHelper.dispose(mainDisposable); + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + @Override + public void onComplete() { + mainDone = true; + drain(); + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(mainDisposable.get()); + } + + @Override + public void dispose() { + disposed = true; + DisposableHelper.dispose(mainDisposable); + DisposableHelper.dispose(otherObserver); + if (getAndIncrement() == 0) { + queue = null; + singleItem = null; + } + } + + void otherSuccess(T value) { + if (compareAndSet(0, 1)) { + actual.onNext(value); + otherState = OTHER_STATE_CONSUMED_OR_EMPTY; + } else { + singleItem = value; + otherState = OTHER_STATE_HAS_VALUE; + if (getAndIncrement() != 0) { + return; + } + } + drainLoop(); + } + + void otherError(Throwable ex) { + if (error.addThrowable(ex)) { + DisposableHelper.dispose(mainDisposable); + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + SimplePlainQueue getOrCreateQueue() { + SimplePlainQueue q = queue; + if (q == null) { + q = new SpscLinkedArrayQueue(bufferSize()); + queue = q; + } + return q; + } + + void drain() { + if (getAndIncrement() == 0) { + drainLoop(); + } + } + + void drainLoop() { + Observer actual = this.actual; + int missed = 1; + for (;;) { + + for (;;) { + if (disposed) { + singleItem = null; + queue = null; + return; + } + + if (error.get() != null) { + singleItem = null; + queue = null; + actual.onError(error.terminate()); + return; + } + + int os = otherState; + if (os == OTHER_STATE_HAS_VALUE) { + T v = singleItem; + singleItem = null; + otherState = OTHER_STATE_CONSUMED_OR_EMPTY; + os = OTHER_STATE_CONSUMED_OR_EMPTY; + actual.onNext(v); + } + + boolean d = mainDone; + SimplePlainQueue q = queue; + T v = q != null ? q.poll() : null; + boolean empty = v == null; + + if (d && empty && os == OTHER_STATE_CONSUMED_OR_EMPTY) { + queue = null; + actual.onComplete(); + return; + } + + if (empty) { + break; + } + + actual.onNext(v); + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class OtherObserver extends AtomicReference + implements SingleObserver { + + private static final long serialVersionUID = -2935427570954647017L; + + final MergeWithObserver parent; + + OtherObserver(MergeWithObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onSuccess(T t) { + parent.otherSuccess(t); + } + + @Override + public void onError(Throwable e) { + parent.otherError(e); + } + + } + } +} diff --git a/src/test/java/io/reactivex/InternalWrongNaming.java b/src/test/java/io/reactivex/InternalWrongNaming.java index 1e4bfc5943..aed20c265d 100644 --- a/src/test/java/io/reactivex/InternalWrongNaming.java +++ b/src/test/java/io/reactivex/InternalWrongNaming.java @@ -182,7 +182,10 @@ public void flowableNoObserver() throws Exception { "FlowableSequenceEqualSingle", "FlowableConcatWithSingle", "FlowableConcatWithMaybe", - "FlowableConcatWithCompletable" + "FlowableConcatWithCompletable", + "FlowableMergeWithSingle", + "FlowableMergeWithMaybe", + "FlowableMergeWithCompletable" ); } } diff --git a/src/test/java/io/reactivex/flowable/FlowableNullTests.java b/src/test/java/io/reactivex/flowable/FlowableNullTests.java index 67c1d61d8d..b5e5301d91 100644 --- a/src/test/java/io/reactivex/flowable/FlowableNullTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableNullTests.java @@ -1620,7 +1620,7 @@ public Object apply(Integer v) { @Test(expected = NullPointerException.class) public void mergeWithNull() { - just1.mergeWith(null); + just1.mergeWith((Publisher)null); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletableTest.java new file mode 100644 index 0000000000..cf5b7917a6 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletableTest.java @@ -0,0 +1,139 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import org.junit.Test; + +import static org.junit.Assert.*; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.CompletableSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableMergeWithCompletableTest { + + @Test + public void normal() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.range(1, 5).mergeWith( + Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + }) + ) + .subscribe(ts); + + ts.assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void take() { + Flowable.range(1, 5) + .mergeWith(Completable.complete()) + .take(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void cancel() { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).test(); + + assertTrue(pp.hasSubscribers()); + assertTrue(cs.hasObservers()); + + ts.cancel(); + + assertFalse(pp.hasSubscribers()); + assertFalse(cs.hasObservers()); + } + + @Test + public void normalBackpressured() { + final TestSubscriber ts = new TestSubscriber(0L); + + Flowable.range(1, 5).mergeWith( + Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + ts.onNext(100); + } + }) + ) + .subscribe(ts); + + ts + .assertValue(100) + .requestMore(2) + .assertValues(100, 1, 2) + .requestMore(2) + .assertValues(100, 1, 2, 3, 4) + .requestMore(1) + .assertResult(100, 1, 2, 3, 4, 5); + } + + @Test + public void mainError() { + Flowable.error(new TestException()) + .mergeWith(Completable.complete()) + .test() + .assertFailure(TestException.class); + } + + @Test + public void otherError() { + Flowable.never() + .mergeWith(Completable.error(new TestException())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void completeRace() { + for (int i = 0; i < 1000; i++) { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + pp.onComplete(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onComplete(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertResult(1); + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybeTest.java new file mode 100644 index 0000000000..c38bf6ae7b --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybeTest.java @@ -0,0 +1,404 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.MaybeSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableMergeWithMaybeTest { + + @Test + public void normal() { + Flowable.range(1, 5) + .mergeWith(Maybe.just(100)) + .test() + .assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void emptyOther() { + Flowable.range(1, 5) + .mergeWith(Maybe.empty()) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void normalLong() { + Flowable.range(1, 512) + .mergeWith(Maybe.just(100)) + .test() + .assertValueCount(513) + .assertComplete(); + } + + @Test + public void normalLongRequestExact() { + Flowable.range(1, 512) + .mergeWith(Maybe.just(100)) + .test(513) + .assertValueCount(513) + .assertComplete(); + } + + @Test + public void take() { + Flowable.range(1, 5) + .mergeWith(Maybe.just(100)) + .take(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void cancel() { + final PublishProcessor pp = PublishProcessor.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).test(); + + assertTrue(pp.hasSubscribers()); + assertTrue(cs.hasObservers()); + + ts.cancel(); + + assertFalse(pp.hasSubscribers()); + assertFalse(cs.hasObservers()); + } + + @Test + public void normalBackpressured() { + Flowable.range(1, 5).mergeWith( + Maybe.just(100) + ) + .test(0L) + .assertEmpty() + .requestMore(2) + .assertValues(100, 1) + .requestMore(2) + .assertValues(100, 1, 2, 3) + .requestMore(2) + .assertResult(100, 1, 2, 3, 4, 5); + } + + @Test + public void mainError() { + Flowable.error(new TestException()) + .mergeWith(Maybe.just(100)) + .test() + .assertFailure(TestException.class); + } + + @Test + public void otherError() { + Flowable.never() + .mergeWith(Maybe.error(new TestException())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void completeRace() { + for (int i = 0; i < 10000; i++) { + final PublishProcessor pp = PublishProcessor.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + pp.onComplete(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onSuccess(1); + } + }; + + TestHelper.race(r1, r2); + + ts.assertResult(1, 1); + } + } + + @Test + public void onNextSlowPath() { + final PublishProcessor pp = PublishProcessor.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).subscribeWith(new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + pp.onNext(2); + } + } + }); + + pp.onNext(1); + cs.onSuccess(3); + + pp.onNext(4); + pp.onComplete(); + + ts.assertResult(1, 2, 3, 4); + } + + @Test + public void onSuccessSlowPath() { + final PublishProcessor pp = PublishProcessor.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).subscribeWith(new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + cs.onSuccess(2); + } + } + }); + + pp.onNext(1); + + pp.onNext(3); + pp.onComplete(); + + ts.assertResult(1, 2, 3); + } + + @Test + public void onSuccessSlowPathBackpressured() { + final PublishProcessor pp = PublishProcessor.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).subscribeWith(new TestSubscriber(1) { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + cs.onSuccess(2); + } + } + }); + + pp.onNext(1); + + pp.onNext(3); + pp.onComplete(); + + ts.request(2); + ts.assertResult(1, 2, 3); + } + + @Test + public void onSuccessFastPathBackpressuredRace() { + for (int i = 0; i < 10000; i++) { + final PublishProcessor pp = PublishProcessor.create(); + final MaybeSubject cs = MaybeSubject.create(); + + final TestSubscriber ts = pp.mergeWith(cs).subscribeWith(new TestSubscriber(0)); + + Runnable r1 = new Runnable() { + @Override + public void run() { + cs.onSuccess(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.request(2); + } + }; + + TestHelper.race(r1, r2); + + pp.onNext(2); + pp.onComplete(); + + ts.assertResult(1, 2); + } + } + + @Test + public void onErrorMainOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> subscriber = new AtomicReference>(); + TestSubscriber ts = new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + subscriber.set(s); + } + } + .mergeWith(Maybe.error(new IOException())) + .test(); + + subscriber.get().onError(new TestException()); + + ts.assertFailure(IOException.class) + ; + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void onErrorOtherOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + Flowable.error(new IOException()) + .mergeWith(Maybe.error(new TestException())) + .test() + .assertFailure(IOException.class) + ; + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void onNextRequestRace() { + for (int i = 0; i < 10000; i++) { + final PublishProcessor pp = PublishProcessor.create(); + final MaybeSubject cs = MaybeSubject.create(); + + final TestSubscriber ts = pp.mergeWith(cs).test(0); + + pp.onNext(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.request(3); + } + }; + + TestHelper.race(r1, r2); + + cs.onSuccess(1); + pp.onComplete(); + + ts.assertResult(0, 1, 1); + } + } + + @Test + public void doubleOnSubscribeMain() { + TestHelper.checkDoubleOnSubscribeFlowable( + new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) + throws Exception { + return f.mergeWith(Maybe.just(1)); + } + } + ); + } + + @Test + public void noRequestOnError() { + Flowable.empty() + .mergeWith(Maybe.error(new TestException())) + .test(0) + .assertFailure(TestException.class); + } + + @Test + public void drainExactRequestCancel() { + final PublishProcessor pp = PublishProcessor.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs) + .limit(2) + .subscribeWith(new TestSubscriber(2) { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + cs.onSuccess(2); + } + } + }); + + pp.onNext(1); + + pp.onComplete(); + + ts.request(2); + ts.assertResult(1, 2); + } + + @Test + public void drainRequestWhenLimitReached() { + final PublishProcessor pp = PublishProcessor.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs) + .subscribeWith(new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + for (int i = 0; i < Flowable.bufferSize() - 1; i++) { + pp.onNext(i + 2); + } + } + } + }); + + cs.onSuccess(1); + + pp.onComplete(); + + ts.request(2); + ts.assertValueCount(Flowable.bufferSize()); + ts.assertComplete(); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingleTest.java new file mode 100644 index 0000000000..2ab0568a7e --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingleTest.java @@ -0,0 +1,400 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.SingleSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableMergeWithSingleTest { + + @Test + public void normal() { + Flowable.range(1, 5) + .mergeWith(Single.just(100)) + .test() + .assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void normalLong() { + Flowable.range(1, 512) + .mergeWith(Single.just(100)) + .test() + .assertValueCount(513) + .assertComplete(); + } + + @Test + public void normalLongRequestExact() { + Flowable.range(1, 512) + .mergeWith(Single.just(100)) + .test(513) + .assertValueCount(513) + .assertComplete(); + } + + @Test + public void take() { + Flowable.range(1, 5) + .mergeWith(Single.just(100)) + .take(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void cancel() { + final PublishProcessor pp = PublishProcessor.create(); + final SingleSubject cs = SingleSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).test(); + + assertTrue(pp.hasSubscribers()); + assertTrue(cs.hasObservers()); + + ts.cancel(); + + assertFalse(pp.hasSubscribers()); + assertFalse(cs.hasObservers()); + } + + @Test + public void normalBackpressured() { + final TestSubscriber ts = new TestSubscriber(0L); + + Flowable.range(1, 5).mergeWith( + Single.just(100) + ) + .subscribe(ts); + + ts + .assertEmpty() + .requestMore(2) + .assertValues(100, 1) + .requestMore(2) + .assertValues(100, 1, 2, 3) + .requestMore(2) + .assertResult(100, 1, 2, 3, 4, 5); + } + + @Test + public void mainError() { + Flowable.error(new TestException()) + .mergeWith(Single.just(100)) + .test() + .assertFailure(TestException.class); + } + + @Test + public void otherError() { + Flowable.never() + .mergeWith(Single.error(new TestException())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void completeRace() { + for (int i = 0; i < 10000; i++) { + final PublishProcessor pp = PublishProcessor.create(); + final SingleSubject cs = SingleSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + pp.onComplete(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onSuccess(1); + } + }; + + TestHelper.race(r1, r2); + + ts.assertResult(1, 1); + } + } + + @Test + public void onNextSlowPath() { + final PublishProcessor pp = PublishProcessor.create(); + final SingleSubject cs = SingleSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).subscribeWith(new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + pp.onNext(2); + } + } + }); + + pp.onNext(1); + cs.onSuccess(3); + + pp.onNext(4); + pp.onComplete(); + + ts.assertResult(1, 2, 3, 4); + } + + @Test + public void onSuccessSlowPath() { + final PublishProcessor pp = PublishProcessor.create(); + final SingleSubject cs = SingleSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).subscribeWith(new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + cs.onSuccess(2); + } + } + }); + + pp.onNext(1); + + pp.onNext(3); + pp.onComplete(); + + ts.assertResult(1, 2, 3); + } + + @Test + public void onSuccessSlowPathBackpressured() { + final PublishProcessor pp = PublishProcessor.create(); + final SingleSubject cs = SingleSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs).subscribeWith(new TestSubscriber(1) { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + cs.onSuccess(2); + } + } + }); + + pp.onNext(1); + + pp.onNext(3); + pp.onComplete(); + + ts.request(2); + ts.assertResult(1, 2, 3); + } + + @Test + public void onSuccessFastPathBackpressuredRace() { + for (int i = 0; i < 10000; i++) { + final PublishProcessor pp = PublishProcessor.create(); + final SingleSubject cs = SingleSubject.create(); + + final TestSubscriber ts = pp.mergeWith(cs).subscribeWith(new TestSubscriber(0)); + + Runnable r1 = new Runnable() { + @Override + public void run() { + cs.onSuccess(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.request(2); + } + }; + + TestHelper.race(r1, r2); + + pp.onNext(2); + pp.onComplete(); + + ts.assertResult(1, 2); + } + } + + @Test + public void onErrorMainOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> subscriber = new AtomicReference>(); + TestSubscriber ts = new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + subscriber.set(s); + } + } + .mergeWith(Single.error(new IOException())) + .test(); + + subscriber.get().onError(new TestException()); + + ts.assertFailure(IOException.class) + ; + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void onErrorOtherOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + Flowable.error(new IOException()) + .mergeWith(Single.error(new TestException())) + .test() + .assertFailure(IOException.class) + ; + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void onNextRequestRace() { + for (int i = 0; i < 10000; i++) { + final PublishProcessor pp = PublishProcessor.create(); + final SingleSubject cs = SingleSubject.create(); + + final TestSubscriber ts = pp.mergeWith(cs).test(0); + + pp.onNext(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.request(3); + } + }; + + TestHelper.race(r1, r2); + + cs.onSuccess(1); + pp.onComplete(); + + ts.assertResult(0, 1, 1); + } + } + + @Test + public void doubleOnSubscribeMain() { + TestHelper.checkDoubleOnSubscribeFlowable( + new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) + throws Exception { + return f.mergeWith(Single.just(1)); + } + } + ); + } + + @Test + public void noRequestOnError() { + Flowable.empty() + .mergeWith(Single.error(new TestException())) + .test(0) + .assertFailure(TestException.class); + } + + @Test + public void drainExactRequestCancel() { + final PublishProcessor pp = PublishProcessor.create(); + final SingleSubject cs = SingleSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs) + .limit(2) + .subscribeWith(new TestSubscriber(2) { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + cs.onSuccess(2); + } + } + }); + + pp.onNext(1); + + pp.onComplete(); + + ts.request(2); + ts.assertResult(1, 2); + } + + @Test + public void drainRequestWhenLimitReached() { + final PublishProcessor pp = PublishProcessor.create(); + final SingleSubject cs = SingleSubject.create(); + + TestSubscriber ts = pp.mergeWith(cs) + .subscribeWith(new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + for (int i = 0; i < Flowable.bufferSize() - 1; i++) { + pp.onNext(i + 2); + } + } + } + }); + + cs.onSuccess(1); + + pp.onComplete(); + + ts.request(2); + ts.assertValueCount(Flowable.bufferSize()); + ts.assertComplete(); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletableTest.java new file mode 100644 index 0000000000..872509e164 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletableTest.java @@ -0,0 +1,138 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.observers.TestObserver; +import io.reactivex.subjects.*; + +public class ObservableMergeWithCompletableTest { + + @Test + public void normal() { + final TestObserver to = new TestObserver(); + + Observable.range(1, 5).mergeWith( + Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + to.onNext(100); + } + }) + ) + .subscribe(to); + + to.assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void take() { + final TestObserver to = new TestObserver(); + + Observable.range(1, 5).mergeWith( + Completable.complete() + ) + .take(3) + .subscribe(to); + + to.assertResult(1, 2, 3); + } + + @Test + public void cancel() { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.mergeWith(cs).test(); + + assertTrue(ps.hasObservers()); + assertTrue(cs.hasObservers()); + + to.cancel(); + + assertFalse(ps.hasObservers()); + assertFalse(cs.hasObservers()); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .mergeWith(Completable.complete()) + .test() + .assertFailure(TestException.class); + } + + @Test + public void otherError() { + Observable.never() + .mergeWith(Completable.error(new TestException())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void completeRace() { + for (int i = 0; i < 1000; i++) { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.mergeWith(cs).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(1); + ps.onComplete(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onComplete(); + } + }; + + TestHelper.race(r1, r2); + + to.assertResult(1); + } + } + + @Test + public void isDisposed() { + new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + + assertFalse(((Disposable)observer).isDisposed()); + + observer.onNext(1); + + assertTrue(((Disposable)observer).isDisposed()); + } + }.mergeWith(Completable.complete()) + .take(1) + .test() + .assertResult(1); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java new file mode 100644 index 0000000000..a7d1edf098 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java @@ -0,0 +1,275 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subjects.*; + +public class ObservableMergeWithMaybeTest { + + @Test + public void normal() { + Observable.range(1, 5) + .mergeWith(Maybe.just(100)) + .test() + .assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void emptyOther() { + Observable.range(1, 5) + .mergeWith(Maybe.empty()) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void normalLong() { + Observable.range(1, 512) + .mergeWith(Maybe.just(100)) + .test() + .assertValueCount(513) + .assertComplete(); + } + + @Test + public void take() { + Observable.range(1, 5) + .mergeWith(Maybe.just(100)) + .take(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void cancel() { + final PublishSubject ps = PublishSubject.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestObserver to = ps.mergeWith(cs).test(); + + assertTrue(ps.hasObservers()); + assertTrue(cs.hasObservers()); + + to.cancel(); + + assertFalse(ps.hasObservers()); + assertFalse(cs.hasObservers()); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .mergeWith(Maybe.just(100)) + .test() + .assertFailure(TestException.class); + } + + @Test + public void otherError() { + Observable.never() + .mergeWith(Maybe.error(new TestException())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void completeRace() { + for (int i = 0; i < 10000; i++) { + final PublishSubject ps = PublishSubject.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestObserver to = ps.mergeWith(cs).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(1); + ps.onComplete(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onSuccess(1); + } + }; + + TestHelper.race(r1, r2); + + to.assertResult(1, 1); + } + } + + @Test + public void onNextSlowPath() { + final PublishSubject ps = PublishSubject.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestObserver to = ps.mergeWith(cs).subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + ps.onNext(2); + } + } + }); + + ps.onNext(1); + cs.onSuccess(3); + + ps.onNext(4); + ps.onComplete(); + + to.assertResult(1, 2, 3, 4); + } + + @Test + public void onSuccessSlowPath() { + final PublishSubject ps = PublishSubject.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestObserver to = ps.mergeWith(cs).subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + cs.onSuccess(2); + } + } + }); + + ps.onNext(1); + + ps.onNext(3); + ps.onComplete(); + + to.assertResult(1, 2, 3); + } + + @Test + public void onErrorMainOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> subscriber = new AtomicReference>(); + TestObserver to = new Observable() { + @Override + protected void subscribeActual(Observer s) { + s.onSubscribe(Disposables.empty()); + subscriber.set(s); + } + } + .mergeWith(Maybe.error(new IOException())) + .test(); + + subscriber.get().onError(new TestException()); + + to.assertFailure(IOException.class) + ; + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void onErrorOtherOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + Observable.error(new IOException()) + .mergeWith(Maybe.error(new TestException())) + .test() + .assertFailure(IOException.class) + ; + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void doubleOnSubscribeMain() { + TestHelper.checkDoubleOnSubscribeObservable( + new Function, Observable>() { + @Override + public Observable apply(Observable f) + throws Exception { + return f.mergeWith(Maybe.just(1)); + } + } + ); + } + + @Test + public void isDisposed() { + new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + + assertFalse(((Disposable)observer).isDisposed()); + + observer.onNext(1); + + assertTrue(((Disposable)observer).isDisposed()); + } + }.mergeWith(Maybe.empty()) + .take(1) + .test() + .assertResult(1); + } + + @Test + public void onNextSlowPathCreateQueue() { + final PublishSubject ps = PublishSubject.create(); + final MaybeSubject cs = MaybeSubject.create(); + + TestObserver to = ps.mergeWith(cs).subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + ps.onNext(2); + ps.onNext(3); + } + } + }); + + cs.onSuccess(0); + ps.onNext(1); + + ps.onNext(4); + ps.onComplete(); + + to.assertResult(0, 1, 2, 3, 4); + } + +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java new file mode 100644 index 0000000000..5821461787 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java @@ -0,0 +1,266 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subjects.*; + +public class ObservableMergeWithSingleTest { + + @Test + public void normal() { + Observable.range(1, 5) + .mergeWith(Single.just(100)) + .test() + .assertResult(1, 2, 3, 4, 5, 100); + } + + @Test + public void normalLong() { + Observable.range(1, 512) + .mergeWith(Single.just(100)) + .test() + .assertValueCount(513) + .assertComplete(); + } + + @Test + public void take() { + Observable.range(1, 5) + .mergeWith(Single.just(100)) + .take(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void cancel() { + final PublishSubject ps = PublishSubject.create(); + final SingleSubject cs = SingleSubject.create(); + + TestObserver to = ps.mergeWith(cs).test(); + + assertTrue(ps.hasObservers()); + assertTrue(cs.hasObservers()); + + to.cancel(); + + assertFalse(ps.hasObservers()); + assertFalse(cs.hasObservers()); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .mergeWith(Single.just(100)) + .test() + .assertFailure(TestException.class); + } + + @Test + public void otherError() { + Observable.never() + .mergeWith(Single.error(new TestException())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void completeRace() { + for (int i = 0; i < 10000; i++) { + final PublishSubject ps = PublishSubject.create(); + final SingleSubject cs = SingleSubject.create(); + + TestObserver to = ps.mergeWith(cs).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(1); + ps.onComplete(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onSuccess(1); + } + }; + + TestHelper.race(r1, r2); + + to.assertResult(1, 1); + } + } + + @Test + public void onNextSlowPath() { + final PublishSubject ps = PublishSubject.create(); + final SingleSubject cs = SingleSubject.create(); + + TestObserver to = ps.mergeWith(cs).subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + ps.onNext(2); + } + } + }); + + ps.onNext(1); + cs.onSuccess(3); + + ps.onNext(4); + ps.onComplete(); + + to.assertResult(1, 2, 3, 4); + } + + @Test + public void onSuccessSlowPath() { + final PublishSubject ps = PublishSubject.create(); + final SingleSubject cs = SingleSubject.create(); + + TestObserver to = ps.mergeWith(cs).subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + cs.onSuccess(2); + } + } + }); + + ps.onNext(1); + + ps.onNext(3); + ps.onComplete(); + + to.assertResult(1, 2, 3); + } + + @Test + public void onErrorMainOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> subscriber = new AtomicReference>(); + TestObserver to = new Observable() { + @Override + protected void subscribeActual(Observer s) { + s.onSubscribe(Disposables.empty()); + subscriber.set(s); + } + } + .mergeWith(Single.error(new IOException())) + .test(); + + subscriber.get().onError(new TestException()); + + to.assertFailure(IOException.class) + ; + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void onErrorOtherOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + Observable.error(new IOException()) + .mergeWith(Single.error(new TestException())) + .test() + .assertFailure(IOException.class) + ; + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void doubleOnSubscribeMain() { + TestHelper.checkDoubleOnSubscribeObservable( + new Function, Observable>() { + @Override + public Observable apply(Observable f) + throws Exception { + return f.mergeWith(Single.just(1)); + } + } + ); + } + + @Test + public void isDisposed() { + new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + + assertFalse(((Disposable)observer).isDisposed()); + + observer.onNext(1); + + assertTrue(((Disposable)observer).isDisposed()); + } + }.mergeWith(Single.just(1)) + .take(1) + .test() + .assertResult(1); + } + + @Test + public void onNextSlowPathCreateQueue() { + final PublishSubject ps = PublishSubject.create(); + final SingleSubject cs = SingleSubject.create(); + + TestObserver to = ps.mergeWith(cs).subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + ps.onNext(2); + ps.onNext(3); + } + } + }); + + cs.onSuccess(0); + ps.onNext(1); + + ps.onNext(4); + ps.onComplete(); + + to.assertResult(0, 1, 2, 3, 4); + } +} diff --git a/src/test/java/io/reactivex/observable/ObservableNullTests.java b/src/test/java/io/reactivex/observable/ObservableNullTests.java index 55b5846601..bc97de83d7 100644 --- a/src/test/java/io/reactivex/observable/ObservableNullTests.java +++ b/src/test/java/io/reactivex/observable/ObservableNullTests.java @@ -1685,7 +1685,7 @@ public Object apply(Integer v) { @Test(expected = NullPointerException.class) public void mergeWithNull() { - just1.mergeWith(null); + just1.mergeWith((ObservableSource)null); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/io/reactivex/tck/MergeWithCompletableTckTest.java b/src/test/java/io/reactivex/tck/MergeWithCompletableTckTest.java new file mode 100644 index 0000000000..30e67e95ac --- /dev/null +++ b/src/test/java/io/reactivex/tck/MergeWithCompletableTckTest.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; + +@Test +public class MergeWithCompletableTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + return + Flowable.rangeLong(1, elements) + .mergeWith(Completable.complete()) + ; + } +} diff --git a/src/test/java/io/reactivex/tck/MergeWithMaybeEmptyTckTest.java b/src/test/java/io/reactivex/tck/MergeWithMaybeEmptyTckTest.java new file mode 100644 index 0000000000..3d105c8842 --- /dev/null +++ b/src/test/java/io/reactivex/tck/MergeWithMaybeEmptyTckTest.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; + +@Test +public class MergeWithMaybeEmptyTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + return + Flowable.rangeLong(1, elements) + .mergeWith(Maybe.empty()) + ; + } +} diff --git a/src/test/java/io/reactivex/tck/MergeWithMaybeTckTest.java b/src/test/java/io/reactivex/tck/MergeWithMaybeTckTest.java new file mode 100644 index 0000000000..f5f7d4abef --- /dev/null +++ b/src/test/java/io/reactivex/tck/MergeWithMaybeTckTest.java @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; + +@Test +public class MergeWithMaybeTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + if (elements == 0) { + return Flowable.empty() + .mergeWith(Maybe.empty()); + } + return + Flowable.rangeLong(1, elements - 1) + .mergeWith(Maybe.just(elements)) + ; + } +} diff --git a/src/test/java/io/reactivex/tck/MergeWithSingleTckTest.java b/src/test/java/io/reactivex/tck/MergeWithSingleTckTest.java new file mode 100644 index 0000000000..28c3e8194b --- /dev/null +++ b/src/test/java/io/reactivex/tck/MergeWithSingleTckTest.java @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; + +@Test +public class MergeWithSingleTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + if (elements == 0) { + return Flowable.empty(); + } + return + Flowable.rangeLong(1, elements - 1) + .mergeWith(Single.just(elements)) + ; + } +} From 0f73283c0fb87979f383c4b7f358117c4ebcc034 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 19 Feb 2018 21:41:01 +0100 Subject: [PATCH 103/417] 2.x: Add finite requirement to various collector operators JavaDoc (#5856) * 2.x: Add finite requirement to various collector operators * Updated wording to "accumulator object" --- src/main/java/io/reactivex/Flowable.java | 96 ++++++++++++++++++---- src/main/java/io/reactivex/Observable.java | 95 +++++++++++++++++---- 2 files changed, 158 insertions(+), 33 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index f906f89c20..a80732ef0d 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -6706,12 +6706,16 @@ public final Flowable cast(final Class clazz) { } /** - * Collects items emitted by the source Publisher into a single mutable data structure and returns + * Collects items emitted by the finite source Publisher into a single mutable data structure and returns * a Single that emits this structure. *

                * *

                * This is a simplified version of {@code reduce} that does not need to return the state on each pass. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulator object to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                This operator does not support backpressure because by intent it will receive all values and reduce @@ -6740,12 +6744,16 @@ public final Single collect(Callable initialItemSupplier, Bi } /** - * Collects items emitted by the source Publisher into a single mutable data structure and returns + * Collects items emitted by the finite source Publisher into a single mutable data structure and returns * a Single that emits this structure. *

                * *

                * This is a simplified version of {@code reduce} that does not need to return the state on each pass. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulator object to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                This operator does not support backpressure because by intent it will receive all values and reduce @@ -11148,7 +11156,7 @@ public final Flowable rebatchRequests(int n) { /** * Returns a Maybe that applies a specified accumulator function to the first item emitted by a source * Publisher, then feeds the result of that function along with the second item emitted by the source - * Publisher into the same function, and so on until all items have been emitted by the source Publisher, + * Publisher into the same function, and so on until all items have been emitted by the finite source Publisher, * and emits the final result from the final call to your function as its sole item. *

                * If the source is empty, a {@code NoSuchElementException} is signalled. @@ -11158,6 +11166,10 @@ public final Flowable rebatchRequests(int n) { * This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate," * "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject} method * that does a similar operation on lists. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulator object to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure of its downstream consumer and consumes the @@ -11186,7 +11198,7 @@ public final Maybe reduce(BiFunction reducer) { * Returns a Single that applies a specified accumulator function to the first item emitted by a source * Publisher and a specified seed value, then feeds the result of that function along with the second item * emitted by a Publisher into the same function, and so on until all items have been emitted by the - * source Publisher, emitting the final result from the final call to your function as its sole item. + * finite source Publisher, emitting the final result from the final call to your function as its sole item. *

                * *

                @@ -11211,6 +11223,10 @@ public final Maybe reduce(BiFunction reducer) { * * source.reduceWith(() -> new ArrayList<>(), (list, item) -> list.add(item))); * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulator object to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure of its downstream consumer and consumes the @@ -11244,7 +11260,7 @@ public final Single reduce(R seed, BiFunction reducer) { * Returns a Single that applies a specified accumulator function to the first item emitted by a source * Publisher and a seed value derived from calling a specified seedSupplier, then feeds the result * of that function along with the second item emitted by a Publisher into the same function, and so on until - * all items have been emitted by the source Publisher, emitting the final result from the final call to your + * all items have been emitted by the finite source Publisher, emitting the final result from the final call to your * function as its sole item. *

                * @@ -11252,6 +11268,10 @@ public final Single reduce(R seed, BiFunction reducer) { * This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate," * "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject} method * that does a similar operation on lists. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulator object to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure of its downstream consumer and consumes the @@ -15175,12 +15195,16 @@ public final > Single toList(Callable coll } /** - * Returns a Single that emits a single HashMap containing all items emitted by the source Publisher, + * Returns a Single that emits a single HashMap containing all items emitted by the finite source Publisher, * mapped by the keys returned by a specified {@code keySelector} function. *

                * *

                * If more than one source item maps to the same key, the HashMap will contain the latest of those items. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream and consumes the source {@code Publisher} in an @@ -15206,12 +15230,16 @@ public final Single> toMap(final Function /** * Returns a Single that emits a single HashMap containing values corresponding to items emitted by the - * source Publisher, mapped by the keys returned by a specified {@code keySelector} function. + * finite source Publisher, mapped by the keys returned by a specified {@code keySelector} function. *

                * *

                * If more than one source item maps to the same key, the HashMap will contain a single entry that * corresponds to the latest of those items. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream and consumes the source {@code Publisher} in an @@ -15241,9 +15269,13 @@ public final Single> toMap(final Function * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream and consumes the source {@code Publisher} in an @@ -15277,9 +15309,13 @@ public final Single> toMap(final Function * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                This operator does not support backpressure as by intent it is requesting and buffering everything.
                @@ -15306,10 +15342,14 @@ public final Single>> toMultimap(Function * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream and consumes the source {@code Publisher} in an @@ -15340,9 +15380,13 @@ public final Single>> toMultimap(Function * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream and consumes the source {@code Publisher} in an @@ -15383,9 +15427,13 @@ public final Single>> toMultimap( /** * Returns a Single that emits a single Map, returned by a specified {@code mapFactory} function, that * contains an ArrayList of values, extracted by a specified {@code valueSelector} function from items - * emitted by the source Publisher and keyed by the {@code keySelector} function. + * emitted by the finite source Publisher and keyed by the {@code keySelector} function. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream and consumes the source {@code Publisher} in an @@ -15437,7 +15485,7 @@ public final Observable toObservable() { } /** - * Returns a Single that emits a list that contains the items emitted by the source Publisher, in a + * Returns a Single that emits a list that contains the items emitted by the finite source Publisher, in a * sorted order. Each item emitted by the Publisher must implement {@link Comparable} with respect to all * other items in the sequence. * @@ -15446,6 +15494,10 @@ public final Observable toObservable() { * sequence is terminated with a {@link ClassCastException}. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated list to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream and consumes the source {@code Publisher} in an @@ -15465,10 +15517,14 @@ public final Single> toSortedList() { } /** - * Returns a Single that emits a list that contains the items emitted by the source Publisher, in a + * Returns a Single that emits a list that contains the items emitted by the finite source Publisher, in a * sorted order based on a specified comparison function. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated list to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream and consumes the source {@code Publisher} in an @@ -15493,10 +15549,14 @@ public final Single> toSortedList(final Comparator comparator } /** - * Returns a Single that emits a list that contains the items emitted by the source Publisher, in a + * Returns a Single that emits a list that contains the items emitted by the finite source Publisher, in a * sorted order based on a specified comparison function. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated list to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream and consumes the source {@code Publisher} in an @@ -15524,7 +15584,7 @@ public final Single> toSortedList(final Comparator comparator } /** - * Returns a Flowable that emits a list that contains the items emitted by the source Publisher, in a + * Returns a Flowable that emits a list that contains the items emitted by the finite source Publisher, in a * sorted order. Each item emitted by the Publisher must implement {@link Comparable} with respect to all * other items in the sequence. * @@ -15533,6 +15593,10 @@ public final Single> toSortedList(final Comparator comparator * sequence is terminated with a {@link ClassCastException}. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated list to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream and consumes the source {@code Publisher} in an diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index ebd48d6537..0d8fd01825 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -6116,12 +6116,16 @@ public final Observable cast(final Class clazz) { } /** - * Collects items emitted by the source ObservableSource into a single mutable data structure and returns + * Collects items emitted by the finite source ObservableSource into a single mutable data structure and returns * a Single that emits this structure. *

                * *

                * This is a simplified version of {@code reduce} that does not need to return the state on each pass. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulator object to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code collect} does not operate by default on a particular {@link Scheduler}.
                @@ -6146,12 +6150,16 @@ public final Single collect(Callable initialValueSupplier, B } /** - * Collects items emitted by the source ObservableSource into a single mutable data structure and returns + * Collects items emitted by the finite source ObservableSource into a single mutable data structure and returns * a Single that emits this structure. *

                * *

                * This is a simplified version of {@code reduce} that does not need to return the state on each pass. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulator object to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code collectInto} does not operate by default on a particular {@link Scheduler}.
                @@ -9428,7 +9436,7 @@ public final Observable publish(Function, ? extends /** * Returns a Maybe that applies a specified accumulator function to the first item emitted by a source * ObservableSource, then feeds the result of that function along with the second item emitted by the source - * ObservableSource into the same function, and so on until all items have been emitted by the source ObservableSource, + * ObservableSource into the same function, and so on until all items have been emitted by the finite source ObservableSource, * and emits the final result from the final call to your function as its sole item. *

                * @@ -9436,6 +9444,10 @@ public final Observable publish(Function, ? extends * This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate," * "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject} method * that does a similar operation on lists. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulator object to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code reduce} does not operate by default on a particular {@link Scheduler}.
                @@ -9460,7 +9472,7 @@ public final Maybe reduce(BiFunction reducer) { * Returns a Single that applies a specified accumulator function to the first item emitted by a source * ObservableSource and a specified seed value, then feeds the result of that function along with the second item * emitted by an ObservableSource into the same function, and so on until all items have been emitted by the - * source ObservableSource, emitting the final result from the final call to your function as its sole item. + * finite source ObservableSource, emitting the final result from the final call to your function as its sole item. *

                * *

                @@ -9485,6 +9497,10 @@ public final Maybe reduce(BiFunction reducer) { * * source.reduceWith(() -> new ArrayList<>(), (list, item) -> list.add(item))); * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulator object to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code reduce} does not operate by default on a particular {@link Scheduler}.
                @@ -9514,7 +9530,7 @@ public final Single reduce(R seed, BiFunction reducer) { * Returns a Single that applies a specified accumulator function to the first item emitted by a source * ObservableSource and a seed value derived from calling a specified seedSupplier, then feeds the result * of that function along with the second item emitted by an ObservableSource into the same function, - * and so on until all items have been emitted by the source ObservableSource, emitting the final result + * and so on until all items have been emitted by the finite source ObservableSource, emitting the final result * from the final call to your function as its sole item. *

                * @@ -9522,6 +9538,10 @@ public final Single reduce(R seed, BiFunction reducer) { * This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate," * "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject} method * that does a similar operation on lists. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulator object to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code reduceWith} does not operate by default on a particular {@link Scheduler}.
                @@ -12916,12 +12936,17 @@ public final > Single toList(Callable coll } /** - * Returns a Single that emits a single HashMap containing all items emitted by the source ObservableSource, - * mapped by the keys returned by a specified {@code keySelector} function. + * Returns a Single that emits a single HashMap containing all items emitted by the + * finite source ObservableSource, mapped by the keys returned by a specified + * {@code keySelector} function. *

                * *

                * If more than one source item maps to the same key, the HashMap will contain the latest of those items. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code toMap} does not operate by default on a particular {@link Scheduler}.
                @@ -12943,12 +12968,16 @@ public final Single> toMap(final Function /** * Returns a Single that emits a single HashMap containing values corresponding to items emitted by the - * source ObservableSource, mapped by the keys returned by a specified {@code keySelector} function. + * finite source ObservableSource, mapped by the keys returned by a specified {@code keySelector} function. *

                * *

                * If more than one source item maps to the same key, the HashMap will contain a single entry that * corresponds to the latest of those items. + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code toMap} does not operate by default on a particular {@link Scheduler}.
                @@ -12976,9 +13005,13 @@ public final Single> toMap( /** * Returns a Single that emits a single Map, returned by a specified {@code mapFactory} function, that - * contains keys and values extracted from the items emitted by the source ObservableSource. + * contains keys and values extracted from the items emitted by the finite source ObservableSource. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code toMap} does not operate by default on a particular {@link Scheduler}.
                @@ -13010,9 +13043,13 @@ public final Single> toMap( /** * Returns a Single that emits a single HashMap that contains an ArrayList of items emitted by the - * source ObservableSource keyed by a specified {@code keySelector} function. + * finite source ObservableSource keyed by a specified {@code keySelector} function. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code toMultimap} does not operate by default on a particular {@link Scheduler}.
                @@ -13037,10 +13074,14 @@ public final Single>> toMultimap(Function * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code toMultimap} does not operate by default on a particular {@link Scheduler}.
                @@ -13106,9 +13147,13 @@ public final Single>> toMultimap( /** * Returns a Single that emits a single Map, returned by a specified {@code mapFactory} function, that * contains an ArrayList of values, extracted by a specified {@code valueSelector} function from items - * emitted by the source ObservableSource and keyed by the {@code keySelector} function. + * emitted by the finite source ObservableSource and keyed by the {@code keySelector} function. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code toMultimap} does not operate by default on a particular {@link Scheduler}.
                @@ -13193,7 +13238,7 @@ public final Flowable toFlowable(BackpressureStrategy strategy) { } /** - * Returns a Single that emits a list that contains the items emitted by the source ObservableSource, in a + * Returns a Single that emits a list that contains the items emitted by the finite source ObservableSource, in a * sorted order. Each item emitted by the ObservableSource must implement {@link Comparable} with respect to all * other items in the sequence. * @@ -13202,6 +13247,10 @@ public final Flowable toFlowable(BackpressureStrategy strategy) { * sequence is terminated with a {@link ClassCastException}. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated list to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code toSortedList} does not operate by default on a particular {@link Scheduler}.
                @@ -13217,10 +13266,14 @@ public final Single> toSortedList() { } /** - * Returns a Single that emits a list that contains the items emitted by the source ObservableSource, in a + * Returns a Single that emits a list that contains the items emitted by the finite source ObservableSource, in a * sorted order based on a specified comparison function. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated list to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code toSortedList} does not operate by default on a particular {@link Scheduler}.
                @@ -13241,10 +13294,14 @@ public final Single> toSortedList(final Comparator comparator } /** - * Returns a Single that emits a list that contains the items emitted by the source ObservableSource, in a + * Returns a Single that emits a list that contains the items emitted by the finite source ObservableSource, in a * sorted order based on a specified comparison function. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated list to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code toSortedList} does not operate by default on a particular {@link Scheduler}.
                @@ -13268,7 +13325,7 @@ public final Single> toSortedList(final Comparator comparator } /** - * Returns a Single that emits a list that contains the items emitted by the source ObservableSource, in a + * Returns a Single that emits a list that contains the items emitted by the finite source ObservableSource, in a * sorted order. Each item emitted by the ObservableSource must implement {@link Comparable} with respect to all * other items in the sequence. * @@ -13277,6 +13334,10 @@ public final Single> toSortedList(final Comparator comparator * sequence is terminated with a {@link ClassCastException}. *

                * + *

                + * Note that this operator requires the upstream to signal {@code onComplete} for the accumulated list to + * be emitted. Sources that are infinite and never complete will never emit anything through this + * operator and an infinite source may lead to a fatal {@code OutOfMemoryError}. *

                *
                Scheduler:
                *
                {@code toSortedList} does not operate by default on a particular {@link Scheduler}.
                From d6345dc9283ade1d28afa3507b769108f5929dd0 Mon Sep 17 00:00:00 2001 From: Dave Moten Date: Thu, 22 Feb 2018 23:24:20 +1100 Subject: [PATCH 104/417] 2.x: groupBy add overload with evicting map factory (#5860) --- build.gradle | 4 +- src/main/java/io/reactivex/Flowable.java | 109 +++++++- .../operators/flowable/FlowableGroupBy.java | 68 ++++- .../flowable/FlowableGroupByTest.java | 242 ++++++++++++++++++ 4 files changed, 416 insertions(+), 7 deletions(-) diff --git a/build.gradle b/build.gradle index 8cafd79d9d..ce96b1baef 100644 --- a/build.gradle +++ b/build.gradle @@ -43,6 +43,7 @@ apply plugin: "me.champeau.gradle.jmh" apply plugin: "com.github.hierynomus.license" apply plugin: "com.jfrog.bintray" apply plugin: "com.jfrog.artifactory" +apply plugin: "eclipse" sourceCompatibility = JavaVersion.VERSION_1_6 targetCompatibility = JavaVersion.VERSION_1_6 @@ -55,7 +56,7 @@ def reactiveStreamsVersion = "1.0.2" def mockitoVersion = "2.1.0" def jmhLibVersion = "1.19" def testNgVersion = "6.11" - +def guavaVersion = "24.0-jre" // -------------------------------------- repositories { @@ -73,6 +74,7 @@ dependencies { testImplementation "org.reactivestreams:reactive-streams-tck:$reactiveStreamsVersion" testImplementation "org.testng:testng:$testNgVersion" + testImplementation "com.google.guava:guava:$guavaVersion" } javadoc { diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index a80732ef0d..195577d526 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -9708,9 +9708,116 @@ public final Flowable> groupBy(Function(this, keySelector, valueSelector, bufferSize, delayError)); + return RxJavaPlugins.onAssembly(new FlowableGroupBy(this, keySelector, valueSelector, bufferSize, delayError, null)); } + /** + * Groups the items emitted by a {@code Publisher} according to a specified criterion, and emits these + * grouped items as {@link GroupedFlowable}s. The emitted {@code GroupedFlowable} allows only a single + * {@link Subscriber} during its lifetime and if this {@code Subscriber} cancels before the + * source terminates, the next emission by the source having the same key will trigger a new + * {@code GroupedPublisher} emission. The {@code evictingMapFactory} is used to create a map that will + * be used to hold the {@link GroupedFlowable}s by key. The evicting map created by this factory must + * notify the provided {@code Consumer} with the entry value (not the key!) when an entry in this + * map has been evicted. The next source emission will bring about the completion of the evicted + * {@link GroupedFlowable}s and the arrival of an item with the same key as a completed {@link GroupedFlowable} + * will prompt the creation and emission of a new {@link GroupedFlowable} with that key. + * + *

                A use case for specifying an {@code evictingMapFactory} is where the source is infinite and fast and + * over time the number of keys grows enough to be a concern in terms of the memory footprint of the + * internal hash map containing the {@link GroupedFlowable}s. + * + *

                The map created by an {@code evictingMapFactory} must be thread-safe. + * + *

                An example of an {@code evictingMapFactory} using CacheBuilder from the Guava library is below: + * + *

                +     * Function<Consumer<Object>, Map<Integer, Object>> evictingMapFactory = 
                +     *   notify ->
                +     *       CacheBuilder
                +     *         .newBuilder() 
                +     *         .maximumSize(3)
                +     *         .removalListener(entry -> {
                +     *              try {
                +     *                  // emit the value not the key!
                +     *                  notify.accept(entry.getValue());
                +     *              } catch (Exception e) {
                +     *                  throw new RuntimeException(e);
                +     *              }
                +     *            })
                +     *         .<Integer, Object> build()
                +     *         .asMap();
                +     *
                +     * // Emit 1000 items but ensure that the
                +     * // internal map never has more than 3 items in it           
                +     * Flowable
                +     *   .range(1, 1000)
                +     *   // note that number of keys is 10
                +     *   .groupBy(x -> x % 10, x -> x, true, 16, evictingMapFactory)
                +     *   .flatMap(g -> g)
                +     *   .forEach(System.out::println);
                +     * 
                + * + *

                + * + *

                + * Note: A {@link GroupedFlowable} will cache the items it is to emit until such time as it + * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those + * {@code GroupedFlowable}s that do not concern you. Instead, you can signal to them that they may + * discard their buffers by applying an operator like {@link #ignoreElements} to them. + *

                + *
                Backpressure:
                + *
                Both the returned and its inner {@code GroupedFlowable}s honor backpressure and the source {@code Publisher} + * is consumed in a bounded mode (i.e., requested a fixed amount upfront and replenished based on + * downstream consumption). Note that both the returned and its inner {@code GroupedFlowable}s use + * unbounded internal buffers and if the source {@code Publisher} doesn't honor backpressure, that may + * lead to {@code OutOfMemoryError}.
                + *
                Scheduler:
                + *
                {@code groupBy} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param keySelector + * a function that extracts the key for each item + * @param valueSelector + * a function that extracts the return element for each item + * @param delayError + * if true, the exception from the current Flowable is delayed in each group until that specific group emitted + * the normal values; if false, the exception bypasses values in the groups and is reported immediately. + * @param bufferSize + * the hint for how many {@link GroupedFlowable}s and element in each {@link GroupedFlowable} should be buffered + * @param evictingMapFactory + * The factory used to create a map that will be used by the implementation to hold the + * {@link GroupedFlowable}s. The evicting map created by this factory must + * notify the provided {@code Consumer} with the entry value (not the key!) when + * an entry in this map has been evicted. The next source emission will bring about the + * completion of the evicted {@link GroupedFlowable}s. See example above. + * @param + * the key type + * @param + * the element type + * @return a {@code Publisher} that emits {@link GroupedFlowable}s, each of which corresponds to a + * unique key value and each of which emits those items from the source Publisher that share that + * key value + * @see ReactiveX operators documentation: GroupBy + * + * @since 2.1.10 + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Beta + public final Flowable> groupBy(Function keySelector, + Function valueSelector, + boolean delayError, int bufferSize, + Function, ? extends Map> evictingMapFactory) { + ObjectHelper.requireNonNull(keySelector, "keySelector is null"); + ObjectHelper.requireNonNull(valueSelector, "valueSelector is null"); + ObjectHelper.verifyPositive(bufferSize, "bufferSize"); + ObjectHelper.requireNonNull(evictingMapFactory, "evictingMapFactory is null"); + + return RxJavaPlugins.onAssembly(new FlowableGroupBy(this, keySelector, valueSelector, bufferSize, delayError, evictingMapFactory)); + } + /** * Returns a Flowable that correlates two Publishers when they overlap in time and groups the results. *

                diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java index a89a47ff72..15dc85ebd9 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java @@ -14,7 +14,9 @@ package io.reactivex.internal.operators.flowable; import java.util.Map; +import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.*; import org.reactivestreams.*; @@ -23,11 +25,13 @@ import io.reactivex.annotations.Nullable; import io.reactivex.exceptions.Exceptions; import io.reactivex.flowables.GroupedFlowable; +import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.queue.SpscLinkedArrayQueue; import io.reactivex.internal.subscriptions.*; import io.reactivex.internal.util.BackpressureHelper; +import io.reactivex.internal.util.EmptyComponent; import io.reactivex.plugins.RxJavaPlugins; public final class FlowableGroupBy extends AbstractFlowableWithUpstream> { @@ -35,18 +39,42 @@ public final class FlowableGroupBy extends AbstractFlowableWithUpstream final Function valueSelector; final int bufferSize; final boolean delayError; + final Function, ? extends Map> mapFactory; - public FlowableGroupBy(Flowable source, Function keySelector, Function valueSelector, int bufferSize, boolean delayError) { + public FlowableGroupBy(Flowable source, Function keySelector, Function valueSelector, + int bufferSize, boolean delayError, Function, ? extends Map> mapFactory) { super(source); this.keySelector = keySelector; this.valueSelector = valueSelector; this.bufferSize = bufferSize; this.delayError = delayError; + this.mapFactory = mapFactory; } @Override protected void subscribeActual(Subscriber> s) { - source.subscribe(new GroupBySubscriber(s, keySelector, valueSelector, bufferSize, delayError)); + + final Map> groups; + final Queue> evictedGroups; + + try { + if (mapFactory == null) { + evictedGroups = null; + groups = new ConcurrentHashMap>(); + } else { + evictedGroups = new ConcurrentLinkedQueue>(); + Consumer evictionAction = (Consumer)(Consumer) new EvictionAction(evictedGroups); + groups = (Map>)(Map) mapFactory.apply(evictionAction); + } + } catch (Exception e) { + Exceptions.throwIfFatal(e); + s.onSubscribe(EmptyComponent.INSTANCE); + s.onError(e); + return; + } + GroupBySubscriber subscriber = + new GroupBySubscriber(s, keySelector, valueSelector, bufferSize, delayError, groups, evictedGroups); + source.subscribe(subscriber); } public static final class GroupBySubscriber @@ -62,6 +90,7 @@ public static final class GroupBySubscriber final boolean delayError; final Map> groups; final SpscLinkedArrayQueue> queue; + final Queue> evictedGroups; static final Object NULL_KEY = new Object(); @@ -78,13 +107,16 @@ public static final class GroupBySubscriber boolean outputFused; - public GroupBySubscriber(Subscriber> actual, Function keySelector, Function valueSelector, int bufferSize, boolean delayError) { + public GroupBySubscriber(Subscriber> actual, Function keySelector, + Function valueSelector, int bufferSize, boolean delayError, + Map> groups, Queue> evictedGroups) { this.actual = actual; this.keySelector = keySelector; this.valueSelector = valueSelector; this.bufferSize = bufferSize; this.delayError = delayError; - this.groups = new ConcurrentHashMap>(); + this.groups = groups; + this.evictedGroups = evictedGroups; this.queue = new SpscLinkedArrayQueue>(bufferSize); } @@ -144,6 +176,13 @@ public void onNext(T t) { } group.onNext(v); + + if (evictedGroups != null) { + GroupedUnicast evictedGroup; + while ((evictedGroup = evictedGroups.poll()) != null) { + evictedGroup.onComplete(); + } + } if (newGroup) { q.offer(group); @@ -161,7 +200,9 @@ public void onError(Throwable t) { g.onError(t); } groups.clear(); - + if (evictedGroups != null) { + evictedGroups.clear(); + } error = t; done = true; drain(); @@ -174,6 +215,9 @@ public void onComplete() { g.onComplete(); } groups.clear(); + if (evictedGroups != null) { + evictedGroups.clear(); + } done = true; drain(); } @@ -372,6 +416,20 @@ public boolean isEmpty() { } } + static final class EvictionAction implements Consumer> { + + final Queue> evictedGroups; + + EvictionAction(Queue> evictedGroups) { + this.evictedGroups = evictedGroups; + } + + @Override + public void accept(GroupedUnicast value) { + evictedGroups.offer(value); + } + } + static final class GroupedUnicast extends GroupedFlowable { final State state; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index afbe8e1108..e5497193cc 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -17,14 +17,20 @@ import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; +import java.io.IOException; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; +import io.reactivex.subjects.PublishSubject; import org.junit.Test; import org.mockito.Mockito; import org.reactivestreams.*; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.RemovalListener; +import com.google.common.cache.RemovalNotification; + import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.flowables.GroupedFlowable; @@ -1842,4 +1848,240 @@ public Publisher apply(GroupedFlowable g) throws Exce .test() .assertResult(1); } + + @Test + public void mapFactoryThrows() { + final IOException ex = new IOException("boo"); + Function, Map> evictingMapFactory = // + new Function, Map>() { + + @Override + public Map apply(final Consumer notify) throws Exception { + throw ex; + } + }; + Flowable.just(1) + .groupBy(Functions.identity(), Functions.identity(), true, 16, evictingMapFactory) + .test() + .assertNoValues() + .assertError(ex); + } + + @Test + public void mapFactoryExpiryCompletesGroupedFlowable() { + final List completed = new CopyOnWriteArrayList(); + Function, Map> evictingMapFactory = createEvictingMapFactorySynchronousOnly(1); + PublishSubject subject = PublishSubject.create(); + TestSubscriber ts = subject.toFlowable(BackpressureStrategy.BUFFER) + .groupBy(Functions.identity(), Functions.identity(), true, 16, evictingMapFactory) + .flatMap(addCompletedKey(completed)) + .test(); + subject.onNext(1); + subject.onNext(2); + subject.onNext(3); + ts.assertValues(1, 2, 3) + .assertNotTerminated(); + assertEquals(Arrays.asList(1, 2), completed); + //ensure coverage of the code that clears the evicted queue + subject.onComplete(); + ts.assertComplete(); + ts.assertValueCount(3); + } + + private static final Function mod5 = new Function() { + + @Override + public Integer apply(Integer n) throws Exception { + return n % 5; + } + }; + + @Test + public void mapFactoryWithExpiringGuavaCacheDemonstrationCodeForUseInJavadoc() { + //javadoc will be a version of this using lambdas and without assertions + final List completed = new CopyOnWriteArrayList(); + //size should be less than 5 to notice the effect + Function, Map> evictingMapFactory = createEvictingMapFactoryGuava(3); + int numValues = 1000; + TestSubscriber ts = + Flowable.range(1, numValues) + .groupBy(mod5, Functions.identity(), true, 16, evictingMapFactory) + .flatMap(addCompletedKey(completed)) + .test() + .assertComplete(); + ts.assertValueCount(numValues); + //the exact eviction behaviour of the guava cache is not specified so we make some approximate tests + assertTrue(completed.size() > numValues *0.9); + } + + @Test + public void mapFactoryEvictionQueueClearedOnErrorCoverageOnly() { + Function, Map> evictingMapFactory = createEvictingMapFactorySynchronousOnly(1); + PublishSubject subject = PublishSubject.create(); + TestSubscriber ts = subject + .toFlowable(BackpressureStrategy.BUFFER) + .groupBy(Functions.identity(), Functions.identity(), true, 16, evictingMapFactory) + .flatMap(new Function, Publisher>() { + @Override + public Publisher apply(GroupedFlowable g) throws Exception { + return g; + } + }) + .test(); + RuntimeException ex = new RuntimeException(); + //ensure coverage of the code that clears the evicted queue + subject.onError(ex); + ts.assertNoValues() + .assertError(ex); + } + + private static Function, Publisher> addCompletedKey( + final List completed) { + return new Function, Publisher>() { + @Override + public Publisher apply(final GroupedFlowable g) throws Exception { + return g.doOnComplete(new Action() { + @Override + public void run() throws Exception { + completed.add(g.getKey()); + } + }); + } + }; + } + + //not thread safe + private static final class SingleThreadEvictingHashMap implements Map { + + private final List list = new ArrayList(); + private final Map map = new HashMap(); + private final int maxSize; + private final Consumer evictedListener; + + SingleThreadEvictingHashMap(int maxSize, Consumer evictedListener) { + this.maxSize = maxSize; + this.evictedListener = evictedListener; + } + + @Override + public int size() { + return map.size(); + } + + @Override + public boolean isEmpty() { + return map.isEmpty(); + } + + @Override + public boolean containsKey(Object key) { + return map.containsKey(key); + } + + @Override + public boolean containsValue(Object value) { + return map.containsValue(value); + } + + @Override + public V get(Object key) { + return map.get(key); + } + + @Override + public V put(K key, V value) { + list.remove(key); + V v; + if (maxSize > 0 && list.size() == maxSize) { + //remove first + K k = list.get(0); + list.remove(0); + v = map.get(k); + } else { + v = null; + } + list.add(key); + V result = map.put(key, value); + if (v != null) { + try { + evictedListener.accept(v); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + return result; + } + + @Override + public V remove(Object key) { + return map.remove(key); + } + + @Override + public void putAll(Map m) { + map.putAll(m); + } + + @Override + public void clear() { + map.clear(); + } + + @Override + public Set keySet() { + return map.keySet(); + } + + @Override + public Collection values() { + return map.values(); + } + + @Override + public Set> entrySet() { + return map.entrySet(); + } + } + + private static Function, Map> createEvictingMapFactoryGuava(final int maxSize) { + Function, Map> evictingMapFactory = // + new Function, Map>(){ + + @Override + public Map apply(final Consumer notify) throws Exception { + return CacheBuilder.newBuilder() // + .maximumSize(maxSize) // + .removalListener(new RemovalListener() { + @Override + public void onRemoval(RemovalNotification notification) { + try { + notify.accept(notification.getValue()); + } catch (Exception e) { + throw new RuntimeException(e); + } + }}) + . build() + .asMap(); + }}; + return evictingMapFactory; + } + + private static Function, Map> createEvictingMapFactorySynchronousOnly(final int maxSize) { + Function, Map> evictingMapFactory = // + new Function, Map>(){ + + @Override + public Map apply(final Consumer notify) throws Exception { + return new SingleThreadEvictingHashMap(maxSize, new Consumer() { + @Override + public void accept(Object object) { + try { + notify.accept(object); + } catch (Exception e) { + throw new RuntimeException(e); + } + }}); + }}; + return evictingMapFactory; + } } From 10210e610c38e0e03b324099c66ab4c0a8fa1fad Mon Sep 17 00:00:00 2001 From: akarnokd Date: Thu, 22 Feb 2018 14:38:12 +0100 Subject: [PATCH 105/417] 2.x: Cleanup after the new groupBy additions --- src/main/java/io/reactivex/Flowable.java | 20 ++++++++--------- .../operators/flowable/FlowableGroupBy.java | 9 ++++---- .../flowable/FlowableGroupByTest.java | 22 +++++++++---------- 3 files changed, 26 insertions(+), 25 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 195577d526..e6f4c9aed9 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -9717,25 +9717,25 @@ public final Flowable> groupBy(Function} with the entry value (not the key!) when an entry in this * map has been evicted. The next source emission will bring about the completion of the evicted * {@link GroupedFlowable}s and the arrival of an item with the same key as a completed {@link GroupedFlowable} * will prompt the creation and emission of a new {@link GroupedFlowable} with that key. * *

                A use case for specifying an {@code evictingMapFactory} is where the source is infinite and fast and - * over time the number of keys grows enough to be a concern in terms of the memory footprint of the + * over time the number of keys grows enough to be a concern in terms of the memory footprint of the * internal hash map containing the {@link GroupedFlowable}s. * *

                The map created by an {@code evictingMapFactory} must be thread-safe. * *

                An example of an {@code evictingMapFactory} using CacheBuilder from the Guava library is below: * - *

                -     * Function<Consumer<Object>, Map<Integer, Object>> evictingMapFactory = 
                +     * 
                
                +     * Function<Consumer<Object>, Map<Integer, Object>> evictingMapFactory =
                      *   notify ->
                      *       CacheBuilder
                -     *         .newBuilder() 
                +     *         .newBuilder()
                      *         .maximumSize(3)
                      *         .removalListener(entry -> {
                      *              try {
                @@ -9749,14 +9749,14 @@ public final  Flowable> groupBy(Function
                +     * 
                * *

                * @@ -9786,7 +9786,7 @@ public final Flowable> groupBy(Function} with the entry value (not the key!) when * an entry in this map has been evicted. The next source emission will bring about the @@ -9808,7 +9808,7 @@ public final Flowable> groupBy(Function Flowable> groupBy(Function keySelector, Function valueSelector, - boolean delayError, int bufferSize, + boolean delayError, int bufferSize, Function, ? extends Map> evictingMapFactory) { ObjectHelper.requireNonNull(keySelector, "keySelector is null"); ObjectHelper.requireNonNull(valueSelector, "valueSelector is null"); @@ -9817,7 +9817,7 @@ public final Flowable> groupBy(Function(this, keySelector, valueSelector, bufferSize, delayError, evictingMapFactory)); } - + /** * Returns a Flowable that correlates two Publishers when they overlap in time and groups the results. *

                diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java index 15dc85ebd9..dd0f362e00 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java @@ -41,7 +41,7 @@ public final class FlowableGroupBy extends AbstractFlowableWithUpstream final boolean delayError; final Function, ? extends Map> mapFactory; - public FlowableGroupBy(Flowable source, Function keySelector, Function valueSelector, + public FlowableGroupBy(Flowable source, Function keySelector, Function valueSelector, int bufferSize, boolean delayError, Function, ? extends Map> mapFactory) { super(source); this.keySelector = keySelector; @@ -52,6 +52,7 @@ public FlowableGroupBy(Flowable source, Function keyS } @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) protected void subscribeActual(Subscriber> s) { final Map> groups; @@ -63,8 +64,8 @@ protected void subscribeActual(Subscriber> s) { groups = new ConcurrentHashMap>(); } else { evictedGroups = new ConcurrentLinkedQueue>(); - Consumer evictionAction = (Consumer)(Consumer) new EvictionAction(evictedGroups); - groups = (Map>)(Map) mapFactory.apply(evictionAction); + Consumer evictionAction = (Consumer) new EvictionAction(evictedGroups); + groups = (Map) mapFactory.apply(evictionAction); } } catch (Exception e) { Exceptions.throwIfFatal(e); @@ -176,7 +177,7 @@ public void onNext(T t) { } group.onNext(v); - + if (evictedGroups != null) { GroupedUnicast evictedGroup; while ((evictedGroup = evictedGroups.poll()) != null) { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index e5497193cc..100887474f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -1848,7 +1848,7 @@ public Publisher apply(GroupedFlowable g) throws Exce .test() .assertResult(1); } - + @Test public void mapFactoryThrows() { final IOException ex = new IOException("boo"); @@ -1860,13 +1860,13 @@ public Map apply(final Consumer notify) throws Exceptio throw ex; } }; - Flowable.just(1) - .groupBy(Functions.identity(), Functions.identity(), true, 16, evictingMapFactory) - .test() + Flowable.just(1) + .groupBy(Functions.identity(), Functions.identity(), true, 16, evictingMapFactory) + .test() .assertNoValues() .assertError(ex); } - + @Test public void mapFactoryExpiryCompletesGroupedFlowable() { final List completed = new CopyOnWriteArrayList(); @@ -1887,7 +1887,7 @@ public void mapFactoryExpiryCompletesGroupedFlowable() { ts.assertComplete(); ts.assertValueCount(3); } - + private static final Function mod5 = new Function() { @Override @@ -1895,7 +1895,7 @@ public Integer apply(Integer n) throws Exception { return n % 5; } }; - + @Test public void mapFactoryWithExpiringGuavaCacheDemonstrationCodeForUseInJavadoc() { //javadoc will be a version of this using lambdas and without assertions @@ -1911,9 +1911,9 @@ public void mapFactoryWithExpiringGuavaCacheDemonstrationCodeForUseInJavadoc() { .assertComplete(); ts.assertValueCount(numValues); //the exact eviction behaviour of the guava cache is not specified so we make some approximate tests - assertTrue(completed.size() > numValues *0.9); + assertTrue(completed.size() > numValues * 0.9); } - + @Test public void mapFactoryEvictionQueueClearedOnErrorCoverageOnly() { Function, Map> evictingMapFactory = createEvictingMapFactorySynchronousOnly(1); @@ -2045,7 +2045,7 @@ public Set> entrySet() { private static Function, Map> createEvictingMapFactoryGuava(final int maxSize) { Function, Map> evictingMapFactory = // - new Function, Map>(){ + new Function, Map>() { @Override public Map apply(final Consumer notify) throws Exception { @@ -2068,7 +2068,7 @@ public void onRemoval(RemovalNotification notification) { private static Function, Map> createEvictingMapFactorySynchronousOnly(final int maxSize) { Function, Map> evictingMapFactory = // - new Function, Map>(){ + new Function, Map>() { @Override public Map apply(final Consumer notify) throws Exception { From 237084f1cdff7fcf7caefb4c80c14f2d2d052fb7 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 23 Feb 2018 11:07:52 +0100 Subject: [PATCH 106/417] 2.x: Fix Javadoc warnings, links to the JDK types (#5861) --- build.gradle | 6 ++++-- src/main/java/io/reactivex/CompletableObserver.java | 1 - src/main/java/io/reactivex/MaybeObserver.java | 1 - src/main/java/io/reactivex/Observer.java | 1 - src/main/java/io/reactivex/SingleObserver.java | 1 - 5 files changed, 4 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index ce96b1baef..12a5b04978 100644 --- a/build.gradle +++ b/build.gradle @@ -91,8 +91,10 @@ javadoc { options.addStringOption("doctitle").value = "" options.addStringOption("header").value = "" - options.links("http://docs.oracle.com/javase/7/docs/api/") - options.links("http://www.reactive-streams.org/reactive-streams-$%7BreactiveStreamsVersion%7D-javadoc/") + options.links( + "https://docs.oracle.com/javase/7/docs/api/", + "http://www.reactive-streams.org/reactive-streams-$%7BreactiveStreamsVersion%7D-javadoc/" + ) if (JavaVersion.current().isJava7()) { // "./gradle/stylesheet.css" only supports Java 7 diff --git a/src/main/java/io/reactivex/CompletableObserver.java b/src/main/java/io/reactivex/CompletableObserver.java index a33a479128..eac7c9436b 100644 --- a/src/main/java/io/reactivex/CompletableObserver.java +++ b/src/main/java/io/reactivex/CompletableObserver.java @@ -28,7 +28,6 @@ * Calling the {@code CompletableObserver}'s method must happen in a serialized fashion, that is, they must not * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must * adhere to the following protocol: - *

                *

                    onSubscribe (onError | onComplete)?
                *

                * Subscribing a {@code CompletableObserver} to multiple {@code CompletableSource}s is not recommended. If such reuse diff --git a/src/main/java/io/reactivex/MaybeObserver.java b/src/main/java/io/reactivex/MaybeObserver.java index d2f4792245..76784484f1 100644 --- a/src/main/java/io/reactivex/MaybeObserver.java +++ b/src/main/java/io/reactivex/MaybeObserver.java @@ -28,7 +28,6 @@ * Calling the {@code MaybeObserver}'s method must happen in a serialized fashion, that is, they must not * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must * adhere to the following protocol: - *

                *

                    onSubscribe (onSuccess | onError | onComplete)?
                *

                * Note that unlike with the {@code Observable} protocol, {@link #onComplete()} is not called after the success item has been diff --git a/src/main/java/io/reactivex/Observer.java b/src/main/java/io/reactivex/Observer.java index cc3e62a573..4c446e67fb 100644 --- a/src/main/java/io/reactivex/Observer.java +++ b/src/main/java/io/reactivex/Observer.java @@ -30,7 +30,6 @@ * Calling the {@code Observer}'s method must happen in a serialized fashion, that is, they must not * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must * adhere to the following protocol: - *

                *

                    onSubscribe onNext* (onError | onComplete)?
                *

                * Subscribing an {@code Observer} to multiple {@code ObservableSource}s is not recommended. If such reuse diff --git a/src/main/java/io/reactivex/SingleObserver.java b/src/main/java/io/reactivex/SingleObserver.java index ed8adf58c7..6fefe167a8 100644 --- a/src/main/java/io/reactivex/SingleObserver.java +++ b/src/main/java/io/reactivex/SingleObserver.java @@ -28,7 +28,6 @@ * Calling the {@code SingleObserver}'s method must happen in a serialized fashion, that is, they must not * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must * adhere to the following protocol: - *

                *

                    onSubscribe (onSuccess | onError)?
                *

                * Subscribing a {@code SingleObserver} to multiple {@code SingleSource}s is not recommended. If such reuse From 569c5abe4a7f21f1a986829e43df206216c98521 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sat, 24 Feb 2018 11:17:51 +0100 Subject: [PATCH 107/417] Release 2.1.10 --- CHANGES.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index ca54235019..f277c7b5c8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,37 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.10 - February 24, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.10%7C)) + +#### API changes + +- [Pull 5845](https://github.com/ReactiveX/RxJava/pull/5845): Add efficient `concatWith(Single|Maybe|Completable)` overloads to `Flowable` and `Observable`. +- [Pull 5847](https://github.com/ReactiveX/RxJava/pull/5847): Add efficient `mergeWith(Single|Maybe|Completable)` overloads to `Flowable` and `Observable`. +- [Pull 5860](https://github.com/ReactiveX/RxJava/pull/5860): Add `Flowable.groupBy` overload with evicting map factory. + +#### Documentation changes + +- [Pull 5824](https://github.com/ReactiveX/RxJava/pull/5824): Improve the wording of the `share()` JavaDocs. +- [Pull 5826](https://github.com/ReactiveX/RxJava/pull/5826): Fix `Observable.blockingIterable(int)` and add `Observable.blockingLatest` marbles. +- [Pull 5828](https://github.com/ReactiveX/RxJava/pull/5828): Document size-bounded `replay` emission's item retention property. +- [Pull 5830](https://github.com/ReactiveX/RxJava/pull/5830): Reword the `just()` operator and reference other typical alternatives. +- [Pull 5834](https://github.com/ReactiveX/RxJava/pull/5834): Fix copy-paste errors in `SingleSubject` JavaDoc. +- [Pull 5837](https://github.com/ReactiveX/RxJava/pull/5837): Detail `distinct()` and `distinctUntilChanged()` in JavaDoc. +- [Pull 5841](https://github.com/ReactiveX/RxJava/pull/5841): Improve JavaDoc of `Observer`, `SingleObserver`, `MaybeObserver` and `CompletableObserver`. +- [Pull 5843](https://github.com/ReactiveX/RxJava/pull/5843): Expand the JavaDocs of the `Scheduler` API. +- [Pull 5844](https://github.com/ReactiveX/RxJava/pull/5844): Explain the properties of the `{Flowable|Observable|Single|Maybe|Completable}Emitter` interfaces in detail. +- [Pull 5848](https://github.com/ReactiveX/RxJava/pull/5848): Improve the wording of the `Maybe.fromCallable` JavaDoc. +- [Pull 5856](https://github.com/ReactiveX/RxJava/pull/5856): Add finite requirement to various collector operators' JavaDoc. + +#### Bugfixes + +- [Pull 5833](https://github.com/ReactiveX/RxJava/pull/5833): Fix `Observable.switchMap` main `onError` not disposing the current inner source. + +#### Other changes + +- [Pull 5838](https://github.com/ReactiveX/RxJava/pull/5838): Added nullability annotation for completable assembly. +- [Pull 5858](https://github.com/ReactiveX/RxJava/pull/5858): Remove unnecessary comment from `Observable.timeInterval(TimeUnit)`. + ### Version 2.1.9 - January 24, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.9%7C)) #### API changes From 3346ff9a868b74ae767905e5e4185e81d58f4a98 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 26 Feb 2018 12:45:35 +0100 Subject: [PATCH 108/417] 2.x: Expand the documentation of the Flowable.lift() operator (#5863) --- src/main/java/io/reactivex/Flowable.java | 150 ++++++++++++++++++++--- 1 file changed, 133 insertions(+), 17 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index e6f4c9aed9..c4486b81ed 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -10063,34 +10063,150 @@ public final Single lastOrError() { } /** - * This method requires advanced knowledge about building operators; please consider + * This method requires advanced knowledge about building operators, please consider * other standard composition methods first; - * Lifts a function to the current Publisher and returns a new Publisher that when subscribed to will pass - * the values of the current Publisher through the Operator function. + * Returns a {@code Flowable} which, when subscribed to, invokes the {@link FlowableOperator#apply(Subscriber) apply(Subscriber)} method + * of the provided {@link FlowableOperator} for each individual downstream {@link Subscriber} and allows the + * insertion of a custom operator by accessing the downstream's {@link Subscriber} during this subscription phase + * and providing a new {@code Subscriber}, containing the custom operator's intended business logic, that will be + * used in the subscription process going further upstream. + *

                + * Generally, such a new {@code Subscriber} will wrap the downstream's {@code Subscriber} and forwards the + * {@code onNext}, {@code onError} and {@code onComplete} events from the upstream directly or according to the + * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the + * flow control calls of {@code cancel} and {@code request} that would have travelled upstream and perform + * additional actions depending on the same business logic requirements. *

                - * In other words, this allows chaining Subscribers together on a Publisher for acting on the values within - * the Publisher. - *

                {@code - * Publisher.map(...).filter(...).take(5).lift(new OperatorA()).lift(new OperatorB(...)).subscribe() + * Example: + *

                
                +     * // Step 1: Create the consumer type that will be returned by the FlowableOperator.apply():
                +     * 
                +     * public final class CustomSubscriber<T> implements FlowableSubscriber<T>, Subscription {
                +     *
                +     *     // The donstream's Subscriber that will receive the onXXX events
                +     *     final Subscriber<? super String> downstream;
                +     *
                +     *     // The connection to the upstream source that will call this class' onXXX methods
                +     *     Subscription upstream;
                +     *
                +     *     // The constructor takes the downstream subscriber and usually any other parameters
                +     *     public CustomSubscriber(Subscriber<? super String> downstream) {
                +     *         this.downstream = downstream;
                +     *     }
                +     *
                +     *     // In the subscription phase, the upstream sends a Subscription to this class
                +     *     // and subsequently this class has to send a Subscription to the downstream.
                +     *     // Note that relaying the upstream's Subscription directly is not allowed in RxJava
                +     *     @Override
                +     *     public void onSubscribe(Subscription s) {
                +     *         if (upstream != null) {
                +     *             s.cancel();
                +     *         } else {
                +     *             upstream = s;
                +     *             downstream.onSubscribe(this);
                +     *         }
                +     *     }
                +     *
                +     *     // The upstream calls this with the next item and the implementation's
                +     *     // responsibility is to emit an item to the downstream based on the intended
                +     *     // business logic, or if it can't do so for the particular item,
                +     *     // request more from the upstream
                +     *     @Override
                +     *     public void onNext(T item) {
                +     *         String str = item.toString();
                +     *         if (str.length() < 2) {
                +     *             downstream.onNext(str);
                +     *         } else {
                +     *             upstream.request(1);
                +     *         }
                +     *     }
                +     *
                +     *     // Some operators may handle the upstream's error while others
                +     *     // could just forward it to the downstream.
                +     *     @Override
                +     *     public void onError(Throwable throwable) {
                +     *         downstream.onError(throwable);
                +     *     }
                +     *
                +     *     // When the upstream completes, usually the downstream should complete as well.
                +     *     @Override
                +     *     public void onComplete() {
                +     *         downstream.onComplete();
                +     *     }
                +     *
                +     *     // Some operators have to intercept the downstream's request calls to trigger
                +     *     // the emission of queued items while others can simply forward the request
                +     *     // amount as is.
                +     *     @Override
                +     *     public void request(long n) {
                +     *         upstream.request(n);
                +     *     }
                +     *
                +     *     // Some operators may use their own resources which should be cleaned up if
                +     *     // the downstream cancels the flow before it completed. Operators without
                +     *     // resources can simply forward the cancellation to the upstream.
                +     *     // In some cases, a cancelled flag may be set by this method so that other parts
                +     *     // of this class may detect the cancellation and stop sending events
                +     *     // to the downstream.
                +     *     @Override
                +     *     public void cancel() {
                +     *         upstream.cancel();
                +     *     }
                      * }
                +     *
                +     * // Step 2: Create a class that implements the FlowableOperator interface and
                +     * //         returns the custom consumer type from above in its apply() method.
                +     * //         Such class may define additional parameters to be submitted to
                +     * //         the custom consumer type.
                +     *
                +     * final class CustomOperator<T> implements FlowableOperator<String> {
                +     *     @Override
                +     *     public Subscriber<? super String> apply(Subscriber<? super T> upstream) {
                +     *         return new CustomSubscriber<T>(upstream);
                +     *     }
                +     * }
                +     *
                +     * // Step 3: Apply the custom operator via lift() in a flow by creating an instance of it
                +     * //         or reusing an existing one.
                +     *
                +     * Flowable.range(5, 10)
                +     * .lift(new CustomOperator<Integer>())
                +     * .test()
                +     * .assertResult("5", "6", "7", "8", "9");
                +     * 
                *

                - * If the operator you are creating is designed to act on the individual items emitted by a source - * Publisher, use {@code lift}. If your operator is designed to transform the source Publisher as a whole - * (for instance, by applying a particular set of existing RxJava operators to it) use {@link #compose}. + * Creating custom operators can be complicated and it is recommended one consults the + * RxJava wiki: Writing operators page about + * the tools, requirements, rules, considerations and pitfalls of implementing them. + *

                + * Note that implementing custom operators via this {@code lift()} method adds slightly more overhead by requiring + * an additional allocation and indirection per assembled flows. Instead, extending the abstract {@code Flowable} + * class and creating a {@link FlowableTransformer} with it is recommended. + *

                + * Note also that it is not possible to stop the subscription phase in {@code lift()} as the {@code apply()} method + * requires a non-null {@code Subscriber} instance to be returned, which is then unconditionally subscribed to + * the upstream {@code Flowable}. For example, if the operator decided there is no reason to subscribe to the + * upstream source because of some optimization possibility or a failure to prepare the operator, it still has to + * return a {@code Subscriber} that should immediately cancel the upstream's {@code Subscription} in its + * {@code onSubscribe} method. Again, using a {@code FlowableTransformer} and extending the {@code Flowable} is + * a better option as {@link #subscribeActual} can decide to not subscribe to its upstream after all. *

                *
                Backpressure:
                - *
                The {@code Operator} instance provided is responsible to be backpressure-aware or - * document the fact that the consumer of the returned {@code Publisher} has to apply one of + *
                The {@code Subscriber} instance returned by the {@link FlowableOperator} is responsible to be + * backpressure-aware or document the fact that the consumer of the returned {@code Publisher} has to apply one of * the {@code onBackpressureXXX} operators.
                *
                Scheduler:
                - *
                {@code lift} does not operate by default on a particular {@link Scheduler}.
                + *
                {@code lift} does not operate by default on a particular {@link Scheduler}, however, the + * {@link FlowableOperator} may use a {@code Scheduler} to support its own asynchronous behavior.
                *
                * * @param the output value type - * @param lifter the Operator that implements the Publisher-operating function to be applied to the source - * Publisher - * @return a Flowable that is the result of applying the lifted Operator to the source Publisher - * @see RxJava wiki: Implementing Your Own Operators + * @param lifter the {@link FlowableOperator} that receives the downstream's {@code Subscriber} and should return + * a {@code Subscriber} with custom behavior to be used as the consumer for the current + * {@code Flowable}. + * @return the new Flowable instance + * @see RxJava wiki: Writing operators + * @see #compose(FlowableTransformer) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.SPECIAL) From 5f452559382bab37efd181071c047f260fd26fd1 Mon Sep 17 00:00:00 2001 From: Dave Moten Date: Tue, 27 Feb 2018 10:22:45 +1100 Subject: [PATCH 109/417] enhance test for groupBy with evicting map factory (#5867) --- .../internal/operators/flowable/FlowableGroupByTest.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index 100887474f..cccfb38a0f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -1996,7 +1996,7 @@ public V put(K key, V value) { //remove first K k = list.get(0); list.remove(0); - v = map.get(k); + v = map.remove(k); } else { v = null; } @@ -2014,16 +2014,20 @@ public V put(K key, V value) { @Override public V remove(Object key) { + list.remove(key); return map.remove(key); } @Override public void putAll(Map m) { - map.putAll(m); + for (Entry entry: m.entrySet()) { + put(entry.getKey(), entry.getValue()); + } } @Override public void clear() { + list.clear(); map.clear(); } From 8068404179b0d2e07da6f0e10ea95110d98e118d Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 28 Feb 2018 09:41:24 +0100 Subject: [PATCH 110/417] 2.x: Improve the JavaDoc of the other lift() operators (#5865) --- src/main/java/io/reactivex/Completable.java | 127 +++++++++++++++- src/main/java/io/reactivex/Flowable.java | 8 +- src/main/java/io/reactivex/Maybe.java | 154 ++++++++++++++++++-- src/main/java/io/reactivex/Observable.java | 146 +++++++++++++++++-- src/main/java/io/reactivex/Single.java | 148 +++++++++++++++++-- 5 files changed, 529 insertions(+), 54 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index c9f891b500..134119fa08 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1369,15 +1369,132 @@ public final Completable doFinally(Action onFinally) { } /** - * Advanced use without safeguards: lifts a CompletableOperator - * transformation into the chain of Completables. + * This method requires advanced knowledge about building operators, please consider + * other standard composition methods first; + * Returns a {@code Completable} which, when subscribed to, invokes the {@link CompletableOperator#apply(CompletableObserver) apply(CompletableObserver)} method + * of the provided {@link CompletableOperator} for each individual downstream {@link Completable} and allows the + * insertion of a custom operator by accessing the downstream's {@link CompletableObserver} during this subscription phase + * and providing a new {@code CompletableObserver}, containing the custom operator's intended business logic, that will be + * used in the subscription process going further upstream. + *

                + * Generally, such a new {@code CompletableObserver} will wrap the downstream's {@code CompletableObserver} and forwards the + * {@code onError} and {@code onComplete} events from the upstream directly or according to the + * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the + * flow control calls of {@code dispose} and {@code isDisposed} that would have traveled upstream and perform + * additional actions depending on the same business logic requirements. + *

                + * Example: + *

                
                +     * // Step 1: Create the consumer type that will be returned by the CompletableOperator.apply():
                +     * 
                +     * public final class CustomCompletableObserver implements CompletableObserver, Disposable {
                +     *
                +     *     // The donstream's CompletableObserver that will receive the onXXX events
                +     *     final CompletableObserver downstream;
                +     *
                +     *     // The connection to the upstream source that will call this class' onXXX methods
                +     *     Disposable upstream;
                +     *
                +     *     // The constructor takes the downstream subscriber and usually any other parameters
                +     *     public CustomCompletableObserver(CompletableObserver downstream) {
                +     *         this.downstream = downstream;
                +     *     }
                +     *
                +     *     // In the subscription phase, the upstream sends a Disposable to this class
                +     *     // and subsequently this class has to send a Disposable to the downstream.
                +     *     // Note that relaying the upstream's Disposable directly is not allowed in RxJava
                +     *     @Override
                +     *     public void onSubscribe(Disposable s) {
                +     *         if (upstream != null) {
                +     *             s.cancel();
                +     *         } else {
                +     *             upstream = s;
                +     *             downstream.onSubscribe(this);
                +     *         }
                +     *     }
                +     *
                +     *     // Some operators may handle the upstream's error while others
                +     *     // could just forward it to the downstream.
                +     *     @Override
                +     *     public void onError(Throwable throwable) {
                +     *         downstream.onError(throwable);
                +     *     }
                +     *
                +     *     // When the upstream completes, usually the downstream should complete as well.
                +     *     // In completable, this could also mean doing some side-effects
                +     *     @Override
                +     *     public void onComplete() {
                +     *         System.out.println("Sequence completed");
                +     *         downstream.onComplete();
                +     *     }
                +     *
                +     *     // Some operators may use their own resources which should be cleaned up if
                +     *     // the downstream disposes the flow before it completed. Operators without
                +     *     // resources can simply forward the dispose to the upstream.
                +     *     // In some cases, a disposed flag may be set by this method so that other parts
                +     *     // of this class may detect the dispose and stop sending events
                +     *     // to the downstream.
                +     *     @Override
                +     *     public void dispose() {
                +     *         upstream.dispose();
                +     *     }
                +     *
                +     *     // Some operators may simply forward the call to the upstream while others
                +     *     // can return the disposed flag set in dispose().
                +     *     @Override
                +     *     public boolean isDisposed() {
                +     *         return upstream.isDisposed();
                +     *     }
                +     * }
                +     *
                +     * // Step 2: Create a class that implements the CompletableOperator interface and
                +     * //         returns the custom consumer type from above in its apply() method.
                +     * //         Such class may define additional parameters to be submitted to
                +     * //         the custom consumer type.
                +     *
                +     * final class CustomCompletableOperator implements CompletableOperator {
                +     *     @Override
                +     *     public CompletableObserver apply(CompletableObserver upstream) {
                +     *         return new CustomCompletableObserver(upstream);
                +     *     }
                +     * }
                +     *
                +     * // Step 3: Apply the custom operator via lift() in a flow by creating an instance of it
                +     * //         or reusing an existing one.
                +     *
                +     * Completable.complete()
                +     * .lift(new CustomCompletableOperator())
                +     * .test()
                +     * .assertResult();
                +     * 
                + *

                + * Creating custom operators can be complicated and it is recommended one consults the + * RxJava wiki: Writing operators page about + * the tools, requirements, rules, considerations and pitfalls of implementing them. + *

                + * Note that implementing custom operators via this {@code lift()} method adds slightly more overhead by requiring + * an additional allocation and indirection per assembled flows. Instead, extending the abstract {@code Completable} + * class and creating a {@link CompletableTransformer} with it is recommended. + *

                + * Note also that it is not possible to stop the subscription phase in {@code lift()} as the {@code apply()} method + * requires a non-null {@code CompletableObserver} instance to be returned, which is then unconditionally subscribed to + * the upstream {@code Completable}. For example, if the operator decided there is no reason to subscribe to the + * upstream source because of some optimization possibility or a failure to prepare the operator, it still has to + * return a {@code CompletableObserver} that should immediately dispose the upstream's {@code Disposable} in its + * {@code onSubscribe} method. Again, using a {@code CompletableTransformer} and extending the {@code Completable} is + * a better option as {@link #subscribeActual} can decide to not subscribe to its upstream after all. *

                *
                Scheduler:
                - *
                {@code lift} does not operate by default on a particular {@link Scheduler}.
                + *
                {@code lift} does not operate by default on a particular {@link Scheduler}, however, the + * {@link CompletableOperator} may use a {@code Scheduler} to support its own asynchronous behavior.
                *
                - * @param onLift the lifting function that transforms the child subscriber with a parent subscriber. + * + * @param onLift the {@link CompletableOperator} that receives the downstream's {@code CompletableObserver} and should return + * a {@code CompletableObserver} with custom behavior to be used as the consumer for the current + * {@code Completable}. * @return the new Completable instance - * @throws NullPointerException if onLift is null + * @see RxJava wiki: Writing operators + * @see #compose(CompletableTransformer) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index c4486b81ed..f9d7148c8b 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -10068,13 +10068,13 @@ public final Single lastOrError() { * Returns a {@code Flowable} which, when subscribed to, invokes the {@link FlowableOperator#apply(Subscriber) apply(Subscriber)} method * of the provided {@link FlowableOperator} for each individual downstream {@link Subscriber} and allows the * insertion of a custom operator by accessing the downstream's {@link Subscriber} during this subscription phase - * and providing a new {@code Subscriber}, containing the custom operator's intended business logic, that will be + * and providing a new {@code Subscriber}, containing the custom operator's intended business logic, that will be * used in the subscription process going further upstream. *

                * Generally, such a new {@code Subscriber} will wrap the downstream's {@code Subscriber} and forwards the * {@code onNext}, {@code onError} and {@code onComplete} events from the upstream directly or according to the - * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the - * flow control calls of {@code cancel} and {@code request} that would have travelled upstream and perform + * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the + * flow control calls of {@code cancel} and {@code request} that would have traveled upstream and perform * additional actions depending on the same business logic requirements. *

                * Example: @@ -10192,7 +10192,7 @@ public final Single lastOrError() { * a better option as {@link #subscribeActual} can decide to not subscribe to its upstream after all. *

                *
                Backpressure:
                - *
                The {@code Subscriber} instance returned by the {@link FlowableOperator} is responsible to be + *
                The {@code Subscriber} instance returned by the {@link FlowableOperator} is responsible to be * backpressure-aware or document the fact that the consumer of the returned {@code Publisher} has to apply one of * the {@code onBackpressureXXX} operators.
                *
                Scheduler:
                diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 83b7c92969..1f21b32a89 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3110,27 +3110,151 @@ public final Single isEmpty() { } /** - * Lifts a function to the current Maybe and returns a new Maybe that when subscribed to will pass the - * values of the current Maybe through the MaybeOperator function. + * This method requires advanced knowledge about building operators, please consider + * other standard composition methods first; + * Returns a {@code Maybe} which, when subscribed to, invokes the {@link MaybeOperator#apply(MaybeObserver) apply(MaybeObserver)} method + * of the provided {@link MaybeOperator} for each individual downstream {@link Maybe} and allows the + * insertion of a custom operator by accessing the downstream's {@link MaybeObserver} during this subscription phase + * and providing a new {@code MaybeObserver}, containing the custom operator's intended business logic, that will be + * used in the subscription process going further upstream. + *

                + * Generally, such a new {@code MaybeObserver} will wrap the downstream's {@code MaybeObserver} and forwards the + * {@code onSuccess}, {@code onError} and {@code onComplete} events from the upstream directly or according to the + * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the + * flow control calls of {@code dispose} and {@code isDisposed} that would have traveled upstream and perform + * additional actions depending on the same business logic requirements. *

                - * In other words, this allows chaining TaskExecutors together on a Maybe for acting on the values within - * the Maybe. + * Example: + *

                
                +     * // Step 1: Create the consumer type that will be returned by the MaybeOperator.apply():
                +     * 
                +     * public final class CustomMaybeObserver<T> implements MaybeObserver<T>, Disposable {
                +     *
                +     *     // The donstream's MaybeObserver that will receive the onXXX events
                +     *     final MaybeObserver<? super String> downstream;
                +     *
                +     *     // The connection to the upstream source that will call this class' onXXX methods
                +     *     Disposable upstream;
                +     *
                +     *     // The constructor takes the downstream subscriber and usually any other parameters
                +     *     public CustomMaybeObserver(MaybeObserver<? super String> downstream) {
                +     *         this.downstream = downstream;
                +     *     }
                +     *
                +     *     // In the subscription phase, the upstream sends a Disposable to this class
                +     *     // and subsequently this class has to send a Disposable to the downstream.
                +     *     // Note that relaying the upstream's Disposable directly is not allowed in RxJava
                +     *     @Override
                +     *     public void onSubscribe(Disposable s) {
                +     *         if (upstream != null) {
                +     *             s.cancel();
                +     *         } else {
                +     *             upstream = s;
                +     *             downstream.onSubscribe(this);
                +     *         }
                +     *     }
                +     *
                +     *     // The upstream calls this with the next item and the implementation's
                +     *     // responsibility is to emit an item to the downstream based on the intended
                +     *     // business logic, or if it can't do so for the particular item,
                +     *     // request more from the upstream
                +     *     @Override
                +     *     public void onSuccess(T item) {
                +     *         String str = item.toString();
                +     *         if (str.length() < 2) {
                +     *             downstream.onSuccess(str);
                +     *         } else {
                +     *             // Maybe is usually expected to produce one of the onXXX events
                +     *             downstream.onComplete();
                +     *         }
                +     *     }
                +     *
                +     *     // Some operators may handle the upstream's error while others
                +     *     // could just forward it to the downstream.
                +     *     @Override
                +     *     public void onError(Throwable throwable) {
                +     *         downstream.onError(throwable);
                +     *     }
                +     *
                +     *     // When the upstream completes, usually the downstream should complete as well.
                +     *     @Override
                +     *     public void onComplete() {
                +     *         downstream.onComplete();
                +     *     }
                +     *
                +     *     // Some operators may use their own resources which should be cleaned up if
                +     *     // the downstream disposes the flow before it completed. Operators without
                +     *     // resources can simply forward the dispose to the upstream.
                +     *     // In some cases, a disposed flag may be set by this method so that other parts
                +     *     // of this class may detect the dispose and stop sending events
                +     *     // to the downstream.
                +     *     @Override
                +     *     public void dispose() {
                +     *         upstream.dispose();
                +     *     }
                +     *
                +     *     // Some operators may simply forward the call to the upstream while others
                +     *     // can return the disposed flag set in dispose().
                +     *     @Override
                +     *     public boolean isDisposed() {
                +     *         return upstream.isDisposed();
                +     *     }
                +     * }
                +     *
                +     * // Step 2: Create a class that implements the MaybeOperator interface and
                +     * //         returns the custom consumer type from above in its apply() method.
                +     * //         Such class may define additional parameters to be submitted to
                +     * //         the custom consumer type.
                +     *
                +     * final class CustomMaybeOperator<T> implements MaybeOperator<String> {
                +     *     @Override
                +     *     public MaybeObserver<? super String> apply(MaybeObserver<? super T> upstream) {
                +     *         return new CustomMaybeObserver<T>(upstream);
                +     *     }
                +     * }
                +     *
                +     * // Step 3: Apply the custom operator via lift() in a flow by creating an instance of it
                +     * //         or reusing an existing one.
                +     *
                +     * Maybe.just(5)
                +     * .lift(new CustomMaybeOperator<Integer>())
                +     * .test()
                +     * .assertResult("5");
                +     *
                +     * Maybe.just(15)
                +     * .lift(new CustomMaybeOperator<Integer>())
                +     * .test()
                +     * .assertResult();
                +     * 
                + *

                + * Creating custom operators can be complicated and it is recommended one consults the + * RxJava wiki: Writing operators page about + * the tools, requirements, rules, considerations and pitfalls of implementing them. *

                - * {@code task.map(...).filter(...).lift(new OperatorA()).lift(new OperatorB(...)).subscribe() } + * Note that implementing custom operators via this {@code lift()} method adds slightly more overhead by requiring + * an additional allocation and indirection per assembled flows. Instead, extending the abstract {@code Maybe} + * class and creating a {@link MaybeTransformer} with it is recommended. *

                - * If the operator you are creating is designed to act on the item emitted by a source Maybe, use - * {@code lift}. If your operator is designed to transform the source Maybe as a whole (for instance, by - * applying a particular set of existing RxJava operators to it) use {@link #compose}. + * Note also that it is not possible to stop the subscription phase in {@code lift()} as the {@code apply()} method + * requires a non-null {@code MaybeObserver} instance to be returned, which is then unconditionally subscribed to + * the upstream {@code Maybe}. For example, if the operator decided there is no reason to subscribe to the + * upstream source because of some optimization possibility or a failure to prepare the operator, it still has to + * return a {@code MaybeObserver} that should immediately dispose the upstream's {@code Disposable} in its + * {@code onSubscribe} method. Again, using a {@code MaybeTransformer} and extending the {@code Maybe} is + * a better option as {@link #subscribeActual} can decide to not subscribe to its upstream after all. *

                - *
                Scheduler:
                - *
                {@code lift} does not operate by default on a particular {@link Scheduler}.
                + *
                Scheduler:
                + *
                {@code lift} does not operate by default on a particular {@link Scheduler}, however, the + * {@link MaybeOperator} may use a {@code Scheduler} to support its own asynchronous behavior.
                *
                * - * @param the downstream's value type (output) - * @param lift - * the MaybeOperator that implements the Maybe-operating function to be applied to the source Maybe - * @return a Maybe that is the result of applying the lifted Operator to the source Maybe - * @see RxJava wiki: Implementing Your Own Operators + * @param the output value type + * @param lift the {@link MaybeOperator} that receives the downstream's {@code MaybeObserver} and should return + * a {@code MaybeObserver} with custom behavior to be used as the consumer for the current + * {@code Maybe}. + * @return the new Maybe instance + * @see RxJava wiki: Writing operators + * @see #compose(MaybeTransformer) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 0d8fd01825..da7160f81e 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -8899,30 +8899,146 @@ public final Single lastOrError() { } /** - * This method requires advanced knowledge about building operators; please consider + * This method requires advanced knowledge about building operators, please consider * other standard composition methods first; - * Lifts a function to the current ObservableSource and returns a new ObservableSource that when subscribed to will pass - * the values of the current ObservableSource through the Operator function. + * Returns an {@code Observable} which, when subscribed to, invokes the {@link ObservableOperator#apply(Observer) apply(Observer)} method + * of the provided {@link ObservableOperator} for each individual downstream {@link Observer} and allows the + * insertion of a custom operator by accessing the downstream's {@link Observer} during this subscription phase + * and providing a new {@code Observer}, containing the custom operator's intended business logic, that will be + * used in the subscription process going further upstream. + *

                + * Generally, such a new {@code Observer} will wrap the downstream's {@code Observer} and forwards the + * {@code onNext}, {@code onError} and {@code onComplete} events from the upstream directly or according to the + * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the + * flow control calls of {@code dispose} and {@code isDisposed} that would have traveled upstream and perform + * additional actions depending on the same business logic requirements. *

                - * In other words, this allows chaining Observers together on an ObservableSource for acting on the values within - * the ObservableSource. - *

                {@code - * ObservableSource.map(...).filter(...).take(5).lift(new OperatorA()).lift(new OperatorB(...)).subscribe() + * Example: + *

                
                +     * // Step 1: Create the consumer type that will be returned by the ObservableOperator.apply():
                +     * 
                +     * public final class CustomObserver<T> implements Observer<T>, Disposable {
                +     *
                +     *     // The donstream's Observer that will receive the onXXX events
                +     *     final Observer<? super String> downstream;
                +     *
                +     *     // The connection to the upstream source that will call this class' onXXX methods
                +     *     Disposable upstream;
                +     *
                +     *     // The constructor takes the downstream subscriber and usually any other parameters
                +     *     public CustomObserver(Observer<? super String> downstream) {
                +     *         this.downstream = downstream;
                +     *     }
                +     *
                +     *     // In the subscription phase, the upstream sends a Disposable to this class
                +     *     // and subsequently this class has to send a Disposable to the downstream.
                +     *     // Note that relaying the upstream's Disposable directly is not allowed in RxJava
                +     *     @Override
                +     *     public void onSubscribe(Disposable s) {
                +     *         if (upstream != null) {
                +     *             s.cancel();
                +     *         } else {
                +     *             upstream = s;
                +     *             downstream.onSubscribe(this);
                +     *         }
                +     *     }
                +     *
                +     *     // The upstream calls this with the next item and the implementation's
                +     *     // responsibility is to emit an item to the downstream based on the intended
                +     *     // business logic, or if it can't do so for the particular item,
                +     *     // request more from the upstream
                +     *     @Override
                +     *     public void onNext(T item) {
                +     *         String str = item.toString();
                +     *         if (str.length() < 2) {
                +     *             downstream.onNext(str);
                +     *         }
                +     *         // Observable doesn't support backpressure, therefore, there is no
                +     *         // need or opportunity to call upstream.request(1) if an item
                +     *         // is not produced to the downstream
                +     *     }
                +     *
                +     *     // Some operators may handle the upstream's error while others
                +     *     // could just forward it to the downstream.
                +     *     @Override
                +     *     public void onError(Throwable throwable) {
                +     *         downstream.onError(throwable);
                +     *     }
                +     *
                +     *     // When the upstream completes, usually the downstream should complete as well.
                +     *     @Override
                +     *     public void onComplete() {
                +     *         downstream.onComplete();
                +     *     }
                +     *
                +     *     // Some operators may use their own resources which should be cleaned up if
                +     *     // the downstream disposes the flow before it completed. Operators without
                +     *     // resources can simply forward the dispose to the upstream.
                +     *     // In some cases, a disposed flag may be set by this method so that other parts
                +     *     // of this class may detect the dispose and stop sending events
                +     *     // to the downstream.
                +     *     @Override
                +     *     public void dispose() {
                +     *         upstream.dispose();
                +     *     }
                +     *
                +     *     // Some operators may simply forward the call to the upstream while others
                +     *     // can return the disposed flag set in dispose().
                +     *     @Override
                +     *     public boolean isDisposed() {
                +     *         return upstream.isDisposed();
                +     *     }
                      * }
                +     *
                +     * // Step 2: Create a class that implements the ObservableOperator interface and
                +     * //         returns the custom consumer type from above in its apply() method.
                +     * //         Such class may define additional parameters to be submitted to
                +     * //         the custom consumer type.
                +     *
                +     * final class CustomOperator<T> implements ObservableOperator<String> {
                +     *     @Override
                +     *     public Observer<? super String> apply(Observer<? super T> upstream) {
                +     *         return new CustomObserver<T>(upstream);
                +     *     }
                +     * }
                +     *
                +     * // Step 3: Apply the custom operator via lift() in a flow by creating an instance of it
                +     * //         or reusing an existing one.
                +     *
                +     * Observable.range(5, 10)
                +     * .lift(new CustomOperator<Integer>())
                +     * .test()
                +     * .assertResult("5", "6", "7", "8", "9");
                +     * 
                *

                - * If the operator you are creating is designed to act on the individual items emitted by a source - * ObservableSource, use {@code lift}. If your operator is designed to transform the source ObservableSource as a whole - * (for instance, by applying a particular set of existing RxJava operators to it) use {@link #compose}. + * Creating custom operators can be complicated and it is recommended one consults the + * RxJava wiki: Writing operators page about + * the tools, requirements, rules, considerations and pitfalls of implementing them. + *

                + * Note that implementing custom operators via this {@code lift()} method adds slightly more overhead by requiring + * an additional allocation and indirection per assembled flows. Instead, extending the abstract {@code Observable} + * class and creating an {@link ObservableTransformer} with it is recommended. + *

                + * Note also that it is not possible to stop the subscription phase in {@code lift()} as the {@code apply()} method + * requires a non-null {@code Observer} instance to be returned, which is then unconditionally subscribed to + * the upstream {@code Observable}. For example, if the operator decided there is no reason to subscribe to the + * upstream source because of some optimization possibility or a failure to prepare the operator, it still has to + * return an {@code Observer} that should immediately dispose the upstream's {@code Disposable} in its + * {@code onSubscribe} method. Again, using an {@code ObservableTransformer} and extending the {@code Observable} is + * a better option as {@link #subscribeActual} can decide to not subscribe to its upstream after all. *

                *
                Scheduler:
                - *
                {@code lift} does not operate by default on a particular {@link Scheduler}.
                + *
                {@code lift} does not operate by default on a particular {@link Scheduler}, however, the + * {@link ObservableOperator} may use a {@code Scheduler} to support its own asynchronous behavior.
                *
                * * @param the output value type - * @param lifter the Operator that implements the ObservableSource-operating function to be applied to the source - * ObservableSource - * @return an Observable that is the result of applying the lifted Operator to the source ObservableSource - * @see RxJava wiki: Implementing Your Own Operators + * @param lifter the {@link ObservableOperator} that receives the downstream's {@code Observer} and should return + * an {@code Observer} with custom behavior to be used as the consumer for the current + * {@code Observable}. + * @return the new Observable instance + * @see RxJava wiki: Writing operators + * @see #compose(ObservableTransformer) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 63cee36923..8f4ab31fd4 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2487,27 +2487,145 @@ public final T blockingGet() { } /** - * Lifts a function to the current Single and returns a new Single that when subscribed to will pass the - * values of the current Single through the Operator function. + * This method requires advanced knowledge about building operators, please consider + * other standard composition methods first; + * Returns a {@code Single} which, when subscribed to, invokes the {@link SingleOperator#apply(SingleObserver) apply(SingleObserver)} method + * of the provided {@link SingleOperator} for each individual downstream {@link Single} and allows the + * insertion of a custom operator by accessing the downstream's {@link SingleObserver} during this subscription phase + * and providing a new {@code SingleObserver}, containing the custom operator's intended business logic, that will be + * used in the subscription process going further upstream. + *

                + * Generally, such a new {@code SingleObserver} will wrap the downstream's {@code SingleObserver} and forwards the + * {@code onSuccess} and {@code onError} events from the upstream directly or according to the + * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the + * flow control calls of {@code dispose} and {@code isDisposed} that would have traveled upstream and perform + * additional actions depending on the same business logic requirements. *

                - * In other words, this allows chaining TaskExecutors together on a Single for acting on the values within - * the Single. + * Example: + *

                
                +     * // Step 1: Create the consumer type that will be returned by the SingleOperator.apply():
                +     * 
                +     * public final class CustomSingleObserver<T> implements SingleObserver<T>, Disposable {
                +     *
                +     *     // The donstream's SingleObserver that will receive the onXXX events
                +     *     final SingleObserver<? super String> downstream;
                +     *
                +     *     // The connection to the upstream source that will call this class' onXXX methods
                +     *     Disposable upstream;
                +     *
                +     *     // The constructor takes the downstream subscriber and usually any other parameters
                +     *     public CustomSingleObserver(SingleObserver<? super String> downstream) {
                +     *         this.downstream = downstream;
                +     *     }
                +     *
                +     *     // In the subscription phase, the upstream sends a Disposable to this class
                +     *     // and subsequently this class has to send a Disposable to the downstream.
                +     *     // Note that relaying the upstream's Disposable directly is not allowed in RxJava
                +     *     @Override
                +     *     public void onSubscribe(Disposable s) {
                +     *         if (upstream != null) {
                +     *             s.cancel();
                +     *         } else {
                +     *             upstream = s;
                +     *             downstream.onSubscribe(this);
                +     *         }
                +     *     }
                +     *
                +     *     // The upstream calls this with the next item and the implementation's
                +     *     // responsibility is to emit an item to the downstream based on the intended
                +     *     // business logic, or if it can't do so for the particular item,
                +     *     // request more from the upstream
                +     *     @Override
                +     *     public void onSuccess(T item) {
                +     *         String str = item.toString();
                +     *         if (str.length() < 2) {
                +     *             downstream.onSuccess(str);
                +     *         } else {
                +     *             // Single is usually expected to produce one of the onXXX events
                +     *             downstream.onError(new NoSuchElementException());
                +     *         }
                +     *     }
                +     *
                +     *     // Some operators may handle the upstream's error while others
                +     *     // could just forward it to the downstream.
                +     *     @Override
                +     *     public void onError(Throwable throwable) {
                +     *         downstream.onError(throwable);
                +     *     }
                +     *
                +     *     // Some operators may use their own resources which should be cleaned up if
                +     *     // the downstream disposes the flow before it completed. Operators without
                +     *     // resources can simply forward the dispose to the upstream.
                +     *     // In some cases, a disposed flag may be set by this method so that other parts
                +     *     // of this class may detect the dispose and stop sending events
                +     *     // to the downstream.
                +     *     @Override
                +     *     public void dispose() {
                +     *         upstream.dispose();
                +     *     }
                +     *
                +     *     // Some operators may simply forward the call to the upstream while others
                +     *     // can return the disposed flag set in dispose().
                +     *     @Override
                +     *     public boolean isDisposed() {
                +     *         return upstream.isDisposed();
                +     *     }
                +     * }
                +     *
                +     * // Step 2: Create a class that implements the SingleOperator interface and
                +     * //         returns the custom consumer type from above in its apply() method.
                +     * //         Such class may define additional parameters to be submitted to
                +     * //         the custom consumer type.
                +     *
                +     * final class CustomSingleOperator<T> implements SingleOperator<String> {
                +     *     @Override
                +     *     public SingleObserver<? super String> apply(SingleObserver<? super T> upstream) {
                +     *         return new CustomSingleObserver<T>(upstream);
                +     *     }
                +     * }
                +     *
                +     * // Step 3: Apply the custom operator via lift() in a flow by creating an instance of it
                +     * //         or reusing an existing one.
                +     *
                +     * Single.just(5)
                +     * .lift(new CustomSingleOperator<Integer>())
                +     * .test()
                +     * .assertResult("5");
                +     *
                +     * Single.just(15)
                +     * .lift(new CustomSingleOperator<Integer>())
                +     * .test()
                +     * .assertFailure(NoSuchElementException.class);
                +     * 
                *

                - * {@code task.map(...).filter(...).lift(new OperatorA()).lift(new OperatorB(...)).subscribe() } + * Creating custom operators can be complicated and it is recommended one consults the + * RxJava wiki: Writing operators page about + * the tools, requirements, rules, considerations and pitfalls of implementing them. *

                - * If the operator you are creating is designed to act on the item emitted by a source Single, use - * {@code lift}. If your operator is designed to transform the source Single as a whole (for instance, by - * applying a particular set of existing RxJava operators to it) use {@link #compose}. + * Note that implementing custom operators via this {@code lift()} method adds slightly more overhead by requiring + * an additional allocation and indirection per assembled flows. Instead, extending the abstract {@code Single} + * class and creating a {@link SingleTransformer} with it is recommended. + *

                + * Note also that it is not possible to stop the subscription phase in {@code lift()} as the {@code apply()} method + * requires a non-null {@code SingleObserver} instance to be returned, which is then unconditionally subscribed to + * the upstream {@code Single}. For example, if the operator decided there is no reason to subscribe to the + * upstream source because of some optimization possibility or a failure to prepare the operator, it still has to + * return a {@code SingleObserver} that should immediately dispose the upstream's {@code Disposable} in its + * {@code onSubscribe} method. Again, using a {@code SingleTransformer} and extending the {@code Single} is + * a better option as {@link #subscribeActual} can decide to not subscribe to its upstream after all. *

                - *
                Scheduler:
                - *
                {@code lift} does not operate by default on a particular {@link Scheduler}.
                + *
                Scheduler:
                + *
                {@code lift} does not operate by default on a particular {@link Scheduler}, however, the + * {@link SingleOperator} may use a {@code Scheduler} to support its own asynchronous behavior.
                *
                * - * @param the downstream's value type (output) - * @param lift - * the Operator that implements the Single-operating function to be applied to the source Single - * @return a Single that is the result of applying the lifted Operator to the source Single - * @see RxJava wiki: Implementing Your Own Operators + * @param the output value type + * @param lift the {@link SingleOperator} that receives the downstream's {@code SingleObserver} and should return + * a {@code SingleObserver} with custom behavior to be used as the consumer for the current + * {@code Single}. + * @return the new Single instance + * @see RxJava wiki: Writing operators + * @see #compose(SingleTransformer) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) From 84004a617557946f9f64f7f362f0dcbe0b798530 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 1 Mar 2018 13:05:52 +0100 Subject: [PATCH 111/417] 2.x: Add Flowable.concatMapCompletable{DelayError} operator (#5871) --- src/main/java/io/reactivex/Flowable.java | 163 ++++++++ .../mixed/FlowableConcatMapCompletable.java | 291 +++++++++++++ .../FlowableConcatMapCompletableTest.java | 391 ++++++++++++++++++ 3 files changed, 845 insertions(+) create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletableTest.java diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index f9d7148c8b..5835cbd068 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -25,6 +25,7 @@ import io.reactivex.internal.functions.*; import io.reactivex.internal.fuseable.*; import io.reactivex.internal.operators.flowable.*; +import io.reactivex.internal.operators.mixed.*; import io.reactivex.internal.operators.observable.ObservableFromPublisher; import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.internal.subscribers.*; @@ -6886,6 +6887,168 @@ public final Flowable concatMap(Function(this, mapper, prefetch, ErrorMode.IMMEDIATE)); } + /** + * Maps the upstream intems into {@link CompletableSource}s and subscribes to them one after the + * other completes. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param mapper the function called with the upstream item and should return + * a {@code CompletableSource} to become the next source to + * be subscribed to + * @return a new Completable instance + * @since 2.1.11 - experimental + * @see #concatMapCompletableDelayError(Function) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.FULL) + @Experimental + public final Completable concatMapCompletable(Function mapper) { + return concatMapCompletable(mapper, 2); + } + + /** + * Maps the upstream intems into {@link CompletableSource}s and subscribes to them one after the + * other completes. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param mapper the function called with the upstream item and should return + * a {@code CompletableSource} to become the next source to + * be subscribed to + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code CompletableSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code CompletableSource}s. + * @return a new Completable instance + * @since 2.1.11 - experimental + * @see #concatMapCompletableDelayError(Function, boolean, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.FULL) + @Experimental + public final Completable concatMapCompletable(Function mapper, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new FlowableConcatMapCompletable(this, mapper, ErrorMode.IMMEDIATE, prefetch)); + } + + /** + * Maps the upstream intems into {@link CompletableSource}s and subscribes to them one after the + * other terminates, delaying all errors till both this {@code Flowable} and all + * inner {@code CompletableSource}s terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param mapper the function called with the upstream item and should return + * a {@code CompletableSource} to become the next source to + * be subscribed to + * @return a new Completable instance + * @since 2.1.11 - experimental + * @see #concatMapCompletable(Function, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.FULL) + @Experimental + public final Completable concatMapCompletableDelayError(Function mapper) { + return concatMapCompletableDelayError(mapper, true, 2); + } + + /** + * Maps the upstream intems into {@link CompletableSource}s and subscribes to them one after the + * other terminates, optionally delaying all errors till both this {@code Flowable} and all + * inner {@code CompletableSource}s terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param mapper the function called with the upstream item and should return + * a {@code CompletableSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Flowable} or any of the + * inner {@code CompletableSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Flowable} is delayed until the current inner + * {@code CompletableSource} terminates and only then is + * it emitted to the downstream. + * @return a new Completable instance + * @since 2.1.11 - experimental + * @see #concatMapCompletable(Function) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.FULL) + @Experimental + public final Completable concatMapCompletableDelayError(Function mapper, boolean tillTheEnd) { + return concatMapCompletableDelayError(mapper, tillTheEnd, 2); + } + + /** + * Maps the upstream intems into {@link CompletableSource}s and subscribes to them one after the + * other terminates, optionally delaying all errors till both this {@code Flowable} and all + * inner {@code CompletableSource}s terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param mapper the function called with the upstream item and should return + * a {@code CompletableSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Flowable} or any of the + * inner {@code CompletableSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Flowable} is delayed until the current inner + * {@code CompletableSource} terminates and only then is + * it emitted to the downstream. + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code CompletableSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code CompletableSource}s. + * @return a new Completable instance + * @since 2.1.11 - experimental + * @see #concatMapCompletable(Function, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.FULL) + @Experimental + public final Completable concatMapCompletableDelayError(Function mapper, boolean tillTheEnd, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new FlowableConcatMapCompletable(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch)); + } + /** * Maps each of the items into a Publisher, subscribes to them one after the other, * one at a time and emits their values in order diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java new file mode 100644 index 0000000000..1482c137b4 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java @@ -0,0 +1,291 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.Subscription; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.*; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps the upstream intems into {@link CompletableSource}s and subscribes to them one after the + * other completes or terminates (in error-delaying mode). + * @param the upstream value type + * @since 2.1.11 - experimental + */ +@Experimental +public final class FlowableConcatMapCompletable extends Completable { + + final Flowable source; + + final Function mapper; + + final ErrorMode errorMode; + + final int prefetch; + + public FlowableConcatMapCompletable(Flowable source, + Function mapper, + ErrorMode errorMode, + int prefetch) { + this.source = source; + this.mapper = mapper; + this.errorMode = errorMode; + this.prefetch = prefetch; + } + + @Override + protected void subscribeActual(CompletableObserver s) { + source.subscribe(new ConcatMapCompletableObserver(s, mapper, errorMode, prefetch)); + } + + static final class ConcatMapCompletableObserver + extends AtomicInteger + implements FlowableSubscriber, Disposable { + + private static final long serialVersionUID = 3610901111000061034L; + + final CompletableObserver downstream; + + final Function mapper; + + final ErrorMode errorMode; + + final AtomicThrowable errors; + + final ConcatMapInnerObserver inner; + + final int prefetch; + + final SimplePlainQueue queue; + + Subscription upstream; + + volatile boolean active; + + volatile boolean done; + + volatile boolean disposed; + + int consumed; + + ConcatMapCompletableObserver(CompletableObserver downstream, + Function mapper, + ErrorMode errorMode, int prefetch) { + this.downstream = downstream; + this.mapper = mapper; + this.errorMode = errorMode; + this.prefetch = prefetch; + this.errors = new AtomicThrowable(); + this.inner = new ConcatMapInnerObserver(this); + this.queue = new SpscArrayQueue(prefetch); + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); + s.request(prefetch); + } + } + + @Override + public void onNext(T t) { + if (queue.offer(t)) { + drain(); + } else { + upstream.cancel(); + onError(new MissingBackpressureException("Queue full?!")); + } + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (errorMode == ErrorMode.IMMEDIATE) { + inner.dispose(); + t = errors.terminate(); + if (t != ExceptionHelper.TERMINATED) { + downstream.onError(t); + } + if (getAndIncrement() == 0) { + queue.clear(); + } + } else { + done = true; + drain(); + } + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @Override + public void dispose() { + disposed = true; + upstream.cancel(); + inner.dispose(); + if (getAndIncrement() == 0) { + queue.clear(); + } + } + + @Override + public boolean isDisposed() { + return disposed; + } + + void innerError(Throwable ex) { + if (errors.addThrowable(ex)) { + if (errorMode == ErrorMode.IMMEDIATE) { + upstream.cancel(); + ex = errors.terminate(); + if (ex != ExceptionHelper.TERMINATED) { + downstream.onError(ex); + } + if (getAndIncrement() == 0) { + queue.clear(); + } + } else { + active = false; + drain(); + } + } else { + RxJavaPlugins.onError(ex); + } + } + + void innerComplete() { + active = false; + drain(); + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + do { + if (disposed) { + queue.clear(); + return; + } + + if (!active) { + + if (errorMode == ErrorMode.BOUNDARY) { + if (errors.get() != null) { + queue.clear(); + Throwable ex = errors.terminate(); + downstream.onError(ex); + return; + } + } + + boolean d = done; + T v = queue.poll(); + boolean empty = v == null; + + if (d && empty) { + Throwable ex = errors.terminate(); + if (ex != null) { + downstream.onError(ex); + } else { + downstream.onComplete(); + } + return; + } + + if (!empty) { + + int limit = prefetch - (prefetch >> 1); + int c = consumed + 1; + if (c == limit) { + consumed = 0; + upstream.request(limit); + } else { + consumed = c; + } + + CompletableSource cs; + + try { + cs = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null CompletableSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + queue.clear(); + upstream.cancel(); + errors.addThrowable(ex); + ex = errors.terminate(); + downstream.onError(ex); + return; + } + active = true; + cs.subscribe(inner); + } + } + } while (decrementAndGet() != 0); + } + + static final class ConcatMapInnerObserver extends AtomicReference + implements CompletableObserver { + + private static final long serialVersionUID = 5638352172918776687L; + + final ConcatMapCompletableObserver parent; + + ConcatMapInnerObserver(ConcatMapCompletableObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(this, d); + } + + @Override + public void onError(Throwable e) { + parent.innerError(e); + } + + @Override + public void onComplete() { + parent.innerComplete(); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletableTest.java new file mode 100644 index 0000000000..ef0e291581 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletableTest.java @@ -0,0 +1,391 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; +import org.reactivestreams.Subscriber; + +import io.reactivex.*; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.CompletableSubject; + +public class FlowableConcatMapCompletableTest { + + @Test + public void simple() { + Flowable.range(1, 5) + .concatMapCompletable(Functions.justFunction(Completable.complete())) + .test() + .assertResult(); + } + + @Test + public void simple2() { + final AtomicInteger counter = new AtomicInteger(); + Flowable.range(1, 5) + .concatMapCompletable(Functions.justFunction(Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + counter.incrementAndGet(); + } + }))) + .test() + .assertResult(); + + assertEquals(5, counter.get()); + } + + @Test + public void simpleLongPrefetch() { + Flowable.range(1, 1024) + .concatMapCompletable(Functions.justFunction(Completable.complete()), 32) + .test() + .assertResult(); + } + + @Test + public void mainError() { + Flowable.error(new TestException()) + .concatMapCompletable(Functions.justFunction(Completable.complete())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Flowable.just(1) + .concatMapCompletable(Functions.justFunction(Completable.error(new TestException()))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerErrorDelayed() { + Flowable.range(1, 5) + .concatMapCompletableDelayError( + new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return Completable.error(new TestException()); + } + } + ) + .test() + .assertFailure(CompositeException.class) + .assertOf(new Consumer>() { + @Override + public void accept(TestObserver to) throws Exception { + assertEquals(5, ((CompositeException)to.errors().get(0)).getExceptions().size()); + } + }); + } + + @Test + public void mapperCrash() { + Flowable.just(1) + .concatMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void immediateError() { + PublishProcessor pp = PublishProcessor.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.concatMapCompletable( + Functions.justFunction(cs)).test(); + + to.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + assertFalse(cs.hasObservers()); + + pp.onNext(1); + + assertTrue(cs.hasObservers()); + + pp.onError(new TestException()); + + assertFalse(cs.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void immediateError2() { + PublishProcessor pp = PublishProcessor.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.concatMapCompletable( + Functions.justFunction(cs)).test(); + + to.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + assertFalse(cs.hasObservers()); + + pp.onNext(1); + + assertTrue(cs.hasObservers()); + + cs.onError(new TestException()); + + assertFalse(pp.hasSubscribers()); + + to.assertFailure(TestException.class); + } + + @Test + public void boundaryError() { + PublishProcessor pp = PublishProcessor.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.concatMapCompletableDelayError( + Functions.justFunction(cs), false).test(); + + to.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + assertFalse(cs.hasObservers()); + + pp.onNext(1); + + assertTrue(cs.hasObservers()); + + pp.onError(new TestException()); + + assertTrue(cs.hasObservers()); + + to.assertEmpty(); + + cs.onComplete(); + + to.assertFailure(TestException.class); + } + + @Test + public void endError() { + PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + final CompletableSubject cs2 = CompletableSubject.create(); + + TestObserver to = pp.concatMapCompletableDelayError( + new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + if (v == 1) { + return cs; + } + return cs2; + } + }, true, 32 + ) + .test(); + + to.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + assertFalse(cs.hasObservers()); + + pp.onNext(1); + + assertTrue(cs.hasObservers()); + + cs.onError(new TestException()); + + assertTrue(pp.hasSubscribers()); + + pp.onNext(2); + + to.assertEmpty(); + + cs2.onComplete(); + + assertTrue(pp.hasSubscribers()); + + to.assertEmpty(); + + pp.onComplete(); + + to.assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowableToCompletable( + new Function, Completable>() { + @Override + public Completable apply(Flowable f) + throws Exception { + return f.concatMapCompletable( + Functions.justFunction(Completable.complete())); + } + } + ); + } + + @Test + public void disposed() { + TestHelper.checkDisposed( + Flowable.never() + .concatMapCompletable( + Functions.justFunction(Completable.complete())) + ); + } + + @Test + public void queueOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onNext(2); + s.onNext(3); + s.onError(new TestException()); + } + } + .concatMapCompletable( + Functions.justFunction(Completable.never()), 1 + ) + .test() + .assertFailure(MissingBackpressureException.class); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void immediateOuterInnerErrorRace() { + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.concatMapCompletable( + Functions.justFunction(cs) + ) + .test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onError(ex); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + to.assertError(new Predicate() { + @Override + public boolean test(Throwable e) throws Exception { + return e instanceof TestException || e instanceof CompositeException; + } + }) + .assertNotComplete(); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void disposeInDrainLoop() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + final TestObserver to = pp.concatMapCompletable( + Functions.justFunction(cs) + ) + .test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onComplete(); + to.cancel(); + } + }; + + TestHelper.race(r1, r2); + + to.assertEmpty(); + } + } + + @Test + public void doneButNotEmpty() { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + final TestObserver to = pp.concatMapCompletable( + Functions.justFunction(cs) + ) + .test(); + + pp.onNext(1); + pp.onNext(2); + pp.onComplete(); + + cs.onComplete(); + + to.assertResult(); + } +} From 137dfe1404bfbad98bb024b52f69546a0eb59567 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 1 Mar 2018 17:46:05 +0100 Subject: [PATCH 112/417] 2.x: Add Flowable.switchMapCompletable{DelayError} operator (#5870) --- src/main/java/io/reactivex/Flowable.java | 92 +++++ .../mixed/FlowableSwitchMapCompletable.java | 239 +++++++++++ .../FlowableSwitchMapCompletableTest.java | 389 ++++++++++++++++++ 3 files changed, 720 insertions(+) create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletableTest.java diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 5835cbd068..f177750a7b 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -14114,6 +14114,98 @@ public final Flowable switchMap(Function + * + *

                + * Since a {@code CompletableSource} doesn't produce any items, the resulting reactive type of + * this operator is a {@link Completable} that can only indicate successful completion or + * a failure in any of the inner {@code CompletableSource}s or the failure of the current + * {@link Flowable}. + *

                + *
                Backpressure:
                + *
                The operator consumes the current {@link Flowable} in an unbounded manner and otherwise + * does not have backpressure in its return type because no items are ever produced.
                + *
                Scheduler:
                + *
                {@code switchMapCompletable} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If either this {@code Flowable} or the active {@code CompletableSource} signals an {@code onError}, + * the resulting {@code Completable} is terminated immediately with that {@code Throwable}. + * Use the {@link #switchMapCompletableDelayError(Function)} to delay such inner failures until + * every inner {@code CompletableSource}s and the main {@code Flowable} terminates in some fashion. + * If they fail concurrently, the operator may combine the {@code Throwable}s into a + * {@link io.reactivex.exceptions.CompositeException CompositeException} + * and signal it to the downstream instead. If any inactivated (switched out) {@code CompletableSource} + * signals an {@code onError} late, the {@code Throwable}s will be signalled to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. + *
                + *
                + * @param mapper the function called with each upstream item and should return a + * {@link CompletableSource} to be subscribed to and awaited for + * (non blockingly) for its terminal event + * @return the new Completable instance + * @since 2.1.11 - experimental + * @see #switchMapCompletableDelayError(Function) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Completable switchMapCompletable(@NonNull Function mapper) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new FlowableSwitchMapCompletable(this, mapper, false)); + } + + /** + * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while + * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one + * active {@code CompletableSource} running and delaying any main or inner errors until all + * of them terminate. + *

                + * + *

                + * Since a {@code CompletableSource} doesn't produce any items, the resulting reactive type of + * this operator is a {@link Completable} that can only indicate successful completion or + * a failure in any of the inner {@code CompletableSource}s or the failure of the current + * {@link Flowable}. + *

                + *
                Backpressure:
                + *
                The operator consumes the current {@link Flowable} in an unbounded manner and otherwise + * does not have backpressure in its return type because no items are ever produced.
                + *
                Scheduler:
                + *
                {@code switchMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                Errors of this {@code Flowable} and all the {@code CompletableSource}s, who had the chance + * to run to their completion, are delayed until + * all of them terminate in some fashion. At this point, if there was only one failure, the respective + * {@code Throwable} is emitted to the dowstream. It there were more than one failures, the + * operator combines all {@code Throwable}s into a {@link io.reactivex.exceptions.CompositeException CompositeException} + * and signals that to the downstream. + * If any inactivated (switched out) {@code CompletableSource} + * signals an {@code onError} late, the {@code Throwable}s will be signalled to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. + *
                + *
                + * @param mapper the function called with each upstream item and should return a + * {@link CompletableSource} to be subscribed to and awaited for + * (non blockingly) for its terminal event + * @return the new Completable instance + * @since 2.1.11 - experimental + * @see #switchMapCompletableDelayError(Function) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Completable switchMapCompletableDelayError(@NonNull Function mapper) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new FlowableSwitchMapCompletable(this, mapper, true)); + } + /** * Returns a new Publisher by applying a function that you supply to each item emitted by the source * Publisher that returns a Publisher, and then emitting the items emitted by the most recently emitted diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java new file mode 100644 index 0000000000..2d0f753fc8 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java @@ -0,0 +1,239 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.AtomicReference; + +import org.reactivestreams.Subscription; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while + * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one + * active {@code CompletableSource} running. + * + * @param the upstream value type + * @since 2.1.11 - experimental + */ +@Experimental +public final class FlowableSwitchMapCompletable extends Completable { + + final Flowable source; + + final Function mapper; + + final boolean delayErrors; + + public FlowableSwitchMapCompletable(Flowable source, + Function mapper, boolean delayErrors) { + this.source = source; + this.mapper = mapper; + this.delayErrors = delayErrors; + } + + @Override + protected void subscribeActual(CompletableObserver s) { + source.subscribe(new SwitchMapCompletableObserver(s, mapper, delayErrors)); + } + + static final class SwitchMapCompletableObserver implements FlowableSubscriber, Disposable { + + final CompletableObserver downstream; + + final Function mapper; + + final boolean delayErrors; + + final AtomicThrowable errors; + + final AtomicReference inner; + + static final SwitchMapInnerObserver INNER_DISPOSED = new SwitchMapInnerObserver(null); + + volatile boolean done; + + Subscription upstream; + + SwitchMapCompletableObserver(CompletableObserver downstream, + Function mapper, boolean delayErrors) { + this.downstream = downstream; + this.mapper = mapper; + this.delayErrors = delayErrors; + this.errors = new AtomicThrowable(); + this.inner = new AtomicReference(); + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); + s.request(Long.MAX_VALUE); + } + } + + @Override + public void onNext(T t) { + CompletableSource c; + + try { + c = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null CompletableSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.cancel(); + onError(ex); + return; + } + + SwitchMapInnerObserver o = new SwitchMapInnerObserver(this); + + for (;;) { + SwitchMapInnerObserver current = inner.get(); + if (current == INNER_DISPOSED) { + break; + } + if (inner.compareAndSet(current, o)) { + if (current != null) { + current.dispose(); + } + c.subscribe(o); + break; + } + } + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (delayErrors) { + onComplete(); + } else { + disposeInner(); + Throwable ex = errors.terminate(); + if (ex != ExceptionHelper.TERMINATED) { + downstream.onError(ex); + } + } + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + if (inner.get() == null) { + Throwable ex = errors.terminate(); + if (ex == null) { + downstream.onComplete(); + } else { + downstream.onError(ex); + } + } + } + + void disposeInner() { + SwitchMapInnerObserver o = inner.getAndSet(INNER_DISPOSED); + if (o != null && o != INNER_DISPOSED) { + o.dispose(); + } + } + + @Override + public void dispose() { + upstream.cancel(); + disposeInner(); + } + + @Override + public boolean isDisposed() { + return inner.get() == INNER_DISPOSED; + } + + void innerError(SwitchMapInnerObserver sender, Throwable error) { + if (inner.compareAndSet(sender, null)) { + if (errors.addThrowable(error)) { + if (delayErrors) { + if (done) { + Throwable ex = errors.terminate(); + downstream.onError(ex); + } + } else { + dispose(); + Throwable ex = errors.terminate(); + if (ex != ExceptionHelper.TERMINATED) { + downstream.onError(ex); + } + } + return; + } + } + RxJavaPlugins.onError(error); + } + + void innerComplete(SwitchMapInnerObserver sender) { + if (inner.compareAndSet(sender, null)) { + if (done) { + Throwable ex = errors.terminate(); + if (ex == null) { + downstream.onComplete(); + } else { + downstream.onError(ex); + } + } + } + } + + static final class SwitchMapInnerObserver extends AtomicReference + implements CompletableObserver { + + private static final long serialVersionUID = -8003404460084760287L; + + final SwitchMapCompletableObserver parent; + + SwitchMapInnerObserver(SwitchMapCompletableObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onError(Throwable e) { + parent.innerError(this, e); + } + + @Override + public void onComplete() { + parent.innerComplete(this); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletableTest.java new file mode 100644 index 0000000000..5bd6196fad --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletableTest.java @@ -0,0 +1,389 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.Test; +import org.reactivestreams.Subscriber; + +import io.reactivex.*; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.CompletableSubject; + +public class FlowableSwitchMapCompletableTest { + + @Test + public void normal() { + Flowable.range(1, 10) + .switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return Completable.complete(); + } + }) + .test() + .assertResult(); + } + + @Test + public void mainError() { + Flowable.error(new TestException()) + .switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return Completable.complete(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + PublishProcessor pp = PublishProcessor.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.switchMapCompletable(Functions.justFunction(cs)) + .test(); + + assertTrue(pp.hasSubscribers()); + assertFalse(cs.hasObservers()); + + pp.onNext(1); + + assertTrue(cs.hasObservers()); + + to.assertEmpty(); + + cs.onError(new TestException()); + + to.assertFailure(TestException.class); + + assertFalse(pp.hasSubscribers()); + assertFalse(cs.hasObservers()); + } + + @Test + public void switchOver() { + final CompletableSubject[] css = { + CompletableSubject.create(), + CompletableSubject.create() + }; + + PublishProcessor pp = PublishProcessor.create(); + + TestObserver to = pp.switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return css[v]; + } + }) + .test(); + + to.assertEmpty(); + + pp.onNext(0); + + assertTrue(css[0].hasObservers()); + + pp.onNext(1); + + assertFalse(css[0].hasObservers()); + assertTrue(css[1].hasObservers()); + + pp.onComplete(); + + to.assertEmpty(); + + assertTrue(css[1].hasObservers()); + + css[1].onComplete(); + + to.assertResult(); + } + + @Test + public void dispose() { + PublishProcessor pp = PublishProcessor.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.switchMapCompletable(Functions.justFunction(cs)) + .test(); + + pp.onNext(1); + + assertTrue(pp.hasSubscribers()); + assertTrue(cs.hasObservers()); + + to.dispose(); + + assertFalse(pp.hasSubscribers()); + assertFalse(cs.hasObservers()); + } + + @Test + public void checkDisposed() { + PublishProcessor pp = PublishProcessor.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestHelper.checkDisposed(pp.switchMapCompletable(Functions.justFunction(cs))); + } + + @Test + public void checkBadSource() { + TestHelper.checkDoubleOnSubscribeFlowableToCompletable(new Function, Completable>() { + @Override + public Completable apply(Flowable f) throws Exception { + return f.switchMapCompletable(Functions.justFunction(Completable.never())); + } + }); + } + + @Test + public void mapperCrash() { + Flowable.range(1, 5).switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer f) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void mapperCancels() { + final TestObserver to = new TestObserver(); + + Flowable.range(1, 5).switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer f) throws Exception { + to.cancel(); + return Completable.complete(); + } + }) + .subscribe(to); + + to.assertEmpty(); + } + + @Test + public void onNextInnerCompleteRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.switchMapCompletable(Functions.justFunction(cs)).test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onComplete(); + } + }; + + TestHelper.race(r1, r2); + + to.assertEmpty(); + } + } + + @Test + public void onNextInnerErrorRace() { + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.switchMapCompletable(Functions.justFunction(cs)).test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + to.assertError(new Predicate() { + @Override + public boolean test(Throwable e) throws Exception { + return e instanceof TestException || e instanceof CompositeException; + } + }); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void onErrorInnerErrorRace() { + final TestException ex0 = new TestException(); + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.switchMapCompletable(Functions.justFunction(cs)).test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onError(ex0); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + to.assertError(new Predicate() { + @Override + public boolean test(Throwable e) throws Exception { + return e instanceof TestException || e instanceof CompositeException; + } + }); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void innerErrorThenMainError() { + List errors = TestHelper.trackPluginErrors(); + try { + new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onError(new TestException("main")); + } + } + .switchMapCompletable(Functions.justFunction(Completable.error(new TestException("inner")))) + .test() + .assertFailureAndMessage(TestException.class, "inner"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "main"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void innerErrorDelayed() { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.switchMapCompletableDelayError(Functions.justFunction(cs)).test(); + + pp.onNext(1); + + cs.onError(new TestException()); + + to.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + + pp.onComplete(); + + to.assertFailure(TestException.class); + } + + @Test + public void mainCompletesinnerErrorDelayed() { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.switchMapCompletableDelayError(Functions.justFunction(cs)).test(); + + pp.onNext(1); + pp.onComplete(); + + to.assertEmpty(); + + cs.onError(new TestException()); + + to.assertFailure(TestException.class); + } + + @Test + public void mainErrorDelayed() { + final PublishProcessor pp = PublishProcessor.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = pp.switchMapCompletableDelayError(Functions.justFunction(cs)).test(); + + pp.onNext(1); + + pp.onError(new TestException()); + + to.assertEmpty(); + + assertTrue(cs.hasObservers()); + + cs.onComplete(); + + to.assertFailure(TestException.class); + } +} From 44fb7cd2dfbc0127e0734111431e5a693cafac6b Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 1 Mar 2018 19:46:57 +0100 Subject: [PATCH 113/417] 2.x: Add Flowable.concatMap{Maybe,Single}{DelayError} operators (#5872) * 2.x: Add Flowable.concatMap{Maybe,Single}{DelayError} operators * Fix typo in the JavaDocs * Fix the JavaDoc wording of concatMapSingle --- src/main/java/io/reactivex/Flowable.java | 366 ++++++++++++++++- .../mixed/FlowableConcatMapMaybe.java | 342 ++++++++++++++++ .../mixed/FlowableConcatMapSingle.java | 332 ++++++++++++++++ .../mixed/FlowableConcatMapMaybeTest.java | 371 ++++++++++++++++++ .../mixed/FlowableConcatMapSingleTest.java | 286 ++++++++++++++ 5 files changed, 1692 insertions(+), 5 deletions(-) create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index f177750a7b..02c84ed989 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -6888,7 +6888,7 @@ public final Flowable concatMap(Function * @@ -6915,7 +6915,7 @@ public final Completable concatMapCompletable(Function * @@ -6948,7 +6948,7 @@ public final Completable concatMapCompletable(Function @@ -6976,7 +6976,7 @@ public final Completable concatMapCompletableDelayError(Function @@ -7010,7 +7010,7 @@ public final Completable concatMapCompletableDelayError(Function @@ -7313,6 +7313,362 @@ public final Flowable concatMapIterable(final Function(this, mapper, prefetch)); } + /** + * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the + * other succeeds or completes, emits their success value if available or terminates immediately if + * either this {@code Flowable} or the current inner {@code MaybeSource} fail. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure and honors + * the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapMaybe} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code MaybeSource}s + * @param mapper the function called with the upstream item and should return + * a {@code MaybeSource} to become the next source to + * be subscribed to + * @return a new Flowable instance + * @since 2.1.11 - experimental + * @see #concatMapMaybeDelayError(Function) + * @see #concatMapMaybe(Function, int) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatMapMaybe(Function> mapper) { + return concatMapMaybe(mapper, 2); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the + * other succeeds or completes, emits their success value if available or terminates immediately if + * either this {@code Flowable} or the current inner {@code MaybeSource} fail. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure and honors + * the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapMaybe} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code MaybeSource}s + * @param mapper the function called with the upstream item and should return + * a {@code MaybeSource} to become the next source to + * be subscribed to + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code MaybeSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code MaybeSource}s. + * @return a new Flowable instance + * @since 2.1.11 - experimental + * @see #concatMapMaybe(Function) + * @see #concatMapMaybeDelayError(Function, boolean, int) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatMapMaybe(Function> mapper, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new FlowableConcatMapMaybe(this, mapper, ErrorMode.IMMEDIATE, prefetch)); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the + * other terminates, emits their success value if available and delaying all errors + * till both this {@code Flowable} and all inner {@code MaybeSource}s terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure and honors + * the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code MaybeSource}s + * @param mapper the function called with the upstream item and should return + * a {@code MaybeSource} to become the next source to + * be subscribed to + * @return a new Flowable instance + * @since 2.1.11 - experimental + * @see #concatMapMaybe(Function) + * @see #concatMapMaybeDelayError(Function, boolean) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatMapMaybeDelayError(Function> mapper) { + return concatMapMaybeDelayError(mapper, true, 2); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the + * other terminates, emits their success value if available and optionally delaying all errors + * till both this {@code Flowable} and all inner {@code MaybeSource}s terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure and honors + * the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code MaybeSource}s + * @param mapper the function called with the upstream item and should return + * a {@code MaybeSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Flowable} or any of the + * inner {@code MaybeSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Flowable} is delayed until the current inner + * {@code MaybeSource} terminates and only then is + * it emitted to the downstream. + * @return a new Flowable instance + * @since 2.1.11 - experimental + * @see #concatMapMaybe(Function, int) + * @see #concatMapMaybeDelayError(Function, boolean, int) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatMapMaybeDelayError(Function> mapper, boolean tillTheEnd) { + return concatMapMaybeDelayError(mapper, tillTheEnd, 2); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the + * other terminates, emits their success value if available and optionally delaying all errors + * till both this {@code Flowable} and all inner {@code MaybeSource}s terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure and honors + * the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code MaybeSource}s + * @param mapper the function called with the upstream item and should return + * a {@code MaybeSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Flowable} or any of the + * inner {@code MaybeSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Flowable} is delayed until the current inner + * {@code MaybeSource} terminates and only then is + * it emitted to the downstream. + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code MaybeSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code MaybeSource}s. + * @return a new Flowable instance + * @since 2.1.11 - experimental + * @see #concatMapMaybe(Function, int) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatMapMaybeDelayError(Function> mapper, boolean tillTheEnd, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new FlowableConcatMapMaybe(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch)); + } + + /** + * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the + * other succeeds, emits their success values or terminates immediately if + * either this {@code Flowable} or the current inner {@code SingleSource} fail. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure and honors + * the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code SingleSource}s + * @param mapper the function called with the upstream item and should return + * a {@code SingleSource} to become the next source to + * be subscribed to + * @return a new Flowable instance + * @since 2.1.11 - experimental + * @see #concatMapSingleDelayError(Function) + * @see #concatMapSingle(Function, int) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatMapSingle(Function> mapper) { + return concatMapSingle(mapper, 2); + } + + /** + * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the + * other succeeds, emits their success values or terminates immediately if + * either this {@code Flowable} or the current inner {@code SingleSource} fail. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure and honors + * the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code SingleSource}s + * @param mapper the function called with the upstream item and should return + * a {@code SingleSource} to become the next source to + * be subscribed to + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code SingleSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code SingleSource}s. + * @return a new Flowable instance + * @since 2.1.11 - experimental + * @see #concatMapSingle(Function) + * @see #concatMapSingleDelayError(Function, boolean, int) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatMapSingle(Function> mapper, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new FlowableConcatMapSingle(this, mapper, ErrorMode.IMMEDIATE, prefetch)); + } + + /** + * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the + * other succeeds or fails, emits their success values and delays all errors + * till both this {@code Flowable} and all inner {@code SingleSource}s terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure and honors + * the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code SingleSource}s + * @param mapper the function called with the upstream item and should return + * a {@code SingleSource} to become the next source to + * be subscribed to + * @return a new Flowable instance + * @since 2.1.11 - experimental + * @see #concatMapSingle(Function) + * @see #concatMapSingleDelayError(Function, boolean) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatMapSingleDelayError(Function> mapper) { + return concatMapSingleDelayError(mapper, true, 2); + } + + /** + * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the + * other succeeds or fails, emits their success values and optionally delays all errors + * till both this {@code Flowable} and all inner {@code SingleSource}s terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure and honors + * the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code SingleSource}s + * @param mapper the function called with the upstream item and should return + * a {@code SingleSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Flowable} or any of the + * inner {@code SingleSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Flowable} is delayed until the current inner + * {@code SingleSource} terminates and only then is + * it emitted to the downstream. + * @return a new Flowable instance + * @since 2.1.11 - experimental + * @see #concatMapSingle(Function, int) + * @see #concatMapSingleDelayError(Function, boolean, int) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatMapSingleDelayError(Function> mapper, boolean tillTheEnd) { + return concatMapSingleDelayError(mapper, tillTheEnd, 2); + } + + /** + * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the + * other succeeds or fails, emits their success values and optionally delays errors + * till both this {@code Flowable} and all inner {@code SingleSource}s terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator expects the upstream to support backpressure and honors + * the backpressure from downstream. If this {@code Flowable} violates the rule, the operator will + * signal a {@code MissingBackpressureException}.
                + *
                Scheduler:
                + *
                {@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code SingleSource}s + * @param mapper the function called with the upstream item and should return + * a {@code SingleSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Flowable} or any of the + * inner {@code SingleSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Flowable} is delayed until the current inner + * {@code SingleSource} terminates and only then is + * it emitted to the downstream. + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code SingleSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code SingleSource}s. + * @return a new Flowable instance + * @since 2.1.11 - experimental + * @see #concatMapSingle(Function, int) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable concatMapSingleDelayError(Function> mapper, boolean tillTheEnd, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new FlowableConcatMapSingle(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch)); + } + /** * Returns a Flowable that emits the items emitted from the current Publisher, then the next, one after * the other, without interleaving them. diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java new file mode 100644 index 0000000000..8910e0c10a --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java @@ -0,0 +1,342 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.*; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps each upstream item into a {@link MaybeSource}, subscribes to them one after the other terminates + * and relays their success values, optionally delaying any errors till the main and inner sources + * terminate. + * + * @param the upstream element type + * @param the output element type + * + * @since 2.1.11 - experimental + */ +@Experimental +public final class FlowableConcatMapMaybe extends Flowable { + + final Flowable source; + + final Function> mapper; + + final ErrorMode errorMode; + + final int prefetch; + + public FlowableConcatMapMaybe(Flowable source, + Function> mapper, + ErrorMode errorMode, int prefetch) { + this.source = source; + this.mapper = mapper; + this.errorMode = errorMode; + this.prefetch = prefetch; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new ConcatMapMaybeSubscriber(s, mapper, prefetch, errorMode)); + } + + static final class ConcatMapMaybeSubscriber + extends AtomicInteger + implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = -9140123220065488293L; + + final Subscriber downstream; + + final Function> mapper; + + final int prefetch; + + final AtomicLong requested; + + final AtomicThrowable errors; + + final ConcatMapMaybeObserver inner; + + final SimplePlainQueue queue; + + final ErrorMode errorMode; + + Subscription upstream; + + volatile boolean done; + + volatile boolean cancelled; + + long emitted; + + int consumed; + + R item; + + volatile int state; + + /** No inner MaybeSource is running. */ + static final int STATE_INACTIVE = 0; + /** An inner MaybeSource is running but there are no results yet. */ + static final int STATE_ACTIVE = 1; + /** The inner MaybeSource succeeded with a value in {@link #item}. */ + static final int STATE_RESULT_VALUE = 2; + + ConcatMapMaybeSubscriber(Subscriber downstream, + Function> mapper, + int prefetch, ErrorMode errorMode) { + this.downstream = downstream; + this.mapper = mapper; + this.prefetch = prefetch; + this.errorMode = errorMode; + this.requested = new AtomicLong(); + this.errors = new AtomicThrowable(); + this.inner = new ConcatMapMaybeObserver(this); + this.queue = new SpscArrayQueue(prefetch); + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(upstream, s)) { + upstream = s; + downstream.onSubscribe(this); + s.request(prefetch); + } + } + + @Override + public void onNext(T t) { + if (!queue.offer(t)) { + upstream.cancel(); + onError(new MissingBackpressureException("queue full?!")); + return; + } + drain(); + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (errorMode == ErrorMode.IMMEDIATE) { + inner.dispose(); + } + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @Override + public void request(long n) { + BackpressureHelper.add(requested, n); + drain(); + } + + @Override + public void cancel() { + cancelled = true; + upstream.cancel(); + inner.dispose(); + if (getAndIncrement() != 0) { + queue.clear(); + item = null; + } + } + + void innerSuccess(R item) { + this.item = item; + this.state = STATE_RESULT_VALUE; + drain(); + } + + void innerComplete() { + this.state = STATE_INACTIVE; + drain(); + } + + void innerError(Throwable ex) { + if (errors.addThrowable(ex)) { + if (errorMode != ErrorMode.END) { + upstream.cancel(); + } + this.state = STATE_INACTIVE; + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + Subscriber downstream = this.downstream; + ErrorMode errorMode = this.errorMode; + SimplePlainQueue queue = this.queue; + AtomicThrowable errors = this.errors; + AtomicLong requested = this.requested; + int limit = prefetch - (prefetch >> 1); + + for (;;) { + + for (;;) { + if (cancelled) { + queue.clear(); + item = null; + } + + int s = state; + + if (errors.get() != null) { + if (errorMode == ErrorMode.IMMEDIATE + || (errorMode == ErrorMode.BOUNDARY && s == STATE_INACTIVE)) { + queue.clear(); + item = null; + Throwable ex = errors.terminate(); + downstream.onError(ex); + return; + } + } + + if (s == STATE_INACTIVE) { + boolean d = done; + T v = queue.poll(); + boolean empty = v == null; + + if (d && empty) { + Throwable ex = errors.terminate(); + if (ex == null) { + downstream.onComplete(); + } else { + downstream.onError(ex); + } + return; + } + + if (empty) { + break; + } + + int c = consumed + 1; + if (c == limit) { + consumed = 0; + upstream.request(limit); + } else { + consumed = c; + } + + MaybeSource ms; + + try { + ms = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null MaybeSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.cancel(); + queue.clear(); + errors.addThrowable(ex); + ex = errors.terminate(); + downstream.onError(ex); + return; + } + + state = STATE_ACTIVE; + ms.subscribe(inner); + break; + } else if (s == STATE_RESULT_VALUE) { + long e = emitted; + if (e != requested.get()) { + R w = item; + item = null; + + downstream.onNext(w); + + emitted = e + 1; + state = STATE_INACTIVE; + } else { + break; + } + } else { + break; + } + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class ConcatMapMaybeObserver + extends AtomicReference + implements MaybeObserver { + + private static final long serialVersionUID = -3051469169682093892L; + + final ConcatMapMaybeSubscriber parent; + + ConcatMapMaybeObserver(ConcatMapMaybeSubscriber parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(this, d); + } + + @Override + public void onSuccess(R t) { + parent.innerSuccess(t); + } + + @Override + public void onError(Throwable e) { + parent.innerError(e); + } + + @Override + public void onComplete() { + parent.innerComplete(); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java new file mode 100644 index 0000000000..43223ec721 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java @@ -0,0 +1,332 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.*; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps each upstream item into a {@link SingleSource}, subscribes to them one after the other terminates + * and relays their success values, optionally delaying any errors till the main and inner sources + * terminate. + * + * @param the upstream element type + * @param the output element type + * + * @since 2.1.11 - experimental + */ +@Experimental +public final class FlowableConcatMapSingle extends Flowable { + + final Flowable source; + + final Function> mapper; + + final ErrorMode errorMode; + + final int prefetch; + + public FlowableConcatMapSingle(Flowable source, + Function> mapper, + ErrorMode errorMode, int prefetch) { + this.source = source; + this.mapper = mapper; + this.errorMode = errorMode; + this.prefetch = prefetch; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new ConcatMapSingleSubscriber(s, mapper, prefetch, errorMode)); + } + + static final class ConcatMapSingleSubscriber + extends AtomicInteger + implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = -9140123220065488293L; + + final Subscriber downstream; + + final Function> mapper; + + final int prefetch; + + final AtomicLong requested; + + final AtomicThrowable errors; + + final ConcatMapSingleObserver inner; + + final SimplePlainQueue queue; + + final ErrorMode errorMode; + + Subscription upstream; + + volatile boolean done; + + volatile boolean cancelled; + + long emitted; + + int consumed; + + R item; + + volatile int state; + + /** No inner SingleSource is running. */ + static final int STATE_INACTIVE = 0; + /** An inner SingleSource is running but there are no results yet. */ + static final int STATE_ACTIVE = 1; + /** The inner SingleSource succeeded with a value in {@link #item}. */ + static final int STATE_RESULT_VALUE = 2; + + ConcatMapSingleSubscriber(Subscriber downstream, + Function> mapper, + int prefetch, ErrorMode errorMode) { + this.downstream = downstream; + this.mapper = mapper; + this.prefetch = prefetch; + this.errorMode = errorMode; + this.requested = new AtomicLong(); + this.errors = new AtomicThrowable(); + this.inner = new ConcatMapSingleObserver(this); + this.queue = new SpscArrayQueue(prefetch); + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(upstream, s)) { + upstream = s; + downstream.onSubscribe(this); + s.request(prefetch); + } + } + + @Override + public void onNext(T t) { + if (!queue.offer(t)) { + upstream.cancel(); + onError(new MissingBackpressureException("queue full?!")); + return; + } + drain(); + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (errorMode == ErrorMode.IMMEDIATE) { + inner.dispose(); + } + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @Override + public void request(long n) { + BackpressureHelper.add(requested, n); + drain(); + } + + @Override + public void cancel() { + cancelled = true; + upstream.cancel(); + inner.dispose(); + if (getAndIncrement() != 0) { + queue.clear(); + item = null; + } + } + + void innerSuccess(R item) { + this.item = item; + this.state = STATE_RESULT_VALUE; + drain(); + } + + void innerError(Throwable ex) { + if (errors.addThrowable(ex)) { + if (errorMode != ErrorMode.END) { + upstream.cancel(); + } + this.state = STATE_INACTIVE; + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + Subscriber downstream = this.downstream; + ErrorMode errorMode = this.errorMode; + SimplePlainQueue queue = this.queue; + AtomicThrowable errors = this.errors; + AtomicLong requested = this.requested; + int limit = prefetch - (prefetch >> 1); + + for (;;) { + + for (;;) { + if (cancelled) { + queue.clear(); + item = null; + } + + int s = state; + + if (errors.get() != null) { + if (errorMode == ErrorMode.IMMEDIATE + || (errorMode == ErrorMode.BOUNDARY && s == STATE_INACTIVE)) { + queue.clear(); + item = null; + Throwable ex = errors.terminate(); + downstream.onError(ex); + return; + } + } + + if (s == STATE_INACTIVE) { + boolean d = done; + T v = queue.poll(); + boolean empty = v == null; + + if (d && empty) { + Throwable ex = errors.terminate(); + if (ex == null) { + downstream.onComplete(); + } else { + downstream.onError(ex); + } + return; + } + + if (empty) { + break; + } + + int c = consumed + 1; + if (c == limit) { + consumed = 0; + upstream.request(limit); + } else { + consumed = c; + } + + SingleSource ms; + + try { + ms = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null SingleSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.cancel(); + queue.clear(); + errors.addThrowable(ex); + ex = errors.terminate(); + downstream.onError(ex); + return; + } + + state = STATE_ACTIVE; + ms.subscribe(inner); + break; + } else if (s == STATE_RESULT_VALUE) { + long e = emitted; + if (e != requested.get()) { + R w = item; + item = null; + + downstream.onNext(w); + + emitted = e + 1; + state = STATE_INACTIVE; + } else { + break; + } + } else { + break; + } + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class ConcatMapSingleObserver + extends AtomicReference + implements SingleObserver { + + private static final long serialVersionUID = -3051469169682093892L; + + final ConcatMapSingleSubscriber parent; + + ConcatMapSingleObserver(ConcatMapSingleSubscriber parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(this, d); + } + + @Override + public void onSuccess(R t) { + parent.innerSuccess(t); + } + + @Override + public void onError(Throwable e) { + parent.innerError(e); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java new file mode 100644 index 0000000000..6c393acebb --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java @@ -0,0 +1,371 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; +import org.reactivestreams.Subscriber; + +import io.reactivex.*; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.subjects.MaybeSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableConcatMapMaybeTest { + + @Test + public void simple() { + Flowable.range(1, 5) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void simpleLong() { + Flowable.range(1, 1024) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }, 32) + .test() + .assertValueCount(1024) + .assertNoErrors() + .assertComplete(); + } + + @Test + public void backpressure() { + TestSubscriber ts = Flowable.range(1, 1024) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }, 32) + .test(0); + + for (int i = 1; i <= 1024; i++) { + ts.assertValueCount(i - 1) + .assertNoErrors() + .assertNotComplete() + .requestMore(1) + .assertValueCount(i) + .assertNoErrors(); + } + + ts.assertComplete(); + } + + @Test + public void empty() { + Flowable.range(1, 10) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.empty(); + } + }) + .test() + .assertResult(); + } + + @Test + public void mixed() { + Flowable.range(1, 10) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v % 2 == 0) { + return Maybe.just(v); + } + return Maybe.empty(); + } + }) + .test() + .assertResult(2, 4, 6, 8, 10); + } + + @Test + public void mixedLong() { + Flowable.range(1, 1024) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v % 2 == 0) { + return Maybe.just(v).subscribeOn(Schedulers.computation()); + } + return Maybe.empty().subscribeOn(Schedulers.computation()); + } + }) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertValueCount(512) + .assertNoErrors() + .assertComplete() + .assertOf(new Consumer>() { + @Override + public void accept(TestSubscriber ts) throws Exception { + for (int i = 0; i < 512; i ++) { + ts.assertValueAt(i, (i + 1) * 2); + } + } + }); + } + + @Test + public void mainError() { + Flowable.error(new TestException()) + .concatMapMaybe(Functions.justFunction(Maybe.just(1))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Flowable.just(1) + .concatMapMaybe(Functions.justFunction(Maybe.error(new TestException()))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void mainBoundaryErrorInnerSuccess() { + PublishProcessor pp = PublishProcessor.create(); + MaybeSubject ms = MaybeSubject.create(); + + TestSubscriber ts = pp.concatMapMaybeDelayError(Functions.justFunction(ms), false).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + assertTrue(ms.hasObservers()); + + pp.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertFailure(TestException.class, 1); + } + + @Test + public void mainBoundaryErrorInnerEmpty() { + PublishProcessor pp = PublishProcessor.create(); + MaybeSubject ms = MaybeSubject.create(); + + TestSubscriber ts = pp.concatMapMaybeDelayError(Functions.justFunction(ms), false).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + assertTrue(ms.hasObservers()); + + pp.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onComplete(); + + ts.assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable( + new Function, Flowable>() { + @Override + public Flowable apply(Flowable f) + throws Exception { + return f.concatMapMaybeDelayError( + Functions.justFunction(Maybe.empty())); + } + } + ); + } + + @Test + public void queueOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onNext(2); + s.onNext(3); + s.onError(new TestException()); + } + } + .concatMapMaybe( + Functions.justFunction(Maybe.never()), 1 + ) + .test() + .assertFailure(MissingBackpressureException.class); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void limit() { + Flowable.range(1, 5) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }) + .limit(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void cancel() { + Flowable.range(1, 5) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }) + .test(3) + .assertValues(1, 2, 3) + .assertNoErrors() + .assertNotComplete() + .cancel(); + } + + @Test + public void innerErrorAfterMainError() { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final AtomicReference> obs = new AtomicReference>(); + + TestSubscriber ts = pp.concatMapMaybe( + new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return new Maybe() { + @Override + protected void subscribeActual( + MaybeObserver observer) { + observer.onSubscribe(Disposables.empty()); + obs.set(observer); + } + }; + } + } + ).test(); + + pp.onNext(1); + + pp.onError(new TestException("outer")); + obs.get().onError(new TestException("inner")); + + ts.assertFailureAndMessage(TestException.class, "outer"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void delayAllErrors() { + Flowable.range(1, 5) + .concatMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.error(new TestException()); + } + }) + .test() + .assertFailure(CompositeException.class) + .assertOf(new Consumer>() { + @Override + public void accept(TestSubscriber ts) throws Exception { + CompositeException ce = (CompositeException)ts.errors().get(0); + assertEquals(5, ce.getExceptions().size()); + } + }); + } + + @Test + public void mapperCrash() { + final PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = pp + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test(); + + ts.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + + pp.onNext(1); + + ts.assertFailure(TestException.class); + + assertFalse(pp.hasSubscribers()); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java new file mode 100644 index 0000000000..92779f725f --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java @@ -0,0 +1,286 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; +import org.reactivestreams.Subscriber; + +import io.reactivex.*; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.SingleSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableConcatMapSingleTest { + + @Test + public void simple() { + Flowable.range(1, 5) + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void simpleLong() { + Flowable.range(1, 1024) + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }, 32) + .test() + .assertValueCount(1024) + .assertNoErrors() + .assertComplete(); + } + + @Test + public void backpressure() { + TestSubscriber ts = Flowable.range(1, 1024) + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }, 32) + .test(0); + + for (int i = 1; i <= 1024; i++) { + ts.assertValueCount(i - 1) + .assertNoErrors() + .assertNotComplete() + .requestMore(1) + .assertValueCount(i) + .assertNoErrors(); + } + + ts.assertComplete(); + } + + @Test + public void mainError() { + Flowable.error(new TestException()) + .concatMapSingle(Functions.justFunction(Single.just(1))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Flowable.just(1) + .concatMapSingle(Functions.justFunction(Single.error(new TestException()))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void mainBoundaryErrorInnerSuccess() { + PublishProcessor pp = PublishProcessor.create(); + SingleSubject ms = SingleSubject.create(); + + TestSubscriber ts = pp.concatMapSingleDelayError(Functions.justFunction(ms), false).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + assertTrue(ms.hasObservers()); + + pp.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertFailure(TestException.class, 1); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable( + new Function, Flowable>() { + @Override + public Flowable apply(Flowable f) + throws Exception { + return f.concatMapSingleDelayError( + Functions.justFunction(Single.just((Object)1))); + } + } + ); + } + + @Test + public void queueOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onNext(2); + s.onNext(3); + s.onError(new TestException()); + } + } + .concatMapSingle( + Functions.justFunction(Single.never()), 1 + ) + .test() + .assertFailure(MissingBackpressureException.class); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void limit() { + Flowable.range(1, 5) + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }) + .limit(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void cancel() { + Flowable.range(1, 5) + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }) + .test(3) + .assertValues(1, 2, 3) + .assertNoErrors() + .assertNotComplete() + .cancel(); + } + + @Test + public void innerErrorAfterMainError() { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final AtomicReference> obs = new AtomicReference>(); + + TestSubscriber ts = pp.concatMapSingle( + new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return new Single() { + @Override + protected void subscribeActual( + SingleObserver observer) { + observer.onSubscribe(Disposables.empty()); + obs.set(observer); + } + }; + } + } + ).test(); + + pp.onNext(1); + + pp.onError(new TestException("outer")); + obs.get().onError(new TestException("inner")); + + ts.assertFailureAndMessage(TestException.class, "outer"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void delayAllErrors() { + Flowable.range(1, 5) + .concatMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.error(new TestException()); + } + }) + .test() + .assertFailure(CompositeException.class) + .assertOf(new Consumer>() { + @Override + public void accept(TestSubscriber ts) throws Exception { + CompositeException ce = (CompositeException)ts.errors().get(0); + assertEquals(5, ce.getExceptions().size()); + } + }); + } + + @Test + public void mapperCrash() { + final PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = pp + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test(); + + ts.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + + pp.onNext(1); + + ts.assertFailure(TestException.class); + + assertFalse(pp.hasSubscribers()); + } +} From d3ed2690d5d7840b2ed190032f9324aec9a7d8a9 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 2 Mar 2018 09:56:40 +0100 Subject: [PATCH 114/417] 2.x: Add Flowable.switchMap{Maybe,Single}{DelayError} operators (#5873) --- src/main/java/io/reactivex/Flowable.java | 140 ++++ .../mixed/FlowableSwitchMapMaybe.java | 303 ++++++++ .../mixed/FlowableSwitchMapSingle.java | 292 ++++++++ .../mixed/FlowableSwitchMapMaybeTest.java | 649 ++++++++++++++++++ .../mixed/FlowableSwitchMapSingleTest.java | 606 ++++++++++++++++ 5 files changed, 1990 insertions(+) create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybe.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingleTest.java diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 02c84ed989..0e63ea2f1a 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -14648,6 +14648,146 @@ Flowable switchMap0(Function> return RxJavaPlugins.onAssembly(new FlowableSwitchMap(this, mapper, bufferSize, delayError)); } + /** + * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones + * while disposing the older ones (and ignoring their signals) and emits the latest success value of the current one if + * available while failing immediately if this {@code Flowable} or any of the + * active inner {@code MaybeSource}s fail. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator honors backpressure from downstream. The main {@code Flowable} is consumed in an + * unbounded manner (i.e., without backpressure).
                + *
                Scheduler:
                + *
                {@code switchMapMaybe} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                This operator terminates with an {@code onError} if this {@code Flowable} or any of + * the inner {@code MaybeSource}s fail while they are active. When this happens concurrently, their + * individual {@code Throwable} errors may get combined and emitted as a single + * {@link io.reactivex.exceptions.CompositeException CompositeException}. Otherwise, a late + * (i.e., inactive or switched out) {@code onError} from this {@code Flowable} or from any of + * the inner {@code MaybeSource}s will be forwarded to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} as + * {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}
                + *
                + * @param the output value type + * @param mapper the function called with the current upstream event and should + * return a {@code MaybeSource} to replace the current active inner source + * and get subscribed to. + * @return the new Flowable instance + * @since 2.1.11 - experimental + * @see #switchMapMaybe(Function) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable switchMapMaybe(@NonNull Function> mapper) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new FlowableSwitchMapMaybe(this, mapper, false)); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones + * while disposing the older ones (and ignoring their signals) and emits the latest success value of the current one if + * available, delaying errors from this {@code Flowable} or the inner {@code MaybeSource}s until all terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator honors backpressure from downstream. The main {@code Flowable} is consumed in an + * unbounded manner (i.e., without backpressure).
                + *
                Scheduler:
                + *
                {@code switchMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the output value type + * @param mapper the function called with the current upstream event and should + * return a {@code MaybeSource} to replace the current active inner source + * and get subscribed to. + * @return the new Flowable instance + * @since 2.1.11 - experimental + * @see #switchMapMaybe(Function) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable switchMapMaybeDelayError(@NonNull Function> mapper) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new FlowableSwitchMapMaybe(this, mapper, true)); + } + + /** + * Maps the upstream items into {@link SingleSource}s and switches (subscribes) to the newer ones + * while disposing the older ones (and ignoring their signals) and emits the latest success value of the current one + * while failing immediately if this {@code Flowable} or any of the + * active inner {@code SingleSource}s fail. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator honors backpressure from downstream. The main {@code Flowable} is consumed in an + * unbounded manner (i.e., without backpressure).
                + *
                Scheduler:
                + *
                {@code switchMapSingle} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                This operator terminates with an {@code onError} if this {@code Flowable} or any of + * the inner {@code SingleSource}s fail while they are active. When this happens concurrently, their + * individual {@code Throwable} errors may get combined and emitted as a single + * {@link io.reactivex.exceptions.CompositeException CompositeException}. Otherwise, a late + * (i.e., inactive or switched out) {@code onError} from this {@code Flowable} or from any of + * the inner {@code SingleSource}s will be forwarded to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} as + * {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}
                + *
                + * @param the output value type + * @param mapper the function called with the current upstream event and should + * return a {@code SingleSource} to replace the current active inner source + * and get subscribed to. + * @return the new Flowable instance + * @since 2.1.11 - experimental + * @see #switchMapSingle(Function) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable switchMapSingle(@NonNull Function> mapper) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new FlowableSwitchMapSingle(this, mapper, false)); + } + + /** + * Maps the upstream items into {@link SingleSource}s and switches (subscribes) to the newer ones + * while disposing the older ones (and ignoring their signals) and emits the latest success value of the current one, + * delaying errors from this {@code Flowable} or the inner {@code SingleSource}s until all terminate. + *

                + * + *

                + *
                Backpressure:
                + *
                The operator honors backpressure from downstream. The main {@code Flowable} is consumed in an + * unbounded manner (i.e., without backpressure).
                + *
                Scheduler:
                + *
                {@code switchMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the output value type + * @param mapper the function called with the current upstream event and should + * return a {@code SingleSource} to replace the current active inner source + * and get subscribed to. + * @return the new Flowable instance + * @since 2.1.11 - experimental + * @see #switchMapSingle(Function) + */ + @CheckReturnValue + @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Flowable switchMapSingleDelayError(@NonNull Function> mapper) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new FlowableSwitchMapSingle(this, mapper, true)); + } + /** * Returns a Flowable that emits only the first {@code count} items emitted by the source Publisher. If the source emits fewer than * {@code count} items then all of its items are emitted. diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybe.java new file mode 100644 index 0000000000..95b0436321 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybe.java @@ -0,0 +1,303 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones + * while disposing the older ones and emits the latest success value if available, optionally delaying + * errors from the main source or the inner sources. + * + * @param the upstream value type + * @param the downstream value type + * @since 2.1.11 - experimental + */ +@Experimental +public final class FlowableSwitchMapMaybe extends Flowable { + + final Flowable source; + + final Function> mapper; + + final boolean delayErrors; + + public FlowableSwitchMapMaybe(Flowable source, + Function> mapper, + boolean delayErrors) { + this.source = source; + this.mapper = mapper; + this.delayErrors = delayErrors; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new SwitchMapMaybeSubscriber(s, mapper, delayErrors)); + } + + static final class SwitchMapMaybeSubscriber extends AtomicInteger + implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = -5402190102429853762L; + + final Subscriber downstream; + + final Function> mapper; + + final boolean delayErrors; + + final AtomicThrowable errors; + + final AtomicLong requested; + + final AtomicReference> inner; + + static final SwitchMapMaybeObserver INNER_DISPOSED = + new SwitchMapMaybeObserver(null); + + Subscription upstream; + + volatile boolean done; + + volatile boolean cancelled; + + long emitted; + + SwitchMapMaybeSubscriber(Subscriber downstream, + Function> mapper, + boolean delayErrors) { + this.downstream = downstream; + this.mapper = mapper; + this.delayErrors = delayErrors; + this.errors = new AtomicThrowable(); + this.requested = new AtomicLong(); + this.inner = new AtomicReference>(); + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(upstream, s)) { + upstream = s; + downstream.onSubscribe(this); + s.request(Long.MAX_VALUE); + } + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void onNext(T t) { + SwitchMapMaybeObserver current = inner.get(); + if (current != null) { + current.dispose(); + } + + MaybeSource ms; + + try { + ms = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null MaybeSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.cancel(); + inner.getAndSet((SwitchMapMaybeObserver)INNER_DISPOSED); + onError(ex); + return; + } + + SwitchMapMaybeObserver observer = new SwitchMapMaybeObserver(this); + + for (;;) { + current = inner.get(); + if (current == INNER_DISPOSED) { + break; + } + if (inner.compareAndSet(current, observer)) { + ms.subscribe(observer); + break; + } + } + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (!delayErrors) { + disposeInner(); + } + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + void disposeInner() { + SwitchMapMaybeObserver current = inner.getAndSet((SwitchMapMaybeObserver)INNER_DISPOSED); + if (current != null && current != INNER_DISPOSED) { + current.dispose(); + } + } + + @Override + public void request(long n) { + BackpressureHelper.add(requested, n); + drain(); + } + + @Override + public void cancel() { + cancelled = true; + upstream.cancel(); + disposeInner(); + } + + void innerError(SwitchMapMaybeObserver sender, Throwable ex) { + if (inner.compareAndSet(sender, null)) { + if (errors.addThrowable(ex)) { + if (!delayErrors) { + upstream.cancel(); + disposeInner(); + } + drain(); + return; + } + } + RxJavaPlugins.onError(ex); + } + + void innerComplete(SwitchMapMaybeObserver sender) { + if (inner.compareAndSet(sender, null)) { + drain(); + } + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + Subscriber downstream = this.downstream; + AtomicThrowable errors = this.errors; + AtomicReference> inner = this.inner; + AtomicLong requested = this.requested; + long emitted = this.emitted; + + for (;;) { + + for (;;) { + if (cancelled) { + return; + } + + if (errors.get() != null) { + if (!delayErrors) { + Throwable ex = errors.terminate(); + downstream.onError(ex); + return; + } + } + + boolean d = done; + SwitchMapMaybeObserver current = inner.get(); + boolean empty = current == null; + + if (d && empty) { + Throwable ex = errors.terminate(); + if (ex != null) { + downstream.onError(ex); + } else { + downstream.onComplete(); + } + return; + } + + if (empty || current.item == null || emitted == requested.get()) { + break; + } + + inner.compareAndSet(current, null); + + downstream.onNext(current.item); + + emitted++; + } + + this.emitted = emitted; + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class SwitchMapMaybeObserver + extends AtomicReference implements MaybeObserver { + + private static final long serialVersionUID = 8042919737683345351L; + + final SwitchMapMaybeSubscriber parent; + + volatile R item; + + SwitchMapMaybeObserver(SwitchMapMaybeSubscriber parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onSuccess(R t) { + item = t; + parent.drain(); + } + + @Override + public void onError(Throwable e) { + parent.innerError(this, e); + } + + @Override + public void onComplete() { + parent.innerComplete(this); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java new file mode 100644 index 0000000000..813f779902 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java @@ -0,0 +1,292 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps the upstream items into {@link SingleSource}s and switches (subscribes) to the newer ones + * while disposing the older ones and emits the latest success value, optionally delaying + * errors from the main source or the inner sources. + * + * @param the upstream value type + * @param the downstream value type + * @since 2.1.11 - experimental + */ +@Experimental +public final class FlowableSwitchMapSingle extends Flowable { + + final Flowable source; + + final Function> mapper; + + final boolean delayErrors; + + public FlowableSwitchMapSingle(Flowable source, + Function> mapper, + boolean delayErrors) { + this.source = source; + this.mapper = mapper; + this.delayErrors = delayErrors; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new SwitchMapSingleSubscriber(s, mapper, delayErrors)); + } + + static final class SwitchMapSingleSubscriber extends AtomicInteger + implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = -5402190102429853762L; + + final Subscriber downstream; + + final Function> mapper; + + final boolean delayErrors; + + final AtomicThrowable errors; + + final AtomicLong requested; + + final AtomicReference> inner; + + static final SwitchMapSingleObserver INNER_DISPOSED = + new SwitchMapSingleObserver(null); + + Subscription upstream; + + volatile boolean done; + + volatile boolean cancelled; + + long emitted; + + SwitchMapSingleSubscriber(Subscriber downstream, + Function> mapper, + boolean delayErrors) { + this.downstream = downstream; + this.mapper = mapper; + this.delayErrors = delayErrors; + this.errors = new AtomicThrowable(); + this.requested = new AtomicLong(); + this.inner = new AtomicReference>(); + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(upstream, s)) { + upstream = s; + downstream.onSubscribe(this); + s.request(Long.MAX_VALUE); + } + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void onNext(T t) { + SwitchMapSingleObserver current = inner.get(); + if (current != null) { + current.dispose(); + } + + SingleSource ms; + + try { + ms = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.cancel(); + inner.getAndSet((SwitchMapSingleObserver)INNER_DISPOSED); + onError(ex); + return; + } + + SwitchMapSingleObserver observer = new SwitchMapSingleObserver(this); + + for (;;) { + current = inner.get(); + if (current == INNER_DISPOSED) { + break; + } + if (inner.compareAndSet(current, observer)) { + ms.subscribe(observer); + break; + } + } + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (!delayErrors) { + disposeInner(); + } + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + void disposeInner() { + SwitchMapSingleObserver current = inner.getAndSet((SwitchMapSingleObserver)INNER_DISPOSED); + if (current != null && current != INNER_DISPOSED) { + current.dispose(); + } + } + + @Override + public void request(long n) { + BackpressureHelper.add(requested, n); + drain(); + } + + @Override + public void cancel() { + cancelled = true; + upstream.cancel(); + disposeInner(); + } + + void innerError(SwitchMapSingleObserver sender, Throwable ex) { + if (inner.compareAndSet(sender, null)) { + if (errors.addThrowable(ex)) { + if (!delayErrors) { + upstream.cancel(); + disposeInner(); + } + drain(); + return; + } + } + RxJavaPlugins.onError(ex); + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + Subscriber downstream = this.downstream; + AtomicThrowable errors = this.errors; + AtomicReference> inner = this.inner; + AtomicLong requested = this.requested; + long emitted = this.emitted; + + for (;;) { + + for (;;) { + if (cancelled) { + return; + } + + if (errors.get() != null) { + if (!delayErrors) { + Throwable ex = errors.terminate(); + downstream.onError(ex); + return; + } + } + + boolean d = done; + SwitchMapSingleObserver current = inner.get(); + boolean empty = current == null; + + if (d && empty) { + Throwable ex = errors.terminate(); + if (ex != null) { + downstream.onError(ex); + } else { + downstream.onComplete(); + } + return; + } + + if (empty || current.item == null || emitted == requested.get()) { + break; + } + + inner.compareAndSet(current, null); + + downstream.onNext(current.item); + + emitted++; + } + + this.emitted = emitted; + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class SwitchMapSingleObserver + extends AtomicReference implements SingleObserver { + + private static final long serialVersionUID = 8042919737683345351L; + + final SwitchMapSingleSubscriber parent; + + volatile R item; + + SwitchMapSingleObserver(SwitchMapSingleSubscriber parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onSuccess(R t) { + item = t; + parent.drain(); + } + + @Override + public void onError(Throwable e) { + parent.innerError(this, e); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybeTest.java new file mode 100644 index 0000000000..d080928047 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybeTest.java @@ -0,0 +1,649 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.MaybeSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableSwitchMapMaybeTest { + + @Test + public void simple() { + Flowable.range(1, 5) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void simpleEmpty() { + Flowable.range(1, 5) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.empty(); + } + }) + .test() + .assertResult(); + } + + @Test + public void simpleMixed() { + Flowable.range(1, 10) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v % 2 == 0) { + return Maybe.just(v); + } + return Maybe.empty(); + } + }) + .test() + .assertResult(2, 4, 6, 8, 10); + } + + @Test + public void backpressured() { + TestSubscriber ts = Flowable.range(1, 1024) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v % 2 == 0) { + return Maybe.just(v); + } + return Maybe.empty(); + } + }) + .test(0L); + + // backpressure results items skipped + ts + .requestMore(1) + .assertResult(1024); + } + + @Test + public void mainError() { + Flowable.error(new TestException()) + .switchMapMaybe(Functions.justFunction(Maybe.never())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Flowable.just(1) + .switchMapMaybe(Functions.justFunction(Maybe.error(new TestException()))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) + throws Exception { + return f + .switchMapMaybe(Functions.justFunction(Maybe.never())); + } + } + ); + } + + @Test + public void limit() { + Flowable.range(1, 5) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }) + .limit(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void switchOver() { + PublishProcessor pp = PublishProcessor.create(); + + final MaybeSubject ms1 = MaybeSubject.create(); + final MaybeSubject ms2 = MaybeSubject.create(); + + TestSubscriber ts = pp.switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms1; + } + return ms2; + } + }).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms1.hasObservers()); + + pp.onNext(2); + + assertFalse(ms1.hasObservers()); + assertTrue(ms2.hasObservers()); + + ms2.onError(new TestException()); + + assertFalse(pp.hasSubscribers()); + + ts.assertFailure(TestException.class); + } + + @Test + public void switchOverDelayError() { + PublishProcessor pp = PublishProcessor.create(); + + final MaybeSubject ms1 = MaybeSubject.create(); + final MaybeSubject ms2 = MaybeSubject.create(); + + TestSubscriber ts = pp.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms1; + } + return ms2; + } + }).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms1.hasObservers()); + + pp.onNext(2); + + assertFalse(ms1.hasObservers()); + assertTrue(ms2.hasObservers()); + + ms2.onError(new TestException()); + + ts.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + + pp.onComplete(); + + ts.assertFailure(TestException.class); + } + + @Test + public void mainErrorInnerCompleteDelayError() { + PublishProcessor pp = PublishProcessor.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + TestSubscriber ts = pp.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms.hasObservers()); + + pp.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onComplete(); + + ts.assertFailure(TestException.class); + } + + @Test + public void mainErrorInnerSuccessDelayError() { + PublishProcessor pp = PublishProcessor.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + TestSubscriber ts = pp.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms.hasObservers()); + + pp.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertFailure(TestException.class, 1); + } + + @Test + public void mapperCrash() { + Flowable.just(1) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void disposeBeforeSwitchInOnNext() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.just(1) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + ts.cancel(); + return Maybe.just(1); + } + }).subscribe(ts); + + ts.assertEmpty(); + } + + @Test + public void disposeOnNextAfterFirst() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.just(1, 2) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 2) { + ts.cancel(); + } + return Maybe.just(1); + } + }).subscribe(ts); + + ts.assertValue(1) + .assertNoErrors() + .assertNotComplete(); + } + + @Test + public void cancel() { + PublishProcessor pp = PublishProcessor.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + TestSubscriber ts = pp.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + ts.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + assertTrue(ms.hasObservers()); + + ts.cancel(); + + assertFalse(pp.hasSubscribers()); + assertFalse(ms.hasObservers()); + } + + @Test + public void mainErrorAfterTermination() { + List errors = TestHelper.trackPluginErrors(); + try { + new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onError(new TestException("outer")); + } + } + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.error(new TestException("inner")); + } + }) + .test() + .assertFailureAndMessage(TestException.class, "inner"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer"); + } finally { + RxJavaPlugins.reset(); + } + } + + + @Test + public void innerErrorAfterTermination() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> moRef = new AtomicReference>(); + + TestSubscriber ts = new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onError(new TestException("outer")); + } + } + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return new Maybe() { + @Override + protected void subscribeActual( + MaybeObserver observer) { + observer.onSubscribe(Disposables.empty()); + moRef.set(observer); + } + }; + } + }) + .test(); + + ts.assertFailureAndMessage(TestException.class, "outer"); + + moRef.get().onError(new TestException("inner")); + moRef.get().onComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void nextCancelRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final PublishProcessor pp = PublishProcessor.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + final TestSubscriber ts = pp.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertNoErrors() + .assertNotComplete(); + } + } + + @Test + public void nextInnerErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + final TestSubscriber ts = pp.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Maybe.never(); + } + }).test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + if (ts.errorCount() != 0) { + assertTrue(errors.isEmpty()); + ts.assertFailure(TestException.class); + } else if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void mainErrorInnerErrorRace() { + final TestException ex = new TestException(); + final TestException ex2 = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + final TestSubscriber ts = pp.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Maybe.never(); + } + }).test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onError(ex); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onError(ex2); + } + }; + + TestHelper.race(r1, r2); + + ts.assertError(new Predicate() { + @Override + public boolean test(Throwable e) throws Exception { + return e instanceof TestException || e instanceof CompositeException; + } + }); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void nextInnerSuccessRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final PublishProcessor pp = PublishProcessor.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + final TestSubscriber ts = pp.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Maybe.empty(); + } + }).test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onSuccess(3); + } + }; + + TestHelper.race(r1, r2); + + ts.assertNoErrors() + .assertNotComplete(); + } + } + + @Test + public void requestMoreOnNext() { + TestSubscriber ts = new TestSubscriber(1) { + @Override + public void onNext(Integer t) { + super.onNext(t); + requestMore(1); + } + }; + Flowable.range(1, 5) + .switchMapMaybe(Functions.justFunction(Maybe.just(1))) + .subscribe(ts); + + ts.assertResult(1, 1, 1, 1, 1); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingleTest.java new file mode 100644 index 0000000000..3c6c832b76 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingleTest.java @@ -0,0 +1,606 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.SingleSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableSwitchMapSingleTest { + + @Test + public void simple() { + Flowable.range(1, 5) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void mainError() { + Flowable.error(new TestException()) + .switchMapSingle(Functions.justFunction(Single.never())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Flowable.just(1) + .switchMapSingle(Functions.justFunction(Single.error(new TestException()))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) + throws Exception { + return f + .switchMapSingle(Functions.justFunction(Single.never())); + } + } + ); + } + + @Test + public void limit() { + Flowable.range(1, 5) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }) + .limit(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void switchOver() { + PublishProcessor pp = PublishProcessor.create(); + + final SingleSubject ms1 = SingleSubject.create(); + final SingleSubject ms2 = SingleSubject.create(); + + TestSubscriber ts = pp.switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms1; + } + return ms2; + } + }).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms1.hasObservers()); + + pp.onNext(2); + + assertFalse(ms1.hasObservers()); + assertTrue(ms2.hasObservers()); + + ms2.onError(new TestException()); + + assertFalse(pp.hasSubscribers()); + + ts.assertFailure(TestException.class); + } + + @Test + public void switchOverDelayError() { + PublishProcessor pp = PublishProcessor.create(); + + final SingleSubject ms1 = SingleSubject.create(); + final SingleSubject ms2 = SingleSubject.create(); + + TestSubscriber ts = pp.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms1; + } + return ms2; + } + }).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms1.hasObservers()); + + pp.onNext(2); + + assertFalse(ms1.hasObservers()); + assertTrue(ms2.hasObservers()); + + ms2.onError(new TestException()); + + ts.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + + pp.onComplete(); + + ts.assertFailure(TestException.class); + } + + @Test + public void mainErrorInnerCompleteDelayError() { + PublishProcessor pp = PublishProcessor.create(); + + final SingleSubject ms = SingleSubject.create(); + + TestSubscriber ts = pp.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms.hasObservers()); + + pp.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertFailure(TestException.class, 1); + } + + @Test + public void mainErrorInnerSuccessDelayError() { + PublishProcessor pp = PublishProcessor.create(); + + final SingleSubject ms = SingleSubject.create(); + + TestSubscriber ts = pp.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms.hasObservers()); + + pp.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertFailure(TestException.class, 1); + } + + @Test + public void mapperCrash() { + Flowable.just(1) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void disposeBeforeSwitchInOnNext() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.just(1) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + ts.cancel(); + return Single.just(1); + } + }).subscribe(ts); + + ts.assertEmpty(); + } + + @Test + public void disposeOnNextAfterFirst() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.just(1, 2) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 2) { + ts.cancel(); + } + return Single.just(1); + } + }).subscribe(ts); + + ts.assertValue(1) + .assertNoErrors() + .assertNotComplete(); + } + + @Test + public void cancel() { + PublishProcessor pp = PublishProcessor.create(); + + final SingleSubject ms = SingleSubject.create(); + + TestSubscriber ts = pp.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + pp.onNext(1); + + ts.assertEmpty(); + + assertTrue(pp.hasSubscribers()); + assertTrue(ms.hasObservers()); + + ts.cancel(); + + assertFalse(pp.hasSubscribers()); + assertFalse(ms.hasObservers()); + } + + @Test + public void mainErrorAfterTermination() { + List errors = TestHelper.trackPluginErrors(); + try { + new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onError(new TestException("outer")); + } + } + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.error(new TestException("inner")); + } + }) + .test() + .assertFailureAndMessage(TestException.class, "inner"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer"); + } finally { + RxJavaPlugins.reset(); + } + } + + + @Test + public void innerErrorAfterTermination() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> moRef = new AtomicReference>(); + + TestSubscriber ts = new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onError(new TestException("outer")); + } + } + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return new Single() { + @Override + protected void subscribeActual( + SingleObserver observer) { + observer.onSubscribe(Disposables.empty()); + moRef.set(observer); + } + }; + } + }) + .test(); + + ts.assertFailureAndMessage(TestException.class, "outer"); + + moRef.get().onError(new TestException("inner")); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void nextCancelRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final PublishProcessor pp = PublishProcessor.create(); + + final SingleSubject ms = SingleSubject.create(); + + final TestSubscriber ts = pp.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertNoErrors() + .assertNotComplete(); + } + } + + @Test + public void nextInnerErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final SingleSubject ms = SingleSubject.create(); + + final TestSubscriber ts = pp.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Single.never(); + } + }).test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + if (ts.errorCount() != 0) { + assertTrue(errors.isEmpty()); + ts.assertFailure(TestException.class); + } else if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void mainErrorInnerErrorRace() { + final TestException ex = new TestException(); + final TestException ex2 = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final SingleSubject ms = SingleSubject.create(); + + final TestSubscriber ts = pp.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Single.never(); + } + }).test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onError(ex); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onError(ex2); + } + }; + + TestHelper.race(r1, r2); + + ts.assertError(new Predicate() { + @Override + public boolean test(Throwable e) throws Exception { + return e instanceof TestException || e instanceof CompositeException; + } + }); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void nextInnerSuccessRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final PublishProcessor pp = PublishProcessor.create(); + + final SingleSubject ms = SingleSubject.create(); + + final TestSubscriber ts = pp.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Single.never(); + } + }).test(); + + pp.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onSuccess(3); + } + }; + + TestHelper.race(r1, r2); + + ts.assertNoErrors() + .assertNotComplete(); + } + } + + @Test + public void requestMoreOnNext() { + TestSubscriber ts = new TestSubscriber(1) { + @Override + public void onNext(Integer t) { + super.onNext(t); + requestMore(1); + } + }; + Flowable.range(1, 5) + .switchMapSingle(Functions.justFunction(Single.just(1))) + .subscribe(ts); + + ts.assertResult(1, 1, 1, 1, 1); + } + + @Test + public void backpressured() { + Flowable.just(1) + .switchMapSingle(Functions.justFunction(Single.just(1))) + .test(0) + .assertEmpty() + .requestMore(1) + .assertResult(1); + } +} From ebab90300858c764d0112378c89df9aa5a64c419 Mon Sep 17 00:00:00 2001 From: "Artem Zinnatullin :slowpoke" Date: Sat, 3 Mar 2018 02:38:44 -0800 Subject: [PATCH 115/417] 2.x: Add note about NoSuchElementException to Single.zip(). (#5876) * 2.x: Add note about NoSuchElementException to Single.zip(). * Address code review comments. --- src/main/java/io/reactivex/Single.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 8f4ab31fd4..2ef5a5d63e 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -1279,6 +1279,8 @@ public static Single wrap(SingleSource source) { * value and calls a zipper function with an array of these values to return a result * to be emitted to downstream. *

                + * If the {@code Iterable} of {@link SingleSource}s is empty a {@link NoSuchElementException} error is signalled after subscription. + *

                * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function} passed to the method would trigger a {@code ClassCastException}. @@ -1294,7 +1296,8 @@ public static Single wrap(SingleSource source) { * * @param the common value type * @param the result value type - * @param sources the Iterable sequence of SingleSource instances + * @param sources the Iterable sequence of SingleSource instances. An empty sequence will result in an + * {@code onError} signal of {@link NoSuchElementException}. * @param zipper the function that receives an array with values from each SingleSource * and should return a value to be emitted to downstream * @return the new Single instance @@ -1721,6 +1724,8 @@ public static Single zip( * value and calls a zipper function with an array of these values to return a result * to be emitted to downstream. *

                + * If the array of {@link SingleSource}s is empty a {@link NoSuchElementException} error is signalled immediately. + *

                * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function} passed to the method would trigger a {@code ClassCastException}. @@ -1736,7 +1741,8 @@ public static Single zip( * * @param the common value type * @param the result value type - * @param sources the array of SingleSource instances + * @param sources the array of SingleSource instances. An empty sequence will result in an + * {@code onError} signal of {@link NoSuchElementException}. * @param zipper the function that receives an array with values from each SingleSource * and should return a value to be emitted to downstream * @return the new Single instance From f6f6d82782b145ac4155707400db1b2f38cc221f Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sat, 3 Mar 2018 14:36:04 +0100 Subject: [PATCH 116/417] 2.x: Add Observable switchMapX and concatMapX operators (#5875) * 2.x: Add Observable switchMapX and concatMapX operators * Rename local variables to match their datatype better. --- src/main/java/io/reactivex/Observable.java | 550 ++++++++++++++- .../mixed/FlowableConcatMapSingle.java | 6 +- .../mixed/FlowableSwitchMapSingle.java | 6 +- .../mixed/ObservableConcatMapCompletable.java | 277 ++++++++ .../mixed/ObservableConcatMapMaybe.java | 306 +++++++++ .../mixed/ObservableConcatMapSingle.java | 296 ++++++++ .../mixed/ObservableSwitchMapCompletable.java | 235 +++++++ .../mixed/ObservableSwitchMapMaybe.java | 288 ++++++++ .../mixed/ObservableSwitchMapSingle.java | 277 ++++++++ .../ObservableConcatMapCompletable.java | 244 ------- .../observable/ObservableInternalHelper.java | 36 +- .../ObservableConcatMapCompletableTest.java | 362 ++++++++++ .../mixed/ObservableConcatMapMaybeTest.java | 349 ++++++++++ .../mixed/ObservableConcatMapSingleTest.java | 286 ++++++++ .../ObservableSwitchMapCompletableTest.java | 387 +++++++++++ .../mixed/ObservableSwitchMapMaybeTest.java | 645 ++++++++++++++++++ .../mixed/ObservableSwitchMapSingleTest.java | 613 +++++++++++++++++ .../reactivex/tck/ConcatMapMaybeTckTest.java | 37 + .../reactivex/tck/ConcatMapSingleTckTest.java | 37 + 19 files changed, 4949 insertions(+), 288 deletions(-) create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java delete mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletableTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java create mode 100644 src/test/java/io/reactivex/tck/ConcatMapMaybeTckTest.java create mode 100644 src/test/java/io/reactivex/tck/ConcatMapSingleTckTest.java diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index da7160f81e..423bcef036 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -26,6 +26,7 @@ import io.reactivex.internal.fuseable.ScalarCallable; import io.reactivex.internal.observers.*; import io.reactivex.internal.operators.flowable.*; +import io.reactivex.internal.operators.mixed.*; import io.reactivex.internal.operators.observable.*; import io.reactivex.internal.util.*; import io.reactivex.observables.*; @@ -6498,7 +6499,97 @@ public final Completable concatMapCompletable(Function mapper, int capacityHint) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(capacityHint, "capacityHint"); - return RxJavaPlugins.onAssembly(new ObservableConcatMapCompletable(this, mapper, capacityHint)); + return RxJavaPlugins.onAssembly(new ObservableConcatMapCompletable(this, mapper, ErrorMode.IMMEDIATE, capacityHint)); + } + + /** + * Maps the upstream items into {@link CompletableSource}s and subscribes to them one after the + * other terminates, delaying all errors till both this {@code Observable} and all + * inner {@code CompletableSource}s terminate. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param mapper the function called with the upstream item and should return + * a {@code CompletableSource} to become the next source to + * be subscribed to + * @return a new Completable instance + * @since 2.1.11 - experimental + * @see #concatMapCompletable(Function, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Completable concatMapCompletableDelayError(Function mapper) { + return concatMapCompletableDelayError(mapper, true, 2); + } + + /** + * Maps the upstream items into {@link CompletableSource}s and subscribes to them one after the + * other terminates, optionally delaying all errors till both this {@code Observable} and all + * inner {@code CompletableSource}s terminate. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param mapper the function called with the upstream item and should return + * a {@code CompletableSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the + * inner {@code CompletableSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Observable} is delayed until the current inner + * {@code CompletableSource} terminates and only then is + * it emitted to the downstream. + * @return a new Completable instance + * @since 2.1.11 - experimental + * @see #concatMapCompletable(Function) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Completable concatMapCompletableDelayError(Function mapper, boolean tillTheEnd) { + return concatMapCompletableDelayError(mapper, tillTheEnd, 2); + } + + /** + * Maps the upstream items into {@link CompletableSource}s and subscribes to them one after the + * other terminates, optionally delaying all errors till both this {@code Observable} and all + * inner {@code CompletableSource}s terminate. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param mapper the function called with the upstream item and should return + * a {@code CompletableSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the + * inner {@code CompletableSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Observable} is delayed until the current inner + * {@code CompletableSource} terminates and only then is + * it emitted to the downstream. + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code CompletableSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code CompletableSource}s. + * @return a new Completable instance + * @since 2.1.11 - experimental + * @see #concatMapCompletable(Function, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Completable concatMapCompletableDelayError(Function mapper, boolean tillTheEnd, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new ObservableConcatMapCompletable(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch)); } /** @@ -6558,6 +6649,312 @@ public final Observable concatMapIterable(final Function + * + *
                + *
                Scheduler:
                + *
                {@code concatMapMaybe} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code MaybeSource}s + * @param mapper the function called with the upstream item and should return + * a {@code MaybeSource} to become the next source to + * be subscribed to + * @return a new Observable instance + * @since 2.1.11 - experimental + * @see #concatMapMaybeDelayError(Function) + * @see #concatMapMaybe(Function, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatMapMaybe(Function> mapper) { + return concatMapMaybe(mapper, 2); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the + * other succeeds or completes, emits their success value if available or terminates immediately if + * either this {@code Observable} or the current inner {@code MaybeSource} fail. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapMaybe} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code MaybeSource}s + * @param mapper the function called with the upstream item and should return + * a {@code MaybeSource} to become the next source to + * be subscribed to + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code MaybeSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code MaybeSource}s. + * @return a new Observable instance + * @since 2.1.11 - experimental + * @see #concatMapMaybe(Function) + * @see #concatMapMaybeDelayError(Function, boolean, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatMapMaybe(Function> mapper, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new ObservableConcatMapMaybe(this, mapper, ErrorMode.IMMEDIATE, prefetch)); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the + * other terminates, emits their success value if available and delaying all errors + * till both this {@code Observable} and all inner {@code MaybeSource}s terminate. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code MaybeSource}s + * @param mapper the function called with the upstream item and should return + * a {@code MaybeSource} to become the next source to + * be subscribed to + * @return a new Observable instance + * @since 2.1.11 - experimental + * @see #concatMapMaybe(Function) + * @see #concatMapMaybeDelayError(Function, boolean) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatMapMaybeDelayError(Function> mapper) { + return concatMapMaybeDelayError(mapper, true, 2); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the + * other terminates, emits their success value if available and optionally delaying all errors + * till both this {@code Observable} and all inner {@code MaybeSource}s terminate. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code MaybeSource}s + * @param mapper the function called with the upstream item and should return + * a {@code MaybeSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the + * inner {@code MaybeSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Observable} is delayed until the current inner + * {@code MaybeSource} terminates and only then is + * it emitted to the downstream. + * @return a new Observable instance + * @since 2.1.11 - experimental + * @see #concatMapMaybe(Function, int) + * @see #concatMapMaybeDelayError(Function, boolean, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatMapMaybeDelayError(Function> mapper, boolean tillTheEnd) { + return concatMapMaybeDelayError(mapper, tillTheEnd, 2); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the + * other terminates, emits their success value if available and optionally delaying all errors + * till both this {@code Observable} and all inner {@code MaybeSource}s terminate. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code MaybeSource}s + * @param mapper the function called with the upstream item and should return + * a {@code MaybeSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the + * inner {@code MaybeSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Observable} is delayed until the current inner + * {@code MaybeSource} terminates and only then is + * it emitted to the downstream. + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code MaybeSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code MaybeSource}s. + * @return a new Observable instance + * @since 2.1.11 - experimental + * @see #concatMapMaybe(Function, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatMapMaybeDelayError(Function> mapper, boolean tillTheEnd, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new ObservableConcatMapMaybe(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch)); + } + + /** + * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the + * other succeeds, emits their success values or terminates immediately if + * either this {@code Observable} or the current inner {@code SingleSource} fail. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code SingleSource}s + * @param mapper the function called with the upstream item and should return + * a {@code SingleSource} to become the next source to + * be subscribed to + * @return a new Observable instance + * @since 2.1.11 - experimental + * @see #concatMapSingleDelayError(Function) + * @see #concatMapSingle(Function, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatMapSingle(Function> mapper) { + return concatMapSingle(mapper, 2); + } + + /** + * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the + * other succeeds, emits their success values or terminates immediately if + * either this {@code Observable} or the current inner {@code SingleSource} fail. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code SingleSource}s + * @param mapper the function called with the upstream item and should return + * a {@code SingleSource} to become the next source to + * be subscribed to + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code SingleSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code SingleSource}s. + * @return a new Observable instance + * @since 2.1.11 - experimental + * @see #concatMapSingle(Function) + * @see #concatMapSingleDelayError(Function, boolean, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatMapSingle(Function> mapper, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new ObservableConcatMapSingle(this, mapper, ErrorMode.IMMEDIATE, prefetch)); + } + + /** + * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the + * other succeeds or fails, emits their success values and delays all errors + * till both this {@code Observable} and all inner {@code SingleSource}s terminate. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code SingleSource}s + * @param mapper the function called with the upstream item and should return + * a {@code SingleSource} to become the next source to + * be subscribed to + * @return a new Observable instance + * @since 2.1.11 - experimental + * @see #concatMapSingle(Function) + * @see #concatMapSingleDelayError(Function, boolean) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatMapSingleDelayError(Function> mapper) { + return concatMapSingleDelayError(mapper, true, 2); + } + + /** + * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the + * other succeeds or fails, emits their success values and optionally delays all errors + * till both this {@code Observable} and all inner {@code SingleSource}s terminate. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code SingleSource}s + * @param mapper the function called with the upstream item and should return + * a {@code SingleSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the + * inner {@code SingleSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Observable} is delayed until the current inner + * {@code SingleSource} terminates and only then is + * it emitted to the downstream. + * @return a new Observable instance + * @since 2.1.11 - experimental + * @see #concatMapSingle(Function, int) + * @see #concatMapSingleDelayError(Function, boolean, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatMapSingleDelayError(Function> mapper, boolean tillTheEnd) { + return concatMapSingleDelayError(mapper, tillTheEnd, 2); + } + + /** + * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the + * other succeeds or fails, emits their success values and optionally delays errors + * till both this {@code Observable} and all inner {@code SingleSource}s terminate. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the result type of the inner {@code SingleSource}s + * @param mapper the function called with the upstream item and should return + * a {@code SingleSource} to become the next source to + * be subscribed to + * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the + * inner {@code SingleSource}s are delayed until all + * of them terminate. If {@code false}, an error from this + * {@code Observable} is delayed until the current inner + * {@code SingleSource} terminates and only then is + * it emitted to the downstream. + * @param prefetch The number of upstream items to prefetch so that fresh items are + * ready to be mapped when a previous {@code SingleSource} terminates. + * The operator replenishes after half of the prefetch amount has been consumed + * and turned into {@code SingleSource}s. + * @return a new Observable instance + * @since 2.1.11 - experimental + * @see #concatMapSingle(Function, int) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable concatMapSingleDelayError(Function> mapper, boolean tillTheEnd, int prefetch) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + ObjectHelper.verifyPositive(prefetch, "prefetch"); + return RxJavaPlugins.onAssembly(new ObservableConcatMapSingle(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch)); + } + /** * Returns an Observable that emits the items emitted from the current ObservableSource, then the next, one after * the other, without interleaving them. @@ -11723,6 +12120,151 @@ public final Observable switchMap(Function(this, mapper, bufferSize, false)); } + /** + * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while + * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one + * active {@code CompletableSource} running. + *

                + * + *

                + * Since a {@code CompletableSource} doesn't produce any items, the resulting reactive type of + * this operator is a {@link Completable} that can only indicate successful completion or + * a failure in any of the inner {@code CompletableSource}s or the failure of the current + * {@link Observable}. + *

                + *
                Scheduler:
                + *
                {@code switchMapCompletable} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If either this {@code Observable} or the active {@code CompletableSource} signals an {@code onError}, + * the resulting {@code Completable} is terminated immediately with that {@code Throwable}. + * Use the {@link #switchMapCompletableDelayError(Function)} to delay such inner failures until + * every inner {@code CompletableSource}s and the main {@code Observable} terminates in some fashion. + * If they fail concurrently, the operator may combine the {@code Throwable}s into a + * {@link io.reactivex.exceptions.CompositeException CompositeException} + * and signal it to the downstream instead. If any inactivated (switched out) {@code CompletableSource} + * signals an {@code onError} late, the {@code Throwable}s will be signalled to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. + *
                + *
                + * @param mapper the function called with each upstream item and should return a + * {@link CompletableSource} to be subscribed to and awaited for + * (non blockingly) for its terminal event + * @return the new Completable instance + * @since 2.1.11 - experimental + * @see #switchMapCompletableDelayError(Function) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Completable switchMapCompletable(@NonNull Function mapper) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new ObservableSwitchMapCompletable(this, mapper, false)); + } + + /** + * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while + * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one + * active {@code CompletableSource} running and delaying any main or inner errors until all + * of them terminate. + *

                + * + *

                + * Since a {@code CompletableSource} doesn't produce any items, the resulting reactive type of + * this operator is a {@link Completable} that can only indicate successful completion or + * a failure in any of the inner {@code CompletableSource}s or the failure of the current + * {@link Observable}. + *

                + *
                Scheduler:
                + *
                {@code switchMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                Errors of this {@code Observable} and all the {@code CompletableSource}s, who had the chance + * to run to their completion, are delayed until + * all of them terminate in some fashion. At this point, if there was only one failure, the respective + * {@code Throwable} is emitted to the dowstream. It there were more than one failures, the + * operator combines all {@code Throwable}s into a {@link io.reactivex.exceptions.CompositeException CompositeException} + * and signals that to the downstream. + * If any inactivated (switched out) {@code CompletableSource} + * signals an {@code onError} late, the {@code Throwable}s will be signalled to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. + *
                + *
                + * @param mapper the function called with each upstream item and should return a + * {@link CompletableSource} to be subscribed to and awaited for + * (non blockingly) for its terminal event + * @return the new Completable instance + * @since 2.1.11 - experimental + * @see #switchMapCompletableDelayError(Function) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Completable switchMapCompletableDelayError(@NonNull Function mapper) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new ObservableSwitchMapCompletable(this, mapper, true)); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones + * while disposing the older ones (and ignoring their signals) and emits the latest success value of the current one if + * available while failing immediately if this {@code Observable} or any of the + * active inner {@code MaybeSource}s fail. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code switchMapMaybe} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                This operator terminates with an {@code onError} if this {@code Observable} or any of + * the inner {@code MaybeSource}s fail while they are active. When this happens concurrently, their + * individual {@code Throwable} errors may get combined and emitted as a single + * {@link io.reactivex.exceptions.CompositeException CompositeException}. Otherwise, a late + * (i.e., inactive or switched out) {@code onError} from this {@code Observable} or from any of + * the inner {@code MaybeSource}s will be forwarded to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} as + * {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}
                + *
                + * @param the output value type + * @param mapper the function called with the current upstream event and should + * return a {@code MaybeSource} to replace the current active inner source + * and get subscribed to. + * @return the new Observable instance + * @since 2.1.11 - experimental + * @see #switchMapMaybe(Function) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable switchMapMaybe(@NonNull Function> mapper) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new ObservableSwitchMapMaybe(this, mapper, false)); + } + + /** + * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones + * while disposing the older ones (and ignoring their signals) and emits the latest success value of the current one if + * available, delaying errors from this {@code Observable} or the inner {@code MaybeSource}s until all terminate. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code switchMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the output value type + * @param mapper the function called with the current upstream event and should + * return a {@code MaybeSource} to replace the current active inner source + * and get subscribed to. + * @return the new Observable instance + * @since 2.1.11 - experimental + * @see #switchMapMaybe(Function) + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final Observable switchMapMaybeDelayError(@NonNull Function> mapper) { + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new ObservableSwitchMapMaybe(this, mapper, true)); + } + /** * Returns a new ObservableSource by applying a function that you supply to each item emitted by the source * ObservableSource that returns a SingleSource, and then emitting the item emitted by the most recently emitted @@ -11750,7 +12292,8 @@ public final Observable switchMap(Function Observable switchMapSingle(@NonNull Function> mapper) { - return ObservableInternalHelper.switchMapSingle(this, mapper); + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new ObservableSwitchMapSingle(this, mapper, false)); } /** @@ -11781,7 +12324,8 @@ public final Observable switchMapSingle(@NonNull Function Observable switchMapSingleDelayError(@NonNull Function> mapper) { - return ObservableInternalHelper.switchMapSingleDelayError(this, mapper); + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new ObservableSwitchMapSingle(this, mapper, true)); } /** diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java index 43223ec721..6d0548a733 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java @@ -255,10 +255,10 @@ void drain() { consumed = c; } - SingleSource ms; + SingleSource ss; try { - ms = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null SingleSource"); + ss = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null SingleSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); upstream.cancel(); @@ -270,7 +270,7 @@ void drain() { } state = STATE_ACTIVE; - ms.subscribe(inner); + ss.subscribe(inner); break; } else if (s == STATE_RESULT_VALUE) { long e = emitted; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java index 813f779902..3e15dfc7ed 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java @@ -115,10 +115,10 @@ public void onNext(T t) { current.dispose(); } - SingleSource ms; + SingleSource ss; try { - ms = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource"); + ss = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); upstream.cancel(); @@ -135,7 +135,7 @@ public void onNext(T t) { break; } if (inner.compareAndSet(current, observer)) { - ms.subscribe(observer); + ss.subscribe(observer); break; } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java new file mode 100644 index 0000000000..bc765d48b5 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java @@ -0,0 +1,277 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.*; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.queue.SpscLinkedArrayQueue; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps the upstream intems into {@link CompletableSource}s and subscribes to them one after the + * other completes or terminates (in error-delaying mode). + * @param the upstream value type + * @since 2.1.11 - experimental + */ +@Experimental +public final class ObservableConcatMapCompletable extends Completable { + + final Observable source; + + final Function mapper; + + final ErrorMode errorMode; + + final int prefetch; + + public ObservableConcatMapCompletable(Observable source, + Function mapper, + ErrorMode errorMode, + int prefetch) { + this.source = source; + this.mapper = mapper; + this.errorMode = errorMode; + this.prefetch = prefetch; + } + + @Override + protected void subscribeActual(CompletableObserver s) { + source.subscribe(new ConcatMapCompletableObserver(s, mapper, errorMode, prefetch)); + } + + static final class ConcatMapCompletableObserver + extends AtomicInteger + implements Observer, Disposable { + + private static final long serialVersionUID = 3610901111000061034L; + + final CompletableObserver downstream; + + final Function mapper; + + final ErrorMode errorMode; + + final AtomicThrowable errors; + + final ConcatMapInnerObserver inner; + + final int prefetch; + + final SimplePlainQueue queue; + + Disposable upstream; + + volatile boolean active; + + volatile boolean done; + + volatile boolean disposed; + + ConcatMapCompletableObserver(CompletableObserver downstream, + Function mapper, + ErrorMode errorMode, int prefetch) { + this.downstream = downstream; + this.mapper = mapper; + this.errorMode = errorMode; + this.prefetch = prefetch; + this.errors = new AtomicThrowable(); + this.inner = new ConcatMapInnerObserver(this); + this.queue = new SpscLinkedArrayQueue(prefetch); + } + + @Override + public void onSubscribe(Disposable s) { + if (DisposableHelper.validate(upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); + } + } + + @Override + public void onNext(T t) { + queue.offer(t); + drain(); + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (errorMode == ErrorMode.IMMEDIATE) { + disposed = true; + inner.dispose(); + t = errors.terminate(); + if (t != ExceptionHelper.TERMINATED) { + downstream.onError(t); + } + if (getAndIncrement() == 0) { + queue.clear(); + } + } else { + done = true; + drain(); + } + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @Override + public void dispose() { + disposed = true; + upstream.dispose(); + inner.dispose(); + if (getAndIncrement() == 0) { + queue.clear(); + } + } + + @Override + public boolean isDisposed() { + return disposed; + } + + void innerError(Throwable ex) { + if (errors.addThrowable(ex)) { + if (errorMode == ErrorMode.IMMEDIATE) { + disposed = true; + upstream.dispose(); + ex = errors.terminate(); + if (ex != ExceptionHelper.TERMINATED) { + downstream.onError(ex); + } + if (getAndIncrement() == 0) { + queue.clear(); + } + } else { + active = false; + drain(); + } + } else { + RxJavaPlugins.onError(ex); + } + } + + void innerComplete() { + active = false; + drain(); + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + do { + if (disposed) { + queue.clear(); + return; + } + + if (!active) { + + if (errorMode == ErrorMode.BOUNDARY) { + if (errors.get() != null) { + disposed = true; + queue.clear(); + Throwable ex = errors.terminate(); + downstream.onError(ex); + return; + } + } + + boolean d = done; + T v = queue.poll(); + boolean empty = v == null; + + if (d && empty) { + disposed = true; + Throwable ex = errors.terminate(); + if (ex != null) { + downstream.onError(ex); + } else { + downstream.onComplete(); + } + return; + } + + if (!empty) { + + CompletableSource cs; + + try { + cs = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null CompletableSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + disposed = true; + queue.clear(); + upstream.dispose(); + errors.addThrowable(ex); + ex = errors.terminate(); + downstream.onError(ex); + return; + } + active = true; + cs.subscribe(inner); + } + } + } while (decrementAndGet() != 0); + } + + static final class ConcatMapInnerObserver extends AtomicReference + implements CompletableObserver { + + private static final long serialVersionUID = 5638352172918776687L; + + final ConcatMapCompletableObserver parent; + + ConcatMapInnerObserver(ConcatMapCompletableObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(this, d); + } + + @Override + public void onError(Throwable e) { + parent.innerError(e); + } + + @Override + public void onComplete() { + parent.innerComplete(); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java new file mode 100644 index 0000000000..9d83c77e59 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java @@ -0,0 +1,306 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.queue.SpscLinkedArrayQueue; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps each upstream item into a {@link MaybeSource}, subscribes to them one after the other terminates + * and relays their success values, optionally delaying any errors till the main and inner sources + * terminate. + * + * @param the upstream element type + * @param the output element type + * + * @since 2.1.11 - experimental + */ +@Experimental +public final class ObservableConcatMapMaybe extends Observable { + + final Observable source; + + final Function> mapper; + + final ErrorMode errorMode; + + final int prefetch; + + public ObservableConcatMapMaybe(Observable source, + Function> mapper, + ErrorMode errorMode, int prefetch) { + this.source = source; + this.mapper = mapper; + this.errorMode = errorMode; + this.prefetch = prefetch; + } + + @Override + protected void subscribeActual(Observer s) { + source.subscribe(new ConcatMapMaybeMainObserver(s, mapper, prefetch, errorMode)); + } + + static final class ConcatMapMaybeMainObserver + extends AtomicInteger + implements Observer, Disposable { + + private static final long serialVersionUID = -9140123220065488293L; + + final Observer downstream; + + final Function> mapper; + + final AtomicThrowable errors; + + final ConcatMapMaybeObserver inner; + + final SimplePlainQueue queue; + + final ErrorMode errorMode; + + Disposable upstream; + + volatile boolean done; + + volatile boolean cancelled; + + R item; + + volatile int state; + + /** No inner MaybeSource is running. */ + static final int STATE_INACTIVE = 0; + /** An inner MaybeSource is running but there are no results yet. */ + static final int STATE_ACTIVE = 1; + /** The inner MaybeSource succeeded with a value in {@link #item}. */ + static final int STATE_RESULT_VALUE = 2; + + ConcatMapMaybeMainObserver(Observer downstream, + Function> mapper, + int prefetch, ErrorMode errorMode) { + this.downstream = downstream; + this.mapper = mapper; + this.errorMode = errorMode; + this.errors = new AtomicThrowable(); + this.inner = new ConcatMapMaybeObserver(this); + this.queue = new SpscLinkedArrayQueue(prefetch); + } + + @Override + public void onSubscribe(Disposable s) { + if (DisposableHelper.validate(upstream, s)) { + upstream = s; + downstream.onSubscribe(this); + } + } + + @Override + public void onNext(T t) { + queue.offer(t); + drain(); + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (errorMode == ErrorMode.IMMEDIATE) { + inner.dispose(); + } + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @Override + public void dispose() { + cancelled = true; + upstream.dispose(); + inner.dispose(); + if (getAndIncrement() != 0) { + queue.clear(); + item = null; + } + } + + @Override + public boolean isDisposed() { + return cancelled; + } + + void innerSuccess(R item) { + this.item = item; + this.state = STATE_RESULT_VALUE; + drain(); + } + + void innerComplete() { + this.state = STATE_INACTIVE; + drain(); + } + + void innerError(Throwable ex) { + if (errors.addThrowable(ex)) { + if (errorMode != ErrorMode.END) { + upstream.dispose(); + } + this.state = STATE_INACTIVE; + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + Observer downstream = this.downstream; + ErrorMode errorMode = this.errorMode; + SimplePlainQueue queue = this.queue; + AtomicThrowable errors = this.errors; + + for (;;) { + + for (;;) { + if (cancelled) { + queue.clear(); + item = null; + } + + int s = state; + + if (errors.get() != null) { + if (errorMode == ErrorMode.IMMEDIATE + || (errorMode == ErrorMode.BOUNDARY && s == STATE_INACTIVE)) { + queue.clear(); + item = null; + Throwable ex = errors.terminate(); + downstream.onError(ex); + return; + } + } + + if (s == STATE_INACTIVE) { + boolean d = done; + T v = queue.poll(); + boolean empty = v == null; + + if (d && empty) { + Throwable ex = errors.terminate(); + if (ex == null) { + downstream.onComplete(); + } else { + downstream.onError(ex); + } + return; + } + + if (empty) { + break; + } + + MaybeSource ms; + + try { + ms = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null MaybeSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.dispose(); + queue.clear(); + errors.addThrowable(ex); + ex = errors.terminate(); + downstream.onError(ex); + return; + } + + state = STATE_ACTIVE; + ms.subscribe(inner); + break; + } else if (s == STATE_RESULT_VALUE) { + R w = item; + item = null; + downstream.onNext(w); + + state = STATE_INACTIVE; + } else { + break; + } + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class ConcatMapMaybeObserver + extends AtomicReference + implements MaybeObserver { + + private static final long serialVersionUID = -3051469169682093892L; + + final ConcatMapMaybeMainObserver parent; + + ConcatMapMaybeObserver(ConcatMapMaybeMainObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(this, d); + } + + @Override + public void onSuccess(R t) { + parent.innerSuccess(t); + } + + @Override + public void onError(Throwable e) { + parent.innerError(e); + } + + @Override + public void onComplete() { + parent.innerComplete(); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java new file mode 100644 index 0000000000..d29204ccc7 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java @@ -0,0 +1,296 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.*; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps each upstream item into a {@link SingleSource}, subscribes to them one after the other terminates + * and relays their success values, optionally delaying any errors till the main and inner sources + * terminate. + * + * @param the upstream element type + * @param the output element type + * + * @since 2.1.11 - experimental + */ +@Experimental +public final class ObservableConcatMapSingle extends Observable { + + final Observable source; + + final Function> mapper; + + final ErrorMode errorMode; + + final int prefetch; + + public ObservableConcatMapSingle(Observable source, + Function> mapper, + ErrorMode errorMode, int prefetch) { + this.source = source; + this.mapper = mapper; + this.errorMode = errorMode; + this.prefetch = prefetch; + } + + @Override + protected void subscribeActual(Observer s) { + source.subscribe(new ConcatMapSingleMainObserver(s, mapper, prefetch, errorMode)); + } + + static final class ConcatMapSingleMainObserver + extends AtomicInteger + implements Observer, Disposable { + + private static final long serialVersionUID = -9140123220065488293L; + + final Observer downstream; + + final Function> mapper; + + final AtomicThrowable errors; + + final ConcatMapSingleObserver inner; + + final SimplePlainQueue queue; + + final ErrorMode errorMode; + + Disposable upstream; + + volatile boolean done; + + volatile boolean cancelled; + + R item; + + volatile int state; + + /** No inner SingleSource is running. */ + static final int STATE_INACTIVE = 0; + /** An inner SingleSource is running but there are no results yet. */ + static final int STATE_ACTIVE = 1; + /** The inner SingleSource succeeded with a value in {@link #item}. */ + static final int STATE_RESULT_VALUE = 2; + + ConcatMapSingleMainObserver(Observer downstream, + Function> mapper, + int prefetch, ErrorMode errorMode) { + this.downstream = downstream; + this.mapper = mapper; + this.errorMode = errorMode; + this.errors = new AtomicThrowable(); + this.inner = new ConcatMapSingleObserver(this); + this.queue = new SpscArrayQueue(prefetch); + } + + @Override + public void onSubscribe(Disposable s) { + if (DisposableHelper.validate(upstream, s)) { + upstream = s; + downstream.onSubscribe(this); + } + } + + @Override + public void onNext(T t) { + queue.offer(t); + drain(); + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (errorMode == ErrorMode.IMMEDIATE) { + inner.dispose(); + } + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @Override + public void dispose() { + cancelled = true; + upstream.dispose(); + inner.dispose(); + if (getAndIncrement() != 0) { + queue.clear(); + item = null; + } + } + + @Override + public boolean isDisposed() { + return cancelled; + } + + void innerSuccess(R item) { + this.item = item; + this.state = STATE_RESULT_VALUE; + drain(); + } + + void innerError(Throwable ex) { + if (errors.addThrowable(ex)) { + if (errorMode != ErrorMode.END) { + upstream.dispose(); + } + this.state = STATE_INACTIVE; + drain(); + } else { + RxJavaPlugins.onError(ex); + } + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + Observer downstream = this.downstream; + ErrorMode errorMode = this.errorMode; + SimplePlainQueue queue = this.queue; + AtomicThrowable errors = this.errors; + + for (;;) { + + for (;;) { + if (cancelled) { + queue.clear(); + item = null; + } + + int s = state; + + if (errors.get() != null) { + if (errorMode == ErrorMode.IMMEDIATE + || (errorMode == ErrorMode.BOUNDARY && s == STATE_INACTIVE)) { + queue.clear(); + item = null; + Throwable ex = errors.terminate(); + downstream.onError(ex); + return; + } + } + + if (s == STATE_INACTIVE) { + boolean d = done; + T v = queue.poll(); + boolean empty = v == null; + + if (d && empty) { + Throwable ex = errors.terminate(); + if (ex == null) { + downstream.onComplete(); + } else { + downstream.onError(ex); + } + return; + } + + if (empty) { + break; + } + + SingleSource ss; + + try { + ss = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null SingleSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.dispose(); + queue.clear(); + errors.addThrowable(ex); + ex = errors.terminate(); + downstream.onError(ex); + return; + } + + state = STATE_ACTIVE; + ss.subscribe(inner); + break; + } else if (s == STATE_RESULT_VALUE) { + R w = item; + item = null; + downstream.onNext(w); + + state = STATE_INACTIVE; + } else { + break; + } + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class ConcatMapSingleObserver + extends AtomicReference + implements SingleObserver { + + private static final long serialVersionUID = -3051469169682093892L; + + final ConcatMapSingleMainObserver parent; + + ConcatMapSingleObserver(ConcatMapSingleMainObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(this, d); + } + + @Override + public void onSuccess(R t) { + parent.innerSuccess(t); + } + + @Override + public void onError(Throwable e) { + parent.innerError(e); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java new file mode 100644 index 0000000000..650c9dfbd8 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java @@ -0,0 +1,235 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.AtomicReference; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while + * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one + * active {@code CompletableSource} running. + * + * @param the upstream value type + * @since 2.1.11 - experimental + */ +@Experimental +public final class ObservableSwitchMapCompletable extends Completable { + + final Observable source; + + final Function mapper; + + final boolean delayErrors; + + public ObservableSwitchMapCompletable(Observable source, + Function mapper, boolean delayErrors) { + this.source = source; + this.mapper = mapper; + this.delayErrors = delayErrors; + } + + @Override + protected void subscribeActual(CompletableObserver s) { + source.subscribe(new SwitchMapCompletableObserver(s, mapper, delayErrors)); + } + + static final class SwitchMapCompletableObserver implements Observer, Disposable { + + final CompletableObserver downstream; + + final Function mapper; + + final boolean delayErrors; + + final AtomicThrowable errors; + + final AtomicReference inner; + + static final SwitchMapInnerObserver INNER_DISPOSED = new SwitchMapInnerObserver(null); + + volatile boolean done; + + Disposable upstream; + + SwitchMapCompletableObserver(CompletableObserver downstream, + Function mapper, boolean delayErrors) { + this.downstream = downstream; + this.mapper = mapper; + this.delayErrors = delayErrors; + this.errors = new AtomicThrowable(); + this.inner = new AtomicReference(); + } + + @Override + public void onSubscribe(Disposable s) { + if (DisposableHelper.validate(upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); + } + } + + @Override + public void onNext(T t) { + CompletableSource c; + + try { + c = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null CompletableSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.dispose(); + onError(ex); + return; + } + + SwitchMapInnerObserver o = new SwitchMapInnerObserver(this); + + for (;;) { + SwitchMapInnerObserver current = inner.get(); + if (current == INNER_DISPOSED) { + break; + } + if (inner.compareAndSet(current, o)) { + if (current != null) { + current.dispose(); + } + c.subscribe(o); + break; + } + } + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (delayErrors) { + onComplete(); + } else { + disposeInner(); + Throwable ex = errors.terminate(); + if (ex != ExceptionHelper.TERMINATED) { + downstream.onError(ex); + } + } + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + if (inner.get() == null) { + Throwable ex = errors.terminate(); + if (ex == null) { + downstream.onComplete(); + } else { + downstream.onError(ex); + } + } + } + + void disposeInner() { + SwitchMapInnerObserver o = inner.getAndSet(INNER_DISPOSED); + if (o != null && o != INNER_DISPOSED) { + o.dispose(); + } + } + + @Override + public void dispose() { + upstream.dispose(); + disposeInner(); + } + + @Override + public boolean isDisposed() { + return inner.get() == INNER_DISPOSED; + } + + void innerError(SwitchMapInnerObserver sender, Throwable error) { + if (inner.compareAndSet(sender, null)) { + if (errors.addThrowable(error)) { + if (delayErrors) { + if (done) { + Throwable ex = errors.terminate(); + downstream.onError(ex); + } + } else { + dispose(); + Throwable ex = errors.terminate(); + if (ex != ExceptionHelper.TERMINATED) { + downstream.onError(ex); + } + } + return; + } + } + RxJavaPlugins.onError(error); + } + + void innerComplete(SwitchMapInnerObserver sender) { + if (inner.compareAndSet(sender, null)) { + if (done) { + Throwable ex = errors.terminate(); + if (ex == null) { + downstream.onComplete(); + } else { + downstream.onError(ex); + } + } + } + } + + static final class SwitchMapInnerObserver extends AtomicReference + implements CompletableObserver { + + private static final long serialVersionUID = -8003404460084760287L; + + final SwitchMapCompletableObserver parent; + + SwitchMapInnerObserver(SwitchMapCompletableObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onError(Throwable e) { + parent.innerError(this, e); + } + + @Override + public void onComplete() { + parent.innerComplete(this); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java new file mode 100644 index 0000000000..ef7f863603 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java @@ -0,0 +1,288 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.util.AtomicThrowable; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones + * while disposing the older ones and emits the latest success value if available, optionally delaying + * errors from the main source or the inner sources. + * + * @param the upstream value type + * @param the downstream value type + * @since 2.1.11 - experimental + */ +@Experimental +public final class ObservableSwitchMapMaybe extends Observable { + + final Observable source; + + final Function> mapper; + + final boolean delayErrors; + + public ObservableSwitchMapMaybe(Observable source, + Function> mapper, + boolean delayErrors) { + this.source = source; + this.mapper = mapper; + this.delayErrors = delayErrors; + } + + @Override + protected void subscribeActual(Observer s) { + source.subscribe(new SwitchMapMaybeMainObserver(s, mapper, delayErrors)); + } + + static final class SwitchMapMaybeMainObserver extends AtomicInteger + implements Observer, Disposable { + + private static final long serialVersionUID = -5402190102429853762L; + + final Observer downstream; + + final Function> mapper; + + final boolean delayErrors; + + final AtomicThrowable errors; + + final AtomicReference> inner; + + static final SwitchMapMaybeObserver INNER_DISPOSED = + new SwitchMapMaybeObserver(null); + + Disposable upstream; + + volatile boolean done; + + volatile boolean cancelled; + + SwitchMapMaybeMainObserver(Observer downstream, + Function> mapper, + boolean delayErrors) { + this.downstream = downstream; + this.mapper = mapper; + this.delayErrors = delayErrors; + this.errors = new AtomicThrowable(); + this.inner = new AtomicReference>(); + } + + @Override + public void onSubscribe(Disposable s) { + if (DisposableHelper.validate(upstream, s)) { + upstream = s; + downstream.onSubscribe(this); + } + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void onNext(T t) { + SwitchMapMaybeObserver current = inner.get(); + if (current != null) { + current.dispose(); + } + + MaybeSource ms; + + try { + ms = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null MaybeSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.dispose(); + inner.getAndSet((SwitchMapMaybeObserver)INNER_DISPOSED); + onError(ex); + return; + } + + SwitchMapMaybeObserver observer = new SwitchMapMaybeObserver(this); + + for (;;) { + current = inner.get(); + if (current == INNER_DISPOSED) { + break; + } + if (inner.compareAndSet(current, observer)) { + ms.subscribe(observer); + break; + } + } + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (!delayErrors) { + disposeInner(); + } + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + void disposeInner() { + SwitchMapMaybeObserver current = inner.getAndSet((SwitchMapMaybeObserver)INNER_DISPOSED); + if (current != null && current != INNER_DISPOSED) { + current.dispose(); + } + } + + @Override + public void dispose() { + cancelled = true; + upstream.dispose(); + disposeInner(); + } + + @Override + public boolean isDisposed() { + return cancelled; + } + + void innerError(SwitchMapMaybeObserver sender, Throwable ex) { + if (inner.compareAndSet(sender, null)) { + if (errors.addThrowable(ex)) { + if (!delayErrors) { + upstream.dispose(); + disposeInner(); + } + drain(); + return; + } + } + RxJavaPlugins.onError(ex); + } + + void innerComplete(SwitchMapMaybeObserver sender) { + if (inner.compareAndSet(sender, null)) { + drain(); + } + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + Observer downstream = this.downstream; + AtomicThrowable errors = this.errors; + AtomicReference> inner = this.inner; + + for (;;) { + + for (;;) { + if (cancelled) { + return; + } + + if (errors.get() != null) { + if (!delayErrors) { + Throwable ex = errors.terminate(); + downstream.onError(ex); + return; + } + } + + boolean d = done; + SwitchMapMaybeObserver current = inner.get(); + boolean empty = current == null; + + if (d && empty) { + Throwable ex = errors.terminate(); + if (ex != null) { + downstream.onError(ex); + } else { + downstream.onComplete(); + } + return; + } + + if (empty || current.item == null) { + break; + } + + inner.compareAndSet(current, null); + + downstream.onNext(current.item); + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class SwitchMapMaybeObserver + extends AtomicReference implements MaybeObserver { + + private static final long serialVersionUID = 8042919737683345351L; + + final SwitchMapMaybeMainObserver parent; + + volatile R item; + + SwitchMapMaybeObserver(SwitchMapMaybeMainObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onSuccess(R t) { + item = t; + parent.drain(); + } + + @Override + public void onError(Throwable e) { + parent.innerError(this, e); + } + + @Override + public void onComplete() { + parent.innerComplete(this); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java new file mode 100644 index 0000000000..c70bad0bcc --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java @@ -0,0 +1,277 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.util.AtomicThrowable; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Maps the upstream items into {@link SingleSource}s and switches (subscribes) to the newer ones + * while disposing the older ones and emits the latest success value if available, optionally delaying + * errors from the main source or the inner sources. + * + * @param the upstream value type + * @param the downstream value type + * @since 2.1.11 - experimental + */ +@Experimental +public final class ObservableSwitchMapSingle extends Observable { + + final Observable source; + + final Function> mapper; + + final boolean delayErrors; + + public ObservableSwitchMapSingle(Observable source, + Function> mapper, + boolean delayErrors) { + this.source = source; + this.mapper = mapper; + this.delayErrors = delayErrors; + } + + @Override + protected void subscribeActual(Observer s) { + source.subscribe(new SwitchMapSingleMainObserver(s, mapper, delayErrors)); + } + + static final class SwitchMapSingleMainObserver extends AtomicInteger + implements Observer, Disposable { + + private static final long serialVersionUID = -5402190102429853762L; + + final Observer downstream; + + final Function> mapper; + + final boolean delayErrors; + + final AtomicThrowable errors; + + final AtomicReference> inner; + + static final SwitchMapSingleObserver INNER_DISPOSED = + new SwitchMapSingleObserver(null); + + Disposable upstream; + + volatile boolean done; + + volatile boolean cancelled; + + SwitchMapSingleMainObserver(Observer downstream, + Function> mapper, + boolean delayErrors) { + this.downstream = downstream; + this.mapper = mapper; + this.delayErrors = delayErrors; + this.errors = new AtomicThrowable(); + this.inner = new AtomicReference>(); + } + + @Override + public void onSubscribe(Disposable s) { + if (DisposableHelper.validate(upstream, s)) { + upstream = s; + downstream.onSubscribe(this); + } + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void onNext(T t) { + SwitchMapSingleObserver current = inner.get(); + if (current != null) { + current.dispose(); + } + + SingleSource ss; + + try { + ss = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.dispose(); + inner.getAndSet((SwitchMapSingleObserver)INNER_DISPOSED); + onError(ex); + return; + } + + SwitchMapSingleObserver observer = new SwitchMapSingleObserver(this); + + for (;;) { + current = inner.get(); + if (current == INNER_DISPOSED) { + break; + } + if (inner.compareAndSet(current, observer)) { + ss.subscribe(observer); + break; + } + } + } + + @Override + public void onError(Throwable t) { + if (errors.addThrowable(t)) { + if (!delayErrors) { + disposeInner(); + } + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + void disposeInner() { + SwitchMapSingleObserver current = inner.getAndSet((SwitchMapSingleObserver)INNER_DISPOSED); + if (current != null && current != INNER_DISPOSED) { + current.dispose(); + } + } + + @Override + public void dispose() { + cancelled = true; + upstream.dispose(); + disposeInner(); + } + + @Override + public boolean isDisposed() { + return cancelled; + } + + void innerError(SwitchMapSingleObserver sender, Throwable ex) { + if (inner.compareAndSet(sender, null)) { + if (errors.addThrowable(ex)) { + if (!delayErrors) { + upstream.dispose(); + disposeInner(); + } + drain(); + return; + } + } + RxJavaPlugins.onError(ex); + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + Observer downstream = this.downstream; + AtomicThrowable errors = this.errors; + AtomicReference> inner = this.inner; + + for (;;) { + + for (;;) { + if (cancelled) { + return; + } + + if (errors.get() != null) { + if (!delayErrors) { + Throwable ex = errors.terminate(); + downstream.onError(ex); + return; + } + } + + boolean d = done; + SwitchMapSingleObserver current = inner.get(); + boolean empty = current == null; + + if (d && empty) { + Throwable ex = errors.terminate(); + if (ex != null) { + downstream.onError(ex); + } else { + downstream.onComplete(); + } + return; + } + + if (empty || current.item == null) { + break; + } + + inner.compareAndSet(current, null); + + downstream.onNext(current.item); + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class SwitchMapSingleObserver + extends AtomicReference implements SingleObserver { + + private static final long serialVersionUID = 8042919737683345351L; + + final SwitchMapSingleMainObserver parent; + + volatile R item; + + SwitchMapSingleObserver(SwitchMapSingleMainObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onSuccess(R t) { + item = t; + parent.drain(); + } + + @Override + public void onError(Throwable e) { + parent.innerError(this, e); + } + + void dispose() { + DisposableHelper.dispose(this); + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java deleted file mode 100644 index b53de7cde7..0000000000 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java +++ /dev/null @@ -1,244 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ -package io.reactivex.internal.operators.observable; - -import java.util.concurrent.atomic.*; - -import io.reactivex.*; -import io.reactivex.disposables.Disposable; -import io.reactivex.exceptions.Exceptions; -import io.reactivex.functions.Function; -import io.reactivex.internal.disposables.DisposableHelper; -import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.fuseable.*; -import io.reactivex.internal.queue.SpscLinkedArrayQueue; -import io.reactivex.plugins.RxJavaPlugins; - -public final class ObservableConcatMapCompletable extends Completable { - - final ObservableSource source; - final Function mapper; - final int bufferSize; - - public ObservableConcatMapCompletable(ObservableSource source, - Function mapper, int bufferSize) { - this.source = source; - this.mapper = mapper; - this.bufferSize = Math.max(8, bufferSize); - } - @Override - public void subscribeActual(CompletableObserver observer) { - source.subscribe(new SourceObserver(observer, mapper, bufferSize)); - } - - static final class SourceObserver extends AtomicInteger implements Observer, Disposable { - - private static final long serialVersionUID = 6893587405571511048L; - final CompletableObserver actual; - final Function mapper; - final InnerObserver inner; - final int bufferSize; - - SimpleQueue queue; - - Disposable s; - - volatile boolean active; - - volatile boolean disposed; - - volatile boolean done; - - int sourceMode; - - SourceObserver(CompletableObserver actual, - Function mapper, int bufferSize) { - this.actual = actual; - this.mapper = mapper; - this.bufferSize = bufferSize; - this.inner = new InnerObserver(actual, this); - } - @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - if (s instanceof QueueDisposable) { - @SuppressWarnings("unchecked") - QueueDisposable qd = (QueueDisposable) s; - - int m = qd.requestFusion(QueueDisposable.ANY); - if (m == QueueDisposable.SYNC) { - sourceMode = m; - queue = qd; - done = true; - - actual.onSubscribe(this); - - drain(); - return; - } - - if (m == QueueDisposable.ASYNC) { - sourceMode = m; - queue = qd; - - actual.onSubscribe(this); - - return; - } - } - - queue = new SpscLinkedArrayQueue(bufferSize); - - actual.onSubscribe(this); - } - } - @Override - public void onNext(T t) { - if (done) { - return; - } - if (sourceMode == QueueDisposable.NONE) { - queue.offer(t); - } - drain(); - } - @Override - public void onError(Throwable t) { - if (done) { - RxJavaPlugins.onError(t); - return; - } - done = true; - dispose(); - actual.onError(t); - } - @Override - public void onComplete() { - if (done) { - return; - } - done = true; - drain(); - } - - void innerComplete() { - active = false; - drain(); - } - - @Override - public boolean isDisposed() { - return disposed; - } - - @Override - public void dispose() { - disposed = true; - inner.dispose(); - s.dispose(); - - if (getAndIncrement() == 0) { - queue.clear(); - } - } - - void drain() { - if (getAndIncrement() != 0) { - return; - } - - for (;;) { - if (disposed) { - queue.clear(); - return; - } - if (!active) { - - boolean d = done; - - T t; - - try { - t = queue.poll(); - } catch (Throwable ex) { - Exceptions.throwIfFatal(ex); - dispose(); - queue.clear(); - actual.onError(ex); - return; - } - - boolean empty = t == null; - - if (d && empty) { - disposed = true; - actual.onComplete(); - return; - } - - if (!empty) { - CompletableSource c; - - try { - c = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null CompletableSource"); - } catch (Throwable ex) { - Exceptions.throwIfFatal(ex); - dispose(); - queue.clear(); - actual.onError(ex); - return; - } - - active = true; - c.subscribe(inner); - } - } - - if (decrementAndGet() == 0) { - break; - } - } - } - - static final class InnerObserver extends AtomicReference implements CompletableObserver { - private static final long serialVersionUID = -5987419458390772447L; - final CompletableObserver actual; - final SourceObserver parent; - - InnerObserver(CompletableObserver actual, SourceObserver parent) { - this.actual = actual; - this.parent = parent; - } - - @Override - public void onSubscribe(Disposable s) { - DisposableHelper.set(this, s); - } - - @Override - public void onError(Throwable t) { - parent.dispose(); - actual.onError(t); - } - @Override - public void onComplete() { - parent.innerComplete(); - } - - void dispose() { - DisposableHelper.dispose(this); - } - } - } -} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java index b5fe5f48b5..7bc6305703 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java @@ -17,11 +17,8 @@ import io.reactivex.*; import io.reactivex.functions.*; -import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.operators.single.SingleToObservable; +import io.reactivex.internal.functions.*; import io.reactivex.observables.ConnectableObservable; -import io.reactivex.plugins.RxJavaPlugins; /** * Helper utility class to support Observable with inner classes. @@ -294,37 +291,6 @@ public static Function>, ObservableSou return new ZipIterableFunction(zipper); } - public static Observable switchMapSingle(Observable source, final Function> mapper) { - return source.switchMap(convertSingleMapperToObservableMapper(mapper), 1); - } - - public static Observable switchMapSingleDelayError(Observable source, - Function> mapper) { - return source.switchMapDelayError(convertSingleMapperToObservableMapper(mapper), 1); - } - - private static Function> convertSingleMapperToObservableMapper( - final Function> mapper) { - ObjectHelper.requireNonNull(mapper, "mapper is null"); - return new ObservableMapper(mapper); - } - - static final class ObservableMapper implements Function> { - - final Function> mapper; - - ObservableMapper(Function> mapper) { - this.mapper = mapper; - } - - @Override - public Observable apply(T t) throws Exception { - return RxJavaPlugins.onAssembly(new SingleToObservable( - ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource"))); - } - - } - static final class ReplayCallable implements Callable> { private final Observable parent; diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletableTest.java new file mode 100644 index 0000000000..50c79bb01f --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletableTest.java @@ -0,0 +1,362 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subjects.*; + +public class ObservableConcatMapCompletableTest { + + @Test + public void simple() { + Observable.range(1, 5) + .concatMapCompletable(Functions.justFunction(Completable.complete())) + .test() + .assertResult(); + } + + @Test + public void simple2() { + final AtomicInteger counter = new AtomicInteger(); + Observable.range(1, 5) + .concatMapCompletable(Functions.justFunction(Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + counter.incrementAndGet(); + } + }))) + .test() + .assertResult(); + + assertEquals(5, counter.get()); + } + + @Test + public void simpleLongPrefetch() { + Observable.range(1, 1024) + .concatMapCompletable(Functions.justFunction(Completable.complete()), 32) + .test() + .assertResult(); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .concatMapCompletable(Functions.justFunction(Completable.complete())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Observable.just(1) + .concatMapCompletable(Functions.justFunction(Completable.error(new TestException()))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerErrorDelayed() { + Observable.range(1, 5) + .concatMapCompletableDelayError( + new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return Completable.error(new TestException()); + } + } + ) + .test() + .assertFailure(CompositeException.class) + .assertOf(new Consumer>() { + @Override + public void accept(TestObserver to) throws Exception { + assertEquals(5, ((CompositeException)to.errors().get(0)).getExceptions().size()); + } + }); + } + + @Test + public void mapperCrash() { + Observable.just(1) + .concatMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void immediateError() { + PublishSubject ps = PublishSubject.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.concatMapCompletable( + Functions.justFunction(cs)).test(); + + to.assertEmpty(); + + assertTrue(ps.hasObservers()); + assertFalse(cs.hasObservers()); + + ps.onNext(1); + + assertTrue(cs.hasObservers()); + + ps.onError(new TestException()); + + assertFalse(cs.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void immediateError2() { + PublishSubject ps = PublishSubject.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.concatMapCompletable( + Functions.justFunction(cs)).test(); + + to.assertEmpty(); + + assertTrue(ps.hasObservers()); + assertFalse(cs.hasObservers()); + + ps.onNext(1); + + assertTrue(cs.hasObservers()); + + cs.onError(new TestException()); + + assertFalse(ps.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void boundaryError() { + PublishSubject ps = PublishSubject.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.concatMapCompletableDelayError( + Functions.justFunction(cs), false).test(); + + to.assertEmpty(); + + assertTrue(ps.hasObservers()); + assertFalse(cs.hasObservers()); + + ps.onNext(1); + + assertTrue(cs.hasObservers()); + + ps.onError(new TestException()); + + assertTrue(cs.hasObservers()); + + to.assertEmpty(); + + cs.onComplete(); + + to.assertFailure(TestException.class); + } + + @Test + public void endError() { + PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + final CompletableSubject cs2 = CompletableSubject.create(); + + TestObserver to = ps.concatMapCompletableDelayError( + new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + if (v == 1) { + return cs; + } + return cs2; + } + }, true, 32 + ) + .test(); + + to.assertEmpty(); + + assertTrue(ps.hasObservers()); + assertFalse(cs.hasObservers()); + + ps.onNext(1); + + assertTrue(cs.hasObservers()); + + cs.onError(new TestException()); + + assertTrue(ps.hasObservers()); + + ps.onNext(2); + + to.assertEmpty(); + + cs2.onComplete(); + + assertTrue(ps.hasObservers()); + + to.assertEmpty(); + + ps.onComplete(); + + to.assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservableToCompletable( + new Function, Completable>() { + @Override + public Completable apply(Observable f) + throws Exception { + return f.concatMapCompletable( + Functions.justFunction(Completable.complete())); + } + } + ); + } + + @Test + public void disposed() { + TestHelper.checkDisposed( + Observable.never() + .concatMapCompletable( + Functions.justFunction(Completable.complete())) + ); + } + + @Test + public void immediateOuterInnerErrorRace() { + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.concatMapCompletable( + Functions.justFunction(cs) + ) + .test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onError(ex); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + to.assertError(new Predicate() { + @Override + public boolean test(Throwable e) throws Exception { + return e instanceof TestException || e instanceof CompositeException; + } + }) + .assertNotComplete(); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void disposeInDrainLoop() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + final TestObserver to = ps.concatMapCompletable( + Functions.justFunction(cs) + ) + .test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onComplete(); + to.cancel(); + } + }; + + TestHelper.race(r1, r2); + + to.assertEmpty(); + } + } + + @Test + public void doneButNotEmpty() { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + final TestObserver to = ps.concatMapCompletable( + Functions.justFunction(cs) + ) + .test(); + + ps.onNext(1); + ps.onNext(2); + ps.onComplete(); + + cs.onComplete(); + + to.assertResult(); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java new file mode 100644 index 0000000000..154508bcf7 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java @@ -0,0 +1,349 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.subjects.*; + +public class ObservableConcatMapMaybeTest { + + @Test + public void simple() { + Observable.range(1, 5) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void simpleLong() { + Observable.range(1, 1024) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }, 32) + .test() + .assertValueCount(1024) + .assertNoErrors() + .assertComplete(); + } + + @Test + public void empty() { + Observable.range(1, 10) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.empty(); + } + }) + .test() + .assertResult(); + } + + @Test + public void mixed() { + Observable.range(1, 10) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v % 2 == 0) { + return Maybe.just(v); + } + return Maybe.empty(); + } + }) + .test() + .assertResult(2, 4, 6, 8, 10); + } + + @Test + public void mixedLong() { + Observable.range(1, 1024) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v % 2 == 0) { + return Maybe.just(v).subscribeOn(Schedulers.computation()); + } + return Maybe.empty().subscribeOn(Schedulers.computation()); + } + }) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertValueCount(512) + .assertNoErrors() + .assertComplete() + .assertOf(new Consumer>() { + @Override + public void accept(TestObserver ts) throws Exception { + for (int i = 0; i < 512; i ++) { + ts.assertValueAt(i, (i + 1) * 2); + } + } + }); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .concatMapMaybe(Functions.justFunction(Maybe.just(1))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Observable.just(1) + .concatMapMaybe(Functions.justFunction(Maybe.error(new TestException()))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void mainBoundaryErrorInnerSuccess() { + PublishSubject ps = PublishSubject.create(); + MaybeSubject ms = MaybeSubject.create(); + + TestObserver ts = ps.concatMapMaybeDelayError(Functions.justFunction(ms), false).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + assertTrue(ms.hasObservers()); + + ps.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertFailure(TestException.class, 1); + } + + @Test + public void mainBoundaryErrorInnerEmpty() { + PublishSubject ps = PublishSubject.create(); + MaybeSubject ms = MaybeSubject.create(); + + TestObserver ts = ps.concatMapMaybeDelayError(Functions.justFunction(ms), false).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + assertTrue(ms.hasObservers()); + + ps.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onComplete(); + + ts.assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable( + new Function, Observable>() { + @Override + public Observable apply(Observable f) + throws Exception { + return f.concatMapMaybeDelayError( + Functions.justFunction(Maybe.empty())); + } + } + ); + } + + @Test + public void take() { + Observable.range(1, 5) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }) + .take(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void cancel() { + Observable.range(1, 5).concatWith(Observable.never()) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }) + .test() + .assertValues(1, 2, 3, 4, 5) + .assertNoErrors() + .assertNotComplete() + .cancel(); + } + + @Test + public void mainErrorAfterInnerError() { + List errors = TestHelper.trackPluginErrors(); + try { + new Observable() { + @Override + protected void subscribeActual(Observer s) { + s.onSubscribe(Disposables.empty()); + s.onNext(1); + s.onError(new TestException("outer")); + } + } + .concatMapMaybe( + Functions.justFunction(Maybe.error(new TestException("inner"))), 1 + ) + .test() + .assertFailureAndMessage(TestException.class, "inner"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void innerErrorAfterMainError() { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final AtomicReference> obs = new AtomicReference>(); + + TestObserver ts = ps.concatMapMaybe( + new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return new Maybe() { + @Override + protected void subscribeActual( + MaybeObserver observer) { + observer.onSubscribe(Disposables.empty()); + obs.set(observer); + } + }; + } + } + ).test(); + + ps.onNext(1); + + ps.onError(new TestException("outer")); + obs.get().onError(new TestException("inner")); + + ts.assertFailureAndMessage(TestException.class, "outer"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void delayAllErrors() { + Observable.range(1, 5) + .concatMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.error(new TestException()); + } + }) + .test() + .assertFailure(CompositeException.class) + .assertOf(new Consumer>() { + @Override + public void accept(TestObserver ts) throws Exception { + CompositeException ce = (CompositeException)ts.errors().get(0); + assertEquals(5, ce.getExceptions().size()); + } + }); + } + + @Test + public void mapperCrash() { + final PublishSubject ps = PublishSubject.create(); + + TestObserver ts = ps + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test(); + + ts.assertEmpty(); + + assertTrue(ps.hasObservers()); + + ps.onNext(1); + + ts.assertFailure(TestException.class); + + assertFalse(ps.hasObservers()); + } + + @Test + public void disposed() { + TestHelper.checkDisposed(Observable.just(1) + .concatMapMaybe(Functions.justFunction(Maybe.never())) + ); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java new file mode 100644 index 0000000000..48a35df533 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java @@ -0,0 +1,286 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subjects.*; + +public class ObservableConcatMapSingleTest { + + @Test + public void simple() { + Observable.range(1, 5) + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void simpleLong() { + Observable.range(1, 1024) + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }, 32) + .test() + .assertValueCount(1024) + .assertNoErrors() + .assertComplete(); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .concatMapSingle(Functions.justFunction(Single.just(1))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Observable.just(1) + .concatMapSingle(Functions.justFunction(Single.error(new TestException()))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void mainBoundaryErrorInnerSuccess() { + PublishSubject ps = PublishSubject.create(); + SingleSubject ms = SingleSubject.create(); + + TestObserver ts = ps.concatMapSingleDelayError(Functions.justFunction(ms), false).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + assertTrue(ms.hasObservers()); + + ps.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertFailure(TestException.class, 1); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable( + new Function, Observable>() { + @Override + public Observable apply(Observable f) + throws Exception { + return f.concatMapSingleDelayError( + Functions.justFunction(Single.never())); + } + } + ); + } + + @Test + public void take() { + Observable.range(1, 5) + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }) + .take(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void cancel() { + Observable.range(1, 5).concatWith(Observable.never()) + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }) + .test() + .assertValues(1, 2, 3, 4, 5) + .assertNoErrors() + .assertNotComplete() + .cancel(); + } + + @Test + public void mainErrorAfterInnerError() { + List errors = TestHelper.trackPluginErrors(); + try { + new Observable() { + @Override + protected void subscribeActual(Observer s) { + s.onSubscribe(Disposables.empty()); + s.onNext(1); + s.onError(new TestException("outer")); + } + } + .concatMapSingle( + Functions.justFunction(Single.error(new TestException("inner"))), 1 + ) + .test() + .assertFailureAndMessage(TestException.class, "inner"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void innerErrorAfterMainError() { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final AtomicReference> obs = new AtomicReference>(); + + TestObserver ts = ps.concatMapSingle( + new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return new Single() { + @Override + protected void subscribeActual( + SingleObserver observer) { + observer.onSubscribe(Disposables.empty()); + obs.set(observer); + } + }; + } + } + ).test(); + + ps.onNext(1); + + ps.onError(new TestException("outer")); + obs.get().onError(new TestException("inner")); + + ts.assertFailureAndMessage(TestException.class, "outer"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void delayAllErrors() { + Observable.range(1, 5) + .concatMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.error(new TestException()); + } + }) + .test() + .assertFailure(CompositeException.class) + .assertOf(new Consumer>() { + @Override + public void accept(TestObserver ts) throws Exception { + CompositeException ce = (CompositeException)ts.errors().get(0); + assertEquals(5, ce.getExceptions().size()); + } + }); + } + + @Test + public void mapperCrash() { + final PublishSubject ps = PublishSubject.create(); + + TestObserver ts = ps + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test(); + + ts.assertEmpty(); + + assertTrue(ps.hasObservers()); + + ps.onNext(1); + + ts.assertFailure(TestException.class); + + assertFalse(ps.hasObservers()); + } + + @Test + public void disposed() { + TestHelper.checkDisposed(Observable.just(1) + .concatMapSingle(Functions.justFunction(Single.never())) + ); + } + + @Test + public void mainCompletesWhileInnerActive() { + PublishSubject ps = PublishSubject.create(); + SingleSubject ms = SingleSubject.create(); + + TestObserver ts = ps.concatMapSingleDelayError(Functions.justFunction(ms), false).test(); + + ts.assertEmpty(); + + ps.onNext(1); + ps.onNext(2); + ps.onComplete(); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertResult(1, 1); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java new file mode 100644 index 0000000000..17edbf46e5 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java @@ -0,0 +1,387 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subjects.*; + +public class ObservableSwitchMapCompletableTest { + + @Test + public void normal() { + Observable.range(1, 10) + .switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return Completable.complete(); + } + }) + .test() + .assertResult(); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return Completable.complete(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + PublishSubject ps = PublishSubject.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.switchMapCompletable(Functions.justFunction(cs)) + .test(); + + assertTrue(ps.hasObservers()); + assertFalse(cs.hasObservers()); + + ps.onNext(1); + + assertTrue(cs.hasObservers()); + + to.assertEmpty(); + + cs.onError(new TestException()); + + to.assertFailure(TestException.class); + + assertFalse(ps.hasObservers()); + assertFalse(cs.hasObservers()); + } + + @Test + public void switchOver() { + final CompletableSubject[] css = { + CompletableSubject.create(), + CompletableSubject.create() + }; + + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ps.switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + return css[v]; + } + }) + .test(); + + to.assertEmpty(); + + ps.onNext(0); + + assertTrue(css[0].hasObservers()); + + ps.onNext(1); + + assertFalse(css[0].hasObservers()); + assertTrue(css[1].hasObservers()); + + ps.onComplete(); + + to.assertEmpty(); + + assertTrue(css[1].hasObservers()); + + css[1].onComplete(); + + to.assertResult(); + } + + @Test + public void dispose() { + PublishSubject ps = PublishSubject.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.switchMapCompletable(Functions.justFunction(cs)) + .test(); + + ps.onNext(1); + + assertTrue(ps.hasObservers()); + assertTrue(cs.hasObservers()); + + to.dispose(); + + assertFalse(ps.hasObservers()); + assertFalse(cs.hasObservers()); + } + + @Test + public void checkDisposed() { + PublishSubject ps = PublishSubject.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestHelper.checkDisposed(ps.switchMapCompletable(Functions.justFunction(cs))); + } + + @Test + public void checkBadSource() { + TestHelper.checkDoubleOnSubscribeObservableToCompletable(new Function, Completable>() { + @Override + public Completable apply(Observable f) throws Exception { + return f.switchMapCompletable(Functions.justFunction(Completable.never())); + } + }); + } + + @Test + public void mapperCrash() { + Observable.range(1, 5).switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer f) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void mapperCancels() { + final TestObserver to = new TestObserver(); + + Observable.range(1, 5).switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer f) throws Exception { + to.cancel(); + return Completable.complete(); + } + }) + .subscribe(to); + + to.assertEmpty(); + } + + @Test + public void onNextInnerCompleteRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.switchMapCompletable(Functions.justFunction(cs)).test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onComplete(); + } + }; + + TestHelper.race(r1, r2); + + to.assertEmpty(); + } + } + + @Test + public void onNextInnerErrorRace() { + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.switchMapCompletable(Functions.justFunction(cs)).test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + to.assertError(new Predicate() { + @Override + public boolean test(Throwable e) throws Exception { + return e instanceof TestException || e instanceof CompositeException; + } + }); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void onErrorInnerErrorRace() { + final TestException ex0 = new TestException(); + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.switchMapCompletable(Functions.justFunction(cs)).test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onError(ex0); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cs.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + to.assertError(new Predicate() { + @Override + public boolean test(Throwable e) throws Exception { + return e instanceof TestException || e instanceof CompositeException; + } + }); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void innerErrorThenMainError() { + List errors = TestHelper.trackPluginErrors(); + try { + new Observable() { + @Override + protected void subscribeActual(Observer s) { + s.onSubscribe(Disposables.empty()); + s.onNext(1); + s.onError(new TestException("main")); + } + } + .switchMapCompletable(Functions.justFunction(Completable.error(new TestException("inner")))) + .test() + .assertFailureAndMessage(TestException.class, "inner"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "main"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void innerErrorDelayed() { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.switchMapCompletableDelayError(Functions.justFunction(cs)).test(); + + ps.onNext(1); + + cs.onError(new TestException()); + + to.assertEmpty(); + + assertTrue(ps.hasObservers()); + + ps.onComplete(); + + to.assertFailure(TestException.class); + } + + @Test + public void mainCompletesinnerErrorDelayed() { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.switchMapCompletableDelayError(Functions.justFunction(cs)).test(); + + ps.onNext(1); + ps.onComplete(); + + to.assertEmpty(); + + cs.onError(new TestException()); + + to.assertFailure(TestException.class); + } + + @Test + public void mainErrorDelayed() { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = ps.switchMapCompletableDelayError(Functions.justFunction(cs)).test(); + + ps.onNext(1); + + ps.onError(new TestException()); + + to.assertEmpty(); + + assertTrue(cs.hasObservers()); + + cs.onComplete(); + + to.assertFailure(TestException.class); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java new file mode 100644 index 0000000000..65f487a14e --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java @@ -0,0 +1,645 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subjects.*; + +public class ObservableSwitchMapMaybeTest { + + @Test + public void simple() { + Observable.range(1, 5) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void simpleEmpty() { + Observable.range(1, 5) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.empty(); + } + }) + .test() + .assertResult(); + } + + @Test + public void simpleMixed() { + Observable.range(1, 10) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v % 2 == 0) { + return Maybe.just(v); + } + return Maybe.empty(); + } + }) + .test() + .assertResult(2, 4, 6, 8, 10); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .switchMapMaybe(Functions.justFunction(Maybe.never())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Observable.just(1) + .switchMapMaybe(Functions.justFunction(Maybe.error(new TestException()))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>() { + @Override + public Observable apply(Observable f) + throws Exception { + return f + .switchMapMaybe(Functions.justFunction(Maybe.never())); + } + } + ); + } + + @Test + public void take() { + Observable.range(1, 5) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }) + .take(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void switchOver() { + PublishSubject ps = PublishSubject.create(); + + final MaybeSubject ms1 = MaybeSubject.create(); + final MaybeSubject ms2 = MaybeSubject.create(); + + TestObserver ts = ps.switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms1; + } + return ms2; + } + }).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms1.hasObservers()); + + ps.onNext(2); + + assertFalse(ms1.hasObservers()); + assertTrue(ms2.hasObservers()); + + ms2.onError(new TestException()); + + assertFalse(ps.hasObservers()); + + ts.assertFailure(TestException.class); + } + + @Test + public void switchOverDelayError() { + PublishSubject ps = PublishSubject.create(); + + final MaybeSubject ms1 = MaybeSubject.create(); + final MaybeSubject ms2 = MaybeSubject.create(); + + TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms1; + } + return ms2; + } + }).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms1.hasObservers()); + + ps.onNext(2); + + assertFalse(ms1.hasObservers()); + assertTrue(ms2.hasObservers()); + + ms2.onError(new TestException()); + + ts.assertEmpty(); + + assertTrue(ps.hasObservers()); + + ps.onComplete(); + + ts.assertFailure(TestException.class); + } + + @Test + public void mainErrorInnerCompleteDelayError() { + PublishSubject ps = PublishSubject.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms.hasObservers()); + + ps.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onComplete(); + + ts.assertFailure(TestException.class); + } + + @Test + public void mainErrorInnerSuccessDelayError() { + PublishSubject ps = PublishSubject.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms.hasObservers()); + + ps.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertFailure(TestException.class, 1); + } + + @Test + public void mapperCrash() { + Observable.just(1) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void disposeBeforeSwitchInOnNext() { + final TestObserver ts = new TestObserver(); + + Observable.just(1) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + ts.cancel(); + return Maybe.just(1); + } + }).subscribe(ts); + + ts.assertEmpty(); + } + + @Test + public void disposeOnNextAfterFirst() { + final TestObserver ts = new TestObserver(); + + Observable.just(1, 2) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 2) { + ts.cancel(); + } + return Maybe.just(1); + } + }).subscribe(ts); + + ts.assertValue(1) + .assertNoErrors() + .assertNotComplete(); + } + + @Test + public void cancel() { + PublishSubject ps = PublishSubject.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + ts.assertEmpty(); + + assertTrue(ps.hasObservers()); + assertTrue(ms.hasObservers()); + + ts.cancel(); + + assertFalse(ps.hasObservers()); + assertFalse(ms.hasObservers()); + } + + @Test + public void mainErrorAfterTermination() { + List errors = TestHelper.trackPluginErrors(); + try { + new Observable() { + @Override + protected void subscribeActual(Observer s) { + s.onSubscribe(Disposables.empty()); + s.onNext(1); + s.onError(new TestException("outer")); + } + } + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.error(new TestException("inner")); + } + }) + .test() + .assertFailureAndMessage(TestException.class, "inner"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer"); + } finally { + RxJavaPlugins.reset(); + } + } + + + @Test + public void innerErrorAfterTermination() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> moRef = new AtomicReference>(); + + TestObserver ts = new Observable() { + @Override + protected void subscribeActual(Observer s) { + s.onSubscribe(Disposables.empty()); + s.onNext(1); + s.onError(new TestException("outer")); + } + } + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return new Maybe() { + @Override + protected void subscribeActual( + MaybeObserver observer) { + observer.onSubscribe(Disposables.empty()); + moRef.set(observer); + } + }; + } + }) + .test(); + + ts.assertFailureAndMessage(TestException.class, "outer"); + + moRef.get().onError(new TestException("inner")); + moRef.get().onComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void nextCancelRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final PublishSubject ps = PublishSubject.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + final TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertNoErrors() + .assertNotComplete(); + } + } + + @Test + public void nextInnerErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + final TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Maybe.never(); + } + }).test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + if (ts.errorCount() != 0) { + assertTrue(errors.isEmpty()); + ts.assertFailure(TestException.class); + } else if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void mainErrorInnerErrorRace() { + final TestException ex = new TestException(); + final TestException ex2 = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + final TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Maybe.never(); + } + }).test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onError(ex); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onError(ex2); + } + }; + + TestHelper.race(r1, r2); + + ts.assertError(new Predicate() { + @Override + public boolean test(Throwable e) throws Exception { + return e instanceof TestException || e instanceof CompositeException; + } + }); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void nextInnerSuccessRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final PublishSubject ps = PublishSubject.create(); + + final MaybeSubject ms = MaybeSubject.create(); + + final TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Maybe.empty(); + } + }).test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onSuccess(3); + } + }; + + TestHelper.race(r1, r2); + + ts.assertNoErrors() + .assertNotComplete(); + } + } + + @Test + public void checkDisposed() { + PublishSubject ps = PublishSubject.create(); + MaybeSubject ms = MaybeSubject.create(); + + TestHelper.checkDisposed(ps.switchMapMaybe(Functions.justFunction(ms))); + } + + @Test + public void drainReentrant() { + final PublishSubject ps = PublishSubject.create(); + + TestObserver to = new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + ps.onNext(2); + } + } + }; + + ps.switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }).subscribe(to); + + ps.onNext(1); + ps.onComplete(); + + to.assertResult(1, 2); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java new file mode 100644 index 0000000000..cafbf15e4d --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java @@ -0,0 +1,613 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subjects.*; + +public class ObservableSwitchMapSingleTest { + + @Test + public void simple() { + Observable.range(1, 5) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .switchMapSingle(Functions.justFunction(Single.never())) + .test() + .assertFailure(TestException.class); + } + + @Test + public void innerError() { + Observable.just(1) + .switchMapSingle(Functions.justFunction(Single.error(new TestException()))) + .test() + .assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>() { + @Override + public Observable apply(Observable f) + throws Exception { + return f + .switchMapSingle(Functions.justFunction(Single.never())); + } + } + ); + } + + @Test + public void take() { + Observable.range(1, 5) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }) + .take(3) + .test() + .assertResult(1, 2, 3); + } + + @Test + public void switchOver() { + PublishSubject ps = PublishSubject.create(); + + final SingleSubject ms1 = SingleSubject.create(); + final SingleSubject ms2 = SingleSubject.create(); + + TestObserver ts = ps.switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms1; + } + return ms2; + } + }).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms1.hasObservers()); + + ps.onNext(2); + + assertFalse(ms1.hasObservers()); + assertTrue(ms2.hasObservers()); + + ms2.onError(new TestException()); + + assertFalse(ps.hasObservers()); + + ts.assertFailure(TestException.class); + } + + @Test + public void switchOverDelayError() { + PublishSubject ps = PublishSubject.create(); + + final SingleSubject ms1 = SingleSubject.create(); + final SingleSubject ms2 = SingleSubject.create(); + + TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms1; + } + return ms2; + } + }).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms1.hasObservers()); + + ps.onNext(2); + + assertFalse(ms1.hasObservers()); + assertTrue(ms2.hasObservers()); + + ms2.onError(new TestException()); + + ts.assertEmpty(); + + assertTrue(ps.hasObservers()); + + ps.onComplete(); + + ts.assertFailure(TestException.class); + } + + @Test + public void mainErrorInnerCompleteDelayError() { + PublishSubject ps = PublishSubject.create(); + + final SingleSubject ms = SingleSubject.create(); + + TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms.hasObservers()); + + ps.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertFailure(TestException.class, 1); + } + + @Test + public void mainErrorInnerSuccessDelayError() { + PublishSubject ps = PublishSubject.create(); + + final SingleSubject ms = SingleSubject.create(); + + TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + ts.assertEmpty(); + + assertTrue(ms.hasObservers()); + + ps.onError(new TestException()); + + assertTrue(ms.hasObservers()); + + ts.assertEmpty(); + + ms.onSuccess(1); + + ts.assertFailure(TestException.class, 1); + } + + @Test + public void mapperCrash() { + Observable.just(1) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void disposeBeforeSwitchInOnNext() { + final TestObserver ts = new TestObserver(); + + Observable.just(1) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + ts.cancel(); + return Single.just(1); + } + }).subscribe(ts); + + ts.assertEmpty(); + } + + @Test + public void disposeOnNextAfterFirst() { + final TestObserver ts = new TestObserver(); + + Observable.just(1, 2) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 2) { + ts.cancel(); + } + return Single.just(1); + } + }).subscribe(ts); + + ts.assertValue(1) + .assertNoErrors() + .assertNotComplete(); + } + + @Test + public void cancel() { + PublishSubject ps = PublishSubject.create(); + + final SingleSubject ms = SingleSubject.create(); + + TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + ts.assertEmpty(); + + ps.onNext(1); + + ts.assertEmpty(); + + assertTrue(ps.hasObservers()); + assertTrue(ms.hasObservers()); + + ts.cancel(); + + assertFalse(ps.hasObservers()); + assertFalse(ms.hasObservers()); + } + + @Test + public void mainErrorAfterTermination() { + List errors = TestHelper.trackPluginErrors(); + try { + new Observable() { + @Override + protected void subscribeActual(Observer s) { + s.onSubscribe(Disposables.empty()); + s.onNext(1); + s.onError(new TestException("outer")); + } + } + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.error(new TestException("inner")); + } + }) + .test() + .assertFailureAndMessage(TestException.class, "inner"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer"); + } finally { + RxJavaPlugins.reset(); + } + } + + + @Test + public void innerErrorAfterTermination() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> moRef = new AtomicReference>(); + + TestObserver ts = new Observable() { + @Override + protected void subscribeActual(Observer s) { + s.onSubscribe(Disposables.empty()); + s.onNext(1); + s.onError(new TestException("outer")); + } + } + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return new Single() { + @Override + protected void subscribeActual( + SingleObserver observer) { + observer.onSubscribe(Disposables.empty()); + moRef.set(observer); + } + }; + } + }) + .test(); + + ts.assertFailureAndMessage(TestException.class, "outer"); + + moRef.get().onError(new TestException("inner")); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void nextCancelRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final PublishSubject ps = PublishSubject.create(); + + final SingleSubject ms = SingleSubject.create(); + + final TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return ms; + } + }).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertNoErrors() + .assertNotComplete(); + } + } + + @Test + public void nextInnerErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final SingleSubject ms = SingleSubject.create(); + + final TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Single.never(); + } + }).test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + if (ts.errorCount() != 0) { + assertTrue(errors.isEmpty()); + ts.assertFailure(TestException.class); + } else if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void mainErrorInnerErrorRace() { + final TestException ex = new TestException(); + final TestException ex2 = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final SingleSubject ms = SingleSubject.create(); + + final TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Single.never(); + } + }).test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onError(ex); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onError(ex2); + } + }; + + TestHelper.race(r1, r2); + + ts.assertError(new Predicate() { + @Override + public boolean test(Throwable e) throws Exception { + return e instanceof TestException || e instanceof CompositeException; + } + }); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void nextInnerSuccessRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final PublishSubject ps = PublishSubject.create(); + + final SingleSubject ms = SingleSubject.create(); + + final TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + if (v == 1) { + return ms; + } + return Single.never(); + } + }).test(); + + ps.onNext(1); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ms.onSuccess(3); + } + }; + + TestHelper.race(r1, r2); + + ts.assertNoErrors() + .assertNotComplete(); + } + } + + @Test + public void checkDisposed() { + PublishSubject ps = PublishSubject.create(); + SingleSubject ms = SingleSubject.create(); + + TestHelper.checkDisposed(ps.switchMapSingle(Functions.justFunction(ms))); + } + + @Test + public void drainReentrant() { + final PublishSubject ps = PublishSubject.create(); + + TestObserver to = new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + ps.onNext(2); + } + } + }; + + ps.switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + return Single.just(v); + } + }).subscribe(to); + + ps.onNext(1); + ps.onComplete(); + + to.assertResult(1, 2); + } +} diff --git a/src/test/java/io/reactivex/tck/ConcatMapMaybeTckTest.java b/src/test/java/io/reactivex/tck/ConcatMapMaybeTckTest.java new file mode 100644 index 0000000000..0e41d3f515 --- /dev/null +++ b/src/test/java/io/reactivex/tck/ConcatMapMaybeTckTest.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@Test +public class ConcatMapMaybeTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + return + Flowable.range(0, (int)elements) + .concatMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) throws Exception { + return Maybe.just(v); + } + }) + ; + } +} diff --git a/src/test/java/io/reactivex/tck/ConcatMapSingleTckTest.java b/src/test/java/io/reactivex/tck/ConcatMapSingleTckTest.java new file mode 100644 index 0000000000..dcb2564fba --- /dev/null +++ b/src/test/java/io/reactivex/tck/ConcatMapSingleTckTest.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@Test +public class ConcatMapSingleTckTest extends BaseTck { + + @Override + public Publisher createPublisher(long elements) { + return + Flowable.range(0, (int)elements) + .concatMapSingle(new Function>() { + @Override + public Single apply(Integer v) throws Exception { + return Single.just(v); + } + }) + ; + } +} From 0ea2c957d753abd95bab725a29dcdb0356697a85 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 4 Mar 2018 12:39:28 +0100 Subject: [PATCH 117/417] 2.x: Improve coverage and fix small mistakes/untaken paths in operators (#5883) --- src/main/java/io/reactivex/Maybe.java | 9 +- .../operators/flowable/FlowableFlatMap.java | 4 +- .../flowable/FlowableReduceSeedSingle.java | 33 +- .../operators/flowable/FlowableReplay.java | 8 +- .../flowable/FlowableWindowBoundary.java | 6 +- .../FlowableWindowBoundarySelector.java | 20 +- .../FlowableWindowBoundarySupplier.java | 1 - .../flowable/FlowableWindowTimed.java | 8 +- .../observable/ObservableInternalHelper.java | 54 --- .../ObservableReduceSeedSingle.java | 4 +- .../ObservableWindowBoundarySelector.java | 6 +- .../ObservableWindowBoundarySupplier.java | 1 - .../schedulers/InstantPeriodicTask.java | 16 +- .../ScheduledDirectPeriodicTask.java | 12 +- .../internal/schedulers/SchedulerWhen.java | 6 +- .../subscribers/QueueDrainSubscriber.java | 4 +- .../processors/BehaviorProcessor.java | 4 +- .../reactivex/subjects/BehaviorSubject.java | 4 +- .../observers/BlockingMultiObserverTest.java | 135 +++++++ .../DisposableLambdaObserverTest.java | 66 ++++ .../observers/FullArbiterObserverTest.java | 48 +++ .../observers/QueueDrainObserverTest.java | 162 +++++++++ .../flowable/FlowableBufferTest.java | 123 ++++++- .../flowable/FlowableReduceTest.java | 56 +++ .../flowable/FlowableRefCountTest.java | 178 +++++++++- .../flowable/FlowableReplayTest.java | 12 + .../flowable/FlowableSingleTest.java | 33 +- .../FlowableWindowWithFlowableTest.java | 103 +++++- ...lowableWindowWithStartEndFlowableTest.java | 32 ++ .../flowable/FlowableWindowWithTimeTest.java | 81 +++++ .../operators/maybe/MaybeMergeTest.java | 8 + .../maybe/MaybeSwitchIfEmptySingleTest.java | 9 + .../observable/ObservableBufferTest.java | 92 ++++- .../observable/ObservableHideTest.java | 18 + .../ObservableInternalHelperTest.java | 2 - .../observable/ObservableReduceTest.java | 132 +++++++ .../observable/ObservableRefCountTest.java | 176 +++++++++ .../observable/ObservableTakeLastOneTest.java | 9 + .../ObservableWindowWithObservableTest.java | 56 +++ ...vableWindowWithStartEndObservableTest.java | 32 ++ .../ExecutorSchedulerDelayedRunnableTest.java | 56 +++ .../schedulers/InstantPeriodicTaskTest.java | 277 +++++++++++++++ .../schedulers/SchedulerWhenTest.java | 188 +++++++++- .../subscribers/QueueDrainSubscriberTest.java | 336 ++++++++++++++++++ .../processors/BehaviorProcessorTest.java | 166 +++++++-- .../subjects/BehaviorSubjectTest.java | 105 ++++++ 46 files changed, 2713 insertions(+), 178 deletions(-) create mode 100644 src/test/java/io/reactivex/internal/observers/BlockingMultiObserverTest.java create mode 100644 src/test/java/io/reactivex/internal/observers/DisposableLambdaObserverTest.java create mode 100644 src/test/java/io/reactivex/internal/observers/FullArbiterObserverTest.java create mode 100644 src/test/java/io/reactivex/internal/observers/QueueDrainObserverTest.java create mode 100644 src/test/java/io/reactivex/internal/schedulers/ExecutorSchedulerDelayedRunnableTest.java create mode 100644 src/test/java/io/reactivex/internal/schedulers/InstantPeriodicTaskTest.java create mode 100644 src/test/java/io/reactivex/internal/subscribers/QueueDrainSubscriberTest.java diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 1f21b32a89..f3d8cec1a6 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -888,7 +888,7 @@ public static Flowable merge(Publisher public static Flowable merge(Publisher> sources, int maxConcurrency) { ObjectHelper.requireNonNull(sources, "source is null"); ObjectHelper.verifyPositive(maxConcurrency, "maxConcurrency"); - return RxJavaPlugins.onAssembly(new FlowableFlatMapPublisher(sources, MaybeToPublisher.instance(), false, maxConcurrency, Flowable.bufferSize())); + return RxJavaPlugins.onAssembly(new FlowableFlatMapPublisher(sources, MaybeToPublisher.instance(), false, maxConcurrency, 1)); } /** @@ -1222,12 +1222,11 @@ public static Flowable mergeDelayError(IterableReactiveX operators documentation: Merge */ - @SuppressWarnings({ "unchecked", "rawtypes" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public static Flowable mergeDelayError(Publisher> sources) { - return Flowable.fromPublisher(sources).flatMap((Function)MaybeToPublisher.instance(), true); + return mergeDelayError(sources, Integer.MAX_VALUE); } @@ -1267,7 +1266,9 @@ public static Flowable mergeDelayError(Publisher Flowable mergeDelayError(Publisher> sources, int maxConcurrency) { - return Flowable.fromPublisher(sources).flatMap((Function)MaybeToPublisher.instance(), true, maxConcurrency); + ObjectHelper.requireNonNull(sources, "source is null"); + ObjectHelper.verifyPositive(maxConcurrency, "maxConcurrency"); + return RxJavaPlugins.onAssembly(new FlowableFlatMapPublisher(sources, MaybeToPublisher.instance(), true, maxConcurrency, 1)); } /** diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java index c815fdf111..58e185d12d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java @@ -185,10 +185,10 @@ boolean addInner(InnerSubscriber inner) { void removeInner(InnerSubscriber inner) { for (;;) { InnerSubscriber[] a = subscribers.get(); - if (a == CANCELLED || a == EMPTY) { + int n = a.length; + if (n == 0) { return; } - int n = a.length; int j = -1; for (int i = 0; i < n; i++) { if (a[i] == inner) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceSeedSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceSeedSingle.java index 32cf770953..5201f1b396 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceSeedSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceSeedSingle.java @@ -21,6 +21,7 @@ import io.reactivex.functions.BiFunction; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.plugins.RxJavaPlugins; /** * Reduce a sequence of values, starting from a seed value and by using @@ -78,28 +79,36 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T value) { R v = this.value; - try { - this.value = ObjectHelper.requireNonNull(reducer.apply(v, value), "The reducer returned a null value"); - } catch (Throwable ex) { - Exceptions.throwIfFatal(ex); - s.cancel(); - onError(ex); + if (v != null) { + try { + this.value = ObjectHelper.requireNonNull(reducer.apply(v, value), "The reducer returned a null value"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + s.cancel(); + onError(ex); + } } } @Override public void onError(Throwable e) { - value = null; - s = SubscriptionHelper.CANCELLED; - actual.onError(e); + if (value != null) { + value = null; + s = SubscriptionHelper.CANCELLED; + actual.onError(e); + } else { + RxJavaPlugins.onError(e); + } } @Override public void onComplete() { R v = value; - value = null; - s = SubscriptionHelper.CANCELLED; - actual.onSuccess(v); + if (v != null) { + value = null; + s = SubscriptionHelper.CANCELLED; + actual.onSuccess(v); + } } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java index fa6f494acf..8d1f2eaaad 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java @@ -57,7 +57,7 @@ public final class FlowableReplay extends ConnectableFlowable implements H public static Flowable multicastSelector( final Callable> connectableFactory, final Function, ? extends Publisher> selector) { - return Flowable.unsafeCreate(new MultiCastPublisher(connectableFactory, selector)); + return new MulticastFlowable(connectableFactory, selector); } /** @@ -1100,17 +1100,17 @@ Node getHead() { } } - static final class MultiCastPublisher implements Publisher { + static final class MulticastFlowable extends Flowable { private final Callable> connectableFactory; private final Function, ? extends Publisher> selector; - MultiCastPublisher(Callable> connectableFactory, Function, ? extends Publisher> selector) { + MulticastFlowable(Callable> connectableFactory, Function, ? extends Publisher> selector) { this.connectableFactory = connectableFactory; this.selector = selector; } @Override - public void subscribe(Subscriber child) { + protected void subscribeActual(Subscriber child) { ConnectableFlowable co; try { co = ObjectHelper.requireNonNull(connectableFactory.call(), "The connectableFactory returned null"); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java index 9cf1b1100c..58cec89232 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java @@ -93,6 +93,7 @@ public void onSubscribe(Subscription s) { produced(1); } } else { + s.cancel(); a.onError(new MissingBackpressureException("Could not deliver first window due to lack of requests")); return; } @@ -254,11 +255,6 @@ void next() { } } - @Override - public boolean accept(Subscriber> a, Object v) { - // not used by this operator - return false; - } } static final class WindowBoundaryInnerSubscriber extends DisposableSubscriber { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java index 50c7e45dfb..55fee47d51 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java @@ -323,36 +323,22 @@ static final class WindowOperation { static final class OperatorWindowBoundaryOpenSubscriber extends DisposableSubscriber { final WindowBoundaryMainSubscriber parent; - boolean done; - OperatorWindowBoundaryOpenSubscriber(WindowBoundaryMainSubscriber parent) { this.parent = parent; } @Override public void onNext(B t) { - if (done) { - return; - } parent.open(t); } @Override public void onError(Throwable t) { - if (done) { - RxJavaPlugins.onError(t); - return; - } - done = true; parent.error(t); } @Override public void onComplete() { - if (done) { - return; - } - done = true; parent.onComplete(); } } @@ -370,12 +356,8 @@ static final class OperatorWindowBoundaryCloseSubscriber extends Disposabl @Override public void onNext(V t) { - if (done) { - return; - } - done = true; cancel(); - parent.close(this); + onComplete(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java index 5286407e7d..f90d74ad2a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java @@ -326,7 +326,6 @@ public void onComplete() { } done = true; parent.onComplete(); -// parent.next(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java index f0bd22429f..460fd7d814 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java @@ -390,9 +390,7 @@ public void onNext(T t) { tm.dispose(); Disposable task = worker.schedulePeriodically( new ConsumerIndexHolder(producerIndex, this), timespan, timespan, unit); - if (!timer.compareAndSet(tm, task)) { - task.dispose(); - } + timer.replace(task); } } else { window = null; @@ -549,9 +547,7 @@ void drainLoop() { Disposable task = worker.schedulePeriodically( new ConsumerIndexHolder(producerIndex, this), timespan, timespan, unit); - if (!timer.compareAndSet(tm, task)) { - task.dispose(); - } + timer.replace(task); } } else { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java index 7bc6305703..0af4a15f0a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java @@ -199,24 +199,6 @@ public Object apply(Object t) throws Exception { } } - static final class RepeatWhenOuterHandler - implements Function>, ObservableSource> { - private final Function, ? extends ObservableSource> handler; - - RepeatWhenOuterHandler(Function, ? extends ObservableSource> handler) { - this.handler = handler; - } - - @Override - public ObservableSource apply(Observable> no) throws Exception { - return handler.apply(no.map(MapToInt.INSTANCE)); - } - } - - public static Function>, ObservableSource> repeatWhenHandler(final Function, ? extends ObservableSource> handler) { - return new RepeatWhenOuterHandler(handler); - } - public static Callable> replayCallable(final Observable parent) { return new ReplayCallable(parent); } @@ -237,42 +219,6 @@ public static Function, ObservableSource> replayFunction return new ReplayFunction(selector, scheduler); } - enum ErrorMapperFilter implements Function, Throwable>, Predicate> { - INSTANCE; - - @Override - public Throwable apply(Notification t) throws Exception { - return t.getError(); - } - - @Override - public boolean test(Notification t) throws Exception { - return t.isOnError(); - } - } - - static final class RetryWhenInner - implements Function>, ObservableSource> { - private final Function, ? extends ObservableSource> handler; - - RetryWhenInner( - Function, ? extends ObservableSource> handler) { - this.handler = handler; - } - - @Override - public ObservableSource apply(Observable> no) throws Exception { - Observable map = no - .takeWhile(ErrorMapperFilter.INSTANCE) - .map(ErrorMapperFilter.INSTANCE); - return handler.apply(map); - } - } - - public static Function>, ObservableSource> retryWhenHandler(final Function, ? extends ObservableSource> handler) { - return new RetryWhenInner(handler); - } - static final class ZipIterableFunction implements Function>, ObservableSource> { private final Function zipper; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceSeedSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceSeedSingle.java index bbf31f4057..9006957348 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceSeedSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceSeedSingle.java @@ -89,8 +89,8 @@ public void onNext(T value) { @Override public void onError(Throwable e) { R v = value; - value = null; if (v != null) { + value = null; actual.onError(e); } else { RxJavaPlugins.onError(e); @@ -100,8 +100,8 @@ public void onError(Throwable e) { @Override public void onComplete() { R v = value; - value = null; if (v != null) { + value = null; actual.onSuccess(v); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java index eec057bf22..d0da7e2b0a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java @@ -338,12 +338,8 @@ static final class OperatorWindowBoundaryCloseObserver extends DisposableO @Override public void onNext(V t) { - if (done) { - return; - } - done = true; dispose(); - parent.close(this); + onComplete(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySupplier.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySupplier.java index f47d096556..47b0841262 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySupplier.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySupplier.java @@ -296,7 +296,6 @@ public void onComplete() { } done = true; parent.onComplete(); -// parent.next(); } } } diff --git a/src/main/java/io/reactivex/internal/schedulers/InstantPeriodicTask.java b/src/main/java/io/reactivex/internal/schedulers/InstantPeriodicTask.java index 86086987ab..ec9b2a0d2f 100644 --- a/src/main/java/io/reactivex/internal/schedulers/InstantPeriodicTask.java +++ b/src/main/java/io/reactivex/internal/schedulers/InstantPeriodicTask.java @@ -50,16 +50,14 @@ final class InstantPeriodicTask implements Callable, Disposable { @Override public Void call() throws Exception { + runner = Thread.currentThread(); try { - runner = Thread.currentThread(); - try { - task.run(); - setRest(executor.submit(this)); - } catch (Throwable ex) { - RxJavaPlugins.onError(ex); - } - } finally { + task.run(); + setRest(executor.submit(this)); + runner = null; + } catch (Throwable ex) { runner = null; + RxJavaPlugins.onError(ex); } return null; } @@ -86,6 +84,7 @@ void setFirst(Future f) { Future current = first.get(); if (current == CANCELLED) { f.cancel(runner != Thread.currentThread()); + return; } if (first.compareAndSet(current, f)) { return; @@ -98,6 +97,7 @@ void setRest(Future f) { Future current = rest.get(); if (current == CANCELLED) { f.cancel(runner != Thread.currentThread()); + return; } if (rest.compareAndSet(current, f)) { return; diff --git a/src/main/java/io/reactivex/internal/schedulers/ScheduledDirectPeriodicTask.java b/src/main/java/io/reactivex/internal/schedulers/ScheduledDirectPeriodicTask.java index 080928f722..201847ba75 100644 --- a/src/main/java/io/reactivex/internal/schedulers/ScheduledDirectPeriodicTask.java +++ b/src/main/java/io/reactivex/internal/schedulers/ScheduledDirectPeriodicTask.java @@ -35,14 +35,12 @@ public ScheduledDirectPeriodicTask(Runnable runnable) { public void run() { runner = Thread.currentThread(); try { - try { - runnable.run(); - } catch (Throwable ex) { - lazySet(FINISHED); - RxJavaPlugins.onError(ex); - } - } finally { + runnable.run(); runner = null; + } catch (Throwable ex) { + runner = null; + lazySet(FINISHED); + RxJavaPlugins.onError(ex); } } } diff --git a/src/main/java/io/reactivex/internal/schedulers/SchedulerWhen.java b/src/main/java/io/reactivex/internal/schedulers/SchedulerWhen.java index dd91cc11d7..9b97ee6a36 100644 --- a/src/main/java/io/reactivex/internal/schedulers/SchedulerWhen.java +++ b/src/main/java/io/reactivex/internal/schedulers/SchedulerWhen.java @@ -28,8 +28,8 @@ import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; -import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; +import io.reactivex.internal.util.ExceptionHelper; import io.reactivex.processors.FlowableProcessor; import io.reactivex.processors.UnicastProcessor; @@ -116,7 +116,7 @@ public SchedulerWhen(Function>, Completable> comb try { disposable = combine.apply(workerProcessor).subscribe(); } catch (Throwable e) { - Exceptions.propagate(e); + throw ExceptionHelper.wrapOrThrow(e); } } @@ -155,7 +155,7 @@ public Worker createWorker() { static final Disposable DISPOSED = Disposables.disposed(); @SuppressWarnings("serial") - abstract static class ScheduledAction extends AtomicReferenceimplements Disposable { + abstract static class ScheduledAction extends AtomicReference implements Disposable { ScheduledAction() { super(SUBSCRIBED); } diff --git a/src/main/java/io/reactivex/internal/subscribers/QueueDrainSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/QueueDrainSubscriber.java index b23ff5957c..31d97833c2 100644 --- a/src/main/java/io/reactivex/internal/subscribers/QueueDrainSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/QueueDrainSubscriber.java @@ -69,7 +69,7 @@ protected final void fastPathEmitMax(U value, boolean delayError, Disposable dis final Subscriber s = actual; final SimplePlainQueue q = queue; - if (wip.get() == 0 && wip.compareAndSet(0, 1)) { + if (fastEnter()) { long r = requested.get(); if (r != 0L) { if (accept(s, value)) { @@ -98,7 +98,7 @@ protected final void fastPathOrderedEmitMax(U value, boolean delayError, Disposa final Subscriber s = actual; final SimplePlainQueue q = queue; - if (wip.get() == 0 && wip.compareAndSet(0, 1)) { + if (fastEnter()) { long r = requested.get(); if (r != 0L) { if (q.isEmpty()) { diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index edd5c620ef..bc0d416160 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -459,10 +459,10 @@ boolean add(BehaviorSubscription rs) { void remove(BehaviorSubscription rs) { for (;;) { BehaviorSubscription[] a = subscribers.get(); - if (a == TERMINATED || a == EMPTY) { + int len = a.length; + if (len == 0) { return; } - int len = a.length; int j = -1; for (int i = 0; i < len; i++) { if (a[i] == rs) { diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java index 42878adee2..6d0d4641ac 100644 --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java @@ -410,10 +410,10 @@ boolean add(BehaviorDisposable rs) { void remove(BehaviorDisposable rs) { for (;;) { BehaviorDisposable[] a = subscribers.get(); - if (a == TERMINATED || a == EMPTY) { + int len = a.length; + if (len == 0) { return; } - int len = a.length; int j = -1; for (int i = 0; i < len; i++) { if (a[i] == rs) { diff --git a/src/test/java/io/reactivex/internal/observers/BlockingMultiObserverTest.java b/src/test/java/io/reactivex/internal/observers/BlockingMultiObserverTest.java new file mode 100644 index 0000000000..6b4238f8f6 --- /dev/null +++ b/src/test/java/io/reactivex/internal/observers/BlockingMultiObserverTest.java @@ -0,0 +1,135 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.observers; + +import static org.junit.Assert.*; + +import java.util.concurrent.TimeUnit; + +import org.junit.Test; + +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.schedulers.Schedulers; + +public class BlockingMultiObserverTest { + + @Test + public void dispose() { + BlockingMultiObserver bmo = new BlockingMultiObserver(); + bmo.dispose(); + + Disposable d = Disposables.empty(); + + bmo.onSubscribe(d); + } + + @Test + public void blockingGetDefault() { + final BlockingMultiObserver bmo = new BlockingMultiObserver(); + + Schedulers.single().scheduleDirect(new Runnable() { + @Override + public void run() { + bmo.onSuccess(1); + } + }, 100, TimeUnit.MILLISECONDS); + + assertEquals(1, bmo.blockingGet(0).intValue()); + } + + @Test + public void blockingAwait() { + final BlockingMultiObserver bmo = new BlockingMultiObserver(); + + Schedulers.single().scheduleDirect(new Runnable() { + @Override + public void run() { + bmo.onSuccess(1); + } + }, 100, TimeUnit.MILLISECONDS); + + assertTrue(bmo.blockingAwait(1, TimeUnit.MINUTES)); + } + + @Test + public void blockingGetDefaultInterrupt() { + final BlockingMultiObserver bmo = new BlockingMultiObserver(); + + Thread.currentThread().interrupt(); + try { + bmo.blockingGet(0); + fail("Should have thrown"); + } catch (RuntimeException ex) { + assertTrue(ex.getCause() instanceof InterruptedException); + } finally { + Thread.interrupted(); + } + } + + @Test + public void blockingGetErrorInterrupt() { + final BlockingMultiObserver bmo = new BlockingMultiObserver(); + + Thread.currentThread().interrupt(); + try { + assertTrue(bmo.blockingGetError() instanceof InterruptedException); + } finally { + Thread.interrupted(); + } + } + + @Test + public void blockingGetErrorTimeoutInterrupt() { + final BlockingMultiObserver bmo = new BlockingMultiObserver(); + + Thread.currentThread().interrupt(); + try { + bmo.blockingGetError(1, TimeUnit.MINUTES); + fail("Should have thrown"); + } catch (RuntimeException ex) { + assertTrue(ex.getCause() instanceof InterruptedException); + } finally { + Thread.interrupted(); + } + } + + @Test + public void blockingGetErrorDelayed() { + final BlockingMultiObserver bmo = new BlockingMultiObserver(); + + Schedulers.single().scheduleDirect(new Runnable() { + @Override + public void run() { + bmo.onError(new TestException()); + } + }, 100, TimeUnit.MILLISECONDS); + + assertTrue(bmo.blockingGetError() instanceof TestException); + } + + @Test + public void blockingGetErrorTimeoutDelayed() { + final BlockingMultiObserver bmo = new BlockingMultiObserver(); + + Schedulers.single().scheduleDirect(new Runnable() { + @Override + public void run() { + bmo.onError(new TestException()); + } + }, 100, TimeUnit.MILLISECONDS); + + assertTrue(bmo.blockingGetError(1, TimeUnit.MINUTES) instanceof TestException); + } +} diff --git a/src/test/java/io/reactivex/internal/observers/DisposableLambdaObserverTest.java b/src/test/java/io/reactivex/internal/observers/DisposableLambdaObserverTest.java new file mode 100644 index 0000000000..c152f15b37 --- /dev/null +++ b/src/test/java/io/reactivex/internal/observers/DisposableLambdaObserverTest.java @@ -0,0 +1,66 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.observers; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.Test; + +import io.reactivex.TestHelper; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.internal.functions.Functions; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; + +public class DisposableLambdaObserverTest { + + @Test + public void doubleOnSubscribe() { + TestHelper.doubleOnSubscribe(new DisposableLambdaObserver( + new TestObserver(), Functions.emptyConsumer(), Functions.EMPTY_ACTION + )); + } + + @Test + public void disposeCrash() { + List errors = TestHelper.trackPluginErrors(); + try { + DisposableLambdaObserver o = new DisposableLambdaObserver( + new TestObserver(), Functions.emptyConsumer(), + new Action() { + @Override + public void run() throws Exception { + throw new TestException(); + } + } + ); + + o.onSubscribe(Disposables.empty()); + + assertFalse(o.isDisposed()); + + o.dispose(); + + assertTrue(o.isDisposed()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } +} diff --git a/src/test/java/io/reactivex/internal/observers/FullArbiterObserverTest.java b/src/test/java/io/reactivex/internal/observers/FullArbiterObserverTest.java new file mode 100644 index 0000000000..c2b4c64e76 --- /dev/null +++ b/src/test/java/io/reactivex/internal/observers/FullArbiterObserverTest.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.observers; + +import org.junit.Test; + +import io.reactivex.TestHelper; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.TestException; +import io.reactivex.internal.disposables.ObserverFullArbiter; +import io.reactivex.observers.TestObserver; + +public class FullArbiterObserverTest { + + @Test + public void doubleOnSubscribe() { + TestObserver to = new TestObserver(); + ObserverFullArbiter fa = new ObserverFullArbiter(to, null, 16); + FullArbiterObserver fo = new FullArbiterObserver(fa); + to.onSubscribe(fa); + + TestHelper.doubleOnSubscribe(fo); + } + + @Test + public void error() { + TestObserver to = new TestObserver(); + ObserverFullArbiter fa = new ObserverFullArbiter(to, null, 16); + FullArbiterObserver fo = new FullArbiterObserver(fa); + to.onSubscribe(fa); + + fo.onSubscribe(Disposables.empty()); + fo.onError(new TestException()); + + to.assertFailure(TestException.class); + } +} diff --git a/src/test/java/io/reactivex/internal/observers/QueueDrainObserverTest.java b/src/test/java/io/reactivex/internal/observers/QueueDrainObserverTest.java new file mode 100644 index 0000000000..12959cb898 --- /dev/null +++ b/src/test/java/io/reactivex/internal/observers/QueueDrainObserverTest.java @@ -0,0 +1,162 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.observers; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.observers.TestObserver; + +public class QueueDrainObserverTest { + + static final QueueDrainObserver createUnordered(TestObserver to, final Disposable d) { + return new QueueDrainObserver(to, new SpscArrayQueue(4)) { + @Override + public void onNext(Integer t) { + fastPathEmit(t, false, d); + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onComplete() { + } + + @Override + public void onSubscribe(Disposable s) { + } + + @Override + public void accept(Observer a, Integer v) { + super.accept(a, v); + a.onNext(v); + } + }; + } + + static final QueueDrainObserver createOrdered(TestObserver to, final Disposable d) { + return new QueueDrainObserver(to, new SpscArrayQueue(4)) { + @Override + public void onNext(Integer t) { + fastPathOrderedEmit(t, false, d); + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onComplete() { + } + + @Override + public void onSubscribe(Disposable s) { + } + + @Override + public void accept(Observer a, Integer v) { + super.accept(a, v); + a.onNext(v); + } + }; + } + + @Test + public void unorderedSlowPath() { + TestObserver to = new TestObserver(); + Disposable d = Disposables.empty(); + QueueDrainObserver qd = createUnordered(to, d); + to.onSubscribe(Disposables.empty()); + + qd.enter(); + qd.onNext(1); + + to.assertEmpty(); + } + + @Test + public void orderedSlowPath() { + TestObserver to = new TestObserver(); + Disposable d = Disposables.empty(); + QueueDrainObserver qd = createOrdered(to, d); + to.onSubscribe(Disposables.empty()); + + qd.enter(); + qd.onNext(1); + + to.assertEmpty(); + } + + @Test + public void orderedSlowPathNonEmptyQueue() { + TestObserver to = new TestObserver(); + Disposable d = Disposables.empty(); + QueueDrainObserver qd = createOrdered(to, d); + to.onSubscribe(Disposables.empty()); + + qd.queue.offer(0); + qd.onNext(1); + + to.assertValuesOnly(0, 1); + } + + @Test + public void unorderedOnNextRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + TestObserver to = new TestObserver(); + Disposable d = Disposables.empty(); + final QueueDrainObserver qd = createUnordered(to, d); + to.onSubscribe(Disposables.empty()); + + Runnable r1 = new Runnable() { + @Override + public void run() { + qd.onNext(1); + } + }; + + TestHelper.race(r1, r1); + + to.assertValuesOnly(1, 1); + } + } + + @Test + public void orderedOnNextRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + TestObserver to = new TestObserver(); + Disposable d = Disposables.empty(); + final QueueDrainObserver qd = createOrdered(to, d); + to.onSubscribe(Disposables.empty()); + + Runnable r1 = new Runnable() { + @Override + public void run() { + qd.onNext(1); + } + }; + + TestHelper.race(r1, r1); + + to.assertValuesOnly(1, 1); + } + } + +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index 471fc5836e..a65442a895 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -33,7 +33,7 @@ import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.processors.PublishProcessor; +import io.reactivex.processors.*; import io.reactivex.schedulers.*; import io.reactivex.subscribers.*; @@ -2436,4 +2436,125 @@ protected void subscribeActual(Subscriber s) { RxJavaPlugins.reset(); } } + + @Test + public void bufferExactBoundaryDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable( + new Function, Flowable>>() { + @Override + public Flowable> apply(Flowable f) + throws Exception { + return f.buffer(Flowable.never()); + } + } + ); + } + + @SuppressWarnings("unchecked") + @Test + public void bufferExactBoundarySecondBufferCrash() { + PublishProcessor pp = PublishProcessor.create(); + PublishProcessor b = PublishProcessor.create(); + + TestSubscriber> to = pp.buffer(b, new Callable>() { + int calls; + @Override + public List call() throws Exception { + if (++calls == 2) { + throw new TestException(); + } + return new ArrayList(); + } + }).test(); + + b.onNext(1); + + to.assertFailure(TestException.class); + } + + @SuppressWarnings("unchecked") + @Test + public void bufferExactBoundaryBadSource() { + Flowable pp = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + observer.onComplete(); + observer.onNext(1); + observer.onComplete(); + } + }; + + final AtomicReference> ref = new AtomicReference>(); + Flowable b = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ref.set(observer); + } + }; + + TestSubscriber> ts = pp.buffer(b).test(); + + ref.get().onNext(1); + + ts.assertResult(Collections.emptyList()); + } + + @Test + public void bufferExactBoundaryCancelUpfront() { + PublishProcessor pp = PublishProcessor.create(); + PublishProcessor b = PublishProcessor.create(); + + pp.buffer(b).test(0L, true) + .assertEmpty(); + + assertFalse(pp.hasSubscribers()); + assertFalse(b.hasSubscribers()); + } + + @Test + public void bufferExactBoundaryDisposed() { + Flowable pp = new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + + Disposable d = (Disposable)s; + + assertFalse(d.isDisposed()); + + d.dispose(); + + assertTrue(d.isDisposed()); + } + }; + PublishProcessor b = PublishProcessor.create(); + + pp.buffer(b).test(); + } + + @Test + public void bufferBoundaryErrorTwice() { + List errors = TestHelper.trackPluginErrors(); + try { + BehaviorProcessor.createDefault(1) + .buffer(Functions.justCallable(new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onError(new TestException("first")); + s.onError(new TestException("second")); + } + })) + .test() + .assertError(TestException.class) + .assertErrorMessage("first") + .assertNotComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java index e50d8faa57..63e80b3822 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java @@ -29,6 +29,7 @@ import io.reactivex.internal.fuseable.HasUpstreamPublisher; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; @@ -470,4 +471,59 @@ static String blockingOp(Integer x, Integer y) { } return "x" + x + "y" + y; } + + @Test + public void seedDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function, SingleSource>() { + @Override + public SingleSource apply(Flowable o) + throws Exception { + return o.reduce(0, new BiFunction() { + @Override + public Integer apply(Integer a, Integer b) throws Exception { + return a; + } + }); + } + }); + } + + @Test + public void seedDisposed() { + TestHelper.checkDisposed(PublishProcessor.create().reduce(0, new BiFunction() { + @Override + public Integer apply(Integer a, Integer b) throws Exception { + return a; + } + })); + } + + @Test + public void seedBadSource() { + List errors = TestHelper.trackPluginErrors(); + try { + new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + observer.onComplete(); + observer.onNext(1); + observer.onError(new TestException()); + observer.onComplete(); + } + } + .reduce(0, new BiFunction() { + @Override + public Integer apply(Integer a, Integer b) throws Exception { + return a; + } + }) + .test() + .assertResult(0); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index 8150dc9393..9de049a90d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -27,11 +27,13 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.disposables.Disposable; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; import io.reactivex.flowables.ConnectableFlowable; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.internal.util.ExceptionHelper; import io.reactivex.processors.ReplayProcessor; import io.reactivex.schedulers.*; import io.reactivex.subscribers.TestSubscriber; @@ -786,4 +788,178 @@ public void replayIsUnsubscribed() { assertTrue(((Disposable)co).isDisposed()); } + + static final class BadFlowableSubscribe extends ConnectableFlowable { + + @Override + public void connect(Consumer connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Subscriber observer) { + throw new TestException("subscribeActual"); + } + } + + static final class BadFlowableDispose extends ConnectableFlowable implements Disposable { + + @Override + public void dispose() { + throw new TestException("dispose"); + } + + @Override + public boolean isDisposed() { + return false; + } + + @Override + public void connect(Consumer connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Subscriber observer) { + } + } + + static final class BadFlowableConnect extends ConnectableFlowable { + + @Override + public void connect(Consumer connection) { + throw new TestException("connect"); + } + + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + } + } + + @Test + public void badSourceSubscribe() { + BadFlowableSubscribe bo = new BadFlowableSubscribe(); + + try { + bo.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } + + @Test + public void badSourceDispose() { + BadFlowableDispose bf = new BadFlowableDispose(); + + try { + bf.refCount() + .test() + .cancel(); + fail("Should have thrown"); + } catch (TestException expected) { + } + } + + @Test + public void badSourceConnect() { + BadFlowableConnect bf = new BadFlowableConnect(); + + try { + bf.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } + + static final class BadFlowableSubscribe2 extends ConnectableFlowable { + + int count; + + @Override + public void connect(Consumer connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Subscriber observer) { + if (++count == 1) { + observer.onSubscribe(new BooleanSubscription()); + } else { + throw new TestException("subscribeActual"); + } + } + } + + @Test + public void badSourceSubscribe2() { + BadFlowableSubscribe2 bf = new BadFlowableSubscribe2(); + + Flowable o = bf.refCount(); + o.test(); + try { + o.test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } + + static final class BadFlowableConnect2 extends ConnectableFlowable + implements Disposable { + + @Override + public void connect(Consumer connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + observer.onComplete(); + } + + @Override + public void dispose() { + throw new TestException("dispose"); + } + + @Override + public boolean isDisposed() { + return false; + } + } + + @Test + public void badSourceCompleteDisconnect() { + BadFlowableConnect2 bf = new BadFlowableConnect2(); + + try { + bf.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index a9c41366ad..8ad3caa14e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -1755,4 +1755,16 @@ public Publisher apply(Flowable v) throws Exception { .test() .assertFailureAndMessage(NullPointerException.class, "The selector returned a null Publisher"); } + + @Test + public void multicastSelectorCallableConnectableCrash() { + FlowableReplay.multicastSelector(new Callable>() { + @Override + public ConnectableFlowable call() throws Exception { + throw new TestException(); + } + }, Functions.>identity()) + .test() + .assertFailure(TestException.class); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java index 67c5c83881..2aff36bc6a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java @@ -25,10 +25,10 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.Flowable; import io.reactivex.functions.*; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.subscribers.DefaultSubscriber; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subscribers.*; public class FlowableSingleTest { @@ -760,11 +760,40 @@ public SingleSource apply(Flowable o) throws Exception { } }); + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable o) throws Exception { + return o.singleOrError().toFlowable(); + } + }); + TestHelper.checkDoubleOnSubscribeFlowableToMaybe(new Function, MaybeSource>() { @Override public MaybeSource apply(Flowable o) throws Exception { return o.singleElement(); } }); + + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable o) throws Exception { + return o.singleElement().toFlowable(); + } + }); + } + + @Test + public void cancelAsFlowable() { + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = pp.singleOrError().toFlowable().test(); + + assertTrue(pp.hasSubscribers()); + + ts.assertEmpty(); + + ts.cancel(); + + assertFalse(pp.hasSubscribers()); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java index 3994d5dc31..7ceccf678f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java @@ -22,7 +22,7 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; -import org.reactivestreams.Subscriber; +import org.reactivestreams.*; import io.reactivex.*; import io.reactivex.exceptions.*; @@ -615,4 +615,105 @@ public Flowable apply(Flowable v) throws Exception { } }, false, 1, 1, 1); } + + @Test + public void boundaryError() { + BehaviorProcessor.createDefault(1) + .window(Functions.justCallable(Flowable.error(new TestException()))) + .test() + .assertValueCount(1) + .assertNotComplete() + .assertError(TestException.class); + } + + @SuppressWarnings("unchecked") + @Test + public void boundaryMissingBackpressure() { + BehaviorProcessor.createDefault(1) + .window(Functions.justCallable(Flowable.error(new TestException()))) + .test(0) + .assertFailure(MissingBackpressureException.class); + } + + @Test + public void boundaryCallableCrashOnCall2() { + BehaviorProcessor.createDefault(1) + .window(new Callable>() { + int calls; + @Override + public Flowable call() throws Exception { + if (++calls == 2) { + throw new TestException(); + } + return Flowable.just(1); + } + }) + .test() + .assertError(TestException.class) + .assertNotComplete(); + } + + @Test + public void boundarySecondMissingBackpressure() { + BehaviorProcessor.createDefault(1) + .window(Functions.justCallable(Flowable.just(1))) + .test(1) + .assertError(MissingBackpressureException.class) + .assertNotComplete(); + } + + @Test + public void oneWindow() { + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber> ts = BehaviorProcessor.createDefault(1) + .window(Functions.justCallable(pp)) + .take(1) + .test(); + + pp.onNext(1); + + ts + .assertValueCount(1) + .assertNoErrors() + .assertComplete(); + } + + @SuppressWarnings("unchecked") + @Test + public void boundaryDirectMissingBackpressure() { + BehaviorProcessor.create() + .window(Flowable.error(new TestException())) + .test(0) + .assertFailure(MissingBackpressureException.class); + } + + @SuppressWarnings("unchecked") + @Test + public void boundaryDirectMissingBackpressureNoNullPointerException() { + BehaviorProcessor.createDefault(1) + .window(Flowable.error(new TestException())) + .test(0) + .assertFailure(MissingBackpressureException.class); + } + + @Test + public void boundaryDirectSecondMissingBackpressure() { + BehaviorProcessor.createDefault(1) + .window(Flowable.just(1)) + .test(1) + .assertError(MissingBackpressureException.class) + .assertNotComplete(); + } + + @Test + public void boundaryDirectDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>>() { + @Override + public Publisher> apply(Flowable f) + throws Exception { + return f.window(Flowable.never()).takeLast(1); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java index 5177276bed..73535ff5c2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java @@ -26,6 +26,7 @@ import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.*; import io.reactivex.schedulers.TestScheduler; import io.reactivex.subscribers.*; @@ -398,4 +399,35 @@ public void mainError() { .test() .assertFailure(TestException.class); } + + @Test + public void windowCloseIngoresCancel() { + List errors = TestHelper.trackPluginErrors(); + try { + BehaviorProcessor.createDefault(1) + .window(BehaviorProcessor.createDefault(1), new Function>() { + @Override + public Publisher apply(Integer f) throws Exception { + return new Flowable() { + @Override + protected void subscribeActual( + Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onNext(2); + s.onError(new TestException()); + } + }; + } + }) + .test() + .assertValueCount(1) + .assertNoErrors() + .assertNotComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java index 74bcd72152..6d48c40f49 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java @@ -806,5 +806,86 @@ public void countRestartsOnTimeTick() { .assertNoErrors() .assertNotComplete(); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>>() { + @Override + public Publisher> apply(Flowable f) + throws Exception { + return f.window(1, TimeUnit.SECONDS, 1).takeLast(0); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void firstWindowMissingBackpressure() { + Flowable.never() + .window(1, TimeUnit.SECONDS, 1) + .test(0L) + .assertFailure(MissingBackpressureException.class); + } + + @Test + public void nextWindowMissingBackpressure() { + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber> ts = pp.window(1, TimeUnit.SECONDS, 1) + .test(1L); + + pp.onNext(1); + + ts.assertValueCount(1) + .assertError(MissingBackpressureException.class) + .assertNotComplete(); + } + + @Test + public void cancelUpfront() { + Flowable.never() + .window(1, TimeUnit.SECONDS, 1) + .test(0L, true) + .assertEmpty(); + } + + @Test + public void nextWindowMissingBackpressureDrainOnSize() { + final PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber> ts = pp.window(1, TimeUnit.MINUTES, 1) + .subscribeWith(new TestSubscriber>(2) { + int calls; + @Override + public void onNext(Flowable t) { + super.onNext(t); + if (++calls == 2) { + pp.onNext(2); + } + } + }); + + pp.onNext(1); + + ts.assertValueCount(2) + .assertError(MissingBackpressureException.class) + .assertNotComplete(); + } + + @Test + public void nextWindowMissingBackpressureDrainOnTime() { + final PublishProcessor pp = PublishProcessor.create(); + + final TestScheduler sch = new TestScheduler(); + + TestSubscriber> ts = pp.window(1, TimeUnit.MILLISECONDS, sch, 10) + .test(1); + + sch.advanceTimeBy(1, TimeUnit.MILLISECONDS); + + ts.assertValueCount(1) + .assertError(MissingBackpressureException.class) + .assertNotComplete(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeTest.java index 0d9d450a05..176ae9c793 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeTest.java @@ -98,4 +98,12 @@ public Integer call() throws Exception { .assertFailureAndMessage(TestException.class, "2", 0, 0); } } + + @Test + public void scalar() { + Maybe.mergeDelayError( + Flowable.just(Maybe.just(1))) + .test() + .assertResult(1); + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java index cd8db6760f..714ba98272 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java @@ -20,6 +20,7 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; +import io.reactivex.internal.fuseable.HasUpstreamMaybeSource; import io.reactivex.observers.TestObserver; import io.reactivex.processors.PublishProcessor; @@ -102,4 +103,12 @@ public void run() { TestHelper.race(r1, r2); } } + + @SuppressWarnings("rawtypes") + @Test + public void source() { + assertSame(Maybe.empty(), + ((HasUpstreamMaybeSource)(Maybe.empty().switchIfEmpty(Single.just(1)))).source() + ); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 7a435a389c..517a99a3c6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -20,7 +20,7 @@ import java.io.IOException; import java.util.*; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.*; import org.junit.*; import org.mockito.*; @@ -35,7 +35,7 @@ import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; -import io.reactivex.subjects.PublishSubject; +import io.reactivex.subjects.*; public class ObservableBufferTest { @@ -1796,4 +1796,92 @@ protected void subscribeActual(Observer s) { RxJavaPlugins.reset(); } } + + @Test + public void bufferExactBoundaryDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable( + new Function, ObservableSource>>() { + @Override + public ObservableSource> apply(Observable f) + throws Exception { + return f.buffer(Observable.never()); + } + } + ); + } + + @SuppressWarnings("unchecked") + @Test + public void bufferExactBoundarySecondBufferCrash() { + PublishSubject ps = PublishSubject.create(); + PublishSubject b = PublishSubject.create(); + + TestObserver> to = ps.buffer(b, new Callable>() { + int calls; + @Override + public List call() throws Exception { + if (++calls == 2) { + throw new TestException(); + } + return new ArrayList(); + } + }).test(); + + b.onNext(1); + + to.assertFailure(TestException.class); + } + + @SuppressWarnings("unchecked") + @Test + public void bufferExactBoundaryBadSource() { + Observable ps = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); + observer.onNext(1); + observer.onComplete(); + } + }; + + final AtomicReference> ref = new AtomicReference>(); + Observable b = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); + } + }; + + TestObserver> to = ps.buffer(b).test(); + + ref.get().onNext(1); + + to.assertResult(Collections.emptyList()); + } + + @Test + public void bufferBoundaryErrorTwice() { + List errors = TestHelper.trackPluginErrors(); + try { + BehaviorSubject.createDefault(1) + .buffer(Functions.justCallable(new Observable() { + @Override + protected void subscribeActual(Observer s) { + s.onSubscribe(Disposables.empty()); + s.onError(new TestException("first")); + s.onError(new TestException("second")); + } + })) + .test() + .assertError(TestException.class) + .assertErrorMessage("first") + .assertNotComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableHideTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableHideTest.java index 14c6f82c17..d4c2bf002f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableHideTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableHideTest.java @@ -20,6 +20,7 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; import io.reactivex.subjects.PublishSubject; public class ObservableHideTest { @@ -42,6 +43,7 @@ public void testHiding() { verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } + @Test public void testHidingError() { PublishSubject src = PublishSubject.create(); @@ -60,4 +62,20 @@ public void testHidingError() { verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, ObservableSource>() { + @Override + public ObservableSource apply(Observable o) + throws Exception { + return o.hide(); + } + }); + } + + @Test + public void disposed() { + TestHelper.checkDisposed(PublishSubject.create().hide()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableInternalHelperTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableInternalHelperTest.java index 1e18ef043d..e03d651bda 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableInternalHelperTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableInternalHelperTest.java @@ -29,8 +29,6 @@ public void enums() { assertNotNull(ObservableInternalHelper.MapToInt.values()[0]); assertNotNull(ObservableInternalHelper.MapToInt.valueOf("INSTANCE")); - assertNotNull(ObservableInternalHelper.ErrorMapperFilter.values()[0]); - assertNotNull(ObservableInternalHelper.ErrorMapperFilter.valueOf("INSTANCE")); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java index 5faf25b837..5dce27dcaa 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java @@ -14,13 +14,20 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +import java.util.List; +import java.util.concurrent.Callable; + import org.junit.*; import io.reactivex.*; +import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subjects.PublishSubject; public class ObservableReduceTest { Observer observer; @@ -234,5 +241,130 @@ public void testBackpressureWithInitialValue() throws InterruptedException { assertEquals(21, r.intValue()); } + @Test + public void reduceWithSingle() { + Observable.range(1, 5) + .reduceWith(new Callable() { + @Override + public Integer call() throws Exception { + return 0; + } + }, new BiFunction() { + @Override + public Integer apply(Integer a, Integer b) throws Exception { + return a + b; + } + }) + .test() + .assertResult(15); + } + @Test + public void reduceMaybeDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservableToMaybe(new Function, MaybeSource>() { + @Override + public MaybeSource apply(Observable o) + throws Exception { + return o.reduce(new BiFunction() { + @Override + public Object apply(Object a, Object b) throws Exception { + return a; + } + }); + } + }); + } + + @Test + public void reduceMaybeCheckDisposed() { + TestHelper.checkDisposed(Observable.just(new Object()).reduce(new BiFunction() { + @Override + public Object apply(Object a, Object b) throws Exception { + return a; + } + })); + } + + @Test + public void reduceMaybeBadSource() { + List errors = TestHelper.trackPluginErrors(); + try { + new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); + observer.onNext(1); + observer.onError(new TestException()); + observer.onComplete(); + } + }.reduce(new BiFunction() { + @Override + public Object apply(Object a, Object b) throws Exception { + return a; + } + }) + .test() + .assertResult(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void seedDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservableToSingle(new Function, SingleSource>() { + @Override + public SingleSource apply(Observable o) + throws Exception { + return o.reduce(0, new BiFunction() { + @Override + public Integer apply(Integer a, Integer b) throws Exception { + return a; + } + }); + } + }); + } + + @Test + public void seedDisposed() { + TestHelper.checkDisposed(PublishSubject.create().reduce(0, new BiFunction() { + @Override + public Integer apply(Integer a, Integer b) throws Exception { + return a; + } + })); + } + + @Test + public void seedBadSource() { + List errors = TestHelper.trackPluginErrors(); + try { + new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); + observer.onNext(1); + observer.onError(new TestException()); + observer.onComplete(); + } + } + .reduce(0, new BiFunction() { + @Override + public Integer apply(Integer a, Integer b) throws Exception { + return a; + } + }) + .test() + .assertResult(0); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index d30435651c..abd93aa73b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -29,8 +29,10 @@ import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.util.ExceptionHelper; import io.reactivex.observables.ConnectableObservable; import io.reactivex.observers.TestObserver; import io.reactivex.schedulers.*; @@ -770,4 +772,178 @@ public void replayIsUnsubscribed() { assertTrue(((Disposable)co).isDisposed()); } + + static final class BadObservableSubscribe extends ConnectableObservable { + + @Override + public void connect(Consumer connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Observer observer) { + throw new TestException("subscribeActual"); + } + } + + static final class BadObservableDispose extends ConnectableObservable implements Disposable { + + @Override + public void dispose() { + throw new TestException("dispose"); + } + + @Override + public boolean isDisposed() { + return false; + } + + @Override + public void connect(Consumer connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Observer observer) { + } + } + + static final class BadObservableConnect extends ConnectableObservable { + + @Override + public void connect(Consumer connection) { + throw new TestException("connect"); + } + + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + } + } + + @Test + public void badSourceSubscribe() { + BadObservableSubscribe bo = new BadObservableSubscribe(); + + try { + bo.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } + + @Test + public void badSourceDispose() { + BadObservableDispose bo = new BadObservableDispose(); + + try { + bo.refCount() + .test() + .cancel(); + fail("Should have thrown"); + } catch (TestException expected) { + } + } + + @Test + public void badSourceConnect() { + BadObservableConnect bo = new BadObservableConnect(); + + try { + bo.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } + + static final class BadObservableSubscribe2 extends ConnectableObservable { + + int count; + + @Override + public void connect(Consumer connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Observer observer) { + if (++count == 1) { + observer.onSubscribe(Disposables.empty()); + } else { + throw new TestException("subscribeActual"); + } + } + } + + @Test + public void badSourceSubscribe2() { + BadObservableSubscribe2 bo = new BadObservableSubscribe2(); + + Observable o = bo.refCount(); + o.test(); + try { + o.test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } + + static final class BadObservableConnect2 extends ConnectableObservable + implements Disposable { + + @Override + public void connect(Consumer connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); + } + + @Override + public void dispose() { + throw new TestException("dispose"); + } + + @Override + public boolean isDisposed() { + return false; + } + } + + @Test + public void badSourceCompleteDisconnect() { + BadObservableConnect2 bo = new BadObservableConnect2(); + + try { + bo.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java index 15daa252e8..a738d40462 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java @@ -20,6 +20,7 @@ import org.junit.Test; import io.reactivex.*; +import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.observers.TestObserver; @@ -106,4 +107,12 @@ public ObservableSource apply(Observable f) throws Exception { } }); } + + @Test + public void error() { + Observable.error(new TestException()) + .takeLast(1) + .test() + .assertFailure(TestException.class); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java index eeaf5be0de..8319a74d97 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java @@ -582,4 +582,60 @@ public ObservableSource apply(Observable v) throws Exception { } }, false, 1, 1, 1); } + + @Test + public void boundaryError() { + BehaviorSubject.createDefault(1) + .window(Functions.justCallable(Observable.error(new TestException()))) + .test() + .assertValueCount(1) + .assertNotComplete() + .assertError(TestException.class); + } + + @Test + public void boundaryCallableCrashOnCall2() { + BehaviorSubject.createDefault(1) + .window(new Callable>() { + int calls; + @Override + public Observable call() throws Exception { + if (++calls == 2) { + throw new TestException(); + } + return Observable.just(1); + } + }) + .test() + .assertError(TestException.class) + .assertNotComplete(); + } + + @Test + public void oneWindow() { + PublishSubject ps = PublishSubject.create(); + + TestObserver> to = BehaviorSubject.createDefault(1) + .window(Functions.justCallable(ps)) + .take(1) + .test(); + + ps.onNext(1); + + to + .assertValueCount(1) + .assertNoErrors() + .assertComplete(); + } + + @Test + public void boundaryDirectDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>>() { + @Override + public Observable> apply(Observable f) + throws Exception { + return f.window(Observable.never()).takeLast(1); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java index 86e234961a..35a8bb3b60 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java @@ -28,6 +28,7 @@ import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.observers.*; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.TestScheduler; import io.reactivex.subjects.*; @@ -391,4 +392,35 @@ public Object apply(Observable o) throws Exception { } }, false, 1, 1, (Object[])null); } + + @Test + public void windowCloseIngoresCancel() { + List errors = TestHelper.trackPluginErrors(); + try { + BehaviorSubject.createDefault(1) + .window(BehaviorSubject.createDefault(1), new Function>() { + @Override + public Observable apply(Integer f) throws Exception { + return new Observable() { + @Override + protected void subscribeActual( + Observer s) { + s.onSubscribe(Disposables.empty()); + s.onNext(1); + s.onNext(2); + s.onError(new TestException()); + } + }; + } + }) + .test() + .assertValueCount(1) + .assertNoErrors() + .assertNotComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/schedulers/ExecutorSchedulerDelayedRunnableTest.java b/src/test/java/io/reactivex/internal/schedulers/ExecutorSchedulerDelayedRunnableTest.java new file mode 100644 index 0000000000..0356ed6cbf --- /dev/null +++ b/src/test/java/io/reactivex/internal/schedulers/ExecutorSchedulerDelayedRunnableTest.java @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.schedulers; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import io.reactivex.exceptions.TestException; +import io.reactivex.internal.schedulers.ExecutorScheduler.DelayedRunnable; + +public class ExecutorSchedulerDelayedRunnableTest { + + + @Test(expected = TestException.class) + public void delayedRunnableCrash() { + DelayedRunnable dl = new DelayedRunnable(new Runnable() { + @Override + public void run() { + throw new TestException(); + } + }); + dl.run(); + } + + @Test + public void dispose() { + final AtomicInteger count = new AtomicInteger(); + DelayedRunnable dl = new DelayedRunnable(new Runnable() { + @Override + public void run() { + count.incrementAndGet(); + } + }); + + dl.dispose(); + dl.dispose(); + + dl.run(); + + assertEquals(0, count.get()); + } +} diff --git a/src/test/java/io/reactivex/internal/schedulers/InstantPeriodicTaskTest.java b/src/test/java/io/reactivex/internal/schedulers/InstantPeriodicTaskTest.java new file mode 100644 index 0000000000..286be4e33a --- /dev/null +++ b/src/test/java/io/reactivex/internal/schedulers/InstantPeriodicTaskTest.java @@ -0,0 +1,277 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.reactivex.internal.schedulers; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.*; + +import org.junit.Test; + +import io.reactivex.TestHelper; +import io.reactivex.exceptions.TestException; +import io.reactivex.internal.functions.Functions; +import io.reactivex.plugins.RxJavaPlugins; + +public class InstantPeriodicTaskTest { + + @Test + public void taskCrash() throws Exception { + ExecutorService exec = Executors.newSingleThreadExecutor(); + List errors = TestHelper.trackPluginErrors(); + try { + + InstantPeriodicTask task = new InstantPeriodicTask(new Runnable() { + @Override + public void run() { + throw new TestException(); + } + }, exec); + + assertNull(task.call()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + exec.shutdownNow(); + RxJavaPlugins.reset(); + } + } + + @Test + public void dispose() throws Exception { + ExecutorService exec = Executors.newSingleThreadExecutor(); + try { + + InstantPeriodicTask task = new InstantPeriodicTask(new Runnable() { + @Override + public void run() { + throw new TestException(); + } + }, exec); + + assertFalse(task.isDisposed()); + + task.dispose(); + + assertTrue(task.isDisposed()); + + task.dispose(); + + assertTrue(task.isDisposed()); + } finally { + exec.shutdownNow(); + RxJavaPlugins.reset(); + } + } + + @Test + public void dispose2() throws Exception { + ExecutorService exec = Executors.newSingleThreadExecutor(); + try { + + InstantPeriodicTask task = new InstantPeriodicTask(new Runnable() { + @Override + public void run() { + throw new TestException(); + } + }, exec); + + task.setFirst(new FutureTask(Functions.EMPTY_RUNNABLE, null)); + task.setRest(new FutureTask(Functions.EMPTY_RUNNABLE, null)); + + assertFalse(task.isDisposed()); + + task.dispose(); + + assertTrue(task.isDisposed()); + + task.dispose(); + + assertTrue(task.isDisposed()); + } finally { + exec.shutdownNow(); + RxJavaPlugins.reset(); + } + } + + @Test + public void dispose2CurrentThread() throws Exception { + ExecutorService exec = Executors.newSingleThreadExecutor(); + try { + + InstantPeriodicTask task = new InstantPeriodicTask(new Runnable() { + @Override + public void run() { + throw new TestException(); + } + }, exec); + + task.runner = Thread.currentThread(); + + task.setFirst(new FutureTask(Functions.EMPTY_RUNNABLE, null)); + task.setRest(new FutureTask(Functions.EMPTY_RUNNABLE, null)); + + assertFalse(task.isDisposed()); + + task.dispose(); + + assertTrue(task.isDisposed()); + + task.dispose(); + + assertTrue(task.isDisposed()); + } finally { + exec.shutdownNow(); + RxJavaPlugins.reset(); + } + } + + @Test + public void dispose3() throws Exception { + ExecutorService exec = Executors.newSingleThreadExecutor(); + try { + + InstantPeriodicTask task = new InstantPeriodicTask(new Runnable() { + @Override + public void run() { + throw new TestException(); + } + }, exec); + + task.dispose(); + + FutureTask f1 = new FutureTask(Functions.EMPTY_RUNNABLE, null); + task.setFirst(f1); + + assertTrue(f1.isCancelled()); + + FutureTask f2 = new FutureTask(Functions.EMPTY_RUNNABLE, null); + task.setRest(f2); + + assertTrue(f2.isCancelled()); + } finally { + exec.shutdownNow(); + RxJavaPlugins.reset(); + } + } + + @Test + public void disposeOnCurrentThread() throws Exception { + ExecutorService exec = Executors.newSingleThreadExecutor(); + try { + + InstantPeriodicTask task = new InstantPeriodicTask(new Runnable() { + @Override + public void run() { + throw new TestException(); + } + }, exec); + + task.runner = Thread.currentThread(); + + task.dispose(); + + FutureTask f1 = new FutureTask(Functions.EMPTY_RUNNABLE, null); + task.setFirst(f1); + + assertTrue(f1.isCancelled()); + + FutureTask f2 = new FutureTask(Functions.EMPTY_RUNNABLE, null); + task.setRest(f2); + + assertTrue(f2.isCancelled()); + } finally { + exec.shutdownNow(); + RxJavaPlugins.reset(); + } + } + + @Test + public void firstCancelRace() throws Exception { + ExecutorService exec = Executors.newSingleThreadExecutor(); + try { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final InstantPeriodicTask task = new InstantPeriodicTask(new Runnable() { + @Override + public void run() { + throw new TestException(); + } + }, exec); + + final FutureTask f1 = new FutureTask(Functions.EMPTY_RUNNABLE, null); + Runnable r1 = new Runnable() { + @Override + public void run() { + task.setFirst(f1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + task.dispose(); + } + }; + + TestHelper.race(r1, r2); + + assertTrue(f1.isCancelled()); + assertTrue(task.isDisposed()); + } + } finally { + exec.shutdownNow(); + RxJavaPlugins.reset(); + } + } + + @Test + public void restCancelRace() throws Exception { + ExecutorService exec = Executors.newSingleThreadExecutor(); + try { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final InstantPeriodicTask task = new InstantPeriodicTask(new Runnable() { + @Override + public void run() { + throw new TestException(); + } + }, exec); + + final FutureTask f1 = new FutureTask(Functions.EMPTY_RUNNABLE, null); + Runnable r1 = new Runnable() { + @Override + public void run() { + task.setRest(f1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + task.dispose(); + } + }; + + TestHelper.race(r1, r2); + + assertTrue(f1.isCancelled()); + assertTrue(task.isDisposed()); + } + } finally { + exec.shutdownNow(); + RxJavaPlugins.reset(); + } + } +} diff --git a/src/test/java/io/reactivex/internal/schedulers/SchedulerWhenTest.java b/src/test/java/io/reactivex/internal/schedulers/SchedulerWhenTest.java index 52ccdad85c..bbf97be11d 100644 --- a/src/test/java/io/reactivex/internal/schedulers/SchedulerWhenTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/SchedulerWhenTest.java @@ -13,20 +13,24 @@ package io.reactivex.internal.schedulers; -import static io.reactivex.Flowable.just; -import static io.reactivex.Flowable.merge; +import static io.reactivex.Flowable.*; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.*; import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; -import io.reactivex.Completable; -import io.reactivex.Flowable; -import io.reactivex.Scheduler; +import io.reactivex.*; +import io.reactivex.Scheduler.Worker; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; -import io.reactivex.schedulers.Schedulers; -import io.reactivex.schedulers.TestScheduler; +import io.reactivex.internal.schedulers.SchedulerWhen.*; +import io.reactivex.observers.DisposableCompletableObserver; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.schedulers.*; import io.reactivex.subscribers.TestSubscriber; public class SchedulerWhenTest { @@ -219,4 +223,174 @@ public Completable apply(Flowable> t) { merge(just(just(1).subscribeOn(limited).observeOn(comp)).repeat(1000)).blockingSubscribe(); } + + @Test + public void subscribedDisposable() { + SchedulerWhen.SUBSCRIBED.dispose(); + assertFalse(SchedulerWhen.SUBSCRIBED.isDisposed()); + } + + @Test(expected = TestException.class) + public void combineCrashInConstructor() { + new SchedulerWhen(new Function>, Completable>() { + @Override + public Completable apply(Flowable> v) + throws Exception { + throw new TestException(); + } + }, Schedulers.single()); + } + + @Test + public void disposed() { + SchedulerWhen sw = new SchedulerWhen(new Function>, Completable>() { + @Override + public Completable apply(Flowable> v) + throws Exception { + return Completable.never(); + } + }, Schedulers.single()); + + assertFalse(sw.isDisposed()); + + sw.dispose(); + + assertTrue(sw.isDisposed()); + } + + @Test + public void scheduledActiondisposedSetRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final ScheduledAction sa = new ScheduledAction() { + + private static final long serialVersionUID = -672980251643733156L; + + @Override + protected Disposable callActual(Worker actualWorker, + CompletableObserver actionCompletable) { + return Disposables.empty(); + } + + }; + + assertFalse(sa.isDisposed()); + + Runnable r1 = new Runnable() { + @Override + public void run() { + sa.dispose(); + } + }; + + TestHelper.race(r1, r1); + + assertTrue(sa.isDisposed()); + } + } + + @Test + public void scheduledActionStates() { + final AtomicInteger count = new AtomicInteger(); + ScheduledAction sa = new ScheduledAction() { + + private static final long serialVersionUID = -672980251643733156L; + + @Override + protected Disposable callActual(Worker actualWorker, + CompletableObserver actionCompletable) { + count.incrementAndGet(); + return Disposables.empty(); + } + + }; + + assertFalse(sa.isDisposed()); + + sa.dispose(); + + assertTrue(sa.isDisposed()); + + sa.dispose(); + + assertTrue(sa.isDisposed()); + + // should not run when disposed + sa.call(Schedulers.single().createWorker(), null); + + assertEquals(0, count.get()); + + // should not run when already scheduled + sa.set(Disposables.empty()); + + sa.call(Schedulers.single().createWorker(), null); + + assertEquals(0, count.get()); + + // disposed while in call + sa = new ScheduledAction() { + + private static final long serialVersionUID = -672980251643733156L; + + @Override + protected Disposable callActual(Worker actualWorker, + CompletableObserver actionCompletable) { + count.incrementAndGet(); + dispose(); + return Disposables.empty(); + } + + }; + + sa.call(Schedulers.single().createWorker(), null); + + assertEquals(1, count.get()); + } + + @Test + public void onCompleteActionRunCrash() { + final AtomicInteger count = new AtomicInteger(); + + OnCompletedAction a = new OnCompletedAction(new Runnable() { + @Override + public void run() { + throw new TestException(); + } + }, new DisposableCompletableObserver() { + + @Override + public void onComplete() { + count.incrementAndGet(); + } + + @Override + public void onError(Throwable e) { + count.decrementAndGet(); + e.printStackTrace(); + } + }); + + try { + a.run(); + fail("Should have thrown"); + } catch (TestException expected) { + + } + + assertEquals(1, count.get()); + } + + @Test + public void queueWorkerDispose() { + QueueWorker qw = new QueueWorker(PublishProcessor.create(), Schedulers.single().createWorker()); + + assertFalse(qw.isDisposed()); + + qw.dispose(); + + assertTrue(qw.isDisposed()); + + qw.dispose(); + + assertTrue(qw.isDisposed()); + } } diff --git a/src/test/java/io/reactivex/internal/subscribers/QueueDrainSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/QueueDrainSubscriberTest.java new file mode 100644 index 0000000000..d0360d6cd9 --- /dev/null +++ b/src/test/java/io/reactivex/internal/subscribers/QueueDrainSubscriberTest.java @@ -0,0 +1,336 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.subscribers; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.Test; +import org.reactivestreams.*; + +import io.reactivex.TestHelper; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.MissingBackpressureException; +import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subscribers.TestSubscriber; + +public class QueueDrainSubscriberTest { + + static final QueueDrainSubscriber createUnordered(TestSubscriber ts, final Disposable d) { + return new QueueDrainSubscriber(ts, new SpscArrayQueue(4)) { + @Override + public void onNext(Integer t) { + fastPathEmitMax(t, false, d); + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onComplete() { + } + + @Override + public void onSubscribe(Subscription s) { + } + + @Override + public boolean accept(Subscriber a, Integer v) { + super.accept(a, v); + a.onNext(v); + return true; + } + }; + } + + static final QueueDrainSubscriber createOrdered(TestSubscriber ts, final Disposable d) { + return new QueueDrainSubscriber(ts, new SpscArrayQueue(4)) { + @Override + public void onNext(Integer t) { + fastPathOrderedEmitMax(t, false, d); + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onComplete() { + } + + @Override + public void onSubscribe(Subscription s) { + } + + @Override + public boolean accept(Subscriber a, Integer v) { + super.accept(a, v); + a.onNext(v); + return true; + } + }; + } + + static final QueueDrainSubscriber createUnorderedReject(TestSubscriber ts, final Disposable d) { + return new QueueDrainSubscriber(ts, new SpscArrayQueue(4)) { + @Override + public void onNext(Integer t) { + fastPathEmitMax(t, false, d); + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onComplete() { + } + + @Override + public void onSubscribe(Subscription s) { + } + + @Override + public boolean accept(Subscriber a, Integer v) { + super.accept(a, v); + a.onNext(v); + return false; + } + }; + } + + static final QueueDrainSubscriber createOrderedReject(TestSubscriber ts, final Disposable d) { + return new QueueDrainSubscriber(ts, new SpscArrayQueue(4)) { + @Override + public void onNext(Integer t) { + fastPathOrderedEmitMax(t, false, d); + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onComplete() { + } + + @Override + public void onSubscribe(Subscription s) { + } + + @Override + public boolean accept(Subscriber a, Integer v) { + super.accept(a, v); + a.onNext(v); + return false; + } + }; + } + + @Test + public void unorderedFastPathNoRequest() { + TestSubscriber ts = new TestSubscriber(0); + Disposable d = Disposables.empty(); + QueueDrainSubscriber qd = createUnordered(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.onNext(1); + + ts.assertFailure(MissingBackpressureException.class); + + assertTrue(d.isDisposed()); + } + + @Test + public void orderedFastPathNoRequest() { + TestSubscriber ts = new TestSubscriber(0); + Disposable d = Disposables.empty(); + QueueDrainSubscriber qd = createOrdered(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.onNext(1); + + ts.assertFailure(MissingBackpressureException.class); + + assertTrue(d.isDisposed()); + } + + @Test + public void acceptBadRequest() { + TestSubscriber ts = new TestSubscriber(0); + Disposable d = Disposables.empty(); + QueueDrainSubscriber qd = createUnordered(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + assertTrue(qd.accept(ts, 0)); + + List errors = TestHelper.trackPluginErrors(); + try { + qd.requested(-1); + TestHelper.assertError(errors, 0, IllegalArgumentException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void unorderedFastPathRequest1() { + TestSubscriber ts = new TestSubscriber(1); + Disposable d = Disposables.empty(); + QueueDrainSubscriber qd = createUnordered(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.requested(1); + + qd.onNext(1); + + ts.assertValuesOnly(1); + } + + @Test + public void orderedFastPathRequest1() { + TestSubscriber ts = new TestSubscriber(1); + Disposable d = Disposables.empty(); + QueueDrainSubscriber qd = createOrdered(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.requested(1); + + qd.onNext(1); + + ts.assertValuesOnly(1); + } + + @Test + public void unorderedSlowPath() { + TestSubscriber ts = new TestSubscriber(1); + Disposable d = Disposables.empty(); + QueueDrainSubscriber qd = createUnordered(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.enter(); + qd.onNext(1); + + ts.assertEmpty(); + } + + @Test + public void orderedSlowPath() { + TestSubscriber ts = new TestSubscriber(1); + Disposable d = Disposables.empty(); + QueueDrainSubscriber qd = createOrdered(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.enter(); + qd.onNext(1); + + ts.assertEmpty(); + } + + @Test + public void orderedSlowPathNonEmptyQueue() { + TestSubscriber ts = new TestSubscriber(1); + Disposable d = Disposables.empty(); + QueueDrainSubscriber qd = createOrdered(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.queue.offer(0); + qd.requested(2); + qd.onNext(1); + + ts.assertValuesOnly(0, 1); + } + + @Test + public void unorderedOnNextRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + TestSubscriber ts = new TestSubscriber(1); + Disposable d = Disposables.empty(); + final QueueDrainSubscriber qd = createUnordered(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.requested(Long.MAX_VALUE); + Runnable r1 = new Runnable() { + @Override + public void run() { + qd.onNext(1); + } + }; + + TestHelper.race(r1, r1); + + ts.assertValuesOnly(1, 1); + } + } + + @Test + public void orderedOnNextRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + TestSubscriber ts = new TestSubscriber(1); + Disposable d = Disposables.empty(); + final QueueDrainSubscriber qd = createOrdered(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.requested(Long.MAX_VALUE); + Runnable r1 = new Runnable() { + @Override + public void run() { + qd.onNext(1); + } + }; + + TestHelper.race(r1, r1); + + ts.assertValuesOnly(1, 1); + } + } + + @Test + public void unorderedFastPathReject() { + TestSubscriber ts = new TestSubscriber(1); + Disposable d = Disposables.empty(); + QueueDrainSubscriber qd = createUnorderedReject(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.requested(1); + + qd.onNext(1); + + ts.assertValuesOnly(1); + + assertEquals(1, qd.requested()); + } + + @Test + public void orderedFastPathReject() { + TestSubscriber ts = new TestSubscriber(1); + Disposable d = Disposables.empty(); + QueueDrainSubscriber qd = createOrderedReject(ts, d); + ts.onSubscribe(new BooleanSubscription()); + + qd.requested(1); + + qd.onNext(1); + + ts.assertValuesOnly(1); + + assertEquals(1, qd.requested()); + } +} diff --git a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java index ba52d0c806..fd2677207f 100644 --- a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java +++ b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java @@ -13,31 +13,26 @@ package io.reactivex.processors; -import io.reactivex.Flowable; -import io.reactivex.Scheduler; -import io.reactivex.TestHelper; -import io.reactivex.exceptions.MissingBackpressureException; -import io.reactivex.exceptions.TestException; -import io.reactivex.functions.Function; -import io.reactivex.internal.subscriptions.BooleanSubscription; -import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; -import io.reactivex.subscribers.DefaultSubscriber; -import io.reactivex.subscribers.TestSubscriber; -import org.junit.Assert; -import org.junit.Test; -import org.mockito.InOrder; -import org.mockito.Mockito; -import org.reactivestreams.Subscriber; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; +import org.junit.*; +import org.mockito.*; +import org.reactivestreams.Subscriber; + +import io.reactivex.*; +import io.reactivex.exceptions.*; +import io.reactivex.functions.Function; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.BehaviorProcessor.BehaviorSubscription; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.subscribers.*; public class BehaviorProcessorTest extends FlowableProcessorTest { @@ -369,7 +364,7 @@ public void testTakeOneSubscriber() { // FIXME RS subscribers are not allowed to throw // @Test // public void testOnErrorThrowsDoesntPreventDelivery() { -// BehaviorSubject ps = BehaviorSubject.create(); +// BehaviorProcessor ps = BehaviorProcessor.create(); // // ps.subscribe(); // TestSubscriber ts = new TestSubscriber(); @@ -391,7 +386,7 @@ public void testTakeOneSubscriber() { // */ // @Test // public void testOnErrorThrowsDoesntPreventDelivery2() { -// BehaviorSubject ps = BehaviorSubject.create(); +// BehaviorProcessor ps = BehaviorProcessor.create(); // // ps.subscribe(); // ps.subscribe(); @@ -845,4 +840,129 @@ public void run() { } } } + + @Test + public void behaviorDisposableDisposeState() { + BehaviorProcessor bp = BehaviorProcessor.create(); + bp.onNext(1); + + TestSubscriber ts = new TestSubscriber(); + + BehaviorSubscription bs = new BehaviorSubscription(ts, bp); + ts.onSubscribe(bs); + + assertFalse(bs.cancelled); + + bs.cancel(); + + assertTrue(bs.cancelled); + + bs.cancel(); + + assertTrue(bs.cancelled); + + assertTrue(bs.test(2)); + + bs.emitFirst(); + + ts.assertEmpty(); + + bs.emitNext(2, 0); + } + + @Test + public void emitFirstDisposeRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + BehaviorProcessor bp = BehaviorProcessor.create(); + bp.onNext(1); + + TestSubscriber ts = new TestSubscriber(); + + final BehaviorSubscription bs = new BehaviorSubscription(ts, bp); + ts.onSubscribe(bs); + + Runnable r1 = new Runnable() { + @Override + public void run() { + bs.emitFirst(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + bs.cancel(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void emitNextDisposeRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + BehaviorProcessor bp = BehaviorProcessor.create(); + bp.onNext(1); + + TestSubscriber ts = new TestSubscriber(); + + final BehaviorSubscription bs = new BehaviorSubscription(ts, bp); + ts.onSubscribe(bs); + + Runnable r1 = new Runnable() { + @Override + public void run() { + bs.emitNext(2, 0); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + bs.cancel(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void emittingEmitNext() { + BehaviorProcessor bp = BehaviorProcessor.create(); + bp.onNext(1); + + TestSubscriber ts = new TestSubscriber(); + + final BehaviorSubscription bs = new BehaviorSubscription(ts, bp); + ts.onSubscribe(bs); + + bs.emitting = true; + bs.emitNext(2, 1); + bs.emitNext(3, 2); + + assertNotNull(bs.queue); + } + + @Test + public void badRequest() { + List errors = TestHelper.trackPluginErrors(); + try { + BehaviorProcessor bp = BehaviorProcessor.create(); + bp.onNext(1); + + TestSubscriber ts = new TestSubscriber(); + + final BehaviorSubscription bs = new BehaviorSubscription(ts, bp); + ts.onSubscribe(bs); + + bs.request(-1); + + TestHelper.assertError(errors, 0, IllegalArgumentException.class); + } finally { + RxJavaPlugins.reset(); + } + } + } diff --git a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java index cc0b6ae05d..1d57599d16 100644 --- a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java @@ -31,6 +31,7 @@ import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; +import io.reactivex.subjects.BehaviorSubject.BehaviorDisposable; public class BehaviorSubjectTest extends SubjectTest { @@ -771,4 +772,108 @@ public void run() { ts.assertFailure(TestException.class); } } + + @Test + public void behaviorDisposableDisposeState() { + BehaviorSubject bs = BehaviorSubject.create(); + bs.onNext(1); + + TestObserver to = new TestObserver(); + + BehaviorDisposable bd = new BehaviorDisposable(to, bs); + to.onSubscribe(bd); + + assertFalse(bd.isDisposed()); + + bd.dispose(); + + assertTrue(bd.isDisposed()); + + bd.dispose(); + + assertTrue(bd.isDisposed()); + + assertTrue(bd.test(2)); + + bd.emitFirst(); + + to.assertEmpty(); + + bd.emitNext(2, 0); + } + + @Test + public void emitFirstDisposeRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + BehaviorSubject bs = BehaviorSubject.create(); + bs.onNext(1); + + TestObserver to = new TestObserver(); + + final BehaviorDisposable bd = new BehaviorDisposable(to, bs); + to.onSubscribe(bd); + + Runnable r1 = new Runnable() { + @Override + public void run() { + bd.emitFirst(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + bd.dispose(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void emitNextDisposeRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + BehaviorSubject bs = BehaviorSubject.create(); + bs.onNext(1); + + TestObserver to = new TestObserver(); + + final BehaviorDisposable bd = new BehaviorDisposable(to, bs); + to.onSubscribe(bd); + + Runnable r1 = new Runnable() { + @Override + public void run() { + bd.emitNext(2, 0); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + bd.dispose(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void emittingEmitNext() { + BehaviorSubject bs = BehaviorSubject.create(); + bs.onNext(1); + + TestObserver to = new TestObserver(); + + final BehaviorDisposable bd = new BehaviorDisposable(to, bs); + to.onSubscribe(bd); + + bd.emitting = true; + bd.emitNext(2, 1); + bd.emitNext(3, 2); + + assertNotNull(bd.queue); + } } From a267d7efdfe58b5727b5af22070ba3d953fe060a Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 4 Mar 2018 14:38:27 +0100 Subject: [PATCH 118/417] 2.x: Upgrade the algo of Observable.timeout(time|selector) operators (#5886) --- .../disposables/ObserverFullArbiter.java | 180 -------- .../observers/FullArbiterObserver.java | 56 --- .../observable/ObservableTimeout.java | 404 ++++++++++-------- .../observable/ObservableTimeoutTimed.java | 297 ++++++------- .../disposables/ObserverFullArbiterTest.java | 128 ------ .../observers/FullArbiterObserverTest.java | 48 --- .../FlowableTimeoutWithSelectorTest.java | 170 ++++++-- .../observable/ObservableTimeoutTests.java | 91 +++- .../ObservableTimeoutWithSelectorTest.java | 314 +++++++++++++- 9 files changed, 911 insertions(+), 777 deletions(-) delete mode 100644 src/main/java/io/reactivex/internal/disposables/ObserverFullArbiter.java delete mode 100644 src/main/java/io/reactivex/internal/observers/FullArbiterObserver.java delete mode 100644 src/test/java/io/reactivex/internal/disposables/ObserverFullArbiterTest.java delete mode 100644 src/test/java/io/reactivex/internal/observers/FullArbiterObserverTest.java diff --git a/src/main/java/io/reactivex/internal/disposables/ObserverFullArbiter.java b/src/main/java/io/reactivex/internal/disposables/ObserverFullArbiter.java deleted file mode 100644 index dd85b6b473..0000000000 --- a/src/main/java/io/reactivex/internal/disposables/ObserverFullArbiter.java +++ /dev/null @@ -1,180 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ - -package io.reactivex.internal.disposables; - -import java.util.concurrent.atomic.AtomicInteger; - -import io.reactivex.Observer; -import io.reactivex.disposables.Disposable; -import io.reactivex.internal.queue.SpscLinkedArrayQueue; -import io.reactivex.internal.util.NotificationLite; -import io.reactivex.plugins.RxJavaPlugins; - -/** - * Performs full arbitration of Subscriber events with strict drain (i.e., old emissions of another - * subscriber are dropped). - * - * @param the value type - */ -public final class ObserverFullArbiter extends FullArbiterPad1 implements Disposable { - final Observer actual; - final SpscLinkedArrayQueue queue; - - volatile Disposable s; - - Disposable resource; - - volatile boolean cancelled; - - public ObserverFullArbiter(Observer actual, Disposable resource, int capacity) { - this.actual = actual; - this.resource = resource; - this.queue = new SpscLinkedArrayQueue(capacity); - this.s = EmptyDisposable.INSTANCE; - } - - @Override - public void dispose() { - if (!cancelled) { - cancelled = true; - disposeResource(); - } - } - - @Override - public boolean isDisposed() { - Disposable d = resource; - return d != null ? d.isDisposed() : cancelled; - } - - void disposeResource() { - Disposable d = resource; - resource = null; - if (d != null) { - d.dispose(); - } - } - - public boolean setDisposable(Disposable s) { - if (cancelled) { - return false; - } - - queue.offer(this.s, NotificationLite.disposable(s)); - drain(); - return true; - } - - public boolean onNext(T value, Disposable s) { - if (cancelled) { - return false; - } - - queue.offer(s, NotificationLite.next(value)); - drain(); - return true; - } - - public void onError(Throwable value, Disposable s) { - if (cancelled) { - RxJavaPlugins.onError(value); - return; - } - queue.offer(s, NotificationLite.error(value)); - drain(); - } - - public void onComplete(Disposable s) { - queue.offer(s, NotificationLite.complete()); - drain(); - } - - void drain() { - if (wip.getAndIncrement() != 0) { - return; - } - - int missed = 1; - - final SpscLinkedArrayQueue q = queue; - final Observer a = actual; - - for (;;) { - - for (;;) { - Object o = q.poll(); - if (o == null) { - break; - } - - Object v = q.poll(); - - if (o == s) { - if (NotificationLite.isDisposable(v)) { - Disposable next = NotificationLite.getDisposable(v); - s.dispose(); - if (!cancelled) { - s = next; - } else { - next.dispose(); - } - } else if (NotificationLite.isError(v)) { - q.clear(); - disposeResource(); - - Throwable ex = NotificationLite.getError(v); - if (!cancelled) { - cancelled = true; - a.onError(ex); - } else { - RxJavaPlugins.onError(ex); - } - } else if (NotificationLite.isComplete(v)) { - q.clear(); - disposeResource(); - - if (!cancelled) { - cancelled = true; - a.onComplete(); - } - } else { - a.onNext(NotificationLite.getValue(v)); - } - } - } - - missed = wip.addAndGet(-missed); - if (missed == 0) { - break; - } - } - } -} - -/** Pads the object header away. */ -class FullArbiterPad0 { - volatile long p1a, p2a, p3a, p4a, p5a, p6a, p7a; - volatile long p8a, p9a, p10a, p11a, p12a, p13a, p14a, p15a; -} - -/** The work-in-progress counter. */ -class FullArbiterWip extends FullArbiterPad0 { - final AtomicInteger wip = new AtomicInteger(); -} - -/** Pads the wip counter away. */ -class FullArbiterPad1 extends FullArbiterWip { - volatile long p1b, p2b, p3b, p4b, p5b, p6b, p7b; - volatile long p8b, p9b, p10b, p11b, p12b, p13b, p14b, p15b; -} diff --git a/src/main/java/io/reactivex/internal/observers/FullArbiterObserver.java b/src/main/java/io/reactivex/internal/observers/FullArbiterObserver.java deleted file mode 100644 index 79b1bd723d..0000000000 --- a/src/main/java/io/reactivex/internal/observers/FullArbiterObserver.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ - -package io.reactivex.internal.observers; - -import io.reactivex.Observer; -import io.reactivex.disposables.Disposable; -import io.reactivex.internal.disposables.*; - -/** - * Subscriber that communicates with a FullArbiter. - * - * @param the value type - */ -public final class FullArbiterObserver implements Observer { - final ObserverFullArbiter arbiter; - - Disposable s; - - public FullArbiterObserver(ObserverFullArbiter arbiter) { - this.arbiter = arbiter; - } - - @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - arbiter.setDisposable(s); - } - } - - @Override - public void onNext(T t) { - arbiter.onNext(t, s); - } - - @Override - public void onError(Throwable t) { - arbiter.onError(t, s); - } - - @Override - public void onComplete() { - arbiter.onComplete(s); - } -} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java index e3b76736e6..5cfcb620ba 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java @@ -13,17 +13,16 @@ package io.reactivex.internal.operators.observable; -import io.reactivex.internal.functions.ObjectHelper; import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.*; import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; import io.reactivex.internal.disposables.*; -import io.reactivex.internal.observers.FullArbiterObserver; -import io.reactivex.observers.*; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.operators.observable.ObservableTimeoutTimed.TimeoutSupport; import io.reactivex.plugins.RxJavaPlugins; public final class ObservableTimeout extends AbstractObservableWithUpstream { @@ -32,10 +31,10 @@ public final class ObservableTimeout extends AbstractObservableWithUpst final ObservableSource other; public ObservableTimeout( - ObservableSource source, + Observable source, ObservableSource firstTimeoutIndicator, Function> itemTimeoutIndicator, - ObservableSource other) { + ObservableSource other) { super(source); this.firstTimeoutIndicator = firstTimeoutIndicator; this.itemTimeoutIndicator = itemTimeoutIndicator; @@ -43,306 +42,337 @@ public ObservableTimeout( } @Override - public void subscribeActual(Observer t) { + protected void subscribeActual(Observer s) { if (other == null) { - source.subscribe(new TimeoutObserver( - new SerializedObserver(t), - firstTimeoutIndicator, itemTimeoutIndicator)); + TimeoutObserver parent = new TimeoutObserver(s, itemTimeoutIndicator); + s.onSubscribe(parent); + parent.startFirstTimeout(firstTimeoutIndicator); + source.subscribe(parent); } else { - source.subscribe(new TimeoutOtherObserver( - t, firstTimeoutIndicator, itemTimeoutIndicator, other)); + TimeoutFallbackObserver parent = new TimeoutFallbackObserver(s, itemTimeoutIndicator, other); + s.onSubscribe(parent); + parent.startFirstTimeout(firstTimeoutIndicator); + source.subscribe(parent); } } - static final class TimeoutObserver - extends AtomicReference - implements Observer, Disposable, OnTimeout { + interface TimeoutSelectorSupport extends TimeoutSupport { + void onTimeoutError(long idx, Throwable ex); + } + + static final class TimeoutObserver extends AtomicLong + implements Observer, Disposable, TimeoutSelectorSupport { + + private static final long serialVersionUID = 3764492702657003550L; - private static final long serialVersionUID = 2672739326310051084L; final Observer actual; - final ObservableSource firstTimeoutIndicator; - final Function> itemTimeoutIndicator; - Disposable s; + final Function> itemTimeoutIndicator; - volatile long index; + final SequentialDisposable task; - TimeoutObserver(Observer actual, - ObservableSource firstTimeoutIndicator, - Function> itemTimeoutIndicator) { + final AtomicReference upstream; + + TimeoutObserver(Observer actual, Function> itemTimeoutIndicator) { this.actual = actual; - this.firstTimeoutIndicator = firstTimeoutIndicator; this.itemTimeoutIndicator = itemTimeoutIndicator; + this.task = new SequentialDisposable(); + this.upstream = new AtomicReference(); } @Override public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - - Observer a = actual; - - ObservableSource p = firstTimeoutIndicator; - - if (p != null) { - TimeoutInnerObserver tis = new TimeoutInnerObserver(this, 0); - - if (compareAndSet(null, tis)) { - a.onSubscribe(this); - p.subscribe(tis); - } - } else { - a.onSubscribe(this); - } - } + DisposableHelper.setOnce(upstream, s); } @Override public void onNext(T t) { - long idx = index + 1; - index = idx; - - actual.onNext(t); + long idx = get(); + if (idx == Long.MAX_VALUE || !compareAndSet(idx, idx + 1)) { + return; + } - Disposable d = get(); + Disposable d = task.get(); if (d != null) { d.dispose(); } - ObservableSource p; + actual.onNext(t); + + ObservableSource itemTimeoutObservableSource; try { - p = ObjectHelper.requireNonNull(itemTimeoutIndicator.apply(t), "The ObservableSource returned is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - dispose(); - actual.onError(e); + itemTimeoutObservableSource = ObjectHelper.requireNonNull( + itemTimeoutIndicator.apply(t), + "The itemTimeoutIndicator returned a null ObservableSource."); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.get().dispose(); + getAndSet(Long.MAX_VALUE); + actual.onError(ex); return; } - TimeoutInnerObserver tis = new TimeoutInnerObserver(this, idx); + TimeoutConsumer consumer = new TimeoutConsumer(idx + 1, this); + if (task.replace(consumer)) { + itemTimeoutObservableSource.subscribe(consumer); + } + } - if (compareAndSet(d, tis)) { - p.subscribe(tis); + void startFirstTimeout(ObservableSource firstTimeoutIndicator) { + if (firstTimeoutIndicator != null) { + TimeoutConsumer consumer = new TimeoutConsumer(0L, this); + if (task.replace(consumer)) { + firstTimeoutIndicator.subscribe(consumer); + } } } @Override public void onError(Throwable t) { - DisposableHelper.dispose(this); - actual.onError(t); + if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onError(t); + } else { + RxJavaPlugins.onError(t); + } } @Override public void onComplete() { - DisposableHelper.dispose(this); - actual.onComplete(); - } + if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); - @Override - public void dispose() { - if (DisposableHelper.dispose(this)) { - s.dispose(); + actual.onComplete(); } } @Override - public boolean isDisposed() { - return s.isDisposed(); - } + public void onTimeout(long idx) { + if (compareAndSet(idx, Long.MAX_VALUE)) { + DisposableHelper.dispose(upstream); - @Override - public void timeout(long idx) { - if (idx == index) { - dispose(); actual.onError(new TimeoutException()); } } @Override - public void innerError(Throwable e) { - s.dispose(); - actual.onError(e); - } - } - - interface OnTimeout { - void timeout(long index); - - void innerError(Throwable e); - } - - static final class TimeoutInnerObserver extends DisposableObserver { - final OnTimeout parent; - final long index; + public void onTimeoutError(long idx, Throwable ex) { + if (compareAndSet(idx, Long.MAX_VALUE)) { + DisposableHelper.dispose(upstream); - boolean done; - - TimeoutInnerObserver(OnTimeout parent, final long index) { - this.parent = parent; - this.index = index; - } - - @Override - public void onNext(Object t) { - if (done) { - return; + actual.onError(ex); + } else { + RxJavaPlugins.onError(ex); } - done = true; - dispose(); - parent.timeout(index); } @Override - public void onError(Throwable t) { - if (done) { - RxJavaPlugins.onError(t); - return; - } - done = true; - parent.innerError(t); + public void dispose() { + DisposableHelper.dispose(upstream); + task.dispose(); } @Override - public void onComplete() { - if (done) { - return; - } - done = true; - parent.timeout(index); + public boolean isDisposed() { + return DisposableHelper.isDisposed(upstream.get()); } } - static final class TimeoutOtherObserver + static final class TimeoutFallbackObserver extends AtomicReference - implements Observer, Disposable, OnTimeout { + implements Observer, Disposable, TimeoutSelectorSupport { + + private static final long serialVersionUID = -7508389464265974549L; - private static final long serialVersionUID = -1957813281749686898L; final Observer actual; - final ObservableSource firstTimeoutIndicator; - final Function> itemTimeoutIndicator; - final ObservableSource other; - final ObserverFullArbiter arbiter; - Disposable s; + final Function> itemTimeoutIndicator; + + final SequentialDisposable task; - boolean done; + final AtomicLong index; - volatile long index; + final AtomicReference upstream; - TimeoutOtherObserver(Observer actual, - ObservableSource firstTimeoutIndicator, - Function> itemTimeoutIndicator, ObservableSource other) { + ObservableSource fallback; + + TimeoutFallbackObserver(Observer actual, + Function> itemTimeoutIndicator, + ObservableSource fallback) { this.actual = actual; - this.firstTimeoutIndicator = firstTimeoutIndicator; this.itemTimeoutIndicator = itemTimeoutIndicator; - this.other = other; - this.arbiter = new ObserverFullArbiter(actual, this, 8); + this.task = new SequentialDisposable(); + this.fallback = fallback; + this.index = new AtomicLong(); + this.upstream = new AtomicReference(); } @Override public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - - arbiter.setDisposable(s); - - Observer a = actual; - - ObservableSource p = firstTimeoutIndicator; - - if (p != null) { - TimeoutInnerObserver tis = new TimeoutInnerObserver(this, 0); - - if (compareAndSet(null, tis)) { - a.onSubscribe(arbiter); - p.subscribe(tis); - } - } else { - a.onSubscribe(arbiter); - } - } + DisposableHelper.setOnce(upstream, s); } @Override public void onNext(T t) { - if (done) { - return; - } - long idx = index + 1; - index = idx; - - if (!arbiter.onNext(t, s)) { + long idx = index.get(); + if (idx == Long.MAX_VALUE || !index.compareAndSet(idx, idx + 1)) { return; } - Disposable d = get(); + Disposable d = task.get(); if (d != null) { d.dispose(); } - ObservableSource p; + actual.onNext(t); + + ObservableSource itemTimeoutObservableSource; try { - p = ObjectHelper.requireNonNull(itemTimeoutIndicator.apply(t), "The ObservableSource returned is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - actual.onError(e); + itemTimeoutObservableSource = ObjectHelper.requireNonNull( + itemTimeoutIndicator.apply(t), + "The itemTimeoutIndicator returned a null ObservableSource."); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.get().dispose(); + index.getAndSet(Long.MAX_VALUE); + actual.onError(ex); return; } - TimeoutInnerObserver tis = new TimeoutInnerObserver(this, idx); + TimeoutConsumer consumer = new TimeoutConsumer(idx + 1, this); + if (task.replace(consumer)) { + itemTimeoutObservableSource.subscribe(consumer); + } + } - if (compareAndSet(d, tis)) { - p.subscribe(tis); + void startFirstTimeout(ObservableSource firstTimeoutIndicator) { + if (firstTimeoutIndicator != null) { + TimeoutConsumer consumer = new TimeoutConsumer(0L, this); + if (task.replace(consumer)) { + firstTimeoutIndicator.subscribe(consumer); + } } } @Override public void onError(Throwable t) { - if (done) { + if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onError(t); + + task.dispose(); + } else { RxJavaPlugins.onError(t); - return; } - done = true; - dispose(); - arbiter.onError(t, s); } @Override public void onComplete() { - if (done) { - return; + if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onComplete(); + + task.dispose(); } - done = true; - dispose(); - arbiter.onComplete(s); } @Override - public void dispose() { - if (DisposableHelper.dispose(this)) { - s.dispose(); + public void onTimeout(long idx) { + if (index.compareAndSet(idx, Long.MAX_VALUE)) { + DisposableHelper.dispose(upstream); + + ObservableSource f = fallback; + fallback = null; + + f.subscribe(new ObservableTimeoutTimed.FallbackObserver(actual, this)); } } + @Override + public void onTimeoutError(long idx, Throwable ex) { + if (index.compareAndSet(idx, Long.MAX_VALUE)) { + DisposableHelper.dispose(this); + + actual.onError(ex); + } else { + RxJavaPlugins.onError(ex); + } + } + + @Override + public void dispose() { + DisposableHelper.dispose(upstream); + DisposableHelper.dispose(this); + task.dispose(); + } + @Override public boolean isDisposed() { - return s.isDisposed(); + return DisposableHelper.isDisposed(get()); + } + } + + static final class TimeoutConsumer extends AtomicReference + implements Observer, Disposable { + + private static final long serialVersionUID = 8708641127342403073L; + + final TimeoutSelectorSupport parent; + + final long idx; + + TimeoutConsumer(long idx, TimeoutSelectorSupport parent) { + this.idx = idx; + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable s) { + DisposableHelper.setOnce(this, s); + } + + @Override + public void onNext(Object t) { + Disposable upstream = get(); + if (upstream != DisposableHelper.DISPOSED) { + upstream.dispose(); + lazySet(DisposableHelper.DISPOSED); + parent.onTimeout(idx); + } } @Override - public void timeout(long idx) { - if (idx == index) { - dispose(); - other.subscribe(new FullArbiterObserver(arbiter)); + public void onError(Throwable t) { + if (get() != DisposableHelper.DISPOSED) { + lazySet(DisposableHelper.DISPOSED); + parent.onTimeoutError(idx, t); + } else { + RxJavaPlugins.onError(t); } } @Override - public void innerError(Throwable e) { - s.dispose(); - actual.onError(e); + public void onComplete() { + if (get() != DisposableHelper.DISPOSED) { + lazySet(DisposableHelper.DISPOSED); + parent.onTimeout(idx); + } + } + + @Override + public void dispose() { + DisposableHelper.dispose(this); + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(this.get()); } } + } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java index 0c152df34d..fdca2d3882 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java @@ -14,14 +14,11 @@ package io.reactivex.internal.operators.observable; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.*; import io.reactivex.*; -import io.reactivex.Scheduler.Worker; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.*; -import io.reactivex.internal.observers.FullArbiterObserver; -import io.reactivex.observers.SerializedObserver; import io.reactivex.plugins.RxJavaPlugins; public final class ObservableTimeoutTimed extends AbstractObservableWithUpstream { @@ -30,10 +27,7 @@ public final class ObservableTimeoutTimed extends AbstractObservableWithUpstr final Scheduler scheduler; final ObservableSource other; - - static final Disposable NEW_TIMER = new EmptyDisposable(); - - public ObservableTimeoutTimed(ObservableSource source, + public ObservableTimeoutTimed(Observable source, long timeout, TimeUnit unit, Scheduler scheduler, ObservableSource other) { super(source); this.timeout = timeout; @@ -43,265 +37,276 @@ public ObservableTimeoutTimed(ObservableSource source, } @Override - public void subscribeActual(Observer t) { + protected void subscribeActual(Observer s) { if (other == null) { - source.subscribe(new TimeoutTimedObserver( - new SerializedObserver(t), // because errors can race - timeout, unit, scheduler.createWorker())); + TimeoutObserver parent = new TimeoutObserver(s, timeout, unit, scheduler.createWorker()); + s.onSubscribe(parent); + parent.startTimeout(0L); + source.subscribe(parent); } else { - source.subscribe(new TimeoutTimedOtherObserver( - t, // the FullArbiter serializes - timeout, unit, scheduler.createWorker(), other)); + TimeoutFallbackObserver parent = new TimeoutFallbackObserver(s, timeout, unit, scheduler.createWorker(), other); + s.onSubscribe(parent); + parent.startTimeout(0L); + source.subscribe(parent); } } - static final class TimeoutTimedOtherObserver - extends AtomicReference implements Observer, Disposable { - private static final long serialVersionUID = -4619702551964128179L; + static final class TimeoutObserver extends AtomicLong + implements Observer, Disposable, TimeoutSupport { + + private static final long serialVersionUID = 3764492702657003550L; final Observer actual; + final long timeout; - final TimeUnit unit; - final Scheduler.Worker worker; - final ObservableSource other; - Disposable s; + final TimeUnit unit; - final ObserverFullArbiter arbiter; + final Scheduler.Worker worker; - volatile long index; + final SequentialDisposable task; - volatile boolean done; + final AtomicReference upstream; - TimeoutTimedOtherObserver(Observer actual, long timeout, TimeUnit unit, Worker worker, - ObservableSource other) { + TimeoutObserver(Observer actual, long timeout, TimeUnit unit, Scheduler.Worker worker) { this.actual = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; - this.other = other; - this.arbiter = new ObserverFullArbiter(actual, this, 8); + this.task = new SequentialDisposable(); + this.upstream = new AtomicReference(); } @Override public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - if (arbiter.setDisposable(s)) { - actual.onSubscribe(arbiter); - - scheduleTimeout(0L); - } - } - + DisposableHelper.setOnce(upstream, s); } @Override public void onNext(T t) { - if (done) { + long idx = get(); + if (idx == Long.MAX_VALUE || !compareAndSet(idx, idx + 1)) { return; } - long idx = index + 1; - index = idx; - if (arbiter.onNext(t, s)) { - scheduleTimeout(idx); - } - } - - void scheduleTimeout(final long idx) { - Disposable d = get(); - if (d != null) { - d.dispose(); - } + task.get().dispose(); - if (compareAndSet(d, NEW_TIMER)) { - d = worker.schedule(new SubscribeNext(idx), timeout, unit); + actual.onNext(t); - DisposableHelper.replace(this, d); - } + startTimeout(idx + 1); } - void subscribeNext() { - other.subscribe(new FullArbiterObserver(arbiter)); + void startTimeout(long nextIndex) { + task.replace(worker.schedule(new TimeoutTask(nextIndex, this), timeout, unit)); } @Override public void onError(Throwable t) { - if (done) { + if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onError(t); + + worker.dispose(); + } else { RxJavaPlugins.onError(t); - return; } - done = true; - arbiter.onError(t, s); - worker.dispose(); } @Override public void onComplete() { - if (done) { - return; + if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onComplete(); + + worker.dispose(); + } + } + + @Override + public void onTimeout(long idx) { + if (compareAndSet(idx, Long.MAX_VALUE)) { + DisposableHelper.dispose(upstream); + + actual.onError(new TimeoutException()); + + worker.dispose(); } - done = true; - arbiter.onComplete(s); - worker.dispose(); } @Override public void dispose() { - s.dispose(); + DisposableHelper.dispose(upstream); worker.dispose(); } @Override public boolean isDisposed() { - return worker.isDisposed(); + return DisposableHelper.isDisposed(upstream.get()); } + } - final class SubscribeNext implements Runnable { - private final long idx; - SubscribeNext(long idx) { - this.idx = idx; - } + static final class TimeoutTask implements Runnable { - @Override - public void run() { - if (idx == index) { - done = true; - s.dispose(); - DisposableHelper.dispose(TimeoutTimedOtherObserver.this); + final TimeoutSupport parent; - subscribeNext(); + final long idx; - worker.dispose(); - } - } + TimeoutTask(long idx, TimeoutSupport parent) { + this.idx = idx; + this.parent = parent; + } + + @Override + public void run() { + parent.onTimeout(idx); } } - static final class TimeoutTimedObserver - extends AtomicReference - implements Observer, Disposable { - private static final long serialVersionUID = -8387234228317808253L; + static final class TimeoutFallbackObserver extends AtomicReference + implements Observer, Disposable, TimeoutSupport { + + private static final long serialVersionUID = 3764492702657003550L; final Observer actual; + final long timeout; + final TimeUnit unit; + final Scheduler.Worker worker; - Disposable s; + final SequentialDisposable task; + + final AtomicLong index; - volatile long index; + final AtomicReference upstream; - volatile boolean done; + ObservableSource fallback; - TimeoutTimedObserver(Observer actual, long timeout, TimeUnit unit, Worker worker) { + TimeoutFallbackObserver(Observer actual, long timeout, TimeUnit unit, + Scheduler.Worker worker, ObservableSource fallback) { this.actual = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; + this.fallback = fallback; + this.task = new SequentialDisposable(); + this.index = new AtomicLong(); + this.upstream = new AtomicReference(); } @Override public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); - scheduleTimeout(0L); - } - + DisposableHelper.setOnce(upstream, s); } @Override public void onNext(T t) { - if (done) { + long idx = index.get(); + if (idx == Long.MAX_VALUE || !index.compareAndSet(idx, idx + 1)) { return; } - long idx = index + 1; - index = idx; + + task.get().dispose(); actual.onNext(t); - scheduleTimeout(idx); + startTimeout(idx + 1); } - void scheduleTimeout(final long idx) { - Disposable d = get(); - if (d != null) { - d.dispose(); - } - - if (compareAndSet(d, NEW_TIMER)) { - d = worker.schedule(new TimeoutTask(idx), timeout, unit); - - DisposableHelper.replace(this, d); - } + void startTimeout(long nextIndex) { + task.replace(worker.schedule(new TimeoutTask(nextIndex, this), timeout, unit)); } @Override public void onError(Throwable t) { - if (done) { + if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onError(t); + + worker.dispose(); + } else { RxJavaPlugins.onError(t); - return; } - done = true; - - actual.onError(t); - dispose(); } @Override public void onComplete() { - if (done) { - return; + if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { + task.dispose(); + + actual.onComplete(); + + worker.dispose(); } - done = true; + } - actual.onComplete(); - dispose(); + @Override + public void onTimeout(long idx) { + if (index.compareAndSet(idx, Long.MAX_VALUE)) { + DisposableHelper.dispose(upstream); + + ObservableSource f = fallback; + fallback = null; + + f.subscribe(new FallbackObserver(actual, this)); + + worker.dispose(); + } } @Override public void dispose() { - s.dispose(); + DisposableHelper.dispose(upstream); + DisposableHelper.dispose(this); worker.dispose(); } @Override public boolean isDisposed() { - return worker.isDisposed(); + return DisposableHelper.isDisposed(get()); } + } - final class TimeoutTask implements Runnable { - private final long idx; + static final class FallbackObserver implements Observer { - TimeoutTask(long idx) { - this.idx = idx; - } + final Observer actual; - @Override - public void run() { - if (idx == index) { - done = true; - s.dispose(); - DisposableHelper.dispose(TimeoutTimedObserver.this); + final AtomicReference arbiter; - actual.onError(new TimeoutException()); + FallbackObserver(Observer actual, AtomicReference arbiter) { + this.actual = actual; + this.arbiter = arbiter; + } - worker.dispose(); - } - } + @Override + public void onSubscribe(Disposable s) { + DisposableHelper.replace(arbiter, s); } - } - static final class EmptyDisposable implements Disposable { @Override - public void dispose() { } + public void onNext(T t) { + actual.onNext(t); + } @Override - public boolean isDisposed() { - return true; + public void onError(Throwable t) { + actual.onError(t); } + + @Override + public void onComplete() { + actual.onComplete(); + } + } + + interface TimeoutSupport { + + void onTimeout(long idx); + } } diff --git a/src/test/java/io/reactivex/internal/disposables/ObserverFullArbiterTest.java b/src/test/java/io/reactivex/internal/disposables/ObserverFullArbiterTest.java deleted file mode 100644 index 48d3507d7c..0000000000 --- a/src/test/java/io/reactivex/internal/disposables/ObserverFullArbiterTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ - -package io.reactivex.internal.disposables; - -import static org.junit.Assert.*; - -import java.util.List; - -import org.junit.Test; - -import io.reactivex.TestHelper; -import io.reactivex.disposables.*; -import io.reactivex.exceptions.TestException; -import io.reactivex.internal.disposables.ObserverFullArbiter; -import io.reactivex.internal.util.NotificationLite; -import io.reactivex.observers.TestObserver; -import io.reactivex.plugins.RxJavaPlugins; - -public class ObserverFullArbiterTest { - - @Test - public void setSubscriptionAfterCancel() { - ObserverFullArbiter fa = new ObserverFullArbiter(new TestObserver(), null, 128); - - fa.dispose(); - - Disposable bs = Disposables.empty(); - - assertFalse(fa.setDisposable(bs)); - - assertFalse(fa.setDisposable(null)); - } - - @Test - public void cancelAfterPoll() { - ObserverFullArbiter fa = new ObserverFullArbiter(new TestObserver(), null, 128); - - Disposable bs = Disposables.empty(); - - fa.queue.offer(fa.s, NotificationLite.disposable(bs)); - - assertFalse(fa.isDisposed()); - - fa.dispose(); - - assertTrue(fa.isDisposed()); - - fa.drain(); - - assertTrue(bs.isDisposed()); - } - - @Test - public void errorAfterCancel() { - ObserverFullArbiter fa = new ObserverFullArbiter(new TestObserver(), null, 128); - - Disposable bs = Disposables.empty(); - - fa.dispose(); - - List errors = TestHelper.trackPluginErrors(); - try { - fa.onError(new TestException(), bs); - - TestHelper.assertUndeliverable(errors, 0, TestException.class); - } finally { - RxJavaPlugins.reset(); - } - } - - @Test - public void cancelAfterError() { - ObserverFullArbiter fa = new ObserverFullArbiter(new TestObserver(), null, 128); - - List errors = TestHelper.trackPluginErrors(); - try { - fa.queue.offer(fa.s, NotificationLite.error(new TestException())); - - fa.dispose(); - - fa.drain(); - TestHelper.assertUndeliverable(errors, 0, TestException.class); - } finally { - RxJavaPlugins.reset(); - } - } - - @Test - public void offerDifferentSubscription() { - TestObserver ts = new TestObserver(); - - ObserverFullArbiter fa = new ObserverFullArbiter(ts, null, 128); - - Disposable bs = Disposables.empty(); - - fa.queue.offer(bs, NotificationLite.next(1)); - - fa.drain(); - - ts.assertNoValues(); - } - - @Test - public void dontEnterDrain() { - TestObserver ts = new TestObserver(); - - ObserverFullArbiter fa = new ObserverFullArbiter(ts, null, 128); - - fa.queue.offer(fa.s, NotificationLite.next(1)); - - fa.wip.getAndIncrement(); - - fa.drain(); - - ts.assertNoValues(); - } -} diff --git a/src/test/java/io/reactivex/internal/observers/FullArbiterObserverTest.java b/src/test/java/io/reactivex/internal/observers/FullArbiterObserverTest.java deleted file mode 100644 index c2b4c64e76..0000000000 --- a/src/test/java/io/reactivex/internal/observers/FullArbiterObserverTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ - -package io.reactivex.internal.observers; - -import org.junit.Test; - -import io.reactivex.TestHelper; -import io.reactivex.disposables.Disposables; -import io.reactivex.exceptions.TestException; -import io.reactivex.internal.disposables.ObserverFullArbiter; -import io.reactivex.observers.TestObserver; - -public class FullArbiterObserverTest { - - @Test - public void doubleOnSubscribe() { - TestObserver to = new TestObserver(); - ObserverFullArbiter fa = new ObserverFullArbiter(to, null, 16); - FullArbiterObserver fo = new FullArbiterObserver(fa); - to.onSubscribe(fa); - - TestHelper.doubleOnSubscribe(fo); - } - - @Test - public void error() { - TestObserver to = new TestObserver(); - ObserverFullArbiter fa = new ObserverFullArbiter(to, null, 16); - FullArbiterObserver fo = new FullArbiterObserver(fa); - to.onSubscribe(fa); - - fo.onSubscribe(Disposables.empty()); - fo.onError(new TestException()); - - to.assertFailure(TestException.class); - } -} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java index bad1090d85..3641de632c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java @@ -19,7 +19,7 @@ import java.util.*; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.*; import org.junit.Test; import org.mockito.InOrder; @@ -29,12 +29,12 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; -import io.reactivex.exceptions.TestException; -import io.reactivex.functions.Function; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.processors.PublishProcessor; +import io.reactivex.processors.*; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; @@ -414,13 +414,13 @@ public void error() { @Test public void emptyInner() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber to = pp .timeout(Functions.justFunction(Flowable.empty())) .test(); - ps.onNext(1); + pp.onNext(1); to.assertFailure(TimeoutException.class, 1); } @@ -429,9 +429,9 @@ public void emptyInner() { public void badInnerSource() { List errors = TestHelper.trackPluginErrors(); try { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber to = pp .timeout(Functions.justFunction(new Flowable() { @Override protected void subscribeActual(Subscriber observer) { @@ -444,7 +444,7 @@ protected void subscribeActual(Subscriber observer) { })) .test(); - ps.onNext(1); + pp.onNext(1); to.assertFailureAndMessage(TestException.class, "First", 1); @@ -458,9 +458,9 @@ protected void subscribeActual(Subscriber observer) { public void badInnerSourceOther() { List errors = TestHelper.trackPluginErrors(); try { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber to = pp .timeout(Functions.justFunction(new Flowable() { @Override protected void subscribeActual(Subscriber observer) { @@ -473,7 +473,7 @@ protected void subscribeActual(Subscriber observer) { }), Flowable.just(2)) .test(); - ps.onNext(1); + pp.onNext(1); to.assertFailureAndMessage(TestException.class, "First", 1); @@ -513,36 +513,36 @@ protected void subscribeActual(Subscriber observer) { @Test public void selectorTake() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber to = pp .timeout(Functions.justFunction(Flowable.never())) .take(1) .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); to.assertResult(1); } @Test public void selectorFallbackTake() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber to = pp .timeout(Functions.justFunction(Flowable.never()), Flowable.just(2)) .take(1) .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); to.assertResult(1); } @@ -712,7 +712,7 @@ public void run() { } @Test - public void onECompleteOnTimeoutRace() { + public void onCompleteOnTimeoutRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { @@ -763,4 +763,126 @@ public void run() { } } } + + @Test + public void onCompleteOnTimeoutRaceFallback() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor pp = PublishProcessor.create(); + + final Subscriber[] sub = { null, null }; + + final Flowable pp2 = new Flowable() { + + int count; + + @Override + protected void subscribeActual( + Subscriber s) { + assertFalse(((Disposable)s).isDisposed()); + s.onSubscribe(new BooleanSubscription()); + sub[count++] = s; + } + }; + + TestSubscriber ts = pp.timeout(Functions.justFunction(pp2), Flowable.never()).test(); + + pp.onNext(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onComplete(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + sub[0].onComplete(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValueAt(0, 0); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void disposedUpfront() { + PublishProcessor pp = PublishProcessor.create(); + final AtomicInteger counter = new AtomicInteger(); + + Flowable timeoutAndFallback = Flowable.never().doOnSubscribe(new Consumer() { + @Override + public void accept(Subscription s) throws Exception { + counter.incrementAndGet(); + } + }); + + pp + .timeout(timeoutAndFallback, Functions.justFunction(timeoutAndFallback)) + .test(1, true) + .assertEmpty(); + + assertEquals(0, counter.get()); + } + + @Test + public void disposedUpfrontFallback() { + PublishProcessor pp = PublishProcessor.create(); + final AtomicInteger counter = new AtomicInteger(); + + Flowable timeoutAndFallback = Flowable.never().doOnSubscribe(new Consumer() { + @Override + public void accept(Subscription s) throws Exception { + counter.incrementAndGet(); + } + }); + + pp + .timeout(timeoutAndFallback, Functions.justFunction(timeoutAndFallback), timeoutAndFallback) + .test(1, true) + .assertEmpty(); + + assertEquals(0, counter.get()); + } + + @Test + public void timeoutConsumerDoubleOnSubscribe() { + List errors = TestHelper.trackPluginErrors(); + try { + BehaviorProcessor.createDefault(1) + .timeout(Functions.justFunction(new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + BooleanSubscription bs1 = new BooleanSubscription(); + s.onSubscribe(bs1); + + BooleanSubscription bs2 = new BooleanSubscription(); + s.onSubscribe(bs2); + + assertFalse(bs1.isCancelled()); + assertTrue(bs2.isCancelled()); + + s.onComplete(); + } + })) + .test() + .assertFailure(TimeoutException.class, 1); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java index b32903164d..3c244964c9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java @@ -424,12 +424,6 @@ public void timedEmpty() { .assertResult(); } - @Test - public void newTimer() { - ObservableTimeoutTimed.NEW_TIMER.dispose(); - assertTrue(ObservableTimeoutTimed.NEW_TIMER.isDisposed()); - } - @Test public void badSource() { List errors = TestHelper.trackPluginErrors(); @@ -515,4 +509,89 @@ public void timedFallbackTake() { to.assertResult(1); } + + @Test + public void fallbackErrors() { + Observable.never() + .timeout(1, TimeUnit.MILLISECONDS, Observable.error(new TestException())) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertFailure(TestException.class); + } + + @Test + public void onNextOnTimeoutRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final TestScheduler sch = new TestScheduler(); + + final PublishSubject pp = PublishSubject.create(); + + TestObserver ts = pp.timeout(1, TimeUnit.SECONDS, sch).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + sch.advanceTimeBy(1, TimeUnit.SECONDS); + } + }; + + TestHelper.race(r1, r2); + + if (ts.valueCount() != 0) { + if (ts.errorCount() != 0) { + ts.assertFailure(TimeoutException.class, 1); + } else { + ts.assertValuesOnly(1); + } + } else { + ts.assertFailure(TimeoutException.class); + } + } + } + + @Test + public void onNextOnTimeoutRaceFallback() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final TestScheduler sch = new TestScheduler(); + + final PublishSubject pp = PublishSubject.create(); + + TestObserver ts = pp.timeout(1, TimeUnit.SECONDS, sch, Observable.just(2)).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + sch.advanceTimeBy(1, TimeUnit.SECONDS); + } + }; + + TestHelper.race(r1, r2); + + if (ts.isTerminated()) { + int c = ts.valueCount(); + if (c == 1) { + int v = ts.values().get(0); + assertTrue("" + v, v == 1 || v == 2); + } else { + ts.assertResult(1, 2); + } + } else { + ts.assertValuesOnly(1); + } + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java index a76affd787..276971e5c9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java @@ -19,7 +19,7 @@ import java.util.*; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.*; import org.junit.Test; import org.mockito.InOrder; @@ -31,7 +31,7 @@ import io.reactivex.Observer; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; -import io.reactivex.functions.Function; +import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; @@ -546,4 +546,314 @@ public void selectorFallbackTake() { to.assertResult(1); } + + @Test + public void lateOnTimeoutError() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final Observer[] sub = { null, null }; + + final Observable pp2 = new Observable() { + + int count; + + @Override + protected void subscribeActual( + Observer s) { + s.onSubscribe(Disposables.empty()); + sub[count++] = s; + } + }; + + TestObserver ts = ps.timeout(Functions.justFunction(pp2)).test(); + + ps.onNext(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(1); + } + }; + + final Throwable ex = new TestException(); + + Runnable r2 = new Runnable() { + @Override + public void run() { + sub[0].onError(ex); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValueAt(0, 0); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void lateOnTimeoutFallbackRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final Observer[] sub = { null, null }; + + final Observable pp2 = new Observable() { + + int count; + + @Override + protected void subscribeActual( + Observer s) { + assertFalse(((Disposable)s).isDisposed()); + s.onSubscribe(Disposables.empty()); + sub[count++] = s; + } + }; + + TestObserver ts = ps.timeout(Functions.justFunction(pp2), Observable.never()).test(); + + ps.onNext(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(1); + } + }; + + final Throwable ex = new TestException(); + + Runnable r2 = new Runnable() { + @Override + public void run() { + sub[0].onError(ex); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValueAt(0, 0); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void onErrorOnTimeoutRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final Observer[] sub = { null, null }; + + final Observable pp2 = new Observable() { + + int count; + + @Override + protected void subscribeActual( + Observer s) { + assertFalse(((Disposable)s).isDisposed()); + s.onSubscribe(Disposables.empty()); + sub[count++] = s; + } + }; + + TestObserver ts = ps.timeout(Functions.justFunction(pp2)).test(); + + ps.onNext(0); + + final Throwable ex = new TestException(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onError(ex); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + sub[0].onComplete(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValueAt(0, 0); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void onCompleteOnTimeoutRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final Observer[] sub = { null, null }; + + final Observable pp2 = new Observable() { + + int count; + + @Override + protected void subscribeActual( + Observer s) { + assertFalse(((Disposable)s).isDisposed()); + s.onSubscribe(Disposables.empty()); + sub[count++] = s; + } + }; + + TestObserver ts = ps.timeout(Functions.justFunction(pp2)).test(); + + ps.onNext(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onComplete(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + sub[0].onComplete(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValueAt(0, 0); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void onCompleteOnTimeoutRaceFallback() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + final Observer[] sub = { null, null }; + + final Observable pp2 = new Observable() { + + int count; + + @Override + protected void subscribeActual( + Observer s) { + assertFalse(((Disposable)s).isDisposed()); + s.onSubscribe(Disposables.empty()); + sub[count++] = s; + } + }; + + TestObserver ts = ps.timeout(Functions.justFunction(pp2), Observable.never()).test(); + + ps.onNext(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onComplete(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + sub[0].onComplete(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValueAt(0, 0); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void disposedUpfront() { + PublishSubject ps = PublishSubject.create(); + final AtomicInteger counter = new AtomicInteger(); + + Observable timeoutAndFallback = Observable.never().doOnSubscribe(new Consumer() { + @Override + public void accept(Disposable s) throws Exception { + counter.incrementAndGet(); + } + }); + + ps + .timeout(timeoutAndFallback, Functions.justFunction(timeoutAndFallback)) + .test(true) + .assertEmpty(); + + assertEquals(0, counter.get()); + } + + @Test + public void disposedUpfrontFallback() { + PublishSubject ps = PublishSubject.create(); + final AtomicInteger counter = new AtomicInteger(); + + Observable timeoutAndFallback = Observable.never().doOnSubscribe(new Consumer() { + @Override + public void accept(Disposable s) throws Exception { + counter.incrementAndGet(); + } + }); + + ps + .timeout(timeoutAndFallback, Functions.justFunction(timeoutAndFallback), timeoutAndFallback) + .test(true) + .assertEmpty(); + + assertEquals(0, counter.get()); + } } From 855153e7855f5aa1ebc3381126d0c6cc7cbf9628 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 4 Mar 2018 19:19:11 +0100 Subject: [PATCH 119/417] 2.x: Fix window(Observable|Callable) upstream handling (#5887) --- .../observable/ObservableWindowBoundary.java | 269 ++++---- .../ObservableWindowBoundarySupplier.java | 310 +++++---- .../ObservableWindowWithObservableTest.java | 640 +++++++++++++++++- 3 files changed, 943 insertions(+), 276 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundary.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundary.java index d78570ee22..a0fb1f9f10 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundary.java @@ -18,167 +18,199 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; -import io.reactivex.internal.observers.QueueDrainObserver; import io.reactivex.internal.queue.MpscLinkedQueue; -import io.reactivex.internal.util.NotificationLite; -import io.reactivex.observers.*; +import io.reactivex.internal.util.AtomicThrowable; +import io.reactivex.observers.DisposableObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.UnicastSubject; public final class ObservableWindowBoundary extends AbstractObservableWithUpstream> { final ObservableSource other; - final int bufferSize; + final int capacityHint; - public ObservableWindowBoundary(ObservableSource source, ObservableSource other, int bufferSize) { + public ObservableWindowBoundary(ObservableSource source, ObservableSource other, int capacityHint) { super(source); this.other = other; - this.bufferSize = bufferSize; + this.capacityHint = capacityHint; } @Override - public void subscribeActual(Observer> t) { - source.subscribe(new WindowBoundaryMainObserver(new SerializedObserver>(t), other, bufferSize)); + public void subscribeActual(Observer> observer) { + WindowBoundaryMainObserver parent = new WindowBoundaryMainObserver(observer, capacityHint); + + observer.onSubscribe(parent); + other.subscribe(parent.boundaryObserver); + + source.subscribe(parent); } static final class WindowBoundaryMainObserver - extends QueueDrainObserver> - implements Disposable { + extends AtomicInteger + implements Observer, Disposable, Runnable { - final ObservableSource other; - final int bufferSize; + private static final long serialVersionUID = 2233020065421370272L; - Disposable s; + final Observer> downstream; - final AtomicReference boundary = new AtomicReference(); + final int capacityHint; - UnicastSubject window; + final WindowBoundaryInnerObserver boundaryObserver; - static final Object NEXT = new Object(); + final AtomicReference upstream; - final AtomicLong windows = new AtomicLong(); + final AtomicInteger windows; - WindowBoundaryMainObserver(Observer> actual, ObservableSource other, - int bufferSize) { - super(actual, new MpscLinkedQueue()); - this.other = other; - this.bufferSize = bufferSize; - windows.lazySet(1); - } + final MpscLinkedQueue queue; - @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + final AtomicThrowable errors; - Observer> a = actual; - a.onSubscribe(this); + final AtomicBoolean stopWindows; - if (cancelled) { - return; - } + static final Object NEXT_WINDOW = new Object(); - UnicastSubject w = UnicastSubject.create(bufferSize); + volatile boolean done; - window = w; + UnicastSubject window; - a.onNext(w); + WindowBoundaryMainObserver(Observer> downstream, int capacityHint) { + this.downstream = downstream; + this.capacityHint = capacityHint; + this.boundaryObserver = new WindowBoundaryInnerObserver(this); + this.upstream = new AtomicReference(); + this.windows = new AtomicInteger(1); + this.queue = new MpscLinkedQueue(); + this.errors = new AtomicThrowable(); + this.stopWindows = new AtomicBoolean(); + } - WindowBoundaryInnerObserver inner = new WindowBoundaryInnerObserver(this); + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(upstream, d)) { - if (boundary.compareAndSet(null, inner)) { - windows.getAndIncrement(); - other.subscribe(inner); - } + innerNext(); } } @Override public void onNext(T t) { - if (fastEnter()) { - UnicastSubject w = window; - - w.onNext(t); + queue.offer(t); + drain(); + } - if (leave(-1) == 0) { - return; - } + @Override + public void onError(Throwable e) { + boundaryObserver.dispose(); + if (errors.addThrowable(e)) { + done = true; + drain(); } else { - queue.offer(NotificationLite.next(t)); - if (!enter()) { - return; - } + RxJavaPlugins.onError(e); } - drainLoop(); } @Override - public void onError(Throwable t) { - if (done) { - RxJavaPlugins.onError(t); - return; - } - error = t; + public void onComplete() { + boundaryObserver.dispose(); done = true; - if (enter()) { - drainLoop(); - } + drain(); + } - if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); + @Override + public void dispose() { + if (stopWindows.compareAndSet(false, true)) { + boundaryObserver.dispose(); + if (windows.decrementAndGet() == 0) { + DisposableHelper.dispose(upstream); + } } - - actual.onError(t); } @Override - public void onComplete() { - if (done) { - return; - } - done = true; - if (enter()) { - drainLoop(); - } + public boolean isDisposed() { + return stopWindows.get(); + } + @Override + public void run() { if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); + DisposableHelper.dispose(upstream); } + } - actual.onComplete(); - + void innerNext() { + queue.offer(NEXT_WINDOW); + drain(); } - @Override - public void dispose() { - cancelled = true; + void innerError(Throwable e) { + DisposableHelper.dispose(upstream); + if (errors.addThrowable(e)) { + done = true; + drain(); + } else { + RxJavaPlugins.onError(e); + } } - @Override - public boolean isDisposed() { - return cancelled; + void innerComplete() { + DisposableHelper.dispose(upstream); + done = true; + drain(); } - void drainLoop() { - final MpscLinkedQueue q = (MpscLinkedQueue)queue; - final Observer> a = actual; + @SuppressWarnings("unchecked") + void drain() { + if (getAndIncrement() != 0) { + return; + } + int missed = 1; - UnicastSubject w = window; + Observer> downstream = this.downstream; + MpscLinkedQueue queue = this.queue; + AtomicThrowable errors = this.errors; + for (;;) { for (;;) { + if (windows.get() == 0) { + queue.clear(); + window = null; + return; + } + + UnicastSubject w = window; + boolean d = done; - Object o = q.poll(); + if (d && errors.get() != null) { + queue.clear(); + Throwable ex = errors.terminate(); + if (w != null) { + window = null; + w.onError(ex); + } + downstream.onError(ex); + return; + } + + Object v = queue.poll(); - boolean empty = o == null; + boolean empty = v == null; if (d && empty) { - DisposableHelper.dispose(boundary); - Throwable e = error; - if (e != null) { - w.onError(e); + Throwable ex = errors.terminate(); + if (ex == null) { + if (w != null) { + window = null; + w.onComplete(); + } + downstream.onComplete(); } else { - w.onComplete(); + if (w != null) { + window = null; + w.onError(ex); + } + downstream.onError(ex); } return; } @@ -187,48 +219,35 @@ void drainLoop() { break; } - if (o == NEXT) { - w.onComplete(); - - if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); - return; - } - - if (cancelled) { - continue; - } - - w = UnicastSubject.create(bufferSize); + if (v != NEXT_WINDOW) { + w.onNext((T)v); + continue; + } - windows.getAndIncrement(); + if (w != null) { + window = null; + w.onComplete(); + } + if (!stopWindows.get()) { + w = UnicastSubject.create(capacityHint, this); window = w; + windows.getAndIncrement(); - a.onNext(w); - - continue; + downstream.onNext(w); } - - w.onNext(NotificationLite.getValue(o)); } - missed = leave(-missed); + missed = addAndGet(-missed); if (missed == 0) { - return; + break; } } } - - void next() { - queue.offer(NEXT); - if (enter()) { - drainLoop(); - } - } } static final class WindowBoundaryInnerObserver extends DisposableObserver { + final WindowBoundaryMainObserver parent; boolean done; @@ -242,7 +261,7 @@ public void onNext(B t) { if (done) { return; } - parent.next(); + parent.innerNext(); } @Override @@ -252,7 +271,7 @@ public void onError(Throwable t) { return; } done = true; - parent.onError(t); + parent.innerError(t); } @Override @@ -261,7 +280,7 @@ public void onComplete() { return; } done = true; - parent.onComplete(); + parent.innerComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySupplier.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySupplier.java index 47b0841262..c2d319032b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySupplier.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySupplier.java @@ -21,179 +21,213 @@ import io.reactivex.exceptions.Exceptions; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.observers.QueueDrainObserver; import io.reactivex.internal.queue.MpscLinkedQueue; -import io.reactivex.internal.util.NotificationLite; -import io.reactivex.observers.*; +import io.reactivex.internal.util.AtomicThrowable; +import io.reactivex.observers.DisposableObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.UnicastSubject; public final class ObservableWindowBoundarySupplier extends AbstractObservableWithUpstream> { final Callable> other; - final int bufferSize; + final int capacityHint; public ObservableWindowBoundarySupplier( ObservableSource source, - Callable> other, int bufferSize) { + Callable> other, int capacityHint) { super(source); this.other = other; - this.bufferSize = bufferSize; + this.capacityHint = capacityHint; } @Override - public void subscribeActual(Observer> t) { - source.subscribe(new WindowBoundaryMainObserver(new SerializedObserver>(t), other, bufferSize)); + public void subscribeActual(Observer> observer) { + WindowBoundaryMainObserver parent = new WindowBoundaryMainObserver(observer, capacityHint, other); + + source.subscribe(parent); } static final class WindowBoundaryMainObserver - extends QueueDrainObserver> - implements Disposable { + extends AtomicInteger + implements Observer, Disposable, Runnable { - final Callable> other; - final int bufferSize; + private static final long serialVersionUID = 2233020065421370272L; - Disposable s; + final Observer> downstream; - final AtomicReference boundary = new AtomicReference(); + final int capacityHint; - UnicastSubject window; + final AtomicReference> boundaryObserver; - static final Object NEXT = new Object(); + static final WindowBoundaryInnerObserver BOUNDARY_DISPOSED = new WindowBoundaryInnerObserver(null); - final AtomicLong windows = new AtomicLong(); + final AtomicInteger windows; - WindowBoundaryMainObserver(Observer> actual, Callable> other, - int bufferSize) { - super(actual, new MpscLinkedQueue()); - this.other = other; - this.bufferSize = bufferSize; - windows.lazySet(1); - } + final MpscLinkedQueue queue; - @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + final AtomicThrowable errors; - Observer> a = actual; - a.onSubscribe(this); + final AtomicBoolean stopWindows; - if (cancelled) { - return; - } + final Callable> other; - ObservableSource p; + static final Object NEXT_WINDOW = new Object(); - try { - p = ObjectHelper.requireNonNull(other.call(), "The first window ObservableSource supplied is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - s.dispose(); - a.onError(e); - return; - } + Disposable upstream; - UnicastSubject w = UnicastSubject.create(bufferSize); + volatile boolean done; - window = w; - - a.onNext(w); + UnicastSubject window; - WindowBoundaryInnerObserver inner = new WindowBoundaryInnerObserver(this); + WindowBoundaryMainObserver(Observer> downstream, int capacityHint, Callable> other) { + this.downstream = downstream; + this.capacityHint = capacityHint; + this.boundaryObserver = new AtomicReference>(); + this.windows = new AtomicInteger(1); + this.queue = new MpscLinkedQueue(); + this.errors = new AtomicThrowable(); + this.stopWindows = new AtomicBoolean(); + this.other = other; + } - if (boundary.compareAndSet(null, inner)) { - windows.getAndIncrement(); - p.subscribe(inner); - } + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + upstream = d; + downstream.onSubscribe(this); + queue.offer(NEXT_WINDOW); + drain(); } } @Override public void onNext(T t) { - if (fastEnter()) { - UnicastSubject w = window; - - w.onNext(t); + queue.offer(t); + drain(); + } - if (leave(-1) == 0) { - return; - } + @Override + public void onError(Throwable e) { + disposeBoundary(); + if (errors.addThrowable(e)) { + done = true; + drain(); } else { - queue.offer(NotificationLite.next(t)); - if (!enter()) { - return; - } + RxJavaPlugins.onError(e); } - drainLoop(); } @Override - public void onError(Throwable t) { - if (done) { - RxJavaPlugins.onError(t); - return; - } - error = t; + public void onComplete() { + disposeBoundary(); done = true; - if (enter()) { - drainLoop(); - } + drain(); + } - if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); + @Override + public void dispose() { + if (stopWindows.compareAndSet(false, true)) { + disposeBoundary(); + if (windows.decrementAndGet() == 0) { + upstream.dispose(); + } } + } - actual.onError(t); + @SuppressWarnings({ "rawtypes", "unchecked" }) + void disposeBoundary() { + Disposable d = boundaryObserver.getAndSet((WindowBoundaryInnerObserver)BOUNDARY_DISPOSED); + if (d != null && d != BOUNDARY_DISPOSED) { + d.dispose(); + } } @Override - public void onComplete() { - if (done) { - return; - } - done = true; - if (enter()) { - drainLoop(); - } + public boolean isDisposed() { + return stopWindows.get(); + } + @Override + public void run() { if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); + upstream.dispose(); } + } - actual.onComplete(); - + void innerNext(WindowBoundaryInnerObserver sender) { + boundaryObserver.compareAndSet(sender, null); + queue.offer(NEXT_WINDOW); + drain(); } - @Override - public void dispose() { - cancelled = true; + void innerError(Throwable e) { + upstream.dispose(); + if (errors.addThrowable(e)) { + done = true; + drain(); + } else { + RxJavaPlugins.onError(e); + } } - @Override - public boolean isDisposed() { - return cancelled; + void innerComplete() { + upstream.dispose(); + done = true; + drain(); } - void drainLoop() { - final MpscLinkedQueue q = (MpscLinkedQueue)queue; - final Observer> a = actual; + @SuppressWarnings("unchecked") + void drain() { + if (getAndIncrement() != 0) { + return; + } + int missed = 1; - UnicastSubject w = window; + Observer> downstream = this.downstream; + MpscLinkedQueue queue = this.queue; + AtomicThrowable errors = this.errors; + for (;;) { for (;;) { + if (windows.get() == 0) { + queue.clear(); + window = null; + return; + } + + UnicastSubject w = window; + boolean d = done; - Object o = q.poll(); - boolean empty = o == null; + if (d && errors.get() != null) { + queue.clear(); + Throwable ex = errors.terminate(); + if (w != null) { + window = null; + w.onError(ex); + } + downstream.onError(ex); + return; + } + + Object v = queue.poll(); + + boolean empty = v == null; if (d && empty) { - DisposableHelper.dispose(boundary); - Throwable e = error; - if (e != null) { - w.onError(e); + Throwable ex = errors.terminate(); + if (ex == null) { + if (w != null) { + window = null; + w.onComplete(); + } + downstream.onComplete(); } else { - w.onComplete(); + if (w != null) { + window = null; + w.onError(ex); + } + downstream.onError(ex); } return; } @@ -202,62 +236,48 @@ void drainLoop() { break; } - if (o == NEXT) { - w.onComplete(); + if (v != NEXT_WINDOW) { + w.onNext((T)v); + continue; + } - if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); - return; - } + if (w != null) { + window = null; + w.onComplete(); + } - if (cancelled) { - continue; - } + if (!stopWindows.get()) { + w = UnicastSubject.create(capacityHint, this); + window = w; + windows.getAndIncrement(); - ObservableSource p; + ObservableSource otherSource; try { - p = ObjectHelper.requireNonNull(other.call(), "The ObservableSource supplied is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - DisposableHelper.dispose(boundary); - a.onError(e); - return; + otherSource = ObjectHelper.requireNonNull(other.call(), "The other Callable returned a null ObservableSource"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + errors.addThrowable(ex); + done = true; + continue; } - w = UnicastSubject.create(bufferSize); + WindowBoundaryInnerObserver bo = new WindowBoundaryInnerObserver(this); - windows.getAndIncrement(); + if (boundaryObserver.compareAndSet(null, bo)) { + otherSource.subscribe(bo); - window = w; - - a.onNext(w); - - WindowBoundaryInnerObserver b = new WindowBoundaryInnerObserver(this); - - if (boundary.compareAndSet(boundary.get(), b)) { - p.subscribe(b); + downstream.onNext(w); } - - continue; } - - w.onNext(NotificationLite.getValue(o)); } - missed = leave(-missed); + missed = addAndGet(-missed); if (missed == 0) { - return; + break; } } } - - void next() { - queue.offer(NEXT); - if (enter()) { - drainLoop(); - } - } } static final class WindowBoundaryInnerObserver extends DisposableObserver { @@ -276,7 +296,7 @@ public void onNext(B t) { } done = true; dispose(); - parent.next(); + parent.innerNext(this); } @Override @@ -286,7 +306,7 @@ public void onError(Throwable t) { return; } done = true; - parent.onError(t); + parent.innerError(t); } @Override @@ -295,7 +315,7 @@ public void onComplete() { return; } done = true; - parent.onComplete(); + parent.innerComplete(); } } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java index 8319a74d97..6c084f01d6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java @@ -19,17 +19,19 @@ import java.util.*; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.*; import org.junit.Test; import io.reactivex.*; import io.reactivex.Observable; import io.reactivex.Observer; +import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; import io.reactivex.observers.*; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.*; public class ObservableWindowWithObservableTest { @@ -346,8 +348,8 @@ public Observable call() { boundary.onComplete(); - // FIXME source still active because the open window - assertTrue(source.hasObservers()); + + assertFalse(source.hasObservers()); assertFalse(boundary.hasObservers()); ts.assertComplete(); @@ -374,10 +376,13 @@ public Observable call() { ts.dispose(); - // FIXME source has subscribers because the open window assertTrue(source.hasObservers()); - // FIXME boundary has subscribers because the open window - assertTrue(boundary.hasObservers()); + + assertFalse(boundary.hasObservers()); + + ts.values().get(0).test(true); + + assertFalse(source.hasObservers()); ts.assertNotComplete(); ts.assertNoErrors(); @@ -638,4 +643,627 @@ public Observable> apply(Observable f) } }); } + + @Test + public void upstreamDisposedWhenOutputsDisposed() { + PublishSubject source = PublishSubject.create(); + PublishSubject boundary = PublishSubject.create(); + + TestObserver to = source.window(boundary) + .take(1) + .flatMap(new Function, ObservableSource>() { + @Override + public ObservableSource apply( + Observable w) throws Exception { + return w.take(1); + } + }) + .test(); + + source.onNext(1); + + assertFalse("source not disposed", source.hasObservers()); + assertFalse("boundary not disposed", boundary.hasObservers()); + + to.assertResult(1); + } + + @Test + public void mainAndBoundaryBothError() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> ref = new AtomicReference>(); + + TestObserver> to = Observable.error(new TestException("main")) + .window(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); + } + }) + .test(); + + to + .assertValueCount(1) + .assertError(TestException.class) + .assertErrorMessage("main") + .assertNotComplete(); + + ref.get().onError(new TestException("inner")); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void mainCompleteBoundaryErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestObserver> to = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + refMain.set(observer); + } + } + .window(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); + } + }) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + refMain.get().onComplete(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ref.get().onError(ex); + } + }; + + TestHelper.race(r1, r2); + + to + .assertValueCount(1) + .assertTerminated(); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void mainNextBoundaryNextRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestObserver> to = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + refMain.set(observer); + } + } + .window(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); + } + }) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + refMain.get().onNext(1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ref.get().onNext(1); + } + }; + + TestHelper.race(r1, r2); + + to + .assertValueCount(2) + .assertNotComplete() + .assertNoErrors(); + } + } + + @Test + public void takeOneAnotherBoundary() { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestObserver> to = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + refMain.set(observer); + } + } + .window(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); + } + }) + .test(); + + to.assertValueCount(1) + .assertNotTerminated() + .cancel(); + + ref.get().onNext(1); + + to.assertValueCount(1) + .assertNotTerminated(); + } + + @Test + public void disposeMainBoundaryCompleteRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + final TestObserver> to = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + refMain.set(observer); + } + } + .window(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + final AtomicInteger counter = new AtomicInteger(); + observer.onSubscribe(new Disposable() { + + @Override + public void dispose() { + // about a microsecond + for (int i = 0; i < 100; i++) { + counter.incrementAndGet(); + } + } + + @Override + public boolean isDisposed() { + return false; + } + }); + ref.set(observer); + } + }) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + Observer o = ref.get(); + o.onNext(1); + o.onComplete(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void disposeMainBoundaryErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + final TestObserver> to = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + refMain.set(observer); + } + } + .window(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + final AtomicInteger counter = new AtomicInteger(); + observer.onSubscribe(new Disposable() { + + @Override + public void dispose() { + // about a microsecond + for (int i = 0; i < 100; i++) { + counter.incrementAndGet(); + } + } + + @Override + public boolean isDisposed() { + return false; + } + }); + ref.set(observer); + } + }) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + Observer o = ref.get(); + o.onNext(1); + o.onError(ex); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void boundarySupplierDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>>() { + @Override + public Observable> apply(Observable f) + throws Exception { + return f.window(Functions.justCallable(Observable.never())).takeLast(1); + } + }); + } + + @Test + public void selectorUpstreamDisposedWhenOutputsDisposed() { + PublishSubject source = PublishSubject.create(); + PublishSubject boundary = PublishSubject.create(); + + TestObserver to = source.window(Functions.justCallable(boundary)) + .take(1) + .flatMap(new Function, ObservableSource>() { + @Override + public ObservableSource apply( + Observable w) throws Exception { + return w.take(1); + } + }) + .test(); + + source.onNext(1); + + assertFalse("source not disposed", source.hasObservers()); + assertFalse("boundary not disposed", boundary.hasObservers()); + + to.assertResult(1); + } + + @Test + public void supplierMainAndBoundaryBothError() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> ref = new AtomicReference>(); + + TestObserver> to = Observable.error(new TestException("main")) + .window(Functions.justCallable(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); + } + })) + .test(); + + to + .assertValueCount(1) + .assertError(TestException.class) + .assertErrorMessage("main") + .assertNotComplete(); + + ref.get().onError(new TestException("inner")); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void supplierMainCompleteBoundaryErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestObserver> to = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + refMain.set(observer); + } + } + .window(Functions.justCallable(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); + } + })) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + refMain.get().onComplete(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ref.get().onError(ex); + } + }; + + TestHelper.race(r1, r2); + + to + .assertValueCount(1) + .assertTerminated(); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void supplierMainNextBoundaryNextRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestObserver> to = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + refMain.set(observer); + } + } + .window(Functions.justCallable(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); + } + })) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + refMain.get().onNext(1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ref.get().onNext(1); + } + }; + + TestHelper.race(r1, r2); + + to + .assertValueCount(2) + .assertNotComplete() + .assertNoErrors(); + } + } + + @Test + public void supplierTakeOneAnotherBoundary() { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestObserver> to = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + refMain.set(observer); + } + } + .window(Functions.justCallable(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); + } + })) + .test(); + + to.assertValueCount(1) + .assertNotTerminated() + .cancel(); + + ref.get().onNext(1); + + to.assertValueCount(1) + .assertNotTerminated(); + } + + @Test + public void supplierDisposeMainBoundaryCompleteRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + final TestObserver> to = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + refMain.set(observer); + } + } + .window(Functions.justCallable(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + final AtomicInteger counter = new AtomicInteger(); + observer.onSubscribe(new Disposable() { + + @Override + public void dispose() { + // about a microsecond + for (int i = 0; i < 100; i++) { + counter.incrementAndGet(); + } + } + + @Override + public boolean isDisposed() { + return false; + } + }); + ref.set(observer); + } + })) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + Observer o = ref.get(); + o.onNext(1); + o.onComplete(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void supplierDisposeMainBoundaryErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + final TestObserver> to = new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + refMain.set(observer); + } + } + .window(new Callable>() { + int count; + @Override + public ObservableSource call() throws Exception { + if (++count > 1) { + return Observable.never(); + } + return (new Observable() { + @Override + protected void subscribeActual(Observer observer) { + final AtomicInteger counter = new AtomicInteger(); + observer.onSubscribe(new Disposable() { + + @Override + public void dispose() { + // about a microsecond + for (int i = 0; i < 100; i++) { + counter.incrementAndGet(); + } + } + + @Override + public boolean isDisposed() { + return false; + } + }); + ref.set(observer); + } + }); + } + }) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + Observer o = ref.get(); + o.onNext(1); + o.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } } From 9f2c435756483bdfc59fecf4837e54eb9bf3d755 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 5 Mar 2018 00:54:20 +0100 Subject: [PATCH 120/417] 2.x: Fix Flowable.window(Publisher|Callable) upstream handling (#5888) --- build.gradle | 3 +- .../flowable/FlowableWindowBoundary.java | 313 +++++---- .../FlowableWindowBoundarySupplier.java | 355 +++++----- .../FlowableWindowWithFlowableTest.java | 655 +++++++++++++++++- 4 files changed, 990 insertions(+), 336 deletions(-) diff --git a/build.gradle b/build.gradle index 12a5b04978..9da4ae5757 100644 --- a/build.gradle +++ b/build.gradle @@ -57,6 +57,7 @@ def mockitoVersion = "2.1.0" def jmhLibVersion = "1.19" def testNgVersion = "6.11" def guavaVersion = "24.0-jre" +def jacocoVersion = "0.8.0" // -------------------------------------- repositories { @@ -257,7 +258,7 @@ task testng(type: Test) { check.dependsOn testng jacoco { - toolVersion = "0.7.9" // See http://www.eclemma.org/jacoco/. + toolVersion = jacocoVersion // See http://www.eclemma.org/jacoco/. } task GCandMem(dependsOn: "check") doLast { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java index 58cec89232..8c8164f76f 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java @@ -17,186 +17,210 @@ import org.reactivestreams.*; -import io.reactivex.Flowable; -import io.reactivex.disposables.Disposable; +import io.reactivex.*; import io.reactivex.exceptions.MissingBackpressureException; -import io.reactivex.internal.disposables.DisposableHelper; -import io.reactivex.internal.fuseable.SimplePlainQueue; import io.reactivex.internal.queue.MpscLinkedQueue; -import io.reactivex.internal.subscribers.QueueDrainSubscriber; import io.reactivex.internal.subscriptions.SubscriptionHelper; -import io.reactivex.internal.util.NotificationLite; +import io.reactivex.internal.util.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.UnicastProcessor; -import io.reactivex.subscribers.*; +import io.reactivex.subscribers.DisposableSubscriber; public final class FlowableWindowBoundary extends AbstractFlowableWithUpstream> { final Publisher other; - final int bufferSize; + final int capacityHint; - public FlowableWindowBoundary(Flowable source, Publisher other, int bufferSize) { + public FlowableWindowBoundary(Flowable source, Publisher other, int capacityHint) { super(source); this.other = other; - this.bufferSize = bufferSize; + this.capacityHint = capacityHint; } @Override - protected void subscribeActual(Subscriber> s) { - source.subscribe( - new WindowBoundaryMainSubscriber( - new SerializedSubscriber>(s), other, bufferSize)); + protected void subscribeActual(Subscriber> subscriber) { + WindowBoundaryMainSubscriber parent = new WindowBoundaryMainSubscriber(subscriber, capacityHint); + + subscriber.onSubscribe(parent); + + parent.innerNext(); + + other.subscribe(parent.boundarySubscriber); + + source.subscribe(parent); } static final class WindowBoundaryMainSubscriber - extends QueueDrainSubscriber> - implements Subscription { + extends AtomicInteger + implements FlowableSubscriber, Subscription, Runnable { - final Publisher other; - final int bufferSize; + private static final long serialVersionUID = 2233020065421370272L; - Subscription s; + final Subscriber> downstream; - final AtomicReference boundary = new AtomicReference(); + final int capacityHint; - UnicastProcessor window; + final WindowBoundaryInnerSubscriber boundarySubscriber; - static final Object NEXT = new Object(); + final AtomicReference upstream; - final AtomicLong windows = new AtomicLong(); + final AtomicInteger windows; - WindowBoundaryMainSubscriber(Subscriber> actual, Publisher other, - int bufferSize) { - super(actual, new MpscLinkedQueue()); - this.other = other; - this.bufferSize = bufferSize; - windows.lazySet(1); - } + final MpscLinkedQueue queue; - @Override - public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + final AtomicThrowable errors; - Subscriber> a = actual; - a.onSubscribe(this); + final AtomicBoolean stopWindows; - if (cancelled) { - return; - } + final AtomicLong requested; - UnicastProcessor w = UnicastProcessor.create(bufferSize); + static final Object NEXT_WINDOW = new Object(); - long r = requested(); - if (r != 0L) { - a.onNext(w); - if (r != Long.MAX_VALUE) { - produced(1); - } - } else { - s.cancel(); - a.onError(new MissingBackpressureException("Could not deliver first window due to lack of requests")); - return; - } + volatile boolean done; - window = w; + UnicastProcessor window; - WindowBoundaryInnerSubscriber inner = new WindowBoundaryInnerSubscriber(this); + long emitted; + + WindowBoundaryMainSubscriber(Subscriber> downstream, int capacityHint) { + this.downstream = downstream; + this.capacityHint = capacityHint; + this.boundarySubscriber = new WindowBoundaryInnerSubscriber(this); + this.upstream = new AtomicReference(); + this.windows = new AtomicInteger(1); + this.queue = new MpscLinkedQueue(); + this.errors = new AtomicThrowable(); + this.stopWindows = new AtomicBoolean(); + this.requested = new AtomicLong(); + } - if (boundary.compareAndSet(null, inner)) { - windows.getAndIncrement(); - s.request(Long.MAX_VALUE); - other.subscribe(inner); - } + @Override + public void onSubscribe(Subscription d) { + if (SubscriptionHelper.setOnce(upstream, d)) { + d.request(Long.MAX_VALUE); } } @Override public void onNext(T t) { - if (fastEnter()) { - UnicastProcessor w = window; - - w.onNext(t); + queue.offer(t); + drain(); + } - if (leave(-1) == 0) { - return; - } + @Override + public void onError(Throwable e) { + boundarySubscriber.dispose(); + if (errors.addThrowable(e)) { + done = true; + drain(); } else { - queue.offer(NotificationLite.next(t)); - if (!enter()) { - return; - } + RxJavaPlugins.onError(e); } - drainLoop(); } @Override - public void onError(Throwable t) { - if (done) { - RxJavaPlugins.onError(t); - return; - } - error = t; + public void onComplete() { + boundarySubscriber.dispose(); done = true; - if (enter()) { - drainLoop(); - } + drain(); + } - if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); + @Override + public void cancel() { + if (stopWindows.compareAndSet(false, true)) { + boundarySubscriber.dispose(); + if (windows.decrementAndGet() == 0) { + SubscriptionHelper.cancel(upstream); + } } - - actual.onError(t); } @Override - public void onComplete() { - if (done) { - return; - } - done = true; - if (enter()) { - drainLoop(); - } + public void request(long n) { + BackpressureHelper.add(requested, n); + } + @Override + public void run() { if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); + SubscriptionHelper.cancel(upstream); } + } - actual.onComplete(); - + void innerNext() { + queue.offer(NEXT_WINDOW); + drain(); } - @Override - public void request(long n) { - requested(n); + void innerError(Throwable e) { + SubscriptionHelper.cancel(upstream); + if (errors.addThrowable(e)) { + done = true; + drain(); + } else { + RxJavaPlugins.onError(e); + } } - @Override - public void cancel() { - cancelled = true; + void innerComplete() { + SubscriptionHelper.cancel(upstream); + done = true; + drain(); } - void drainLoop() { - final SimplePlainQueue q = queue; - final Subscriber> a = actual; + @SuppressWarnings("unchecked") + void drain() { + if (getAndIncrement() != 0) { + return; + } + int missed = 1; - UnicastProcessor w = window; + Subscriber> downstream = this.downstream; + MpscLinkedQueue queue = this.queue; + AtomicThrowable errors = this.errors; + long emitted = this.emitted; + for (;;) { for (;;) { + if (windows.get() == 0) { + queue.clear(); + window = null; + return; + } + + UnicastProcessor w = window; + boolean d = done; - Object o = q.poll(); + if (d && errors.get() != null) { + queue.clear(); + Throwable ex = errors.terminate(); + if (w != null) { + window = null; + w.onError(ex); + } + downstream.onError(ex); + return; + } - boolean empty = o == null; + Object v = queue.poll(); + + boolean empty = v == null; if (d && empty) { - DisposableHelper.dispose(boundary); - Throwable e = error; - if (e != null) { - w.onError(e); + Throwable ex = errors.terminate(); + if (ex == null) { + if (w != null) { + window = null; + w.onComplete(); + } + downstream.onComplete(); } else { - w.onComplete(); + if (w != null) { + window = null; + w.onError(ex); + } + downstream.onError(ex); } return; } @@ -205,59 +229,44 @@ void drainLoop() { break; } - if (o == NEXT) { - w.onComplete(); - - if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); - return; - } - - if (cancelled) { - continue; - } + if (v != NEXT_WINDOW) { + w.onNext((T)v); + continue; + } - w = UnicastProcessor.create(bufferSize); + if (w != null) { + window = null; + w.onComplete(); + } - long r = requested(); - if (r != 0L) { - windows.getAndIncrement(); + if (!stopWindows.get()) { + w = UnicastProcessor.create(capacityHint, this); + window = w; + windows.getAndIncrement(); - a.onNext(w); - if (r != Long.MAX_VALUE) { - produced(1); - } + if (emitted != requested.get()) { + emitted++; + downstream.onNext(w); } else { - // don't emit new windows - cancelled = true; - a.onError(new MissingBackpressureException("Could not deliver new window due to lack of requests")); - continue; + SubscriptionHelper.cancel(upstream); + boundarySubscriber.dispose(); + errors.addThrowable(new MissingBackpressureException("Could not deliver a window due to lack of requests")); + done = true; } - - window = w; - continue; } - - w.onNext(NotificationLite.getValue(o)); } - missed = leave(-missed); + this.emitted = emitted; + missed = addAndGet(-missed); if (missed == 0) { - return; + break; } } } - - void next() { - queue.offer(NEXT); - if (enter()) { - drainLoop(); - } - } - } static final class WindowBoundaryInnerSubscriber extends DisposableSubscriber { + final WindowBoundaryMainSubscriber parent; boolean done; @@ -271,7 +280,7 @@ public void onNext(B t) { if (done) { return; } - parent.next(); + parent.innerNext(); } @Override @@ -281,7 +290,7 @@ public void onError(Throwable t) { return; } done = true; - parent.onError(t); + parent.innerError(t); } @Override @@ -290,7 +299,7 @@ public void onComplete() { return; } done = true; - parent.onComplete(); + parent.innerComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java index f90d74ad2a..faaf1e7384 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java @@ -18,201 +18,224 @@ import org.reactivestreams.*; -import io.reactivex.Flowable; +import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.*; -import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.fuseable.SimplePlainQueue; import io.reactivex.internal.queue.MpscLinkedQueue; -import io.reactivex.internal.subscribers.QueueDrainSubscriber; import io.reactivex.internal.subscriptions.SubscriptionHelper; -import io.reactivex.internal.util.NotificationLite; +import io.reactivex.internal.util.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.UnicastProcessor; -import io.reactivex.subscribers.*; +import io.reactivex.subscribers.DisposableSubscriber; public final class FlowableWindowBoundarySupplier extends AbstractFlowableWithUpstream> { final Callable> other; - final int bufferSize; + final int capacityHint; public FlowableWindowBoundarySupplier(Flowable source, - Callable> other, int bufferSize) { + Callable> other, int capacityHint) { super(source); this.other = other; - this.bufferSize = bufferSize; + this.capacityHint = capacityHint; } @Override - protected void subscribeActual(Subscriber> s) { - source.subscribe(new WindowBoundaryMainSubscriber( - new SerializedSubscriber>(s), other, bufferSize)); + protected void subscribeActual(Subscriber> subscriber) { + WindowBoundaryMainSubscriber parent = new WindowBoundaryMainSubscriber(subscriber, capacityHint, other); + + source.subscribe(parent); } static final class WindowBoundaryMainSubscriber - extends QueueDrainSubscriber> - implements Subscription { + extends AtomicInteger + implements FlowableSubscriber, Subscription, Runnable { - final Callable> other; - final int bufferSize; + private static final long serialVersionUID = 2233020065421370272L; - Subscription s; + final Subscriber> downstream; - final AtomicReference boundary = new AtomicReference(); + final int capacityHint; - UnicastProcessor window; + final AtomicReference> boundarySubscriber; - static final Object NEXT = new Object(); + static final WindowBoundaryInnerSubscriber BOUNDARY_DISPOSED = new WindowBoundaryInnerSubscriber(null); - final AtomicLong windows = new AtomicLong(); + final AtomicInteger windows; - WindowBoundaryMainSubscriber(Subscriber> actual, Callable> other, - int bufferSize) { - super(actual, new MpscLinkedQueue()); - this.other = other; - this.bufferSize = bufferSize; - windows.lazySet(1); - } + final MpscLinkedQueue queue; - @Override - public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + final AtomicThrowable errors; - Subscriber> a = actual; - a.onSubscribe(this); + final AtomicBoolean stopWindows; - if (cancelled) { - return; - } + final Callable> other; - Publisher p; + static final Object NEXT_WINDOW = new Object(); - try { - p = ObjectHelper.requireNonNull(other.call(), "The first window publisher supplied is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - s.cancel(); - a.onError(e); - return; - } + final AtomicLong requested; - UnicastProcessor w = UnicastProcessor.create(bufferSize); + Subscription upstream; - long r = requested(); - if (r != 0L) { - a.onNext(w); - if (r != Long.MAX_VALUE) { - produced(1); - } - } else { - s.cancel(); - a.onError(new MissingBackpressureException("Could not deliver first window due to lack of requests")); - return; - } + volatile boolean done; - window = w; + UnicastProcessor window; - WindowBoundaryInnerSubscriber inner = new WindowBoundaryInnerSubscriber(this); + long emitted; - if (boundary.compareAndSet(null, inner)) { - windows.getAndIncrement(); - s.request(Long.MAX_VALUE); - p.subscribe(inner); - } - } + WindowBoundaryMainSubscriber(Subscriber> downstream, int capacityHint, Callable> other) { + this.downstream = downstream; + this.capacityHint = capacityHint; + this.boundarySubscriber = new AtomicReference>(); + this.windows = new AtomicInteger(1); + this.queue = new MpscLinkedQueue(); + this.errors = new AtomicThrowable(); + this.stopWindows = new AtomicBoolean(); + this.other = other; + this.requested = new AtomicLong(); } @Override - public void onNext(T t) { - if (done) { - return; + public void onSubscribe(Subscription d) { + if (SubscriptionHelper.validate(upstream, d)) { + upstream = d; + downstream.onSubscribe(this); + queue.offer(NEXT_WINDOW); + drain(); + d.request(Long.MAX_VALUE); } - if (fastEnter()) { - UnicastProcessor w = window; + } - w.onNext(t); + @Override + public void onNext(T t) { + queue.offer(t); + drain(); + } - if (leave(-1) == 0) { - return; - } + @Override + public void onError(Throwable e) { + disposeBoundary(); + if (errors.addThrowable(e)) { + done = true; + drain(); } else { - queue.offer(NotificationLite.next(t)); - if (!enter()) { - return; - } + RxJavaPlugins.onError(e); } - drainLoop(); } @Override - public void onError(Throwable t) { - if (done) { - RxJavaPlugins.onError(t); - return; - } - error = t; + public void onComplete() { + disposeBoundary(); done = true; - if (enter()) { - drainLoop(); - } + drain(); + } - if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); + @Override + public void cancel() { + if (stopWindows.compareAndSet(false, true)) { + disposeBoundary(); + if (windows.decrementAndGet() == 0) { + upstream.cancel(); + } } - - actual.onError(t); } @Override - public void onComplete() { - if (done) { - return; - } - done = true; - if (enter()) { - drainLoop(); + public void request(long n) { + BackpressureHelper.add(requested, n); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + void disposeBoundary() { + Disposable d = boundarySubscriber.getAndSet((WindowBoundaryInnerSubscriber)BOUNDARY_DISPOSED); + if (d != null && d != BOUNDARY_DISPOSED) { + d.dispose(); } + } + @Override + public void run() { if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); + upstream.cancel(); } + } - actual.onComplete(); - + void innerNext(WindowBoundaryInnerSubscriber sender) { + boundarySubscriber.compareAndSet(sender, null); + queue.offer(NEXT_WINDOW); + drain(); } - @Override - public void request(long n) { - requested(n); + void innerError(Throwable e) { + upstream.cancel(); + if (errors.addThrowable(e)) { + done = true; + drain(); + } else { + RxJavaPlugins.onError(e); + } } - @Override - public void cancel() { - cancelled = true; + void innerComplete() { + upstream.cancel(); + done = true; + drain(); } - void drainLoop() { - final SimplePlainQueue q = queue; - final Subscriber> a = actual; + @SuppressWarnings("unchecked") + void drain() { + if (getAndIncrement() != 0) { + return; + } + int missed = 1; - UnicastProcessor w = window; + Subscriber> downstream = this.downstream; + MpscLinkedQueue queue = this.queue; + AtomicThrowable errors = this.errors; + long emitted = this.emitted; + for (;;) { for (;;) { + if (windows.get() == 0) { + queue.clear(); + window = null; + return; + } + + UnicastProcessor w = window; + boolean d = done; - Object o = q.poll(); + if (d && errors.get() != null) { + queue.clear(); + Throwable ex = errors.terminate(); + if (w != null) { + window = null; + w.onError(ex); + } + downstream.onError(ex); + return; + } + + Object v = queue.poll(); - boolean empty = o == null; + boolean empty = v == null; if (d && empty) { - DisposableHelper.dispose(boundary); - Throwable e = error; - if (e != null) { - w.onError(e); + Throwable ex = errors.terminate(); + if (ex == null) { + if (w != null) { + window = null; + w.onComplete(); + } + downstream.onComplete(); } else { - w.onComplete(); + if (w != null) { + window = null; + w.onError(ex); + } + downstream.onError(ex); } return; } @@ -221,73 +244,57 @@ void drainLoop() { break; } - if (o == NEXT) { + if (v != NEXT_WINDOW) { + w.onNext((T)v); + continue; + } + + if (w != null) { + window = null; w.onComplete(); + } - if (windows.decrementAndGet() == 0) { - DisposableHelper.dispose(boundary); - return; - } + if (!stopWindows.get()) { + if (emitted != requested.get()) { + w = UnicastProcessor.create(capacityHint, this); + window = w; + windows.getAndIncrement(); - if (cancelled) { - continue; - } + Publisher otherSource; - Publisher p; + try { + otherSource = ObjectHelper.requireNonNull(other.call(), "The other Callable returned a null Publisher"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + errors.addThrowable(ex); + done = true; + continue; + } - try { - p = ObjectHelper.requireNonNull(other.call(), "The publisher supplied is null"); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - DisposableHelper.dispose(boundary); - a.onError(e); - return; - } + WindowBoundaryInnerSubscriber bo = new WindowBoundaryInnerSubscriber(this); - w = UnicastProcessor.create(bufferSize); + if (boundarySubscriber.compareAndSet(null, bo)) { + otherSource.subscribe(bo); - long r = requested(); - if (r != 0L) { - windows.getAndIncrement(); - - a.onNext(w); - if (r != Long.MAX_VALUE) { - produced(1); + emitted++; + downstream.onNext(w); } } else { - // don't emit new windows - cancelled = true; - a.onError(new MissingBackpressureException("Could not deliver new window due to lack of requests")); - continue; - } - - window = w; - - WindowBoundaryInnerSubscriber b = new WindowBoundaryInnerSubscriber(this); - - if (boundary.compareAndSet(boundary.get(), b)) { - p.subscribe(b); + upstream.cancel(); + disposeBoundary(); + errors.addThrowable(new MissingBackpressureException("Could not deliver a window due to lack of requests")); + done = true; } - - continue; } - - w.onNext(NotificationLite.getValue(o)); } - missed = leave(-missed); + this.emitted = emitted; + missed = addAndGet(-missed); if (missed == 0) { - return; + break; } } } - - void next() { - queue.offer(NEXT); - if (enter()) { - drainLoop(); - } - } } static final class WindowBoundaryInnerSubscriber extends DisposableSubscriber { @@ -305,8 +312,8 @@ public void onNext(B t) { return; } done = true; - cancel(); - parent.next(); + dispose(); + parent.innerNext(this); } @Override @@ -316,7 +323,7 @@ public void onError(Throwable t) { return; } done = true; - parent.onError(t); + parent.innerError(t); } @Override @@ -325,7 +332,7 @@ public void onComplete() { return; } done = true; - parent.onComplete(); + parent.innerComplete(); } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java index 7ceccf678f..d9912f0b01 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java @@ -19,7 +19,7 @@ import java.util.*; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.*; import org.junit.Test; import org.reactivestreams.*; @@ -28,6 +28,8 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.*; import io.reactivex.subscribers.*; @@ -198,7 +200,7 @@ public void onComplete() { } @Test - public void testWindowViaFlowableSourceThrows() { + public void testWindowViaFlowableThrows() { PublishProcessor source = PublishProcessor.create(); PublishProcessor boundary = PublishProcessor.create(); @@ -343,8 +345,8 @@ public Flowable call() { boundary.onComplete(); - // FIXME source still active because the open window - assertTrue(source.hasSubscribers()); + + assertFalse(source.hasSubscribers()); assertFalse(boundary.hasSubscribers()); ts.assertComplete(); @@ -371,10 +373,14 @@ public Flowable call() { ts.dispose(); - // FIXME source has subscribers because the open window + assertTrue(source.hasSubscribers()); - // FIXME boundary has subscribers because the open window - assertTrue(boundary.hasSubscribers()); + + assertFalse(boundary.hasSubscribers()); + + ts.values().get(0).test().cancel(); + + assertFalse(source.hasSubscribers()); ts.assertNotComplete(); ts.assertNoErrors(); @@ -503,8 +509,18 @@ public Flowable apply(Flowable v) throws Exception { TestHelper.checkBadSourceFlowable(new Function, Object>() { @Override - public Object apply(Flowable o) throws Exception { - return Flowable.just(1).window(Functions.justCallable(o)).flatMap(new Function, Flowable>() { + public Object apply(final Flowable o) throws Exception { + return Flowable.just(1).window(new Callable>() { + int count; + @Override + public Publisher call() throws Exception { + if (++count > 1) { + return Flowable.never(); + } + return o; + } + }) + .flatMap(new Function, Flowable>() { @Override public Flowable apply(Flowable v) throws Exception { return v; @@ -716,4 +732,625 @@ public Publisher> apply(Flowable f) } }); } + + @Test + public void upstreamDisposedWhenOutputsDisposed() { + PublishProcessor source = PublishProcessor.create(); + PublishProcessor boundary = PublishProcessor.create(); + + TestSubscriber to = source.window(boundary) + .take(1) + .flatMap(new Function, Flowable>() { + @Override + public Flowable apply( + Flowable w) throws Exception { + return w.take(1); + } + }) + .test(); + + source.onNext(1); + + assertFalse("source not disposed", source.hasSubscribers()); + assertFalse("boundary not disposed", boundary.hasSubscribers()); + + to.assertResult(1); + } + + + @Test + public void mainAndBoundaryBothError() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> ref = new AtomicReference>(); + + TestSubscriber> to = Flowable.error(new TestException("main")) + .window(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ref.set(observer); + } + }) + .test(); + + to + .assertValueCount(1) + .assertError(TestException.class) + .assertErrorMessage("main") + .assertNotComplete(); + + ref.get().onError(new TestException("inner")); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void mainCompleteBoundaryErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestSubscriber> to = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + refMain.set(observer); + } + } + .window(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ref.set(observer); + } + }) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + refMain.get().onComplete(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ref.get().onError(ex); + } + }; + + TestHelper.race(r1, r2); + + to + .assertValueCount(1) + .assertTerminated(); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void mainNextBoundaryNextRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestSubscriber> to = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + refMain.set(observer); + } + } + .window(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ref.set(observer); + } + }) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + refMain.get().onNext(1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ref.get().onNext(1); + } + }; + + TestHelper.race(r1, r2); + + to + .assertValueCount(2) + .assertNotComplete() + .assertNoErrors(); + } + } + + @Test + public void takeOneAnotherBoundary() { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestSubscriber> to = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + refMain.set(observer); + } + } + .window(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ref.set(observer); + } + }) + .test(); + + to.assertValueCount(1) + .assertNotTerminated() + .cancel(); + + ref.get().onNext(1); + + to.assertValueCount(1) + .assertNotTerminated(); + } + + @Test + public void disposeMainBoundaryCompleteRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + final TestSubscriber> to = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + refMain.set(observer); + } + } + .window(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + final AtomicInteger counter = new AtomicInteger(); + observer.onSubscribe(new Subscription() { + + @Override + public void cancel() { + // about a microsecond + for (int i = 0; i < 100; i++) { + counter.incrementAndGet(); + } + } + + @Override + public void request(long n) { + } + }); + ref.set(observer); + } + }) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + Subscriber o = ref.get(); + o.onNext(1); + o.onComplete(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void disposeMainBoundaryErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + final TestSubscriber> to = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + refMain.set(observer); + } + } + .window(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + final AtomicInteger counter = new AtomicInteger(); + observer.onSubscribe(new Subscription() { + + @Override + public void cancel() { + // about a microsecond + for (int i = 0; i < 100; i++) { + counter.incrementAndGet(); + } + } + + @Override + public void request(long n) { + } + }); + ref.set(observer); + } + }) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + Subscriber o = ref.get(); + o.onNext(1); + o.onError(ex); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void boundarySupplierDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>>() { + @Override + public Flowable> apply(Flowable f) + throws Exception { + return f.window(Functions.justCallable(Flowable.never())).takeLast(1); + } + }); + } + + @Test + public void selectorUpstreamDisposedWhenOutputsDisposed() { + PublishProcessor source = PublishProcessor.create(); + PublishProcessor boundary = PublishProcessor.create(); + + TestSubscriber to = source.window(Functions.justCallable(boundary)) + .take(1) + .flatMap(new Function, Flowable>() { + @Override + public Flowable apply( + Flowable w) throws Exception { + return w.take(1); + } + }) + .test(); + + source.onNext(1); + + assertFalse("source not disposed", source.hasSubscribers()); + assertFalse("boundary not disposed", boundary.hasSubscribers()); + + to.assertResult(1); + } + + @Test + public void supplierMainAndBoundaryBothError() { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> ref = new AtomicReference>(); + + TestSubscriber> to = Flowable.error(new TestException("main")) + .window(Functions.justCallable(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ref.set(observer); + } + })) + .test(); + + to + .assertValueCount(1) + .assertError(TestException.class) + .assertErrorMessage("main") + .assertNotComplete(); + + ref.get().onError(new TestException("inner")); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void supplierMainCompleteBoundaryErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestSubscriber> to = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + refMain.set(observer); + } + } + .window(Functions.justCallable(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ref.set(observer); + } + })) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + refMain.get().onComplete(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ref.get().onError(ex); + } + }; + + TestHelper.race(r1, r2); + + to + .assertValueCount(1) + .assertTerminated(); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + + @Test + public void supplierMainNextBoundaryNextRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestSubscriber> to = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + refMain.set(observer); + } + } + .window(Functions.justCallable(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ref.set(observer); + } + })) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + refMain.get().onNext(1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ref.get().onNext(1); + } + }; + + TestHelper.race(r1, r2); + + to + .assertValueCount(2) + .assertNotComplete() + .assertNoErrors(); + } + } + + @Test + public void supplierTakeOneAnotherBoundary() { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + TestSubscriber> to = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + refMain.set(observer); + } + } + .window(Functions.justCallable(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ref.set(observer); + } + })) + .test(); + + to.assertValueCount(1) + .assertNotTerminated() + .cancel(); + + ref.get().onNext(1); + + to.assertValueCount(1) + .assertNotTerminated(); + } + + @Test + public void supplierDisposeMainBoundaryCompleteRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + final TestSubscriber> to = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + refMain.set(observer); + } + } + .window(Functions.justCallable(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + final AtomicInteger counter = new AtomicInteger(); + observer.onSubscribe(new Subscription() { + + @Override + public void cancel() { + // about a microsecond + for (int i = 0; i < 100; i++) { + counter.incrementAndGet(); + } + } + + @Override + public void request(long n) { + } + }); + ref.set(observer); + } + })) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + Subscriber o = ref.get(); + o.onNext(1); + o.onComplete(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void supplierDisposeMainBoundaryErrorRace() { + final TestException ex = new TestException(); + + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + List errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference> refMain = new AtomicReference>(); + final AtomicReference> ref = new AtomicReference>(); + + final TestSubscriber> to = new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + refMain.set(observer); + } + } + .window(new Callable>() { + int count; + @Override + public Flowable call() throws Exception { + if (++count > 1) { + return Flowable.never(); + } + return (new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + final AtomicInteger counter = new AtomicInteger(); + observer.onSubscribe(new Subscription() { + + @Override + public void cancel() { + // about a microsecond + for (int i = 0; i < 100; i++) { + counter.incrementAndGet(); + } + } + + @Override + public void request(long n) { + } + }); + ref.set(observer); + } + }); + } + }) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + Subscriber o = ref.get(); + o.onNext(1); + o.onError(ex); + } + }; + + TestHelper.race(r1, r2); + + if (!errors.isEmpty()) { + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } + } From 3ba1d35d49f651aa1dc4b4cce09845cfde49ffbb Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 5 Mar 2018 01:08:38 +0100 Subject: [PATCH 121/417] 2.x: Cleanup, coverage and related component fixes (#5889) --- .../flowable/FlowableConcatMapEager.java | 4 - .../flowable/FlowablePublishMulticast.java | 20 +- .../processors/UnicastProcessor.java | 4 +- .../reactivex/subjects/BehaviorSubject.java | 18 +- .../flowable/FlowableMulticastTest.java | 111 --------- .../FlowablePublishMulticastTest.java | 224 ++++++++++++++++++ .../flowable/FlowablePublishTest.java | 47 ++++ .../reactivex/observers/ObserverFusion.java | 2 +- .../processors/UnicastProcessorTest.java | 124 +++++++++- .../subjects/UnicastSubjectTest.java | 75 ++++++ 10 files changed, 490 insertions(+), 139 deletions(-) delete mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableMulticastTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticastTest.java diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java index 6d1af9101a..991a96f45c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java @@ -132,10 +132,6 @@ public void onNext(T t) { subscribers.offer(inner); - if (cancelled) { - return; - } - p.subscribe(inner); if (cancelled) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java index ce12c45e9c..d7cd85d716 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java @@ -153,6 +153,8 @@ static final class MulticastProcessor extends Flowable implements Flowable int consumed; + long emitted; + @SuppressWarnings("unchecked") MulticastProcessor(int prefetch, boolean delayError) { this.prefetch = prefetch; @@ -261,10 +263,10 @@ boolean add(MulticastSubscription s) { void remove(MulticastSubscription s) { for (;;) { MulticastSubscription[] current = subscribers.get(); - if (current == TERMINATED || current == EMPTY) { + int n = current.length; + if (n == 0) { return; } - int n = current.length; int j = -1; for (int i = 0; i < n; i++) { @@ -323,6 +325,7 @@ void drain() { int upstreamConsumed = consumed; int localLimit = limit; boolean canRequest = sourceMode != QueueSubscription.SYNC; + long e = emitted; for (;;) { MulticastSubscription[] array = subscribers.get(); @@ -338,10 +341,15 @@ void drain() { if (r > u) { r = u; } + } else { + n--; } } - long e = 0L; + if (n == 0) { + r = e; + } + while (e != r) { if (isDisposed()) { q.clear(); @@ -425,12 +433,9 @@ void drain() { return; } } - - for (MulticastSubscription ms : array) { - BackpressureHelper.produced(ms, e); - } } + emitted = e; consumed = upstreamConsumed; missed = wip.addAndGet(-missed); if (missed == 0) { @@ -465,7 +470,6 @@ static final class MulticastSubscription extends AtomicLong implements Subscription { - private static final long serialVersionUID = 8664815189257569791L; final Subscriber actual; diff --git a/src/main/java/io/reactivex/processors/UnicastProcessor.java b/src/main/java/io/reactivex/processors/UnicastProcessor.java index 5c4717c5aa..e51dcc4dcc 100644 --- a/src/main/java/io/reactivex/processors/UnicastProcessor.java +++ b/src/main/java/io/reactivex/processors/UnicastProcessor.java @@ -180,8 +180,8 @@ public static UnicastProcessor create(int capacityHint, Runnable onCancel } void doTerminate() { - Runnable r = onTerminate.get(); - if (r != null && onTerminate.compareAndSet(r, null)) { + Runnable r = onTerminate.getAndSet(null); + if (r != null) { r.run(); } } diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java index 6d0d4641ac..d69d444ffb 100644 --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java @@ -442,13 +442,10 @@ void remove(BehaviorDisposable rs) { @SuppressWarnings("unchecked") BehaviorDisposable[] terminate(Object terminalValue) { - BehaviorDisposable[] a = subscribers.get(); + BehaviorDisposable[] a = subscribers.getAndSet(TERMINATED); if (a != TERMINATED) { - a = subscribers.getAndSet(TERMINATED); - if (a != TERMINATED) { - // either this or atomics with lots of allocation - setCurrent(terminalValue); - } + // either this or atomics with lots of allocation + setCurrent(terminalValue); } return a; @@ -456,12 +453,9 @@ BehaviorDisposable[] terminate(Object terminalValue) { void setCurrent(Object o) { writeLock.lock(); - try { - index++; - value.lazySet(o); - } finally { - writeLock.unlock(); - } + index++; + value.lazySet(o); + writeLock.unlock(); } static final class BehaviorDisposable implements Disposable, NonThrowingPredicate { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMulticastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMulticastTest.java deleted file mode 100644 index 0a838499a3..0000000000 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMulticastTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (c) 2016-present, RxJava Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See - * the License for the specific language governing permissions and limitations under the License. - */ - -package io.reactivex.internal.operators.flowable; - -public class FlowableMulticastTest { -// @Test -// public void testMulticast() { -// Processor source = PublishProcessor.create(); -// -// ConnectableObservable multicasted = new OperatorMulticast(source, new PublishProcessorFactory()); -// -// @SuppressWarnings("unchecked") -// Observer observer = mock(Observer.class); -// multicasted.subscribe(observer); -// -// source.onNext("one"); -// source.onNext("two"); -// -// multicasted.connect(); -// -// source.onNext("three"); -// source.onNext("four"); -// source.onComplete(); -// -// verify(observer, never()).onNext("one"); -// verify(observer, never()).onNext("two"); -// verify(observer, times(1)).onNext("three"); -// verify(observer, times(1)).onNext("four"); -// verify(observer, times(1)).onComplete(); -// -// } -// -// @Test -// public void testMulticastConnectTwice() { -// Processor source = PublishProcessor.create(); -// -// ConnectableObservable multicasted = new OperatorMulticast(source, new PublishProcessorFactory()); -// -// @SuppressWarnings("unchecked") -// Observer observer = mock(Observer.class); -// multicasted.subscribe(observer); -// -// source.onNext("one"); -// -// Subscription sub = multicasted.connect(); -// Subscription sub2 = multicasted.connect(); -// -// source.onNext("two"); -// source.onComplete(); -// -// verify(observer, never()).onNext("one"); -// verify(observer, times(1)).onNext("two"); -// verify(observer, times(1)).onComplete(); -// -// assertEquals(sub, sub2); -// -// } -// -// @Test -// public void testMulticastDisconnect() { -// Processor source = PublishProcessor.create(); -// -// ConnectableObservable multicasted = new OperatorMulticast(source, new PublishProcessorFactory()); -// -// @SuppressWarnings("unchecked") -// Observer observer = mock(Observer.class); -// multicasted.subscribe(observer); -// -// source.onNext("one"); -// -// Subscription connection = multicasted.connect(); -// source.onNext("two"); -// -// connection.unsubscribe(); -// source.onNext("three"); -// -// // subscribe again -// multicasted.subscribe(observer); -// // reconnect -// multicasted.connect(); -// source.onNext("four"); -// source.onComplete(); -// -// verify(observer, never()).onNext("one"); -// verify(observer, times(1)).onNext("two"); -// verify(observer, never()).onNext("three"); -// verify(observer, times(1)).onNext("four"); -// verify(observer, times(1)).onComplete(); -// -// } -// -// private static final class PublishProcessorFactory implements Callable> { -// -// @Override -// public Subject call() { -// return PublishProcessor. create(); -// } -// -// } -} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticastTest.java new file mode 100644 index 0000000000..8e004d7af7 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticastTest.java @@ -0,0 +1,224 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.Test; + +import io.reactivex.TestHelper; +import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.operators.flowable.FlowablePublishMulticast.*; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.UnicastProcessor; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowablePublishMulticastTest { + + @Test + public void asyncFusedInput() { + MulticastProcessor mp = new MulticastProcessor(128, true); + + UnicastProcessor up = UnicastProcessor.create(); + + up.subscribe(mp); + + TestSubscriber ts1 = mp.test(); + TestSubscriber ts2 = mp.take(1).test(); + + up.onNext(1); + up.onNext(2); + up.onComplete(); + + ts1.assertResult(1, 2); + ts2.assertResult(1); + } + + @Test + public void fusionRejectedInput() { + MulticastProcessor mp = new MulticastProcessor(128, true); + + mp.onSubscribe(new QueueSubscription() { + + @Override + public int requestFusion(int mode) { + return 0; + } + + @Override + public boolean offer(Integer value) { + return false; + } + + @Override + public boolean offer(Integer v1, Integer v2) { + return false; + } + + @Override + public Integer poll() throws Exception { + return null; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public void clear() { + } + + @Override + public void request(long n) { + } + + @Override + public void cancel() { + } + }); + + TestSubscriber ts = mp.test(); + + mp.onNext(1); + mp.onNext(2); + mp.onComplete(); + + ts.assertResult(1, 2); + } + + @Test + public void addRemoveRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final MulticastProcessor mp = new MulticastProcessor(128, true); + + final MulticastSubscription ms1 = new MulticastSubscription(null, mp); + final MulticastSubscription ms2 = new MulticastSubscription(null, mp); + + assertTrue(mp.add(ms1)); + + Runnable r1 = new Runnable() { + @Override + public void run() { + mp.remove(ms1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + mp.add(ms2); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void removeNotFound() { + MulticastProcessor mp = new MulticastProcessor(128, true); + + MulticastSubscription ms1 = new MulticastSubscription(null, mp); + assertTrue(mp.add(ms1)); + + mp.remove(null); + } + + @Test + public void errorAllCancelled() { + MulticastProcessor mp = new MulticastProcessor(128, true); + + MulticastSubscription ms1 = new MulticastSubscription(null, mp); + assertTrue(mp.add(ms1)); + + ms1.set(Long.MIN_VALUE); + + mp.errorAll(null); + } + + + @Test + public void completeAllCancelled() { + MulticastProcessor mp = new MulticastProcessor(128, true); + + MulticastSubscription ms1 = new MulticastSubscription(null, mp); + assertTrue(mp.add(ms1)); + + ms1.set(Long.MIN_VALUE); + + mp.completeAll(); + } + + @Test + public void cancelledWhileFindingRequests() { + final MulticastProcessor mp = new MulticastProcessor(128, true); + + final MulticastSubscription ms1 = new MulticastSubscription(null, mp); + + assertTrue(mp.add(ms1)); + + mp.onSubscribe(new BooleanSubscription()); + + ms1.set(Long.MIN_VALUE); + + mp.drain(); + } + + @Test + public void negativeRequest() { + final MulticastProcessor mp = new MulticastProcessor(128, true); + + final MulticastSubscription ms1 = new MulticastSubscription(null, mp); + + List errors = TestHelper.trackPluginErrors(); + try { + ms1.request(-1); + + TestHelper.assertError(errors, 0, IllegalArgumentException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void outputCancellerDoubleOnSubscribe() { + TestHelper.doubleOnSubscribe(new OutputCanceller(new TestSubscriber(), null)); + } + + @Test + public void dontDropItemsWhenNoReadyConsumers() { + final MulticastProcessor mp = new MulticastProcessor(128, true); + + mp.onSubscribe(new BooleanSubscription()); + + mp.onNext(1); + + TestSubscriber ts = new TestSubscriber(); + final MulticastSubscription ms1 = new MulticastSubscription(ts, mp); + ts.onSubscribe(ms1); + + assertTrue(mp.add(ms1)); + + ms1.set(Long.MIN_VALUE); + + mp.drain(); + + assertFalse(mp.queue.isEmpty()); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java index 20d074fd4c..432f5231c4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java @@ -29,6 +29,7 @@ import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.fuseable.HasUpstreamPublisher; +import io.reactivex.internal.operators.flowable.FlowablePublish.*; import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; @@ -894,4 +895,50 @@ protected void subscribeActual(Subscriber s) { assertTrue(bs.isCancelled()); } + + @Test + public void disposeRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final AtomicReference ref = new AtomicReference(); + + final ConnectableFlowable co = new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + ref.set((Disposable)s); + } + }.publish(); + + co.connect(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ref.get().dispose(); + } + }; + + TestHelper.race(r1, r1); + } + } + + @Test + public void removeNotPresent() { + final AtomicReference> ref = new AtomicReference>(); + + final ConnectableFlowable co = new Flowable() { + @Override + @SuppressWarnings("unchecked") + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + ref.set((PublishSubscriber)s); + } + }.publish(); + + co.connect(); + + ref.get().add(new InnerSubscriber(new TestSubscriber())); + ref.get().remove(null); + } } diff --git a/src/test/java/io/reactivex/observers/ObserverFusion.java b/src/test/java/io/reactivex/observers/ObserverFusion.java index 5e81b02216..a70c577ca3 100644 --- a/src/test/java/io/reactivex/observers/ObserverFusion.java +++ b/src/test/java/io/reactivex/observers/ObserverFusion.java @@ -32,7 +32,7 @@ public enum ObserverFusion { * Use this as follows: *
                      * source
                -     * .to(ObserverFusion.test(0, QueueDisposable.ANY, false))
                +     * .to(ObserverFusion.test(QueueDisposable.ANY, false))
                      * .assertResult(0);
                      * 
                * @param the value type diff --git a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java index fc19064fdd..63e0c840d4 100644 --- a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java @@ -23,7 +23,7 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subscribers.*; @@ -318,4 +318,126 @@ public void run() { TestHelper.race(r1, r2); } } + + @Test + public void subscribeRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final UnicastProcessor us = UnicastProcessor.create(); + + final TestSubscriber ts1 = new TestSubscriber(); + final TestSubscriber ts2 = new TestSubscriber(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + us.subscribe(ts1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + us.subscribe(ts2); + } + }; + + TestHelper.race(r1, r2); + + if (ts1.errorCount() == 0) { + ts2.assertFailure(IllegalStateException.class); + } else + if (ts2.errorCount() == 0) { + ts1.assertFailure(IllegalStateException.class); + } else { + fail("Neither TestObserver failed"); + } + } + } + + @Test + public void hasObservers() { + UnicastProcessor us = UnicastProcessor.create(); + + assertFalse(us.hasSubscribers()); + + TestSubscriber to = us.test(); + + assertTrue(us.hasSubscribers()); + + to.cancel(); + + assertFalse(us.hasSubscribers()); + } + + @Test + public void drainFusedFailFast() { + UnicastProcessor us = UnicastProcessor.create(false); + + + TestSubscriber to = us.to(SubscriberFusion.test(1, QueueDisposable.ANY, false)); + + us.done = true; + us.drainFused(to); + + to.assertResult(); + } + + @Test + public void drainFusedFailFastEmpty() { + UnicastProcessor us = UnicastProcessor.create(false); + + + TestSubscriber to = us.to(SubscriberFusion.test(1, QueueDisposable.ANY, false)); + + us.drainFused(to); + + to.assertEmpty(); + } + + @Test + public void checkTerminatedFailFastEmpty() { + UnicastProcessor us = UnicastProcessor.create(false); + + TestSubscriber to = us.to(SubscriberFusion.test(1, QueueDisposable.ANY, false)); + + us.checkTerminated(true, true, false, to, us.queue); + + to.assertEmpty(); + } + + @Test + public void alreadyCancelled() { + UnicastProcessor us = UnicastProcessor.create(false); + + us.test().cancel(); + + BooleanSubscription bs = new BooleanSubscription(); + us.onSubscribe(bs); + + assertTrue(bs.isCancelled()); + + List errors = TestHelper.trackPluginErrors(); + try { + us.onError(new TestException()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void unicastSubscriptionBadRequest() { + UnicastProcessor us = UnicastProcessor.create(false); + + UnicastProcessor.UnicastQueueSubscription usc = us.new UnicastQueueSubscription(); + + List errors = TestHelper.trackPluginErrors(); + try { + usc.request(-1); + TestHelper.assertError(errors, 0, IllegalArgumentException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java index ec8f678d72..c05855dcf5 100644 --- a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java @@ -383,4 +383,79 @@ public void dispose() { assertTrue(d.isDisposed()); } + + @Test + public void subscribeRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final UnicastSubject us = UnicastSubject.create(); + + final TestObserver ts1 = new TestObserver(); + final TestObserver ts2 = new TestObserver(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + us.subscribe(ts1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + us.subscribe(ts2); + } + }; + + TestHelper.race(r1, r2); + + if (ts1.errorCount() == 0) { + ts2.assertFailure(IllegalStateException.class); + } else + if (ts2.errorCount() == 0) { + ts1.assertFailure(IllegalStateException.class); + } else { + fail("Neither TestObserver failed"); + } + } + } + + @Test + public void hasObservers() { + UnicastSubject us = UnicastSubject.create(); + + assertFalse(us.hasObservers()); + + TestObserver to = us.test(); + + assertTrue(us.hasObservers()); + + to.cancel(); + + assertFalse(us.hasObservers()); + } + + @Test + public void drainFusedFailFast() { + UnicastSubject us = UnicastSubject.create(false); + + + TestObserver to = us.to(ObserverFusion.test(QueueDisposable.ANY, false)); + + us.done = true; + us.drainFused(to); + + to.assertResult(); + } + + @Test + public void drainFusedFailFastEmpty() { + UnicastSubject us = UnicastSubject.create(false); + + + TestObserver to = us.to(ObserverFusion.test(QueueDisposable.ANY, false)); + + us.drainFused(to); + + to.assertEmpty(); + } } From 51dd03b470d52509eb1835a55801c34e6efbb1d7 Mon Sep 17 00:00:00 2001 From: Harshit Bangar Date: Mon, 5 Mar 2018 15:30:50 +0530 Subject: [PATCH 122/417] Added nullable annotations to subjects (#5890) --- .../io/reactivex/subjects/AsyncSubject.java | 14 ++++++----- .../reactivex/subjects/BehaviorSubject.java | 13 ++++++---- .../subjects/CompletableSubject.java | 6 +++-- .../io/reactivex/subjects/MaybeSubject.java | 18 +++++++------ .../io/reactivex/subjects/PublishSubject.java | 2 ++ .../io/reactivex/subjects/ReplaySubject.java | 7 ++++++ .../reactivex/subjects/SerializedSubject.java | 2 ++ .../io/reactivex/subjects/UnicastSubject.java | 25 ++++++++++--------- 8 files changed, 54 insertions(+), 33 deletions(-) diff --git a/src/main/java/io/reactivex/subjects/AsyncSubject.java b/src/main/java/io/reactivex/subjects/AsyncSubject.java index e447ee08ac..519811a803 100644 --- a/src/main/java/io/reactivex/subjects/AsyncSubject.java +++ b/src/main/java/io/reactivex/subjects/AsyncSubject.java @@ -13,6 +13,7 @@ package io.reactivex.subjects; +import io.reactivex.annotations.Nullable; import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; @@ -85,22 +86,22 @@ * AsyncSubject<Object> subject = AsyncSubject.create(); * * TestObserver<Object> to1 = subject.test(); - * + * * to1.assertEmpty(); - * + * * subject.onNext(1); - * + * * // AsyncSubject only emits when onComplete was called. * to1.assertEmpty(); * * subject.onNext(2); * subject.onComplete(); - * + * * // onComplete triggers the emission of the last cached item and the onComplete event. * to1.assertResult(2); - * + * * TestObserver<Object> to2 = subject.test(); - * + * * // late Observers receive the last cached item too * to2.assertResult(2); * @@ -313,6 +314,7 @@ public boolean hasValue() { *

                The method is thread-safe. * @return a single value the Subject currently has or null if no such value exists */ + @Nullable public T getValue() { return subscribers.get() == TERMINATED ? value : null; } diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java index d69d444ffb..3c006beb53 100644 --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java @@ -14,6 +14,7 @@ package io.reactivex.subjects; import io.reactivex.annotations.CheckReturnValue; +import io.reactivex.annotations.Nullable; import java.lang.reflect.Array; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.*; @@ -63,19 +64,19 @@ * observable.onNext(1); * // this will "clear" the cache * observable.onNext(EMPTY); - * + * * TestObserver<Integer> to2 = observable.test(); - * + * * subject.onNext(2); * subject.onComplete(); - * + * * // to1 received both non-empty items * to1.assertResult(1, 2); - * + * * // to2 received only 2 even though the current item was EMPTY * // when it got subscribed * to2.assertResult(2); - * + * * // Observers coming after the subject was terminated receive * // no items and only the onComplete event in this case. * observable.test().assertResult(); @@ -300,6 +301,7 @@ public boolean hasObservers() { } @Override + @Nullable public Throwable getThrowable() { Object o = value.get(); if (NotificationLite.isError(o)) { @@ -313,6 +315,7 @@ public Throwable getThrowable() { *

                The method is thread-safe. * @return a single value the Subject currently has or null if no such value exists */ + @Nullable public T getValue() { Object o = value.get(); if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { diff --git a/src/main/java/io/reactivex/subjects/CompletableSubject.java b/src/main/java/io/reactivex/subjects/CompletableSubject.java index 69e25be91d..93c626baa0 100644 --- a/src/main/java/io/reactivex/subjects/CompletableSubject.java +++ b/src/main/java/io/reactivex/subjects/CompletableSubject.java @@ -13,6 +13,7 @@ package io.reactivex.subjects; +import io.reactivex.annotations.Nullable; import java.util.concurrent.atomic.*; import io.reactivex.*; @@ -65,12 +66,12 @@ * Example usage: *

                
                  * CompletableSubject subject = CompletableSubject.create();
                - * 
                + *
                  * TestObserver<Void> to1 = subject.test();
                  *
                  * // a fresh CompletableSubject is empty
                  * to1.assertEmpty();
                - * 
                + *
                  * subject.onComplete();
                  *
                  * // a CompletableSubject is always void of items
                @@ -213,6 +214,7 @@ void remove(CompletableDisposable inner) {
                      * Returns the terminal error if this CompletableSubject has been terminated with an error, null otherwise.
                      * @return the terminal error or null if not terminated or not with an error
                      */
                +    @Nullable
                     public Throwable getThrowable() {
                         if (observers.get() == TERMINATED) {
                             return error;
                diff --git a/src/main/java/io/reactivex/subjects/MaybeSubject.java b/src/main/java/io/reactivex/subjects/MaybeSubject.java
                index 629e63312b..1fec546d7c 100644
                --- a/src/main/java/io/reactivex/subjects/MaybeSubject.java
                +++ b/src/main/java/io/reactivex/subjects/MaybeSubject.java
                @@ -72,20 +72,20 @@
                  * Example usage:
                  * 
                
                  * MaybeSubject<Integer> subject1 = MaybeSubject.create();
                - * 
                + *
                  * TestObserver<Integer> to1 = subject1.test();
                - * 
                + *
                  * // MaybeSubjects are empty by default
                  * to1.assertEmpty();
                - * 
                + *
                  * subject1.onSuccess(1);
                - * 
                + *
                  * // onSuccess is a terminal event with MaybeSubjects
                  * // TestObserver converts onSuccess into onNext + onComplete
                  * to1.assertResult(1);
                  *
                  * TestObserver<Integer> to2 = subject1.test();
                - * 
                + *
                  * // late Observers receive the terminal signal (onSuccess) too
                  * to2.assertResult(1);
                  *
                @@ -94,14 +94,14 @@
                  * MaybeSubject<Integer> subject2 = MaybeSubject.create();
                  *
                  * TestObserver<Integer> to3 = subject2.test();
                - * 
                + *
                  * subject2.onComplete();
                - * 
                + *
                  * // a completed MaybeSubject completes its MaybeObservers
                  * to3.assertResult();
                  *
                  * TestObserver<Integer> to4 = subject1.test();
                - * 
                + *
                  * // late Observers receive the terminal signal (onComplete) too
                  * to4.assertResult();
                  * 
                @@ -263,6 +263,7 @@ void remove(MaybeDisposable inner) { * Returns the success value if this MaybeSubject was terminated with a success value. * @return the success value or null */ + @Nullable public T getValue() { if (observers.get() == TERMINATED) { return value; @@ -282,6 +283,7 @@ public boolean hasValue() { * Returns the terminal error if this MaybeSubject has been terminated with an error, null otherwise. * @return the terminal error or null if not terminated or not with an error */ + @Nullable public Throwable getThrowable() { if (observers.get() == TERMINATED) { return error; diff --git a/src/main/java/io/reactivex/subjects/PublishSubject.java b/src/main/java/io/reactivex/subjects/PublishSubject.java index 6a13ffdd2a..7d22a81d2d 100644 --- a/src/main/java/io/reactivex/subjects/PublishSubject.java +++ b/src/main/java/io/reactivex/subjects/PublishSubject.java @@ -14,6 +14,7 @@ package io.reactivex.subjects; import io.reactivex.annotations.CheckReturnValue; +import io.reactivex.annotations.Nullable; import java.util.concurrent.atomic.*; import io.reactivex.Observer; @@ -263,6 +264,7 @@ public boolean hasObservers() { } @Override + @Nullable public Throwable getThrowable() { if (subscribers.get() == TERMINATED) { return error; diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java index fe89540733..29634ff1c4 100644 --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java @@ -13,6 +13,7 @@ package io.reactivex.subjects; +import io.reactivex.annotations.Nullable; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.TimeUnit; @@ -395,6 +396,7 @@ public boolean hasObservers() { } @Override + @Nullable public Throwable getThrowable() { Object o = buffer.get(); if (NotificationLite.isError(o)) { @@ -408,6 +410,7 @@ public Throwable getThrowable() { *

                The method is thread-safe. * @return a single value the Subject currently has or null if no such value exists */ + @Nullable public T getValue() { return buffer.getValue(); } @@ -542,6 +545,7 @@ interface ReplayBuffer { int size(); + @Nullable T getValue(); T[] getValues(T[] array); @@ -620,6 +624,7 @@ public void addFinal(Object notificationLite) { } @Override + @Nullable @SuppressWarnings("unchecked") public T getValue() { int s = size; @@ -838,6 +843,7 @@ public void addFinal(Object notificationLite) { } @Override + @Nullable @SuppressWarnings("unchecked") public T getValue() { Node prev = null; @@ -1080,6 +1086,7 @@ public void addFinal(Object notificationLite) { } @Override + @Nullable @SuppressWarnings("unchecked") public T getValue() { TimedNode prev = null; diff --git a/src/main/java/io/reactivex/subjects/SerializedSubject.java b/src/main/java/io/reactivex/subjects/SerializedSubject.java index 53f3381bce..54ffb596a5 100644 --- a/src/main/java/io/reactivex/subjects/SerializedSubject.java +++ b/src/main/java/io/reactivex/subjects/SerializedSubject.java @@ -14,6 +14,7 @@ package io.reactivex.subjects; import io.reactivex.Observer; +import io.reactivex.annotations.Nullable; import io.reactivex.disposables.Disposable; import io.reactivex.internal.util.*; import io.reactivex.internal.util.AppendOnlyLinkedArrayList.NonThrowingPredicate; @@ -193,6 +194,7 @@ public boolean hasThrowable() { } @Override + @Nullable public Throwable getThrowable() { return actual.getThrowable(); } diff --git a/src/main/java/io/reactivex/subjects/UnicastSubject.java b/src/main/java/io/reactivex/subjects/UnicastSubject.java index 2f5d77f6ba..330e2de85a 100644 --- a/src/main/java/io/reactivex/subjects/UnicastSubject.java +++ b/src/main/java/io/reactivex/subjects/UnicastSubject.java @@ -105,37 +105,37 @@ * Example usage: *
                
                  * UnicastSubject<Integer> subject = UnicastSubject.create();
                - * 
                + *
                  * TestObserver<Integer> to1 = subject.test();
                - * 
                + *
                  * // fresh UnicastSubjects are empty
                  * to1.assertEmpty();
                - * 
                + *
                  * TestObserver<Integer> to2 = subject.test();
                - * 
                + *
                  * // A UnicastSubject only allows one Observer during its lifetime
                  * to2.assertFailure(IllegalStateException.class);
                - * 
                + *
                  * subject.onNext(1);
                  * to1.assertValue(1);
                - * 
                + *
                  * subject.onNext(2);
                  * to1.assertValues(1, 2);
                - * 
                + *
                  * subject.onComplete();
                  * to1.assertResult(1, 2);
                - * 
                + *
                  * // ----------------------------------------------------
                - * 
                + *
                  * UnicastSubject<Integer> subject2 = UnicastSubject.create();
                - * 
                + *
                  * // a UnicastSubject caches events util its single Observer subscribes
                  * subject.onNext(1);
                  * subject.onNext(2);
                  * subject.onComplete();
                - * 
                + *
                  * TestObserver<Integer> to3 = subject2.test();
                - * 
                + *
                  * // the cached events are emitted in order
                  * to3.assertResult(1, 2);
                  * 
                @@ -498,6 +498,7 @@ public boolean hasObservers() { } @Override + @Nullable public Throwable getThrowable() { if (done) { return error; From cb05a2614c11ebb7b86e723556f98e50546a50ed Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 5 Mar 2018 17:41:09 +0100 Subject: [PATCH 123/417] 2.x: Improve coverage & related cleanup 03/05 (#5891) * 2.x: Improve coverage & related cleanup 03/05 * Fix camelCase local variable naming errors in tests. --- .../flowable/BlockingFlowableIterable.java | 4 +- .../flowable/FlowableBufferBoundary.java | 8 +- .../operators/flowable/FlowableCache.java | 4 +- .../flowable/FlowableCombineLatest.java | 4 +- .../operators/flowable/FlowableGroupJoin.java | 8 +- .../flowable/FlowableMergeWithMaybe.java | 6 +- .../flowable/FlowableMergeWithSingle.java | 6 +- .../operators/flowable/FlowableReplay.java | 40 +- .../flowable/FlowableSamplePublisher.java | 8 +- .../operators/flowable/FlowableSkipUntil.java | 4 +- .../operators/flowable/FlowableTakeUntil.java | 4 +- .../operators/flowable/FlowableTimeout.java | 4 +- .../flowable/FlowableWindowBoundary.java | 4 +- .../flowable/FlowableWithLatestFromMany.java | 4 +- .../maybe/MaybeDelayOtherPublisher.java | 4 +- .../operators/maybe/MaybeFromFuture.java | 15 +- .../maybe/MaybeTakeUntilPublisher.java | 4 +- .../maybe/MaybeTimeoutPublisher.java | 4 +- .../operators/observable/ObservableSkip.java | 9 +- .../operators/parallel/ParallelJoin.java | 4 +- .../parallel/ParallelReduceFull.java | 4 +- .../parallel/ParallelSortedJoin.java | 4 +- .../single/SingleDelayWithSingle.java | 2 +- .../operators/single/SingleTakeUntil.java | 4 +- .../schedulers/SchedulerPoolFactory.java | 99 +-- .../schedulers/TrampolineScheduler.java | 14 +- .../subscribers/ForEachWhileSubscriber.java | 4 +- .../subscribers/FutureSubscriber.java | 4 +- .../subscriptions/SubscriptionHelper.java | 20 + src/test/java/io/reactivex/TestHelper.java | 104 +++ .../flowable/FlowableBackpressureTests.java | 136 ++-- .../flowable/FlowableCovarianceTest.java | 6 +- .../observers/BlockingFirstObserverTest.java | 48 ++ .../observers/BlockingObserverTest.java | 38 + .../completable/CompletableAmbTest.java | 24 + .../CompletableFromActionTest.java | 40 +- .../CompletableFromCallableTest.java | 37 +- .../CompletableFromPublisherTest.java | 11 + .../CompletableFromRunnableTest.java | 38 +- .../completable/CompletableTimeoutTest.java | 25 + .../CompletableToFlowableTest.java | 33 + .../operators/flowable/FlowableAmbTest.java | 30 +- .../flowable/FlowableCombineLatestTest.java | 6 +- .../flowable/FlowableConcatMapTest.java | 42 ++ .../flowable/FlowableDebounceTest.java | 180 +++-- .../flowable/FlowableFilterTest.java | 16 +- .../flowable/FlowableGroupByTest.java | 2 +- .../flowable/FlowableGroupJoinTest.java | 37 + .../operators/flowable/FlowableHideTest.java | 83 +++ .../flowable/FlowableIgnoreElementsTest.java | 19 + .../flowable/FlowableIntervalTest.java | 22 +- .../flowable/FlowableMergeDelayErrorTest.java | 4 +- .../operators/flowable/FlowableMergeTest.java | 4 +- .../flowable/FlowableRepeatTest.java | 6 +- .../flowable/FlowableReplayTest.java | 8 + .../operators/flowable/FlowableRetryTest.java | 54 +- .../flowable/FlowableSampleTest.java | 12 + .../flowable/FlowableSkipLastTest.java | 12 + .../operators/flowable/FlowableSkipTest.java | 13 +- .../operators/flowable/FlowableTakeTest.java | 24 + .../flowable/FlowableTakeUntilTest.java | 11 + .../flowable/FlowableTimeIntervalTest.java | 12 +- .../flowable/FlowableToListTest.java | 19 + .../flowable/FlowableUnsubscribeOnTest.java | 20 +- .../operators/maybe/MaybeAmbTest.java | 21 + .../operators/maybe/MaybeDelayOtherTest.java | 26 + .../operators/maybe/MaybeFromActionTest.java | 28 + .../operators/maybe/MaybeFromFutureTest.java | 61 ++ .../maybe/MaybeFromRunnableTest.java | 28 + .../operators/maybe/MaybeMapTest.java | 33 + .../observable/ObservableDebounceTest.java | 76 +- .../observable/ObservableDoAfterNextTest.java | 26 +- .../observable/ObservableGroupJoinTest.java | 37 + .../observable/ObservableIntervalTest.java | 15 + .../observable/ObservablePublishTest.java | 18 + .../observable/ObservableRepeatTest.java | 6 +- .../observable/ObservableRetryTest.java | 40 +- .../observable/ObservableSampleTest.java | 12 + .../observable/ObservableSkipLastTest.java | 12 + .../observable/ObservableSkipTest.java | 12 + .../observable/ObservableTakeUntilTest.java | 11 + .../ObservableTimeIntervalTest.java | 11 + .../observable/ObservableTimerTest.java | 15 + .../observable/ObservableToListTest.java | 19 + .../ObservableUnsubscribeOnTest.java | 20 +- .../operators/single/SingleDelayTest.java | 31 +- .../schedulers/SchedulerPoolFactoryTest.java | 117 +++ .../TrampolineSchedulerInternalTest.java | 48 ++ .../DeferredScalarSubscriberTest.java | 12 +- .../SubscriberResourceWrapperTest.java | 30 + .../subscriptions/SubscriptionHelperTest.java | 29 +- .../internal/util/QueueDrainHelperTest.java | 677 +++++++++++++++++- .../observable/ObservableCovarianceTest.java | 6 +- 93 files changed, 2523 insertions(+), 433 deletions(-) create mode 100644 src/test/java/io/reactivex/internal/observers/BlockingFirstObserverTest.java create mode 100644 src/test/java/io/reactivex/internal/observers/BlockingObserverTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/completable/CompletableToFlowableTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/maybe/MaybeMapTest.java diff --git a/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java b/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java index 478aa2281e..2eaaa5ffd3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java @@ -125,9 +125,7 @@ public T next() { @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(batchSize); - } + SubscriptionHelper.setOnce(this, s, batchSize); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java index acf35be0cd..317ad249ee 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java @@ -327,9 +327,7 @@ static final class BufferOpenSubscriber @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override @@ -378,9 +376,7 @@ static final class BufferCloseSubscriber> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java index a4294474be..24cad0d2f7 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java @@ -180,9 +180,7 @@ public void removeChild(ReplaySubscription p) { @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(connection, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(connection, s, Long.MAX_VALUE); } /** diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java index cbdda4a4bc..6ed1f116ef 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java @@ -516,9 +516,7 @@ static final class CombineLatestInnerSubscriber @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(prefetch); - } + SubscriptionHelper.setOnce(this, s, prefetch); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java index 499bc38ff7..c0bfb84e6f 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java @@ -417,9 +417,7 @@ public boolean isDisposed() { @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override @@ -470,9 +468,7 @@ public boolean isDisposed() { @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java index 68c8e2c8f5..7a48d38875 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java @@ -98,10 +98,8 @@ static final class MergeWithObserver extends AtomicInteger } @Override - public void onSubscribe(Subscription d) { - if (SubscriptionHelper.setOnce(mainSubscription, d)) { - d.request(prefetch); - } + public void onSubscribe(Subscription s) { + SubscriptionHelper.setOnce(mainSubscription, s, prefetch); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java index b14c5c9b22..fca1812b78 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java @@ -98,10 +98,8 @@ static final class MergeWithObserver extends AtomicInteger } @Override - public void onSubscribe(Subscription d) { - if (SubscriptionHelper.setOnce(mainSubscription, d)) { - d.request(prefetch); - } + public void onSubscribe(Subscription s) { + SubscriptionHelper.setOnce(mainSubscription, s, prefetch); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java index 8d1f2eaaad..3005eb11c8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java @@ -526,36 +526,16 @@ static final class InnerSubscription extends AtomicLong implements Subscripti public void request(long n) { // ignore negative requests if (SubscriptionHelper.validate(n)) { - // In general, RxJava doesn't prevent concurrent requests (with each other or with - // a cancel) so we need a CAS-loop, but we need to handle - // request overflow and cancelled/not requested state as well. - for (;;) { - // get the current request amount - long r = get(); - // if child called cancel() do nothing - if (r == CANCELLED) { - return; - } - // ignore zero requests except any first that sets in zero - if (r >= 0L && n == 0) { - return; - } - // otherwise, increase the request count - long u = BackpressureHelper.addCap(r, n); - - // try setting the new request value - if (compareAndSet(r, u)) { - // increment the total request counter - BackpressureHelper.add(totalRequested, n); - // if successful, notify the parent dispatcher this child can receive more - // elements - parent.manageRequests(); - - parent.buffer.replay(this); - return; - } - // otherwise, someone else changed the state (perhaps a concurrent - // request or cancellation) so retry + // add to the current requested and cap it at MAX_VALUE + // except when there was a concurrent cancellation + if (BackpressureHelper.addCancel(this, n) != CANCELLED) { + // increment the total request counter + BackpressureHelper.add(totalRequested, n); + // if successful, notify the parent dispatcher this child can receive more + // elements + parent.manageRequests(); + // try replaying any cached content + parent.buffer.replay(this); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java index de9a71b223..a75f4c1e05 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java @@ -93,8 +93,8 @@ public void onComplete() { completeMain(); } - boolean setOther(Subscription o) { - return SubscriptionHelper.setOnce(other, o); + void setOther(Subscription o) { + SubscriptionHelper.setOnce(other, o, Long.MAX_VALUE); } @Override @@ -150,9 +150,7 @@ static final class SamplerSubscriber implements FlowableSubscriber { @Override public void onSubscribe(Subscription s) { - if (parent.setOther(s)) { - s.request(Long.MAX_VALUE); - } + parent.setOther(s); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipUntil.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipUntil.java index 857623d1ac..0f980ac883 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipUntil.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipUntil.java @@ -114,9 +114,7 @@ final class OtherSubscriber extends AtomicReference @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntil.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntil.java index c5352264ff..0743eb1d00 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntil.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntil.java @@ -99,9 +99,7 @@ final class OtherSubscriber extends AtomicReference implements Flo @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java index e01fb5b525..99def36def 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java @@ -343,9 +343,7 @@ static final class TimeoutConsumer extends AtomicReference @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java index 8c8164f76f..46e445bd26 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java @@ -95,9 +95,7 @@ static final class WindowBoundaryMainSubscriber @Override public void onSubscribe(Subscription d) { - if (SubscriptionHelper.setOnce(upstream, d)) { - d.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(upstream, d, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java index 874bf92ccf..2566fe3e5c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java @@ -268,9 +268,7 @@ static final class WithLatestInnerSubscriber @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java index b14b17a671..61ae58f62a 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java @@ -120,9 +120,7 @@ static final class OtherSubscriber extends @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromFuture.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromFuture.java index 1dd41d38bc..7a206007aa 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromFuture.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromFuture.java @@ -17,6 +17,7 @@ import io.reactivex.*; import io.reactivex.disposables.*; +import io.reactivex.exceptions.Exceptions; /** * Waits until the source Future completes or the wait times out; treats a {@code null} @@ -50,17 +51,11 @@ protected void subscribeActual(MaybeObserver observer) { } else { v = future.get(timeout, unit); } - } catch (InterruptedException ex) { - if (!d.isDisposed()) { - observer.onError(ex); - } - return; - } catch (ExecutionException ex) { - if (!d.isDisposed()) { - observer.onError(ex.getCause()); + } catch (Throwable ex) { + if (ex instanceof ExecutionException) { + ex = ex.getCause(); } - return; - } catch (TimeoutException ex) { + Exceptions.throwIfFatal(ex); if (!d.isDisposed()) { observer.onError(ex); } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java index 3ddd26d570..6db80da42f 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java @@ -132,9 +132,7 @@ static final class TakeUntilOtherMaybeObserver @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java index 79c2aea625..801e646e7b 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java @@ -155,9 +155,7 @@ static final class TimeoutOtherMaybeObserver @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java index 5eeefde388..944506365a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java @@ -15,6 +15,7 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; public final class ObservableSkip extends AbstractObservableWithUpstream { final long n; @@ -40,9 +41,11 @@ static final class SkipObserver implements Observer, Disposable { } @Override - public void onSubscribe(Disposable s) { - this.d = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.d, d)) { + this.d = d; + actual.onSubscribe(this); + } } @Override diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java index 04ab4033cc..7a29e1bed4 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java @@ -516,9 +516,7 @@ static final class JoinInnerSubscriber @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(prefetch); - } + SubscriptionHelper.setOnce(this, s, prefetch); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java index 98d536045c..1505ea0ff3 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java @@ -180,9 +180,7 @@ static final class ParallelReduceFullInnerSubscriber @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java index 33abbd132f..43ef716d1a 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java @@ -280,9 +280,7 @@ static final class SortedJoinInnerSubscriber @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java index 32e2462513..b42f678878 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java @@ -54,7 +54,7 @@ static final class OtherObserver @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.set(this, d)) { + if (DisposableHelper.setOnce(this, d)) { actual.onSubscribe(this); } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java b/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java index 8c340e4edf..6d1183e80c 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java @@ -139,9 +139,7 @@ static final class TakeUntilOtherSubscriber @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/schedulers/SchedulerPoolFactory.java b/src/main/java/io/reactivex/internal/schedulers/SchedulerPoolFactory.java index 7aa5bb6a19..b0b1339d29 100644 --- a/src/main/java/io/reactivex/internal/schedulers/SchedulerPoolFactory.java +++ b/src/main/java/io/reactivex/internal/schedulers/SchedulerPoolFactory.java @@ -20,8 +20,6 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; -import io.reactivex.plugins.RxJavaPlugins; - /** * Manages the creating of ScheduledExecutorServices and sets up purging. */ @@ -57,22 +55,25 @@ private SchedulerPoolFactory() { * Starts the purge thread if not already started. */ public static void start() { - if (!PURGE_ENABLED) { - return; - } - for (;;) { - ScheduledExecutorService curr = PURGE_THREAD.get(); - if (curr != null && !curr.isShutdown()) { - return; - } - ScheduledExecutorService next = Executors.newScheduledThreadPool(1, new RxThreadFactory("RxSchedulerPurge")); - if (PURGE_THREAD.compareAndSet(curr, next)) { + tryStart(PURGE_ENABLED); + } - next.scheduleAtFixedRate(new ScheduledTask(), PURGE_PERIOD_SECONDS, PURGE_PERIOD_SECONDS, TimeUnit.SECONDS); + static void tryStart(boolean purgeEnabled) { + if (purgeEnabled) { + for (;;) { + ScheduledExecutorService curr = PURGE_THREAD.get(); + if (curr != null) { + return; + } + ScheduledExecutorService next = Executors.newScheduledThreadPool(1, new RxThreadFactory("RxSchedulerPurge")); + if (PURGE_THREAD.compareAndSet(curr, next)) { - return; - } else { - next.shutdownNow(); + next.scheduleAtFixedRate(new ScheduledTask(), PURGE_PERIOD_SECONDS, PURGE_PERIOD_SECONDS, TimeUnit.SECONDS); + + return; + } else { + next.shutdownNow(); + } } } } @@ -81,7 +82,7 @@ public static void start() { * Stops the purge thread. */ public static void shutdown() { - ScheduledExecutorService exec = PURGE_THREAD.get(); + ScheduledExecutorService exec = PURGE_THREAD.getAndSet(null); if (exec != null) { exec.shutdownNow(); } @@ -89,25 +90,42 @@ public static void shutdown() { } static { - boolean purgeEnable = true; - int purgePeriod = 1; - Properties properties = System.getProperties(); - if (properties.containsKey(PURGE_ENABLED_KEY)) { - purgeEnable = Boolean.getBoolean(PURGE_ENABLED_KEY); - } + PurgeProperties pp = new PurgeProperties(); + pp.load(properties); - if (purgeEnable && properties.containsKey(PURGE_PERIOD_SECONDS_KEY)) { - purgePeriod = Integer.getInteger(PURGE_PERIOD_SECONDS_KEY, purgePeriod); - } - - PURGE_ENABLED = purgeEnable; - PURGE_PERIOD_SECONDS = purgePeriod; + PURGE_ENABLED = pp.purgeEnable; + PURGE_PERIOD_SECONDS = pp.purgePeriod; start(); } + static final class PurgeProperties { + + boolean purgeEnable; + + int purgePeriod; + + void load(Properties properties) { + if (properties.containsKey(PURGE_ENABLED_KEY)) { + purgeEnable = Boolean.parseBoolean(properties.getProperty(PURGE_ENABLED_KEY)); + } else { + purgeEnable = true; + } + + if (purgeEnable && properties.containsKey(PURGE_PERIOD_SECONDS_KEY)) { + try { + purgePeriod = Integer.parseInt(properties.getProperty(PURGE_PERIOD_SECONDS_KEY)); + } catch (NumberFormatException ex) { + purgePeriod = 1; + } + } else { + purgePeriod = 1; + } + } + } + /** * Creates a ScheduledExecutorService with the given factory. * @param factory the thread factory @@ -115,27 +133,26 @@ public static void shutdown() { */ public static ScheduledExecutorService create(ThreadFactory factory) { final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1, factory); - if (PURGE_ENABLED && exec instanceof ScheduledThreadPoolExecutor) { + tryPutIntoPool(PURGE_ENABLED, exec); + return exec; + } + + static void tryPutIntoPool(boolean purgeEnabled, ScheduledExecutorService exec) { + if (purgeEnabled && exec instanceof ScheduledThreadPoolExecutor) { ScheduledThreadPoolExecutor e = (ScheduledThreadPoolExecutor) exec; POOLS.put(e, exec); } - return exec; } static final class ScheduledTask implements Runnable { @Override public void run() { - try { - for (ScheduledThreadPoolExecutor e : new ArrayList(POOLS.keySet())) { - if (e.isShutdown()) { - POOLS.remove(e); - } else { - e.purge(); - } + for (ScheduledThreadPoolExecutor e : new ArrayList(POOLS.keySet())) { + if (e.isShutdown()) { + POOLS.remove(e); + } else { + e.purge(); } - } catch (Throwable e) { - // Exceptions.throwIfFatal(e); nowhere to go - RxJavaPlugins.onError(e); } } } diff --git a/src/main/java/io/reactivex/internal/schedulers/TrampolineScheduler.java b/src/main/java/io/reactivex/internal/schedulers/TrampolineScheduler.java index 20421072e5..49a053f9db 100644 --- a/src/main/java/io/reactivex/internal/schedulers/TrampolineScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/TrampolineScheduler.java @@ -190,14 +190,12 @@ public void run() { long t = worker.now(TimeUnit.MILLISECONDS); if (execTime > t) { long delay = execTime - t; - if (delay > 0) { - try { - Thread.sleep(delay); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - RxJavaPlugins.onError(e); - return; - } + try { + Thread.sleep(delay); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + RxJavaPlugins.onError(e); + return; } } diff --git a/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java index 812a0d601e..c296ffe088 100644 --- a/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java @@ -48,9 +48,7 @@ public ForEachWhileSubscriber(Predicate onNext, @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java index b2a06f53e6..9537556008 100644 --- a/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java @@ -110,9 +110,7 @@ public T get(long timeout, TimeUnit unit) throws InterruptedException, Execution @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this.s, s)) { - s.request(Long.MAX_VALUE); - } + SubscriptionHelper.setOnce(this.s, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java b/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java index 071aefb683..cddd53b8d1 100644 --- a/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java +++ b/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java @@ -239,4 +239,24 @@ public static void deferredRequest(AtomicReference field, AtomicLo } } } + + /** + * Atomically sets the subscription on the field if it is still null and issues a positive request + * to the given {@link Subscription}. + *

                + * If the field is not null and doesn't contain the {@link #CANCELLED} + * instance, the {@link #reportSubscriptionSet()} is called. + * @param field the target field + * @param s the new subscription to set + * @param request the amount to request, positive (not verified) + * @return true if the operation succeeded, false if the target field was not null. + * @since 2.1.11 + */ + public static boolean setOnce(AtomicReference field, Subscription s, long request) { + if (setOnce(field, s)) { + s.request(request); + return true; + } + return false; + } } diff --git a/src/test/java/io/reactivex/TestHelper.java b/src/test/java/io/reactivex/TestHelper.java index b0bbf1d9a6..b6660c19d6 100644 --- a/src/test/java/io/reactivex/TestHelper.java +++ b/src/test/java/io/reactivex/TestHelper.java @@ -2050,6 +2050,110 @@ protected void subscribeActual(CompletableObserver observer) { } } + /** + * Check if the given transformed reactive type reports multiple onSubscribe calls to + * RxJavaPlugins. + * @param transform the transform to drive an operator + */ + public static void checkDoubleOnSubscribeCompletableToFlowable(Function> transform) { + List errors = trackPluginErrors(); + try { + final Boolean[] b = { null, null }; + final CountDownLatch cdl = new CountDownLatch(1); + + Completable source = new Completable() { + @Override + protected void subscribeActual(CompletableObserver observer) { + try { + Disposable d1 = Disposables.empty(); + + observer.onSubscribe(d1); + + Disposable d2 = Disposables.empty(); + + observer.onSubscribe(d2); + + b[0] = d1.isDisposed(); + b[1] = d2.isDisposed(); + } finally { + cdl.countDown(); + } + } + }; + + Publisher out = transform.apply(source); + + out.subscribe(NoOpConsumer.INSTANCE); + + try { + assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + + assertEquals("First disposed?", false, b[0]); + assertEquals("Second not disposed?", true, b[1]); + + assertError(errors, 0, IllegalStateException.class, "Disposable already set!"); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } finally { + RxJavaPlugins.reset(); + } + } + + /** + * Check if the given transformed reactive type reports multiple onSubscribe calls to + * RxJavaPlugins. + * @param transform the transform to drive an operator + */ + public static void checkDoubleOnSubscribeCompletableToObservable(Function> transform) { + List errors = trackPluginErrors(); + try { + final Boolean[] b = { null, null }; + final CountDownLatch cdl = new CountDownLatch(1); + + Completable source = new Completable() { + @Override + protected void subscribeActual(CompletableObserver observer) { + try { + Disposable d1 = Disposables.empty(); + + observer.onSubscribe(d1); + + Disposable d2 = Disposables.empty(); + + observer.onSubscribe(d2); + + b[0] = d1.isDisposed(); + b[1] = d2.isDisposed(); + } finally { + cdl.countDown(); + } + } + }; + + ObservableSource out = transform.apply(source); + + out.subscribe(NoOpConsumer.INSTANCE); + + try { + assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + + assertEquals("First disposed?", false, b[0]); + assertEquals("Second not disposed?", true, b[1]); + + assertError(errors, 0, IllegalStateException.class, "Disposable already set!"); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } finally { + RxJavaPlugins.reset(); + } + } + /** * Check if the operator applied to a Maybe source propagates dispose properly. * @param the source value type diff --git a/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java b/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java index 8e658cd5d7..9ad78fd1e4 100644 --- a/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java @@ -80,20 +80,20 @@ public void doAfterTest() { @Test public void testObserveOn() { - int NUM = (int) (Flowable.bufferSize() * 2.1); + int num = (int) (Flowable.bufferSize() * 2.1); AtomicInteger c = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); - incrementingIntegers(c).observeOn(Schedulers.computation()).take(NUM).subscribe(ts); + incrementingIntegers(c).observeOn(Schedulers.computation()).take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println("testObserveOn => Received: " + ts.valueCount() + " Emitted: " + c.get()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); assertTrue(c.get() < Flowable.bufferSize() * 4); } @Test public void testObserveOnWithSlowConsumer() { - int NUM = (int) (Flowable.bufferSize() * 0.2); + int num = (int) (Flowable.bufferSize() * 0.2); AtomicInteger c = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); incrementingIntegers(c).observeOn(Schedulers.computation()).map( @@ -108,28 +108,28 @@ public Integer apply(Integer i) { return i; } } - ).take(NUM).subscribe(ts); + ).take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println("testObserveOnWithSlowConsumer => Received: " + ts.valueCount() + " Emitted: " + c.get()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); assertTrue(c.get() < Flowable.bufferSize() * 2); } @Test public void testMergeSync() { - int NUM = (int) (Flowable.bufferSize() * 4.1); + int num = (int) (Flowable.bufferSize() * 4.1); AtomicInteger c1 = new AtomicInteger(); AtomicInteger c2 = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); Flowable merged = Flowable.merge(incrementingIntegers(c1), incrementingIntegers(c2)); - merged.take(NUM).subscribe(ts); + merged.take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); - System.out.println("Expected: " + NUM + " got: " + ts.valueCount()); + System.out.println("Expected: " + num + " got: " + ts.valueCount()); System.out.println("testMergeSync => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); // either one can starve the other, but neither should be capable of doing more than 5 batches (taking 4.1) // TODO is it possible to make this deterministic rather than one possibly starving the other? // benjchristensen => In general I'd say it's not worth trying to make it so, as "fair" algoritms generally take a performance hit @@ -139,7 +139,7 @@ public void testMergeSync() { @Test public void testMergeAsync() { - int NUM = (int) (Flowable.bufferSize() * 4.1); + int num = (int) (Flowable.bufferSize() * 4.1); AtomicInteger c1 = new AtomicInteger(); AtomicInteger c2 = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); @@ -147,11 +147,11 @@ public void testMergeAsync() { incrementingIntegers(c1).subscribeOn(Schedulers.computation()), incrementingIntegers(c2).subscribeOn(Schedulers.computation())); - merged.take(NUM).subscribe(ts); + merged.take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println("testMergeAsync => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); // either one can starve the other, but neither should be capable of doing more than 5 batches (taking 4.1) // TODO is it possible to make this deterministic rather than one possibly starving the other? // benjchristensen => In general I'd say it's not worth trying to make it so, as "fair" algoritms generally take a performance hit @@ -167,7 +167,7 @@ public void testMergeAsyncThenObserveOnLoop() { System.out.println("testMergeAsyncThenObserveOnLoop >> " + i); } // Verify there is no MissingBackpressureException - int NUM = (int) (Flowable.bufferSize() * 4.1); + int num = (int) (Flowable.bufferSize() * 4.1); AtomicInteger c1 = new AtomicInteger(); AtomicInteger c2 = new AtomicInteger(); @@ -178,7 +178,7 @@ public void testMergeAsyncThenObserveOnLoop() { merged .observeOn(Schedulers.io()) - .take(NUM) + .take(num) .subscribe(ts); @@ -186,13 +186,13 @@ public void testMergeAsyncThenObserveOnLoop() { ts.assertComplete(); ts.assertNoErrors(); System.out.println("testMergeAsyncThenObserveOn => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); } } @Test public void testMergeAsyncThenObserveOn() { - int NUM = (int) (Flowable.bufferSize() * 4.1); + int num = (int) (Flowable.bufferSize() * 4.1); AtomicInteger c1 = new AtomicInteger(); AtomicInteger c2 = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); @@ -200,11 +200,11 @@ public void testMergeAsyncThenObserveOn() { incrementingIntegers(c1).subscribeOn(Schedulers.computation()), incrementingIntegers(c2).subscribeOn(Schedulers.computation())); - merged.observeOn(Schedulers.newThread()).take(NUM).subscribe(ts); + merged.observeOn(Schedulers.newThread()).take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println("testMergeAsyncThenObserveOn => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); // either one can starve the other, but neither should be capable of doing more than 5 batches (taking 4.1) // TODO is it possible to make this deterministic rather than one possibly starving the other? // benjchristensen => In general I'd say it's not worth trying to make it so, as "fair" algoritms generally take a performance hit @@ -215,7 +215,7 @@ public void testMergeAsyncThenObserveOn() { @Test public void testFlatMapSync() { - int NUM = (int) (Flowable.bufferSize() * 2.1); + int num = (int) (Flowable.bufferSize() * 2.1); AtomicInteger c = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); @@ -226,20 +226,20 @@ public Publisher apply(Integer i) { return incrementingIntegers(new AtomicInteger()).take(10); } }) - .take(NUM).subscribe(ts); + .take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println("testFlatMapSync => Received: " + ts.valueCount() + " Emitted: " + c.get()); - assertEquals(NUM, ts.valueCount()); - // expect less than 1 buffer since the flatMap is emitting 10 each time, so it is NUM/10 that will be taken. + assertEquals(num, ts.valueCount()); + // expect less than 1 buffer since the flatMap is emitting 10 each time, so it is num/10 that will be taken. assertTrue(c.get() < Flowable.bufferSize()); } @Test @Ignore("The test is non-deterministic and can't be made deterministic") public void testFlatMapAsync() { - int NUM = (int) (Flowable.bufferSize() * 2.1); + int num = (int) (Flowable.bufferSize() * 2.1); AtomicInteger c = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); @@ -254,12 +254,12 @@ public Publisher apply(Integer i) { } } ) - .take(NUM).subscribe(ts); + .take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println("testFlatMapAsync => Received: " + ts.valueCount() + " Emitted: " + c.get() + " Size: " + Flowable.bufferSize()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); // even though we only need 10, it will request at least Flowable.bufferSize(), and then as it drains keep requesting more // and then it will be non-deterministic when the take() causes the unsubscribe as it is scheduled on 10 different schedulers (threads) // normally this number is ~250 but can get up to ~1200 when Flowable.bufferSize() == 1024 @@ -268,7 +268,7 @@ public Publisher apply(Integer i) { @Test public void testZipSync() { - int NUM = (int) (Flowable.bufferSize() * 4.1); + int num = (int) (Flowable.bufferSize() * 4.1); AtomicInteger c1 = new AtomicInteger(); AtomicInteger c2 = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); @@ -283,20 +283,20 @@ public Integer apply(Integer t1, Integer t2) { } }); - zipped.take(NUM) + zipped.take(num) .subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println("testZipSync => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); assertTrue(c1.get() < Flowable.bufferSize() * 7); assertTrue(c2.get() < Flowable.bufferSize() * 7); } @Test public void testZipAsync() { - int NUM = (int) (Flowable.bufferSize() * 2.1); + int num = (int) (Flowable.bufferSize() * 2.1); AtomicInteger c1 = new AtomicInteger(); AtomicInteger c2 = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); @@ -310,11 +310,11 @@ public Integer apply(Integer t1, Integer t2) { } }); - zipped.take(NUM).subscribe(ts); + zipped.take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println("testZipAsync => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); int max = Flowable.bufferSize() * 5; assertTrue("" + c1.get() + " >= " + max, c1.get() < max); assertTrue("" + c2.get() + " >= " + max, c2.get() < max); @@ -324,16 +324,16 @@ public Integer apply(Integer t1, Integer t2) { public void testSubscribeOnScheduling() { // in a loop for repeating the concurrency in this to increase chance of failure for (int i = 0; i < 100; i++) { - int NUM = (int) (Flowable.bufferSize() * 2.1); + int num = (int) (Flowable.bufferSize() * 2.1); AtomicInteger c = new AtomicInteger(); ConcurrentLinkedQueue threads = new ConcurrentLinkedQueue(); TestSubscriber ts = new TestSubscriber(); // observeOn is there to make it async and need backpressure - incrementingIntegers(c, threads).subscribeOn(Schedulers.computation()).observeOn(Schedulers.computation()).take(NUM).subscribe(ts); + incrementingIntegers(c, threads).subscribeOn(Schedulers.computation()).observeOn(Schedulers.computation()).take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println("testSubscribeOnScheduling => Received: " + ts.valueCount() + " Emitted: " + c.get()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); assertTrue(c.get() < Flowable.bufferSize() * 4); Thread first = null; for (Thread t : threads) { @@ -354,7 +354,7 @@ public void testSubscribeOnScheduling() { @Test public void testTakeFilterSkipChainAsync() { - int NUM = (int) (Flowable.bufferSize() * 2.1); + int num = (int) (Flowable.bufferSize() * 2.1); AtomicInteger c = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); incrementingIntegers(c).observeOn(Schedulers.computation()) @@ -364,19 +364,19 @@ public void testTakeFilterSkipChainAsync() { public boolean test(Integer i) { return i > 11000; } - }).take(NUM).subscribe(ts); + }).take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); // emit 10000 that are skipped // emit next 1000 that are filtered out - // take NUM - // so emitted is at least 10000+1000+NUM + extra for buffer size/threshold + // take num + // so emitted is at least 10000+1000+num + extra for buffer size/threshold int expected = 10000 + 1000 + Flowable.bufferSize() * 3 + Flowable.bufferSize() / 2; System.out.println("testTakeFilterSkipChain => Received: " + ts.valueCount() + " Emitted: " + c.get() + " Expected: " + expected); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); assertTrue(c.get() < expected); } @@ -525,23 +525,23 @@ public void testOnBackpressureDrop() { if (System.currentTimeMillis() - t > TimeUnit.SECONDS.toMillis(9)) { break; } - int NUM = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow + int num = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow AtomicInteger c = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); firehose(c).onBackpressureDrop() .observeOn(Schedulers.computation()) - .map(SLOW_PASS_THRU).take(NUM).subscribe(ts); + .map(SLOW_PASS_THRU).take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); List onNextEvents = ts.values(); - assertEquals(NUM, onNextEvents.size()); + assertEquals(num, onNextEvents.size()); - Integer lastEvent = onNextEvents.get(NUM - 1); + Integer lastEvent = onNextEvents.get(num - 1); System.out.println("testOnBackpressureDrop => Received: " + onNextEvents.size() + " Emitted: " + c.get() + " Last value: " + lastEvent); // it drop, so we should get some number far higher than what would have sequentially incremented - assertTrue(NUM - 1 <= lastEvent.intValue()); + assertTrue(num - 1 <= lastEvent.intValue()); } } @@ -551,7 +551,7 @@ public void testOnBackpressureDropWithAction() { final AtomicInteger emitCount = new AtomicInteger(); final AtomicInteger dropCount = new AtomicInteger(); final AtomicInteger passCount = new AtomicInteger(); - final int NUM = Flowable.bufferSize() * 3; // > 1 so that take doesn't prevent buffer overflow + final int num = Flowable.bufferSize() * 3; // > 1 so that take doesn't prevent buffer overflow TestSubscriber ts = new TestSubscriber(); firehose(emitCount) @@ -569,19 +569,19 @@ public void accept(Integer v) { }) .observeOn(Schedulers.computation()) .map(SLOW_PASS_THRU) - .take(NUM).subscribe(ts); + .take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); List onNextEvents = ts.values(); - Integer lastEvent = onNextEvents.get(NUM - 1); + Integer lastEvent = onNextEvents.get(num - 1); System.out.println(testName.getMethodName() + " => Received: " + onNextEvents.size() + " Passed: " + passCount.get() + " Dropped: " + dropCount.get() + " Emitted: " + emitCount.get() + " Last value: " + lastEvent); - assertEquals(NUM, onNextEvents.size()); - // in reality, NUM < passCount - assertTrue(NUM <= passCount.get()); + assertEquals(num, onNextEvents.size()); + // in reality, num < passCount + assertTrue(num <= passCount.get()); // it drop, so we should get some number far higher than what would have sequentially incremented - assertTrue(NUM - 1 <= lastEvent.intValue()); + assertTrue(num - 1 <= lastEvent.intValue()); assertTrue(0 < dropCount.get()); assertEquals(emitCount.get(), passCount.get() + dropCount.get()); } @@ -590,22 +590,22 @@ public void accept(Integer v) { @Test(timeout = 10000) public void testOnBackpressureDropSynchronous() { for (int i = 0; i < 100; i++) { - int NUM = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow + int num = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow AtomicInteger c = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); firehose(c).onBackpressureDrop() - .map(SLOW_PASS_THRU).take(NUM).subscribe(ts); + .map(SLOW_PASS_THRU).take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); List onNextEvents = ts.values(); - assertEquals(NUM, onNextEvents.size()); + assertEquals(num, onNextEvents.size()); - Integer lastEvent = onNextEvents.get(NUM - 1); + Integer lastEvent = onNextEvents.get(num - 1); System.out.println("testOnBackpressureDrop => Received: " + onNextEvents.size() + " Emitted: " + c.get() + " Last value: " + lastEvent); // it drop, so we should get some number far higher than what would have sequentially incremented - assertTrue(NUM - 1 <= lastEvent.intValue()); + assertTrue(num - 1 <= lastEvent.intValue()); } } @@ -613,7 +613,7 @@ public void testOnBackpressureDropSynchronous() { public void testOnBackpressureDropSynchronousWithAction() { for (int i = 0; i < 100; i++) { final AtomicInteger dropCount = new AtomicInteger(); - int NUM = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow + int num = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow AtomicInteger c = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); firehose(c).onBackpressureDrop(new Consumer() { @@ -622,18 +622,18 @@ public void accept(Integer j) { dropCount.incrementAndGet(); } }) - .map(SLOW_PASS_THRU).take(NUM).subscribe(ts); + .map(SLOW_PASS_THRU).take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); List onNextEvents = ts.values(); - assertEquals(NUM, onNextEvents.size()); + assertEquals(num, onNextEvents.size()); - Integer lastEvent = onNextEvents.get(NUM - 1); + Integer lastEvent = onNextEvents.get(num - 1); System.out.println("testOnBackpressureDrop => Received: " + onNextEvents.size() + " Dropped: " + dropCount.get() + " Emitted: " + c.get() + " Last value: " + lastEvent); // it drop, so we should get some number far higher than what would have sequentially incremented - assertTrue(NUM - 1 <= lastEvent.intValue()); + assertTrue(num - 1 <= lastEvent.intValue()); // no drop in synchronous mode assertEquals(0, dropCount.get()); assertEquals(c.get(), onNextEvents.size()); @@ -642,7 +642,7 @@ public void accept(Integer j) { @Test(timeout = 2000) public void testOnBackpressureBuffer() { - int NUM = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow + int num = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow AtomicInteger c = new AtomicInteger(); TestSubscriber ts = new TestSubscriber(); @@ -654,14 +654,14 @@ public boolean test(Integer t1) { }) .onBackpressureBuffer() .observeOn(Schedulers.computation()) - .map(SLOW_PASS_THRU).take(NUM).subscribe(ts); + .map(SLOW_PASS_THRU).take(num).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println("testOnBackpressureBuffer => Received: " + ts.valueCount() + " Emitted: " + c.get()); - assertEquals(NUM, ts.valueCount()); + assertEquals(num, ts.valueCount()); // it buffers, so we should get the right value sequentially - assertEquals(NUM - 1, ts.values().get(NUM - 1).intValue()); + assertEquals(num - 1, ts.values().get(num - 1).intValue()); } /** @@ -694,8 +694,8 @@ public void request(long n) { if (threadsSeen != null) { threadsSeen.offer(Thread.currentThread()); } - long _c = BackpressureHelper.add(requested, n); - if (_c == 0) { + long c = BackpressureHelper.add(requested, n); + if (c == 0) { while (!cancelled) { counter.incrementAndGet(); s.onNext(i++); diff --git a/src/test/java/io/reactivex/flowable/FlowableCovarianceTest.java b/src/test/java/io/reactivex/flowable/FlowableCovarianceTest.java index 2e8e5f1af6..80e1785eff 100644 --- a/src/test/java/io/reactivex/flowable/FlowableCovarianceTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableCovarianceTest.java @@ -48,7 +48,7 @@ public void testCovarianceOfFrom() { @Test public void testSortedList() { - Comparator SORT_FUNCTION = new Comparator() { + Comparator sortFunction = new Comparator() { @Override public int compare(Media t1, Media t2) { return 1; @@ -57,11 +57,11 @@ public int compare(Media t1, Media t2) { // this one would work without the covariance generics Flowable o = Flowable.just(new Movie(), new TVSeason(), new Album()); - o.toSortedList(SORT_FUNCTION); + o.toSortedList(sortFunction); // this one would NOT work without the covariance generics Flowable o2 = Flowable.just(new Movie(), new ActionMovie(), new HorrorMovie()); - o2.toSortedList(SORT_FUNCTION); + o2.toSortedList(sortFunction); } @Test diff --git a/src/test/java/io/reactivex/internal/observers/BlockingFirstObserverTest.java b/src/test/java/io/reactivex/internal/observers/BlockingFirstObserverTest.java new file mode 100644 index 0000000000..6f69e1fd73 --- /dev/null +++ b/src/test/java/io/reactivex/internal/observers/BlockingFirstObserverTest.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.observers; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; + +public class BlockingFirstObserverTest { + + @Test + public void firstValueOnly() { + BlockingFirstObserver bf = new BlockingFirstObserver(); + Disposable d = Disposables.empty(); + bf.onSubscribe(d); + + bf.onNext(1); + + assertTrue(d.isDisposed()); + + assertEquals(1, bf.value.intValue()); + assertEquals(0, bf.getCount()); + + bf.onNext(2); + + assertEquals(1, bf.value.intValue()); + assertEquals(0, bf.getCount()); + + bf.onError(new TestException()); + assertEquals(1, bf.value.intValue()); + assertNull(bf.error); + assertEquals(0, bf.getCount()); + } +} diff --git a/src/test/java/io/reactivex/internal/observers/BlockingObserverTest.java b/src/test/java/io/reactivex/internal/observers/BlockingObserverTest.java new file mode 100644 index 0000000000..72f2ab6bd6 --- /dev/null +++ b/src/test/java/io/reactivex/internal/observers/BlockingObserverTest.java @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.observers; + +import static org.junit.Assert.*; + +import java.util.*; + +import org.junit.Test; + +public class BlockingObserverTest { + + @Test + public void dispose() { + Queue q = new ArrayDeque(); + + BlockingObserver bo = new BlockingObserver(q); + + bo.dispose(); + + assertEquals(BlockingObserver.TERMINATED, q.poll()); + + bo.dispose(); + + assertNull(q.poll()); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java index dbb9bf79db..992acdc6e6 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java @@ -16,11 +16,14 @@ import static org.junit.Assert.*; import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import io.reactivex.*; +import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; +import io.reactivex.internal.operators.completable.CompletableAmb.Amb; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; @@ -162,4 +165,25 @@ public void ambArrayOrder() { Completable.ambArray(Completable.complete(), error).test().assertComplete(); } + @Test + public void ambRace() { + TestObserver to = new TestObserver(); + to.onSubscribe(Disposables.empty()); + + CompositeDisposable cd = new CompositeDisposable(); + AtomicBoolean once = new AtomicBoolean(); + Amb a = new Amb(once, cd, to); + + a.onComplete(); + a.onComplete(); + + List errors = TestHelper.trackPluginErrors(); + try { + a.onError(new TestException()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromActionTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromActionTest.java index 6a590afbbb..42b7025dcf 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromActionTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromActionTest.java @@ -13,12 +13,15 @@ package io.reactivex.internal.operators.completable; -import io.reactivex.Completable; -import io.reactivex.functions.Action; +import static org.junit.Assert.assertEquals; + import java.util.concurrent.atomic.AtomicInteger; + import org.junit.Test; -import static org.junit.Assert.assertEquals; +import io.reactivex.Completable; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; public class CompletableFromActionTest { @Test(expected = NullPointerException.class) @@ -97,4 +100,35 @@ public void run() throws Exception { .test() .assertFailure(UnsupportedOperationException.class); } + + @Test + public void fromActionDisposed() { + final AtomicInteger calls = new AtomicInteger(); + Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + calls.incrementAndGet(); + } + }) + .test(true) + .assertEmpty(); + + assertEquals(1, calls.get()); + } + + @Test + public void fromActionErrorsDisposed() { + final AtomicInteger calls = new AtomicInteger(); + Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + calls.incrementAndGet(); + throw new TestException(); + } + }) + .test(true) + .assertEmpty(); + + assertEquals(1, calls.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java index cdd987c8aa..b0d551a64e 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java @@ -13,23 +13,22 @@ package io.reactivex.internal.operators.completable; -import io.reactivex.Completable; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; -import io.reactivex.Observer; -import io.reactivex.TestHelper; -import io.reactivex.disposables.Disposable; -import io.reactivex.observers.TestObserver; -import io.reactivex.schedulers.Schedulers; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.TestException; +import io.reactivex.observers.TestObserver; +import io.reactivex.schedulers.Schedulers; public class CompletableFromCallableTest { @Test(expected = NullPointerException.class) @@ -164,4 +163,20 @@ public String answer(InvocationOnMock invocation) throws Throwable { verify(observer).onSubscribe(any(Disposable.class)); verifyNoMoreInteractions(observer); } + + @Test + public void fromActionErrorsDisposed() { + final AtomicInteger calls = new AtomicInteger(); + Completable.fromCallable(new Callable() { + @Override + public Object call() throws Exception { + calls.incrementAndGet(); + throw new TestException(); + } + }) + .test(true) + .assertEmpty(); + + assertEquals(1, calls.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromPublisherTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromPublisherTest.java index b972e3427e..03db0c5fe0 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromPublisherTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromPublisherTest.java @@ -16,6 +16,7 @@ import org.junit.Test; import io.reactivex.*; +import io.reactivex.functions.Function; public class CompletableFromPublisherTest { @Test(expected = NullPointerException.class) @@ -48,4 +49,14 @@ public void fromPublisherThrows() { public void dispose() { TestHelper.checkDisposed(Completable.fromPublisher(Flowable.just(1))); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowableToCompletable(new Function, Completable>() { + @Override + public Completable apply(Flowable f) throws Exception { + return Completable.fromPublisher(f); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromRunnableTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromRunnableTest.java index 48bb226df2..849fd9a81b 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromRunnableTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromRunnableTest.java @@ -13,11 +13,14 @@ package io.reactivex.internal.operators.completable; -import io.reactivex.Completable; +import static org.junit.Assert.assertEquals; + import java.util.concurrent.atomic.AtomicInteger; + import org.junit.Test; -import static org.junit.Assert.assertEquals; +import io.reactivex.Completable; +import io.reactivex.exceptions.TestException; public class CompletableFromRunnableTest { @Test(expected = NullPointerException.class) @@ -96,4 +99,35 @@ public void run() { .test() .assertFailure(UnsupportedOperationException.class); } + + @Test + public void fromRunnableDisposed() { + final AtomicInteger calls = new AtomicInteger(); + Completable.fromRunnable(new Runnable() { + @Override + public void run() { + calls.incrementAndGet(); + } + }) + .test(true) + .assertEmpty(); + + assertEquals(1, calls.get()); + } + + @Test + public void fromRunnableErrorsDisposed() { + final AtomicInteger calls = new AtomicInteger(); + Completable.fromRunnable(new Runnable() { + @Override + public void run() { + calls.incrementAndGet(); + throw new TestException(); + } + }) + .test(true) + .assertEmpty(); + + assertEquals(1, calls.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java index fe6a8478dc..3df78394f3 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java @@ -17,12 +17,15 @@ import java.util.List; import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import io.reactivex.*; +import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Action; +import io.reactivex.internal.operators.completable.CompletableTimeout.TimeOutObserver; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; @@ -146,4 +149,26 @@ public void run() { } } } + + @Test + public void ambRace() { + TestObserver to = new TestObserver(); + to.onSubscribe(Disposables.empty()); + + CompositeDisposable cd = new CompositeDisposable(); + AtomicBoolean once = new AtomicBoolean(); + TimeOutObserver a = new TimeOutObserver(cd, once, to); + + a.onComplete(); + a.onComplete(); + + List errors = TestHelper.trackPluginErrors(); + try { + a.onError(new TestException()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableToFlowableTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableToFlowableTest.java new file mode 100644 index 0000000000..54661a96db --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableToFlowableTest.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import org.junit.Test; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +public class CompletableToFlowableTest { + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeCompletableToFlowable(new Function>() { + @Override + public Publisher apply(Completable c) throws Exception { + return c.toFlowable(); + } + }); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java index ba6b837a37..7a1fcdf2ce 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java @@ -94,16 +94,16 @@ public void run() { @Test public void testAmb() { - Flowable Flowable1 = createFlowable(new String[] { + Flowable flowable1 = createFlowable(new String[] { "1", "11", "111", "1111" }, 2000, null); - Flowable Flowable2 = createFlowable(new String[] { + Flowable flowable2 = createFlowable(new String[] { "2", "22", "222", "2222" }, 1000, null); - Flowable Flowable3 = createFlowable(new String[] { + Flowable flowable3 = createFlowable(new String[] { "3", "33", "333", "3333" }, 3000, null); @SuppressWarnings("unchecked") - Flowable o = Flowable.ambArray(Flowable1, - Flowable2, Flowable3); + Flowable o = Flowable.ambArray(flowable1, + flowable2, flowable3); @SuppressWarnings("unchecked") DefaultSubscriber observer = mock(DefaultSubscriber.class); @@ -124,16 +124,16 @@ public void testAmb() { public void testAmb2() { IOException expectedException = new IOException( "fake exception"); - Flowable Flowable1 = createFlowable(new String[] {}, + Flowable flowable1 = createFlowable(new String[] {}, 2000, new IOException("fake exception")); - Flowable Flowable2 = createFlowable(new String[] { + Flowable flowable2 = createFlowable(new String[] { "2", "22", "222", "2222" }, 1000, expectedException); - Flowable Flowable3 = createFlowable(new String[] {}, + Flowable flowable3 = createFlowable(new String[] {}, 3000, new IOException("fake exception")); @SuppressWarnings("unchecked") - Flowable o = Flowable.ambArray(Flowable1, - Flowable2, Flowable3); + Flowable o = Flowable.ambArray(flowable1, + flowable2, flowable3); @SuppressWarnings("unchecked") DefaultSubscriber observer = mock(DefaultSubscriber.class); @@ -152,16 +152,16 @@ public void testAmb2() { @Test public void testAmb3() { - Flowable Flowable1 = createFlowable(new String[] { + Flowable flowable1 = createFlowable(new String[] { "1" }, 2000, null); - Flowable Flowable2 = createFlowable(new String[] {}, + Flowable flowable2 = createFlowable(new String[] {}, 1000, null); - Flowable Flowable3 = createFlowable(new String[] { + Flowable flowable3 = createFlowable(new String[] { "3" }, 3000, null); @SuppressWarnings("unchecked") - Flowable o = Flowable.ambArray(Flowable1, - Flowable2, Flowable3); + Flowable o = Flowable.ambArray(flowable1, + flowable2, flowable3); @SuppressWarnings("unchecked") DefaultSubscriber observer = mock(DefaultSubscriber.class); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java index f43a58dedc..1abc20903f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java @@ -751,11 +751,11 @@ public void testBackpressureLoop() { public void testBackpressure() { BiFunction combineLatestFunction = getConcatStringIntegerCombineLatestFunction(); - int NUM = Flowable.bufferSize() * 4; + int num = Flowable.bufferSize() * 4; TestSubscriber ts = new TestSubscriber(); Flowable.combineLatest( Flowable.just("one", "two"), - Flowable.range(2, NUM), + Flowable.range(2, num), combineLatestFunction ) .observeOn(Schedulers.computation()) @@ -767,7 +767,7 @@ public void testBackpressure() { assertEquals("two2", events.get(0)); assertEquals("two3", events.get(1)); assertEquals("two4", events.get(2)); - assertEquals(NUM, events.size()); + assertEquals(num, events.size()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java new file mode 100644 index 0000000000..c1ad560478 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import org.junit.Test; + +import io.reactivex.internal.operators.flowable.FlowableConcatMap.WeakScalarSubscription; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableConcatMapTest { + + @Test + public void weakSubscriptionRequest() { + TestSubscriber ts = new TestSubscriber(0); + WeakScalarSubscription ws = new WeakScalarSubscription(1, ts); + ts.onSubscribe(ws); + + ws.request(0); + + ts.assertEmpty(); + + ws.request(1); + + ts.assertResult(1); + + ws.request(1); + + ts.assertResult(1); + } + +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java index db108689ce..b87cd59fbf 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java @@ -14,36 +14,38 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.junit.*; import org.mockito.InOrder; import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.disposables.*; +import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.processors.PublishProcessor; +import io.reactivex.processors.*; import io.reactivex.schedulers.TestScheduler; import io.reactivex.subscribers.TestSubscriber; public class FlowableDebounceTest { private TestScheduler scheduler; - private Subscriber observer; + private Subscriber Subscriber; private Scheduler.Worker innerScheduler; @Before public void before() { scheduler = new TestScheduler(); - observer = TestHelper.mockSubscriber(); + Subscriber = TestHelper.mockSubscriber(); innerScheduler = scheduler.createWorker(); } @@ -51,25 +53,25 @@ public void before() { public void testDebounceWithCompleted() { Flowable source = Flowable.unsafeCreate(new Publisher() { @Override - public void subscribe(Subscriber observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 100, "one"); // Should be skipped since "two" will arrive before the timeout expires. - publishNext(observer, 400, "two"); // Should be published since "three" will arrive after the timeout expires. - publishNext(observer, 900, "three"); // Should be skipped since onComplete will arrive before the timeout expires. - publishCompleted(observer, 1000); // Should be published as soon as the timeout expires. + public void subscribe(Subscriber subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 100, "one"); // Should be skipped since "two" will arrive before the timeout expires. + publishNext(subscriber, 400, "two"); // Should be published since "three" will arrive after the timeout expires. + publishNext(subscriber, 900, "three"); // Should be skipped since onComplete will arrive before the timeout expires. + publishCompleted(subscriber, 1000); // Should be published as soon as the timeout expires. } }); Flowable sampled = source.debounce(400, TimeUnit.MILLISECONDS, scheduler); - sampled.subscribe(observer); + sampled.subscribe(Subscriber); scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(Subscriber); // must go to 800 since it must be 400 after when two is sent, which is at 400 scheduler.advanceTimeTo(800, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("two"); + inOrder.verify(Subscriber, times(1)).onNext("two"); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(Subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -77,29 +79,29 @@ public void subscribe(Subscriber observer) { public void testDebounceNeverEmits() { Flowable source = Flowable.unsafeCreate(new Publisher() { @Override - public void subscribe(Subscriber observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); // all should be skipped since they are happening faster than the 200ms timeout - publishNext(observer, 100, "a"); // Should be skipped - publishNext(observer, 200, "b"); // Should be skipped - publishNext(observer, 300, "c"); // Should be skipped - publishNext(observer, 400, "d"); // Should be skipped - publishNext(observer, 500, "e"); // Should be skipped - publishNext(observer, 600, "f"); // Should be skipped - publishNext(observer, 700, "g"); // Should be skipped - publishNext(observer, 800, "h"); // Should be skipped - publishCompleted(observer, 900); // Should be published as soon as the timeout expires. + publishNext(subscriber, 100, "a"); // Should be skipped + publishNext(subscriber, 200, "b"); // Should be skipped + publishNext(subscriber, 300, "c"); // Should be skipped + publishNext(subscriber, 400, "d"); // Should be skipped + publishNext(subscriber, 500, "e"); // Should be skipped + publishNext(subscriber, 600, "f"); // Should be skipped + publishNext(subscriber, 700, "g"); // Should be skipped + publishNext(subscriber, 800, "h"); // Should be skipped + publishCompleted(subscriber, 900); // Should be published as soon as the timeout expires. } }); Flowable sampled = source.debounce(200, TimeUnit.MILLISECONDS, scheduler); - sampled.subscribe(observer); + sampled.subscribe(Subscriber); scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(0)).onNext(anyString()); + InOrder inOrder = inOrder(Subscriber); + inOrder.verify(Subscriber, times(0)).onNext(anyString()); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(Subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -107,51 +109,51 @@ public void subscribe(Subscriber observer) { public void testDebounceWithError() { Flowable source = Flowable.unsafeCreate(new Publisher() { @Override - public void subscribe(Subscriber observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); Exception error = new TestException(); - publishNext(observer, 100, "one"); // Should be published since "two" will arrive after the timeout expires. - publishNext(observer, 600, "two"); // Should be skipped since onError will arrive before the timeout expires. - publishError(observer, 700, error); // Should be published as soon as the timeout expires. + publishNext(subscriber, 100, "one"); // Should be published since "two" will arrive after the timeout expires. + publishNext(subscriber, 600, "two"); // Should be skipped since onError will arrive before the timeout expires. + publishError(subscriber, 700, error); // Should be published as soon as the timeout expires. } }); Flowable sampled = source.debounce(400, TimeUnit.MILLISECONDS, scheduler); - sampled.subscribe(observer); + sampled.subscribe(Subscriber); scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(Subscriber); // 100 + 400 means it triggers at 500 scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS); - inOrder.verify(observer).onNext("one"); + inOrder.verify(Subscriber).onNext("one"); scheduler.advanceTimeTo(701, TimeUnit.MILLISECONDS); - inOrder.verify(observer).onError(any(TestException.class)); + inOrder.verify(Subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); } - private void publishCompleted(final Subscriber observer, long delay) { + private void publishCompleted(final Subscriber subscriber, long delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onComplete(); + subscriber.onComplete(); } }, delay, TimeUnit.MILLISECONDS); } - private void publishError(final Subscriber observer, long delay, final Exception error) { + private void publishError(final Subscriber subscriber, long delay, final Exception error) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onError(error); + subscriber.onError(error); } }, delay, TimeUnit.MILLISECONDS); } - private void publishNext(final Subscriber observer, final long delay, final T value) { + private void publishNext(final Subscriber subscriber, final long delay, final T value) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onNext(value); + subscriber.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } @@ -338,12 +340,12 @@ public void badSource() { try { new Flowable() { @Override - protected void subscribeActual(Subscriber observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onComplete(); - observer.onNext(1); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); + subscriber.onNext(1); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .debounce(1, TimeUnit.SECONDS, new TestScheduler()) @@ -407,4 +409,82 @@ public void backpressureNoRequestTimed() { .awaitDone(5, TimeUnit.SECONDS) .assertFailure(MissingBackpressureException.class); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable o) throws Exception { + return o.debounce(Functions.justFunction(Flowable.never())); + } + }); + } + + @Test + public void disposeInOnNext() { + final TestSubscriber to = new TestSubscriber(); + + BehaviorProcessor.createDefault(1) + .debounce(new Function>() { + @Override + public Flowable apply(Integer o) throws Exception { + to.cancel(); + return Flowable.never(); + } + }) + .subscribeWith(to) + .assertEmpty(); + + assertTrue(to.isDisposed()); + } + + @Test + public void disposedInOnComplete() { + final TestSubscriber to = new TestSubscriber(); + + new Flowable() { + @Override + protected void subscribeActual(Subscriber subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + to.cancel(); + subscriber.onComplete(); + } + } + .debounce(Functions.justFunction(Flowable.never())) + .subscribeWith(to) + .assertEmpty(); + } + + @Test + public void emitLate() { + final AtomicReference> ref = new AtomicReference>(); + + TestSubscriber to = Flowable.range(1, 2) + .debounce(new Function>() { + @Override + public Flowable apply(Integer o) throws Exception { + if (o != 1) { + return Flowable.never(); + } + return new Flowable() { + @Override + protected void subscribeActual(Subscriber subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + ref.set(subscriber); + } + }; + } + }) + .test(); + + ref.get().onNext(1); + + to + .assertResult(2); + } + + @Test + public void badRequestReported() { + TestHelper.assertBadRequestReported(Flowable.never().debounce(Functions.justFunction(Flowable.never()))); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java index eaa2d87515..bda46e6ac1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java @@ -39,7 +39,7 @@ public class FlowableFilterTest { @Test public void testFilter() { Flowable w = Flowable.just("one", "two", "three"); - Flowable Flowable = w.filter(new Predicate() { + Flowable flowable = w.filter(new Predicate() { @Override public boolean test(String t1) { @@ -47,15 +47,15 @@ public boolean test(String t1) { } }); - Subscriber Subscriber = TestHelper.mockSubscriber(); + Subscriber subscriber = TestHelper.mockSubscriber(); - Flowable.subscribe(Subscriber); + flowable.subscribe(subscriber); - verify(Subscriber, Mockito.never()).onNext("one"); - verify(Subscriber, times(1)).onNext("two"); - verify(Subscriber, Mockito.never()).onNext("three"); - verify(Subscriber, Mockito.never()).onError(any(Throwable.class)); - verify(Subscriber, times(1)).onComplete(); + verify(subscriber, Mockito.never()).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } /** diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index cccfb38a0f..e5a18c80af 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -2021,7 +2021,7 @@ public V remove(Object key) { @Override public void putAll(Map m) { for (Entry entry: m.entrySet()) { - put(entry.getKey(), entry.getValue()); + put(entry.getKey(), entry.getValue()); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java index fb5d55d265..9bc958c730 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java @@ -15,6 +15,7 @@ */ package io.reactivex.internal.operators.flowable; +import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @@ -28,6 +29,7 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.flowable.FlowableGroupJoin.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.subscribers.TestSubscriber; @@ -687,4 +689,39 @@ public Flowable apply(Object r, Flowable l) throws Exception { to.assertResult(2); } + + @Test + public void leftRightState() { + JoinSupport js = mock(JoinSupport.class); + + LeftRightSubscriber o = new LeftRightSubscriber(js, false); + + assertFalse(o.isDisposed()); + + o.onNext(1); + o.onNext(2); + + o.dispose(); + + assertTrue(o.isDisposed()); + + verify(js).innerValue(false, 1); + verify(js).innerValue(false, 2); + } + + @Test + public void leftRightEndState() { + JoinSupport js = mock(JoinSupport.class); + + LeftRightEndSubscriber o = new LeftRightEndSubscriber(js, false, 0); + + assertFalse(o.isDisposed()); + + o.onNext(1); + o.onNext(2); + + assertTrue(o.isDisposed()); + + verify(js).innerClose(false, o); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java new file mode 100644 index 0000000000..df67bccf02 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java @@ -0,0 +1,83 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import static org.junit.Assert.assertFalse; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import org.junit.Test; +import org.reactivestreams.Subscriber; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.processors.PublishProcessor; + +public class FlowableHideTest { + @Test + public void testHiding() { + PublishProcessor src = PublishProcessor.create(); + + Flowable dst = src.hide(); + + assertFalse(dst instanceof PublishProcessor); + + Subscriber o = TestHelper.mockSubscriber(); + + dst.subscribe(o); + + src.onNext(1); + src.onComplete(); + + verify(o).onNext(1); + verify(o).onComplete(); + verify(o, never()).onError(any(Throwable.class)); + } + + @Test + public void testHidingError() { + PublishProcessor src = PublishProcessor.create(); + + Flowable dst = src.hide(); + + assertFalse(dst instanceof PublishProcessor); + + Subscriber o = TestHelper.mockSubscriber(); + + dst.subscribe(o); + + src.onError(new TestException()); + + verify(o, never()).onNext(any()); + verify(o, never()).onComplete(); + verify(o).onError(any(TestException.class)); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable o) + throws Exception { + return o.hide(); + } + }); + } + + @Test + public void disposed() { + TestHelper.checkDisposed(PublishProcessor.create().hide()); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java index de62bf09ad..4c07e86ffb 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java @@ -325,4 +325,23 @@ public void dispose() { TestHelper.checkDisposed(Flowable.just(1).ignoreElements().toFlowable()); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable o) + throws Exception { + return o.ignoreElements().toFlowable(); + } + }); + + TestHelper.checkDoubleOnSubscribeFlowableToCompletable(new Function, Completable>() { + @Override + public Completable apply(Flowable o) + throws Exception { + return o.ignoreElements(); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIntervalTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIntervalTest.java index 93824d331b..541de65872 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIntervalTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIntervalTest.java @@ -17,8 +17,10 @@ import org.junit.Test; -import io.reactivex.Flowable; +import io.reactivex.*; +import io.reactivex.internal.operators.flowable.FlowableInterval.IntervalSubscriber; import io.reactivex.schedulers.Schedulers; +import io.reactivex.subscribers.TestSubscriber; public class FlowableIntervalTest { @@ -29,4 +31,22 @@ public void cancel() { .test() .assertResult(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); } + + @Test + public void badRequest() { + TestHelper.assertBadRequestReported(Flowable.interval(1, TimeUnit.MILLISECONDS, Schedulers.trampoline())); + } + + @Test + public void cancelledOnRun() { + TestSubscriber ts = new TestSubscriber(); + IntervalSubscriber is = new IntervalSubscriber(ts); + ts.onSubscribe(is); + + is.cancel(); + + is.run(); + + ts.assertEmpty(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java index d0f3f81a84..fd4a8a9a21 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java @@ -221,7 +221,7 @@ public void testMergeFlowableOfFlowables() { final Flowable o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); final Flowable o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - Flowable> FlowableOfFlowables = Flowable.unsafeCreate(new Publisher>() { + Flowable> flowableOfFlowables = Flowable.unsafeCreate(new Publisher>() { @Override public void subscribe(Subscriber> observer) { @@ -233,7 +233,7 @@ public void subscribe(Subscriber> observer) { } }); - Flowable m = Flowable.mergeDelayError(FlowableOfFlowables); + Flowable m = Flowable.mergeDelayError(flowableOfFlowables); m.subscribe(stringObserver); verify(stringObserver, never()).onError(any(Throwable.class)); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java index b095878415..e4e68f3922 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java @@ -78,7 +78,7 @@ public void testMergeFlowableOfFlowables() { final Flowable o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); final Flowable o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - Flowable> FlowableOfFlowables = Flowable.unsafeCreate(new Publisher>() { + Flowable> flowableOfFlowables = Flowable.unsafeCreate(new Publisher>() { @Override public void subscribe(Subscriber> observer) { @@ -90,7 +90,7 @@ public void subscribe(Subscriber> observer) { } }); - Flowable m = Flowable.merge(FlowableOfFlowables); + Flowable m = Flowable.merge(flowableOfFlowables); m.subscribe(stringObserver); verify(stringObserver, never()).onError(any(Throwable.class)); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java index 2be61592cf..b74221fdea 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java @@ -37,7 +37,7 @@ public class FlowableRepeatTest { @Test(timeout = 2000) public void testRepetition() { - int NUM = 10; + int num = 10; final AtomicInteger count = new AtomicInteger(); int value = Flowable.unsafeCreate(new Publisher() { @@ -47,9 +47,9 @@ public void subscribe(final Subscriber o) { o.onComplete(); } }).repeat().subscribeOn(Schedulers.computation()) - .take(NUM).blockingLast(); + .take(num).blockingLast(); - assertEquals(NUM, value); + assertEquals(num, value); } @Test(timeout = 2000) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index 8ad3caa14e..3c0c1ffc22 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -1767,4 +1767,12 @@ public ConnectableFlowable call() throws Exception { .test() .assertFailure(TestException.class); } + + @Test + public void badRequest() { + TestHelper.assertBadRequestReported( + Flowable.never() + .replay() + ); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java index 25cb51af5a..062470229d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java @@ -112,13 +112,13 @@ public static class Tuple { @Test public void testRetryIndefinitely() { Subscriber observer = TestHelper.mockSubscriber(); - int NUM_RETRIES = 20; - Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); + int numRetries = 20; + Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); origin.retry().subscribe(new TestSubscriber(observer)); InOrder inOrder = inOrder(observer); // should show 3 attempts - inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); // should have no errors inOrder.verify(observer, never()).onError(any(Throwable.class)); // should have a single success @@ -131,8 +131,8 @@ public void testRetryIndefinitely() { @Test public void testSchedulingNotificationHandler() { Subscriber observer = TestHelper.mockSubscriber(); - int NUM_RETRIES = 2; - Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); + int numRetries = 2; + Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); TestSubscriber subscriber = new TestSubscriber(observer); origin.retryWhen(new Function, Flowable>() { @Override @@ -156,7 +156,7 @@ public void accept(Throwable e) { subscriber.awaitTerminalEvent(); InOrder inOrder = inOrder(observer); // should show 3 attempts - inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(1 + numRetries)).onNext("beginningEveryTime"); // should have no errors inOrder.verify(observer, never()).onError(any(Throwable.class)); // should have a single success @@ -169,8 +169,8 @@ public void accept(Throwable e) { @Test public void testOnNextFromNotificationHandler() { Subscriber observer = TestHelper.mockSubscriber(); - int NUM_RETRIES = 2; - Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); + int numRetries = 2; + Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); origin.retryWhen(new Function, Flowable>() { @Override public Flowable apply(Flowable t1) { @@ -186,7 +186,7 @@ public Integer apply(Throwable t1) { InOrder inOrder = inOrder(observer); // should show 3 attempts - inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); // should have no errors inOrder.verify(observer, never()).onError(any(Throwable.class)); // should have a single success @@ -283,15 +283,15 @@ public void testOriginFails() { @Test public void testRetryFail() { - int NUM_RETRIES = 1; - int NUM_FAILURES = 2; + int numRetries = 1; + int numFailures = 2; Subscriber observer = TestHelper.mockSubscriber(); - Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); - origin.retry(NUM_RETRIES).subscribe(observer); + Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(numFailures)); + origin.retry(numRetries).subscribe(observer); InOrder inOrder = inOrder(observer); // should show 2 attempts (first time fail, second time (1st retry) fail) - inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(1 + numRetries)).onNext("beginningEveryTime"); // should only retry once, fail again and emit onError inOrder.verify(observer, times(1)).onError(any(RuntimeException.class)); // no success @@ -302,14 +302,14 @@ public void testRetryFail() { @Test public void testRetrySuccess() { - int NUM_FAILURES = 1; + int numFailures = 1; Subscriber observer = TestHelper.mockSubscriber(); - Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); + Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(numFailures)); origin.retry(3).subscribe(observer); InOrder inOrder = inOrder(observer); // should show 3 attempts - inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(1 + numFailures)).onNext("beginningEveryTime"); // should have no errors inOrder.verify(observer, never()).onError(any(Throwable.class)); // should have a single success @@ -321,14 +321,14 @@ public void testRetrySuccess() { @Test public void testInfiniteRetry() { - int NUM_FAILURES = 20; + int numFailures = 20; Subscriber observer = TestHelper.mockSubscriber(); - Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); + Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(numFailures)); origin.retry().subscribe(observer); InOrder inOrder = inOrder(observer); // should show 3 attempts - inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(1 + numFailures)).onNext("beginningEveryTime"); // should have no errors inOrder.verify(observer, never()).onError(any(Throwable.class)); // should have a single success @@ -710,10 +710,10 @@ public void testTimeoutWithRetry() { public void testRetryWithBackpressure() throws InterruptedException { final int NUM_LOOPS = 1; for (int j = 0;j < NUM_LOOPS; j++) { - final int NUM_RETRIES = Flowable.bufferSize() * 2; + final int numRetries = Flowable.bufferSize() * 2; for (int i = 0; i < 400; i++) { Subscriber observer = TestHelper.mockSubscriber(); - Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); + Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); TestSubscriber ts = new TestSubscriber(observer); origin.retry().observeOn(Schedulers.computation()).subscribe(ts); ts.awaitTerminalEvent(5, TimeUnit.SECONDS); @@ -721,8 +721,8 @@ public void testRetryWithBackpressure() throws InterruptedException { InOrder inOrder = inOrder(observer); // should have no errors verify(observer, never()).onError(any(Throwable.class)); - // should show NUM_RETRIES attempts - inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime"); + // should show numRetries attempts + inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); // should have a single success inOrder.verify(observer, times(1)).onNext("onSuccessOnly"); // should have a single successful onComplete @@ -735,7 +735,7 @@ public void testRetryWithBackpressure() throws InterruptedException { @Test//(timeout = 15000) public void testRetryWithBackpressureParallel() throws InterruptedException { final int NUM_LOOPS = 1; - final int NUM_RETRIES = Flowable.bufferSize() * 2; + final int numRetries = Flowable.bufferSize() * 2; int ncpu = Runtime.getRuntime().availableProcessors(); ExecutorService exec = Executors.newFixedThreadPool(Math.max(ncpu / 2, 2)); try { @@ -756,13 +756,13 @@ public void testRetryWithBackpressureParallel() throws InterruptedException { public void run() { final AtomicInteger nexts = new AtomicInteger(); try { - Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); + Flowable origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); TestSubscriber ts = new TestSubscriber(); origin.retry() .observeOn(Schedulers.computation()).subscribe(ts); ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); List onNextEvents = new ArrayList(ts.values()); - if (onNextEvents.size() != NUM_RETRIES + 2) { + if (onNextEvents.size() != numRetries + 2) { for (Throwable t : ts.errors()) { onNextEvents.add(t.toString()); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java index 8c15a44130..f168dc1891 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java @@ -24,6 +24,7 @@ import io.reactivex.*; import io.reactivex.exceptions.*; +import io.reactivex.functions.Function; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.processors.*; import io.reactivex.schedulers.*; @@ -444,4 +445,15 @@ public void run() { ts.assertResult(1); } } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable o) + throws Exception { + return o.sample(1, TimeUnit.SECONDS); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTest.java index fb37d544b5..9918af965d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTest.java @@ -24,6 +24,7 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; @@ -121,4 +122,15 @@ public void error() { .assertFailure(TestException.class); } + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable o) + throws Exception { + return o.skipLast(1); + } + }); + } + } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java index 3cbf19df51..7597e23f69 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java @@ -24,7 +24,7 @@ import org.reactivestreams.Subscriber; import io.reactivex.*; -import io.reactivex.functions.LongConsumer; +import io.reactivex.functions.*; import io.reactivex.subscribers.TestSubscriber; public class FlowableSkipTest { @@ -175,4 +175,15 @@ public void dispose() { TestHelper.checkDisposed(Flowable.just(1).skip(2)); } + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable o) + throws Exception { + return o.skip(1); + } + }); + } + } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java index 653b7f034f..c19b2108b1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java @@ -471,4 +471,28 @@ public Flowable apply(Flowable o) throws Exception { }); } + + @Test + public void badRequest() { + TestHelper.assertBadRequestReported(Flowable.never().take(1)); + } + + @Test + public void requestRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final TestSubscriber ts = Flowable.range(1, 2).take(2).test(0L); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts.request(1); + } + }; + + TestHelper.race(r1, r1); + + ts.assertResult(1, 2); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java index cb00a08030..ce7bd20179 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java @@ -20,6 +20,7 @@ import org.reactivestreams.*; import io.reactivex.*; +import io.reactivex.functions.Function; import io.reactivex.processors.PublishProcessor; import io.reactivex.subscribers.TestSubscriber; @@ -282,4 +283,14 @@ public void testBackpressure() { public void dispose() { TestHelper.checkDisposed(PublishProcessor.create().takeUntil(Flowable.never())); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable c) throws Exception { + return c.takeUntil(Flowable.never()); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeIntervalTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeIntervalTest.java index 10e69d885b..bf96ef9e45 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeIntervalTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeIntervalTest.java @@ -19,7 +19,7 @@ import org.junit.*; import org.mockito.InOrder; -import org.reactivestreams.Subscriber; +import org.reactivestreams.*; import io.reactivex.*; import io.reactivex.exceptions.TestException; @@ -137,4 +137,14 @@ public void error() { .assertFailure(TestException.class); } + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>>() { + @Override + public Publisher> apply(Flowable f) + throws Exception { + return f.timeInterval(); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java index b5b86cf9e2..6babda3c89 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java @@ -25,6 +25,7 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; @@ -466,4 +467,22 @@ public void run() { } } } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>>() { + @Override + public Flowable> apply(Flowable f) + throws Exception { + return f.toList().toFlowable(); + } + }); + TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function, Single>>() { + @Override + public Single> apply(Flowable f) + throws Exception { + return f.toList(); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java index cc9218a1d8..d678bf11bf 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java @@ -35,7 +35,7 @@ public class FlowableUnsubscribeOnTest { @Test(timeout = 5000) public void unsubscribeWhenSubscribeOnAndUnsubscribeOnAreOnSameThread() throws InterruptedException { - UIEventLoopScheduler UI_EVENT_LOOP = new UIEventLoopScheduler(); + UIEventLoopScheduler uiEventLoop = new UIEventLoopScheduler(); try { final ThreadSubscription subscription = new ThreadSubscription(); final AtomicReference subscribeThread = new AtomicReference(); @@ -52,8 +52,8 @@ public void subscribe(Subscriber t1) { }); TestSubscriber ts = new TestSubscriber(); - w.subscribeOn(UI_EVENT_LOOP).observeOn(Schedulers.computation()) - .unsubscribeOn(UI_EVENT_LOOP) + w.subscribeOn(uiEventLoop).observeOn(Schedulers.computation()) + .unsubscribeOn(uiEventLoop) .take(2) .subscribe(ts); @@ -70,18 +70,18 @@ public void subscribe(Subscriber t1) { System.out.println("unsubscribeThread: " + unsubscribeThread); System.out.println("subscribeThread.get(): " + subscribeThread.get()); - assertTrue(unsubscribeThread == UI_EVENT_LOOP.getThread()); + assertTrue(unsubscribeThread == uiEventLoop.getThread()); ts.assertValues(1, 2); ts.assertTerminated(); } finally { - UI_EVENT_LOOP.shutdown(); + uiEventLoop.shutdown(); } } @Test(timeout = 5000) public void unsubscribeWhenSubscribeOnAndUnsubscribeOnAreOnDifferentThreads() throws InterruptedException { - UIEventLoopScheduler UI_EVENT_LOOP = new UIEventLoopScheduler(); + UIEventLoopScheduler uiEventLoop = new UIEventLoopScheduler(); try { final ThreadSubscription subscription = new ThreadSubscription(); final AtomicReference subscribeThread = new AtomicReference(); @@ -99,7 +99,7 @@ public void subscribe(Subscriber t1) { TestSubscriber observer = new TestSubscriber(); w.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.computation()) - .unsubscribeOn(UI_EVENT_LOOP) + .unsubscribeOn(uiEventLoop) .take(2) .subscribe(observer); @@ -114,15 +114,15 @@ public void subscribe(Subscriber t1) { assertNotSame(Thread.currentThread(), subscribeThread.get()); // True for Schedulers.newThread() - System.out.println("UI Thread: " + UI_EVENT_LOOP.getThread()); + System.out.println("UI Thread: " + uiEventLoop.getThread()); System.out.println("unsubscribeThread: " + unsubscribeThread); System.out.println("subscribeThread.get(): " + subscribeThread.get()); - assertSame(unsubscribeThread, UI_EVENT_LOOP.getThread()); + assertSame(unsubscribeThread, uiEventLoop.getThread()); observer.assertValues(1, 2); observer.assertTerminated(); } finally { - UI_EVENT_LOOP.shutdown(); + uiEventLoop.shutdown(); } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java index 9f3f888ba9..a50c685233 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java @@ -20,6 +20,7 @@ import org.junit.Test; import io.reactivex.*; +import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.TestException; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; @@ -108,4 +109,24 @@ public void run() { } } } + + @Test + public void disposeNoFurtherSignals() { + @SuppressWarnings("unchecked") + TestObserver to = Maybe.ambArray(new Maybe() { + @Override + protected void subscribeActual( + MaybeObserver observer) { + observer.onSubscribe(Disposables.empty()); + observer.onSuccess(1); + observer.onSuccess(2); + observer.onComplete(); + } + }, Maybe.never()) + .test(); + + to.cancel(); + + to.assertResult(1); + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java index 086db5388f..ce23150c9a 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java @@ -18,10 +18,12 @@ import java.util.List; import org.junit.Test; +import org.reactivestreams.Subscriber; import io.reactivex.*; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; +import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.observers.TestObserver; import io.reactivex.processors.PublishProcessor; @@ -216,4 +218,28 @@ public MaybeSource apply(Completable c) throws Exception { public void withOtherPublisherDispose() { TestHelper.checkDisposed(Maybe.just(1).delay(Flowable.just(1))); } + + @Test + public void withOtherPublisherDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeMaybe(new Function, MaybeSource>() { + @Override + public MaybeSource apply(Maybe c) throws Exception { + return c.delay(Flowable.never()); + } + }); + } + + @Test + public void otherPublisherNextSlipsThrough() { + Maybe.just(1).delay(new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onNext(2); + } + }) + .test() + .assertResult(1); + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromActionTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromActionTest.java index bdd305a23c..6e7c1b242f 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromActionTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromActionTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.maybe; import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.util.List; import java.util.concurrent.*; @@ -154,4 +155,31 @@ public void run() throws Exception { RxJavaPlugins.reset(); } } + + @Test + public void disposedUpfront() throws Exception { + Action run = mock(Action.class); + + Maybe.fromAction(run) + .test(true) + .assertEmpty(); + + verify(run, never()).run(); + } + + @Test + public void cancelWhileRunning() { + final TestObserver to = new TestObserver(); + + Maybe.fromAction(new Action() { + @Override + public void run() throws Exception { + to.dispose(); + } + }) + .subscribeWith(to) + .assertEmpty(); + + assertTrue(to.isDisposed()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromFutureTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromFutureTest.java index 4f3ab7f571..d08b93a50a 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromFutureTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromFutureTest.java @@ -13,12 +13,17 @@ package io.reactivex.internal.operators.maybe; +import static org.junit.Assert.assertTrue; + import java.util.concurrent.*; import org.junit.Test; import io.reactivex.Maybe; +import io.reactivex.exceptions.TestException; import io.reactivex.internal.functions.Functions; +import io.reactivex.observers.TestObserver; +import io.reactivex.schedulers.Schedulers; public class MaybeFromFutureTest { @@ -58,4 +63,60 @@ public void interrupt() { Maybe.fromFuture(ft, 1, TimeUnit.MILLISECONDS).test() .assertFailure(InterruptedException.class); } + + @Test + public void cancelWhileRunning() { + final TestObserver to = new TestObserver(); + + FutureTask ft = new FutureTask(new Runnable() { + @Override + public void run() { + to.cancel(); + } + }, null); + + Schedulers.single().scheduleDirect(ft, 100, TimeUnit.MILLISECONDS); + + Maybe.fromFuture(ft) + .subscribeWith(to) + .assertEmpty(); + + assertTrue(to.isDisposed()); + } + + @Test + public void cancelAndCrashWhileRunning() { + final TestObserver to = new TestObserver(); + + FutureTask ft = new FutureTask(new Runnable() { + @Override + public void run() { + to.cancel(); + throw new TestException(); + } + }, null); + + Schedulers.single().scheduleDirect(ft, 100, TimeUnit.MILLISECONDS); + + Maybe.fromFuture(ft) + .subscribeWith(to) + .assertEmpty(); + + assertTrue(to.isDisposed()); + } + + @Test + public void futureNull() { + FutureTask ft = new FutureTask(new Runnable() { + @Override + public void run() { + } + }, null); + + Schedulers.single().scheduleDirect(ft, 100, TimeUnit.MILLISECONDS); + + Maybe.fromFuture(ft) + .test() + .assertResult(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromRunnableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromRunnableTest.java index b7c2f9b3ee..08d0bbc4b3 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromRunnableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromRunnableTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.maybe; import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.util.List; import java.util.concurrent.*; @@ -158,4 +159,31 @@ public void run() { RxJavaPlugins.reset(); } } + + @Test + public void disposedUpfront() { + Runnable run = mock(Runnable.class); + + Maybe.fromRunnable(run) + .test(true) + .assertEmpty(); + + verify(run, never()).run(); + } + + @Test + public void cancelWhileRunning() { + final TestObserver to = new TestObserver(); + + Maybe.fromRunnable(new Runnable() { + @Override + public void run() { + to.dispose(); + } + }) + .subscribeWith(to) + .assertEmpty(); + + assertTrue(to.isDisposed()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMapTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMapTest.java new file mode 100644 index 0000000000..393c170e1b --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMapTest.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.maybe; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.functions.Function; +import io.reactivex.internal.functions.Functions; + +public class MaybeMapTest { + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeMaybe(new Function, MaybeSource>() { + @Override + public MaybeSource apply(Maybe m) throws Exception { + return m.map(Functions.identity()); + } + }); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java index 39588be465..95cd9a1163 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java @@ -20,6 +20,7 @@ import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.junit.*; import org.mockito.InOrder; @@ -32,7 +33,7 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.TestScheduler; -import io.reactivex.subjects.PublishSubject; +import io.reactivex.subjects.*; public class ObservableDebounceTest { @@ -376,4 +377,77 @@ public void debounceWithEmpty() { .test() .assertResult(1); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>() { + @Override + public Observable apply(Observable o) throws Exception { + return o.debounce(Functions.justFunction(Observable.never())); + } + }); + } + + @Test + public void disposeInOnNext() { + final TestObserver to = new TestObserver(); + + BehaviorSubject.createDefault(1) + .debounce(new Function>() { + @Override + public ObservableSource apply(Integer o) throws Exception { + to.cancel(); + return Observable.never(); + } + }) + .subscribeWith(to) + .assertEmpty(); + + assertTrue(to.isDisposed()); + } + + @Test + public void disposedInOnComplete() { + final TestObserver to = new TestObserver(); + + new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + to.cancel(); + observer.onComplete(); + } + } + .debounce(Functions.justFunction(Observable.never())) + .subscribeWith(to) + .assertEmpty(); + } + + @Test + public void emitLate() { + final AtomicReference> ref = new AtomicReference>(); + + TestObserver to = Observable.range(1, 2) + .debounce(new Function>() { + @Override + public ObservableSource apply(Integer o) throws Exception { + if (o != 1) { + return Observable.never(); + } + return new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); + } + }; + } + }) + .test(); + + ref.get().onNext(1); + + to + .assertResult(2); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoAfterNextTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoAfterNextTest.java index ca6280562c..a6002a9117 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoAfterNextTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoAfterNextTest.java @@ -26,8 +26,7 @@ import io.reactivex.internal.functions.Functions; import io.reactivex.internal.fuseable.QueueSubscription; import io.reactivex.observers.*; -import io.reactivex.processors.UnicastProcessor; -import io.reactivex.subscribers.*; +import io.reactivex.subjects.UnicastSubject; public class ObservableDoAfterNextTest { @@ -58,6 +57,17 @@ public void just() { assertEquals(Arrays.asList(1, -1), values); } + @Test + public void justHidden() { + Observable.just(1) + .hide() + .doAfterNext(afterNext) + .subscribeWith(ts) + .assertResult(1); + + assertEquals(Arrays.asList(1, -1), values); + } + @Test public void range() { Observable.range(1, 5) @@ -118,9 +128,9 @@ public void asyncFusedRejected() { @Test public void asyncFused() { - TestSubscriber ts0 = SubscriberFusion.newTest(QueueSubscription.ASYNC); + TestObserver ts0 = ObserverFusion.newTest(QueueSubscription.ASYNC); - UnicastProcessor up = UnicastProcessor.create(); + UnicastSubject up = UnicastSubject.create(); TestHelper.emit(up, 1, 2, 3, 4, 5); @@ -128,7 +138,7 @@ public void asyncFused() { .doAfterNext(afterNext) .subscribe(ts0); - SubscriberFusion.assertFusion(ts0, QueueSubscription.ASYNC) + ObserverFusion.assertFusion(ts0, QueueSubscription.ASYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -215,9 +225,9 @@ public void asyncFusedRejectedConditional() { @Test public void asyncFusedConditional() { - TestSubscriber ts0 = SubscriberFusion.newTest(QueueSubscription.ASYNC); + TestObserver ts0 = ObserverFusion.newTest(QueueSubscription.ASYNC); - UnicastProcessor up = UnicastProcessor.create(); + UnicastSubject up = UnicastSubject.create(); TestHelper.emit(up, 1, 2, 3, 4, 5); @@ -226,7 +236,7 @@ public void asyncFusedConditional() { .filter(Functions.alwaysTrue()) .subscribe(ts0); - SubscriberFusion.assertFusion(ts0, QueueSubscription.ASYNC) + ObserverFusion.assertFusion(ts0, QueueSubscription.ASYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java index ac89708573..53f3bff298 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java @@ -15,6 +15,7 @@ */ package io.reactivex.internal.operators.observable; +import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @@ -30,6 +31,7 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.observable.ObservableGroupJoin.*; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.PublishSubject; @@ -688,4 +690,39 @@ public Observable apply(Object r, Observable l) throws Exception to.assertResult(2); } + + @Test + public void leftRightState() { + JoinSupport js = mock(JoinSupport.class); + + LeftRightObserver o = new LeftRightObserver(js, false); + + assertFalse(o.isDisposed()); + + o.onNext(1); + o.onNext(2); + + o.dispose(); + + assertTrue(o.isDisposed()); + + verify(js).innerValue(false, 1); + verify(js).innerValue(false, 2); + } + + @Test + public void leftRightEndState() { + JoinSupport js = mock(JoinSupport.class); + + LeftRightEndObserver o = new LeftRightEndObserver(js, false, 0); + + assertFalse(o.isDisposed()); + + o.onNext(1); + o.onNext(2); + + assertTrue(o.isDisposed()); + + verify(js).innerClose(false, o); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableIntervalTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableIntervalTest.java index ff8a2e149a..e834a2accb 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableIntervalTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableIntervalTest.java @@ -18,6 +18,8 @@ import org.junit.Test; import io.reactivex.*; +import io.reactivex.internal.operators.observable.ObservableInterval.IntervalObserver; +import io.reactivex.observers.TestObserver; import io.reactivex.schedulers.*; public class ObservableIntervalTest { @@ -34,4 +36,17 @@ public void cancel() { .test() .assertResult(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); } + + @Test + public void cancelledOnRun() { + TestObserver ts = new TestObserver(); + IntervalObserver is = new IntervalObserver(ts); + ts.onSubscribe(is); + + is.dispose(); + + is.run(); + + ts.assertEmpty(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java index e4f04bba95..9005371fe2 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java @@ -720,4 +720,22 @@ protected void subscribeActual(Observer s) { assertTrue(bs.isDisposed()); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, ObservableSource>() { + @Override + public ObservableSource apply(final Observable o) + throws Exception { + return Observable.never().publish(new Function, ObservableSource>() { + @Override + public ObservableSource apply(Observable v) + throws Exception { + return o; + } + }); + } + } + ); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java index 075f726283..04fc4cddf8 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java @@ -37,7 +37,7 @@ public class ObservableRepeatTest { @Test(timeout = 2000) public void testRepetition() { - int NUM = 10; + int num = 10; final AtomicInteger count = new AtomicInteger(); int value = Observable.unsafeCreate(new ObservableSource() { @@ -47,9 +47,9 @@ public void subscribe(final Observer o) { o.onComplete(); } }).repeat().subscribeOn(Schedulers.computation()) - .take(NUM).blockingLast(); + .take(num).blockingLast(); - assertEquals(NUM, value); + assertEquals(num, value); } @Test(timeout = 2000) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java index 4eaf547898..2d5e3d2aa8 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java @@ -111,13 +111,13 @@ public static class Tuple { @Test public void testRetryIndefinitely() { Observer observer = TestHelper.mockObserver(); - int NUM_RETRIES = 20; - Observable origin = Observable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); + int numRetries = 20; + Observable origin = Observable.unsafeCreate(new FuncWithErrors(numRetries)); origin.retry().subscribe(new TestObserver(observer)); InOrder inOrder = inOrder(observer); // should show 3 attempts - inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); // should have no errors inOrder.verify(observer, never()).onError(any(Throwable.class)); // should have a single success @@ -130,8 +130,8 @@ public void testRetryIndefinitely() { @Test public void testSchedulingNotificationHandler() { Observer observer = TestHelper.mockObserver(); - int NUM_RETRIES = 2; - Observable origin = Observable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); + int numRetries = 2; + Observable origin = Observable.unsafeCreate(new FuncWithErrors(numRetries)); TestObserver to = new TestObserver(observer); origin.retryWhen(new Function, Observable>() { @Override @@ -157,7 +157,7 @@ public void accept(Throwable e) { to.awaitTerminalEvent(); InOrder inOrder = inOrder(observer); // should show 3 attempts - inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(1 + numRetries)).onNext("beginningEveryTime"); // should have no errors inOrder.verify(observer, never()).onError(any(Throwable.class)); // should have a single success @@ -170,8 +170,8 @@ public void accept(Throwable e) { @Test public void testOnNextFromNotificationHandler() { Observer observer = TestHelper.mockObserver(); - int NUM_RETRIES = 2; - Observable origin = Observable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); + int numRetries = 2; + Observable origin = Observable.unsafeCreate(new FuncWithErrors(numRetries)); origin.retryWhen(new Function, Observable>() { @Override public Observable apply(Observable t1) { @@ -187,7 +187,7 @@ public Integer apply(Throwable t1) { InOrder inOrder = inOrder(observer); // should show 3 attempts - inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); // should have no errors inOrder.verify(observer, never()).onError(any(Throwable.class)); // should have a single success @@ -284,15 +284,15 @@ public void testOriginFails() { @Test public void testRetryFail() { - int NUM_RETRIES = 1; - int NUM_FAILURES = 2; + int numRetries = 1; + int numFailures = 2; Observer observer = TestHelper.mockObserver(); - Observable origin = Observable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); - origin.retry(NUM_RETRIES).subscribe(observer); + Observable origin = Observable.unsafeCreate(new FuncWithErrors(numFailures)); + origin.retry(numRetries).subscribe(observer); InOrder inOrder = inOrder(observer); // should show 2 attempts (first time fail, second time (1st retry) fail) - inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(1 + numRetries)).onNext("beginningEveryTime"); // should only retry once, fail again and emit onError inOrder.verify(observer, times(1)).onError(any(RuntimeException.class)); // no success @@ -303,14 +303,14 @@ public void testRetryFail() { @Test public void testRetrySuccess() { - int NUM_FAILURES = 1; + int numFailures = 1; Observer observer = TestHelper.mockObserver(); - Observable origin = Observable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); + Observable origin = Observable.unsafeCreate(new FuncWithErrors(numFailures)); origin.retry(3).subscribe(observer); InOrder inOrder = inOrder(observer); // should show 3 attempts - inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(1 + numFailures)).onNext("beginningEveryTime"); // should have no errors inOrder.verify(observer, never()).onError(any(Throwable.class)); // should have a single success @@ -322,14 +322,14 @@ public void testRetrySuccess() { @Test public void testInfiniteRetry() { - int NUM_FAILURES = 20; + int numFailures = 20; Observer observer = TestHelper.mockObserver(); - Observable origin = Observable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); + Observable origin = Observable.unsafeCreate(new FuncWithErrors(numFailures)); origin.retry().subscribe(observer); InOrder inOrder = inOrder(observer); // should show 3 attempts - inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime"); + inOrder.verify(observer, times(1 + numFailures)).onNext("beginningEveryTime"); // should have no errors inOrder.verify(observer, never()).onError(any(Throwable.class)); // should have a single success diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java index a45881ef83..92569c5d92 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java @@ -24,6 +24,7 @@ import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import io.reactivex.schedulers.*; import io.reactivex.subjects.PublishSubject; @@ -426,4 +427,15 @@ public void run() { } } + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>() { + @Override + public Observable apply(Observable o) + throws Exception { + return o.sample(1, TimeUnit.SECONDS); + } + }); + } + } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java index 73484edcf6..b88bd7855b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java @@ -24,6 +24,7 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import io.reactivex.schedulers.Schedulers; @@ -120,4 +121,15 @@ public void error() { .test() .assertFailure(TestException.class); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>() { + @Override + public Observable apply(Observable o) + throws Exception { + return o.skipLast(1); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java index 6b54ad0b3e..681475c22c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java @@ -21,6 +21,7 @@ import org.junit.Test; import io.reactivex.*; +import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; public class ObservableSkipTest { @@ -148,4 +149,15 @@ public void testRequestOverflowDoesNotOccur() { public void dispose() { TestHelper.checkDisposed(Observable.just(1).skip(2)); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>() { + @Override + public Observable apply(Observable o) + throws Exception { + return o.skip(1); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java index 4a23b3dd55..9c6fcba337 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java @@ -20,6 +20,7 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; +import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import io.reactivex.subjects.PublishSubject; @@ -260,4 +261,14 @@ public void testDownstreamUnsubscribes() { public void dispose() { TestHelper.checkDisposed(PublishSubject.create().takeUntil(Observable.never())); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>() { + @Override + public Observable apply(Observable c) throws Exception { + return c.takeUntil(Observable.never()); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeIntervalTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeIntervalTest.java index 3c1bfd1e2a..4542892ba6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeIntervalTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeIntervalTest.java @@ -135,4 +135,15 @@ public void error() { .test() .assertFailure(TestException.class); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>>() { + @Override + public Observable> apply(Observable f) + throws Exception { + return f.timeInterval(); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java index e94d5c1ec4..6101e11977 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.List; @@ -24,8 +25,10 @@ import org.mockito.*; import io.reactivex.*; +import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; +import io.reactivex.internal.operators.observable.ObservableTimer.TimerObserver; import io.reactivex.observables.ConnectableObservable; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; @@ -339,4 +342,16 @@ public Long apply(Long v) throws Exception { } } + @Test + public void cancelledAndRun() { + TestObserver to = new TestObserver(); + to.onSubscribe(Disposables.empty()); + TimerObserver tm = new TimerObserver(to); + + tm.dispose(); + + tm.run(); + + to.assertEmpty(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java index 251d98f6b3..fa838ad5f1 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java @@ -26,6 +26,7 @@ import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; public class ObservableToListTest { @@ -270,4 +271,22 @@ public Collection call() throws Exception { .assertFailure(NullPointerException.class) .assertErrorMessage("The collectionSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources."); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>>() { + @Override + public Observable> apply(Observable f) + throws Exception { + return f.toList().toObservable(); + } + }); + TestHelper.checkDoubleOnSubscribeObservableToSingle(new Function, Single>>() { + @Override + public Single> apply(Observable f) + throws Exception { + return f.toList(); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java index 744c585646..cdb21dafa5 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java @@ -34,7 +34,7 @@ public class ObservableUnsubscribeOnTest { @Test(timeout = 5000) public void unsubscribeWhenSubscribeOnAndUnsubscribeOnAreOnSameThread() throws InterruptedException { - UIEventLoopScheduler UI_EVENT_LOOP = new UIEventLoopScheduler(); + UIEventLoopScheduler uiEventLoop = new UIEventLoopScheduler(); try { final ThreadSubscription subscription = new ThreadSubscription(); final AtomicReference subscribeThread = new AtomicReference(); @@ -51,8 +51,8 @@ public void subscribe(Observer t1) { }); TestObserver observer = new TestObserver(); - w.subscribeOn(UI_EVENT_LOOP).observeOn(Schedulers.computation()) - .unsubscribeOn(UI_EVENT_LOOP) + w.subscribeOn(uiEventLoop).observeOn(Schedulers.computation()) + .unsubscribeOn(uiEventLoop) .take(2) .subscribe(observer); @@ -69,18 +69,18 @@ public void subscribe(Observer t1) { System.out.println("unsubscribeThread: " + unsubscribeThread); System.out.println("subscribeThread.get(): " + subscribeThread.get()); - assertTrue(unsubscribeThread.toString(), unsubscribeThread == UI_EVENT_LOOP.getThread()); + assertTrue(unsubscribeThread.toString(), unsubscribeThread == uiEventLoop.getThread()); observer.assertValues(1, 2); observer.assertTerminated(); } finally { - UI_EVENT_LOOP.shutdown(); + uiEventLoop.shutdown(); } } @Test(timeout = 5000) public void unsubscribeWhenSubscribeOnAndUnsubscribeOnAreOnDifferentThreads() throws InterruptedException { - UIEventLoopScheduler UI_EVENT_LOOP = new UIEventLoopScheduler(); + UIEventLoopScheduler uiEventLoop = new UIEventLoopScheduler(); try { final ThreadSubscription subscription = new ThreadSubscription(); final AtomicReference subscribeThread = new AtomicReference(); @@ -98,7 +98,7 @@ public void subscribe(Observer t1) { TestObserver observer = new TestObserver(); w.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.computation()) - .unsubscribeOn(UI_EVENT_LOOP) + .unsubscribeOn(uiEventLoop) .take(2) .subscribe(observer); @@ -113,15 +113,15 @@ public void subscribe(Observer t1) { assertNotSame(Thread.currentThread(), subscribeThread.get()); // True for Schedulers.newThread() - System.out.println("UI Thread: " + UI_EVENT_LOOP.getThread()); + System.out.println("UI Thread: " + uiEventLoop.getThread()); System.out.println("unsubscribeThread: " + unsubscribeThread); System.out.println("subscribeThread.get(): " + subscribeThread.get()); - assertSame(unsubscribeThread, UI_EVENT_LOOP.getThread()); + assertSame(unsubscribeThread, uiEventLoop.getThread()); observer.assertValues(1, 2); observer.assertTerminated(); } finally { - UI_EVENT_LOOP.shutdown(); + uiEventLoop.shutdown(); } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleDelayTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleDelayTest.java index ed8a692d19..d0c2ea165b 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleDelayTest.java @@ -13,11 +13,11 @@ package io.reactivex.internal.operators.single; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotEquals; import java.util.List; import java.util.concurrent.*; -import java.util.concurrent.atomic.*; +import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; import org.reactivestreams.Subscriber; @@ -29,8 +29,7 @@ import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; -import io.reactivex.schedulers.TestScheduler; +import io.reactivex.schedulers.*; import io.reactivex.subjects.PublishSubject; public class SingleDelayTest { @@ -246,4 +245,28 @@ public void withSingleDispose() { public void withCompletableDispose() { TestHelper.checkDisposed(Completable.complete().andThen(Single.just(1))); } + + @Test + public void withCompletableDoubleOnSubscribe() { + + TestHelper.checkDoubleOnSubscribeCompletableToSingle(new Function>() { + @Override + public Single apply(Completable c) throws Exception { + return c.andThen(Single.just((Object)1)); + } + }); + + } + + @Test + public void withSingleDoubleOnSubscribe() { + + TestHelper.checkDoubleOnSubscribeSingle(new Function, Single>() { + @Override + public Single apply(Single s) throws Exception { + return Single.just((Object)1).delaySubscription(s); + } + }); + + } } diff --git a/src/test/java/io/reactivex/internal/schedulers/SchedulerPoolFactoryTest.java b/src/test/java/io/reactivex/internal/schedulers/SchedulerPoolFactoryTest.java index a8209f681d..603929ddb4 100644 --- a/src/test/java/io/reactivex/internal/schedulers/SchedulerPoolFactoryTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/SchedulerPoolFactoryTest.java @@ -16,9 +16,15 @@ package io.reactivex.internal.schedulers; +import static org.junit.Assert.*; + +import java.util.Properties; + import org.junit.Test; import io.reactivex.TestHelper; +import io.reactivex.internal.schedulers.SchedulerPoolFactory.PurgeProperties; +import io.reactivex.schedulers.Schedulers; public class SchedulerPoolFactoryTest { @@ -26,4 +32,115 @@ public class SchedulerPoolFactoryTest { public void utilityClass() { TestHelper.checkUtilityClass(SchedulerPoolFactory.class); } + + @Test + public void multiStartStop() { + SchedulerPoolFactory.shutdown(); + + SchedulerPoolFactory.shutdown(); + + SchedulerPoolFactory.tryStart(false); + + assertNull(SchedulerPoolFactory.PURGE_THREAD.get()); + + SchedulerPoolFactory.start(); + + // restart schedulers + Schedulers.shutdown(); + + Schedulers.start(); + } + + @Test + public void startRace() throws InterruptedException { + try { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + SchedulerPoolFactory.shutdown(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + SchedulerPoolFactory.start(); + } + }; + + TestHelper.race(r1, r1); + } + + } finally { + // restart schedulers + Schedulers.shutdown(); + + Thread.sleep(200); + + Schedulers.start(); + } + } + + @Test + public void loadPurgeProperties() { + Properties props1 = new Properties(); + + PurgeProperties pp = new PurgeProperties(); + pp.load(props1); + + assertTrue(pp.purgeEnable); + assertEquals(pp.purgePeriod, 1); + } + + @Test + public void loadPurgePropertiesDisabled() { + Properties props1 = new Properties(); + props1.setProperty(SchedulerPoolFactory.PURGE_ENABLED_KEY, "false"); + + PurgeProperties pp = new PurgeProperties(); + pp.load(props1); + + assertFalse(pp.purgeEnable); + assertEquals(pp.purgePeriod, 1); + } + + @Test + public void loadPurgePropertiesEnabledCustomPeriod() { + Properties props1 = new Properties(); + props1.setProperty(SchedulerPoolFactory.PURGE_ENABLED_KEY, "true"); + props1.setProperty(SchedulerPoolFactory.PURGE_PERIOD_SECONDS_KEY, "2"); + + PurgeProperties pp = new PurgeProperties(); + pp.load(props1); + + assertTrue(pp.purgeEnable); + assertEquals(pp.purgePeriod, 2); + } + + @Test + public void loadPurgePropertiesEnabledCustomPeriodNaN() { + Properties props1 = new Properties(); + props1.setProperty(SchedulerPoolFactory.PURGE_ENABLED_KEY, "true"); + props1.setProperty(SchedulerPoolFactory.PURGE_PERIOD_SECONDS_KEY, "abc"); + + PurgeProperties pp = new PurgeProperties(); + pp.load(props1); + + assertTrue(pp.purgeEnable); + assertEquals(pp.purgePeriod, 1); + } + + @Test + public void putIntoPoolNoPurge() { + int s = SchedulerPoolFactory.POOLS.size(); + + SchedulerPoolFactory.tryPutIntoPool(false, null); + + assertEquals(s, SchedulerPoolFactory.POOLS.size()); + } + + @Test + public void putIntoPoolNonThreadPool() { + int s = SchedulerPoolFactory.POOLS.size(); + + SchedulerPoolFactory.tryPutIntoPool(true, null); + + assertEquals(s, SchedulerPoolFactory.POOLS.size()); + } } diff --git a/src/test/java/io/reactivex/internal/schedulers/TrampolineSchedulerInternalTest.java b/src/test/java/io/reactivex/internal/schedulers/TrampolineSchedulerInternalTest.java index 35d5aa5568..2b76b3067a 100644 --- a/src/test/java/io/reactivex/internal/schedulers/TrampolineSchedulerInternalTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/TrampolineSchedulerInternalTest.java @@ -25,7 +25,9 @@ import io.reactivex.Scheduler.Worker; import io.reactivex.internal.disposables.EmptyDisposable; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.schedulers.TrampolineScheduler.*; import io.reactivex.schedulers.Schedulers; +import static org.mockito.Mockito.*; public class TrampolineSchedulerInternalTest { @@ -160,4 +162,50 @@ public void run() { w.dispose(); } } + + @Test + public void sleepingRunnableDisposedOnRun() { + TrampolineWorker w = new TrampolineWorker(); + + Runnable r = mock(Runnable.class); + + SleepingRunnable run = new SleepingRunnable(r, w, 0); + w.dispose(); + run.run(); + + verify(r, never()).run(); + } + + @Test + public void sleepingRunnableNoDelayRun() { + TrampolineWorker w = new TrampolineWorker(); + + Runnable r = mock(Runnable.class); + + SleepingRunnable run = new SleepingRunnable(r, w, 0); + + run.run(); + + verify(r).run(); + } + + @Test + public void sleepingRunnableDisposedOnDelayedRun() { + final TrampolineWorker w = new TrampolineWorker(); + + Runnable r = mock(Runnable.class); + + SleepingRunnable run = new SleepingRunnable(r, w, System.currentTimeMillis() + 200); + + Schedulers.single().scheduleDirect(new Runnable() { + @Override + public void run() { + w.dispose(); + } + }, 100, TimeUnit.MILLISECONDS); + + run.run(); + + verify(r, never()).run(); + } } diff --git a/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java index f73fba6ea4..59a7f22fc4 100644 --- a/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java @@ -28,7 +28,6 @@ import io.reactivex.*; import io.reactivex.Scheduler.Worker; import io.reactivex.exceptions.TestException; -import io.reactivex.internal.subscribers.DeferredScalarSubscriber; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; @@ -424,4 +423,15 @@ public void downstreamRequest(long n) { request(n); } } + + @Test + public void doubleOnSubscribe() { + TestHelper.doubleOnSubscribe(new DeferredScalarSubscriber(new TestSubscriber()) { + private static final long serialVersionUID = -4445381578878059054L; + + @Override + public void onNext(Integer t) { + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/subscribers/SubscriberResourceWrapperTest.java b/src/test/java/io/reactivex/internal/subscribers/SubscriberResourceWrapperTest.java index d5a5fc6ac1..c519202ff8 100644 --- a/src/test/java/io/reactivex/internal/subscribers/SubscriberResourceWrapperTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/SubscriberResourceWrapperTest.java @@ -16,9 +16,12 @@ import static org.junit.Assert.*; import org.junit.Test; +import org.reactivestreams.Subscriber; +import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.subscribers.TestSubscriber; @@ -80,4 +83,31 @@ public void complete() { ts.assertResult(); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable o) throws Exception { + return o.lift(new FlowableOperator() { + @Override + public Subscriber apply( + Subscriber s) throws Exception { + return new SubscriberResourceWrapper(s); + } + }); + } + }); + } + + @Test + public void badRequest() { + TestHelper.assertBadRequestReported(Flowable.never().lift(new FlowableOperator() { + @Override + public Subscriber apply( + Subscriber s) throws Exception { + return new SubscriberResourceWrapper(s); + } + })); + } } diff --git a/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java b/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java index 3b98ee30c7..f7314b1d68 100644 --- a/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java +++ b/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java @@ -14,7 +14,7 @@ package io.reactivex.internal.subscriptions; import static org.junit.Assert.*; - +import static org.mockito.Mockito.*; import java.util.List; import java.util.concurrent.atomic.*; @@ -22,6 +22,7 @@ import org.reactivestreams.Subscription; import io.reactivex.TestHelper; +import io.reactivex.exceptions.ProtocolViolationException; import io.reactivex.plugins.RxJavaPlugins; public class SubscriptionHelperTest { @@ -230,4 +231,30 @@ public void run() { assertEquals(0, r.get()); } } + + @Test + public void setOnceAndRequest() { + AtomicReference ref = new AtomicReference(); + + Subscription sub = mock(Subscription.class); + + assertTrue(SubscriptionHelper.setOnce(ref, sub, 1)); + + verify(sub).request(1); + verify(sub, never()).cancel(); + + List errors = TestHelper.trackPluginErrors(); + try { + sub = mock(Subscription.class); + + assertFalse(SubscriptionHelper.setOnce(ref, sub, 1)); + + verify(sub, never()).request(anyLong()); + verify(sub).cancel(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java b/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java index 1c24351a65..dded845762 100644 --- a/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java +++ b/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java @@ -16,15 +16,20 @@ import static org.junit.Assert.*; import java.io.IOException; -import java.util.ArrayDeque; +import java.util.*; import java.util.concurrent.atomic.AtomicLong; import org.junit.Test; -import org.reactivestreams.Subscription; +import org.reactivestreams.*; +import io.reactivex.Observer; import io.reactivex.TestHelper; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.*; import io.reactivex.functions.BooleanSupplier; +import io.reactivex.internal.queue.SpscArrayQueue; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.observers.TestObserver; import io.reactivex.subscribers.TestSubscriber; public class QueueDrainHelperTest { @@ -205,4 +210,672 @@ public boolean getAsBoolean() throws Exception { ts.assertValue(1).assertNoErrors().assertNotComplete(); } + + @Test + public void drainMaxLoopMissingBackpressure() { + TestSubscriber ts = new TestSubscriber(); + ts.onSubscribe(new BooleanSubscription()); + + QueueDrain qd = new QueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return null; + } + + @Override + public boolean enter() { + return true; + } + + @Override + public long requested() { + return 0; + } + + @Override + public long produced(long n) { + return 0; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public boolean accept(Subscriber a, Integer v) { + return false; + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + q.offer(1); + + QueueDrainHelper.drainMaxLoop(q, ts, false, null, qd); + + ts.assertFailure(MissingBackpressureException.class); + } + + @Test + public void drainMaxLoopMissingBackpressureWithResource() { + TestSubscriber ts = new TestSubscriber(); + ts.onSubscribe(new BooleanSubscription()); + + QueueDrain qd = new QueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return null; + } + + @Override + public boolean enter() { + return true; + } + + @Override + public long requested() { + return 0; + } + + @Override + public long produced(long n) { + return 0; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public boolean accept(Subscriber a, Integer v) { + return false; + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + q.offer(1); + + Disposable d = Disposables.empty(); + + QueueDrainHelper.drainMaxLoop(q, ts, false, d, qd); + + ts.assertFailure(MissingBackpressureException.class); + + assertTrue(d.isDisposed()); + } + + @Test + public void drainMaxLoopDontAccept() { + TestSubscriber ts = new TestSubscriber(); + ts.onSubscribe(new BooleanSubscription()); + + QueueDrain qd = new QueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return null; + } + + @Override + public boolean enter() { + return true; + } + + @Override + public long requested() { + return 1; + } + + @Override + public long produced(long n) { + return 0; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public boolean accept(Subscriber a, Integer v) { + return false; + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + q.offer(1); + + QueueDrainHelper.drainMaxLoop(q, ts, false, null, qd); + + ts.assertEmpty(); + } + + @Test + public void checkTerminatedDelayErrorEmpty() { + TestSubscriber ts = new TestSubscriber(); + ts.onSubscribe(new BooleanSubscription()); + + QueueDrain qd = new QueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return null; + } + + @Override + public boolean enter() { + return true; + } + + @Override + public long requested() { + return 0; + } + + @Override + public long produced(long n) { + return 0; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public boolean accept(Subscriber a, Integer v) { + return false; + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + + QueueDrainHelper.checkTerminated(true, true, ts, true, q, qd); + + ts.assertResult(); + } + + @Test + public void checkTerminatedDelayErrorNonEmpty() { + TestSubscriber ts = new TestSubscriber(); + ts.onSubscribe(new BooleanSubscription()); + + QueueDrain qd = new QueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return null; + } + + @Override + public boolean enter() { + return true; + } + + @Override + public long requested() { + return 0; + } + + @Override + public long produced(long n) { + return 0; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public boolean accept(Subscriber a, Integer v) { + return false; + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + + QueueDrainHelper.checkTerminated(true, false, ts, true, q, qd); + + ts.assertEmpty(); + } + + @Test + public void checkTerminatedDelayErrorEmptyError() { + TestSubscriber ts = new TestSubscriber(); + ts.onSubscribe(new BooleanSubscription()); + + QueueDrain qd = new QueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return new TestException(); + } + + @Override + public boolean enter() { + return true; + } + + @Override + public long requested() { + return 0; + } + + @Override + public long produced(long n) { + return 0; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public boolean accept(Subscriber a, Integer v) { + return false; + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + + QueueDrainHelper.checkTerminated(true, true, ts, true, q, qd); + + ts.assertFailure(TestException.class); + } + + @Test + public void checkTerminatedNonDelayErrorError() { + TestSubscriber ts = new TestSubscriber(); + ts.onSubscribe(new BooleanSubscription()); + + QueueDrain qd = new QueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return new TestException(); + } + + @Override + public boolean enter() { + return true; + } + + @Override + public long requested() { + return 0; + } + + @Override + public long produced(long n) { + return 0; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public boolean accept(Subscriber a, Integer v) { + return false; + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + + QueueDrainHelper.checkTerminated(true, false, ts, false, q, qd); + + ts.assertFailure(TestException.class); + } + + @Test + public void observerCheckTerminatedDelayErrorEmpty() { + TestObserver ts = new TestObserver(); + ts.onSubscribe(Disposables.empty()); + + ObservableQueueDrain qd = new ObservableQueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return null; + } + + @Override + public boolean enter() { + return true; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public void accept(Observer a, Integer v) { + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + + QueueDrainHelper.checkTerminated(true, true, ts, true, q, null, qd); + + ts.assertResult(); + } + + @Test + public void observerCheckTerminatedDelayErrorEmptyResource() { + TestObserver ts = new TestObserver(); + ts.onSubscribe(Disposables.empty()); + + ObservableQueueDrain qd = new ObservableQueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return null; + } + + @Override + public boolean enter() { + return true; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public void accept(Observer a, Integer v) { + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + + Disposable d = Disposables.empty(); + + QueueDrainHelper.checkTerminated(true, true, ts, true, q, d, qd); + + ts.assertResult(); + + assertTrue(d.isDisposed()); + } + + @Test + public void observerCheckTerminatedDelayErrorNonEmpty() { + TestObserver ts = new TestObserver(); + ts.onSubscribe(Disposables.empty()); + + ObservableQueueDrain qd = new ObservableQueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return null; + } + + @Override + public boolean enter() { + return true; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public void accept(Observer a, Integer v) { + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + + QueueDrainHelper.checkTerminated(true, false, ts, true, q, null, qd); + + ts.assertEmpty(); + } + + @Test + public void observerCheckTerminatedDelayErrorEmptyError() { + TestObserver ts = new TestObserver(); + ts.onSubscribe(Disposables.empty()); + + ObservableQueueDrain qd = new ObservableQueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return new TestException(); + } + + @Override + public boolean enter() { + return true; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public void accept(Observer a, Integer v) { + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + + QueueDrainHelper.checkTerminated(true, true, ts, true, q, null, qd); + + ts.assertFailure(TestException.class); + } + + @Test + public void observerCheckTerminatedNonDelayErrorError() { + TestObserver ts = new TestObserver(); + ts.onSubscribe(Disposables.empty()); + + ObservableQueueDrain qd = new ObservableQueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return new TestException(); + } + + @Override + public boolean enter() { + return true; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public void accept(Observer a, Integer v) { + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + + QueueDrainHelper.checkTerminated(true, false, ts, false, q, null, qd); + + ts.assertFailure(TestException.class); + } + @Test + public void observerCheckTerminatedNonDelayErrorErrorResource() { + TestObserver ts = new TestObserver(); + ts.onSubscribe(Disposables.empty()); + + ObservableQueueDrain qd = new ObservableQueueDrain() { + @Override + public boolean cancelled() { + return false; + } + + @Override + public boolean done() { + return false; + } + + @Override + public Throwable error() { + return new TestException(); + } + + @Override + public boolean enter() { + return true; + } + + @Override + public int leave(int m) { + return 0; + } + + @Override + public void accept(Observer a, Integer v) { + } + }; + + SpscArrayQueue q = new SpscArrayQueue(32); + + Disposable d = Disposables.empty(); + + QueueDrainHelper.checkTerminated(true, false, ts, false, q, d, qd); + + ts.assertFailure(TestException.class); + + assertTrue(d.isDisposed()); + } + + @Test + public void postCompleteAlreadyComplete() { + + TestSubscriber ts = new TestSubscriber(); + + Queue q = new ArrayDeque(); + q.offer(1); + + AtomicLong state = new AtomicLong(QueueDrainHelper.COMPLETED_MASK); + + QueueDrainHelper.postComplete(ts, q, state, new BooleanSupplier() { + @Override + public boolean getAsBoolean() throws Exception { + return false; + } + }); + } } diff --git a/src/test/java/io/reactivex/observable/ObservableCovarianceTest.java b/src/test/java/io/reactivex/observable/ObservableCovarianceTest.java index 4d4d3753c4..5861cbfd57 100644 --- a/src/test/java/io/reactivex/observable/ObservableCovarianceTest.java +++ b/src/test/java/io/reactivex/observable/ObservableCovarianceTest.java @@ -47,7 +47,7 @@ public void testCovarianceOfFrom() { @Test public void testSortedList() { - Comparator SORT_FUNCTION = new Comparator() { + Comparator sortFunction = new Comparator() { @Override public int compare(Media t1, Media t2) { return 1; @@ -56,11 +56,11 @@ public int compare(Media t1, Media t2) { // this one would work without the covariance generics Observable o = Observable.just(new Movie(), new TVSeason(), new Album()); - o.toSortedList(SORT_FUNCTION); + o.toSortedList(sortFunction); // this one would NOT work without the covariance generics Observable o2 = Observable.just(new Movie(), new ActionMovie(), new HorrorMovie()); - o2.toSortedList(SORT_FUNCTION); + o2.toSortedList(sortFunction); } @Test From e3f38ecd422eddb527b4d41494b8569eacb159f1 Mon Sep 17 00:00:00 2001 From: Adam Speakman Date: Wed, 7 Mar 2018 23:46:52 +1300 Subject: [PATCH 124/417] Fix buffer() documentation to correctly describe onError behaviour (#5895) * Corrected documentation for buffer onError behaviour The operator does not emit the buffer in case of error. Suspect these docs were copied over to 2.x before the fix from #3561 was merged. * Corrected documentation for Flowable.buffer onError behaviour * Update boundary buffer documentation to change source -> supplied The word 'source' is incorrect here, since the buffer is emitted whenever the supplied Publisher emits an item --- src/main/java/io/reactivex/Flowable.java | 98 ++++++++++++-------- src/main/java/io/reactivex/Observable.java | 102 +++++++++++++-------- 2 files changed, 128 insertions(+), 72 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 0e63ea2f1a..13cef7fc07 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -5871,8 +5871,9 @@ public final void blockingSubscribe(Subscriber subscriber) { /** * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits connected, non-overlapping buffers, each containing {@code count} items. When the source - * Publisher completes or encounters an error, the resulting Publisher emits the current buffer and - * propagates the notification from the source Publisher. + * Publisher completes, the resulting Publisher emits the current buffer and propagates the notification from the + * source Publisher. Note that if the source Publisher issues an onError notification the event is passed on + * immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5900,8 +5901,9 @@ public final Flowable> buffer(int count) { /** * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits buffers every {@code skip} items, each containing {@code count} items. When the source - * Publisher completes or encounters an error, the resulting Publisher emits the current buffer and - * propagates the notification from the source Publisher. + * Publisher completes, the resulting Publisher emits the current buffer and propagates the notification from the + * source Publisher. Note that if the source Publisher issues an onError notification the event is passed on + * immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5933,8 +5935,9 @@ public final Flowable> buffer(int count, int skip) { /** * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits buffers every {@code skip} items, each containing {@code count} items. When the source - * Publisher completes or encounters an error, the resulting Publisher emits the current buffer and - * propagates the notification from the source Publisher. + * Publisher completes, the resulting Publisher emits the current buffer and propagates the notification from the + * source Publisher. Note that if the source Publisher issues an onError notification the event is passed on + * immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5973,8 +5976,9 @@ public final > Flowable buffer(int count, int /** * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits connected, non-overlapping buffers, each containing {@code count} items. When the source - * Publisher completes or encounters an error, the resulting Publisher emits the current buffer and - * propagates the notification from the source Publisher. + * Publisher completes, the resulting Publisher emits the current buffer and propagates the notification from the + * source Publisher. Note that if the source Publisher issues an onError notification the event is passed on + * immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -6007,8 +6011,9 @@ public final > Flowable buffer(int count, Cal * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher starts a new buffer periodically, as determined by the {@code timeskip} argument. It emits * each buffer after a fixed timespan, specified by the {@code timespan} argument. When the source - * Publisher completes or encounters an error, the resulting Publisher emits the current buffer and - * propagates the notification from the source Publisher. + * Publisher completes, the resulting Publisher emits the current buffer and propagates the notification from the + * source Publisher. Note that if the source Publisher issues an onError notification the event is passed on + * immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -6040,8 +6045,10 @@ public final Flowable> buffer(long timespan, long timeskip, TimeUnit uni * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher starts a new buffer periodically, as determined by the {@code timeskip} argument, and on the * specified {@code scheduler}. It emits each buffer after a fixed timespan, specified by the - * {@code timespan} argument. When the source Publisher completes or encounters an error, the resulting - * Publisher emits the current buffer and propagates the notification from the source Publisher. + * {@code timespan} argument. When the source Publisher completes, the resulting Publisher emits the current buffer + * and propagates the notification from the source Publisher. Note that if the source Publisher issues an onError + * notification the event is passed on immediately without first emitting the buffer it is in the process of + * assembling. *

                * *

                @@ -6075,8 +6082,10 @@ public final Flowable> buffer(long timespan, long timeskip, TimeUnit uni * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher starts a new buffer periodically, as determined by the {@code timeskip} argument, and on the * specified {@code scheduler}. It emits each buffer after a fixed timespan, specified by the - * {@code timespan} argument. When the source Publisher completes or encounters an error, the resulting - * Publisher emits the current buffer and propagates the notification from the source Publisher. + * {@code timespan} argument. When the source Publisher completes, the resulting Publisher emits the current buffer + * and propagates the notification from the source Publisher. Note that if the source Publisher issues an onError + * notification the event is passed on immediately without first emitting the buffer it is in the process of + * assembling. *

                * *

                @@ -6117,8 +6126,10 @@ public final > Flowable buffer(long timespan, /** * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits connected, non-overlapping buffers, each of a fixed duration specified by the - * {@code timespan} argument. When the source Publisher completes or encounters an error, the resulting - * Publisher emits the current buffer and propagates the notification from the source Publisher. + * {@code timespan} argument. When the source Publisher completes, the resulting Publisher emits the current buffer + * and propagates the notification from the source Publisher. Note that if the source Publisher issues an onError + * notification the event is passed on immediately without first emitting the buffer it is in the process of + * assembling. *

                * *

                @@ -6149,8 +6160,9 @@ public final Flowable> buffer(long timespan, TimeUnit unit) { * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument or a maximum size specified by the {@code count} argument (whichever is reached - * first). When the source Publisher completes or encounters an error, the resulting Publisher emits the - * current buffer and propagates the notification from the source Publisher. + * first). When the source Publisher completes, the resulting Publisher emits the current buffer and propagates the + * notification from the source Publisher. Note that if the source Publisher issues an onError notification the event + * is passed on immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -6184,9 +6196,10 @@ public final Flowable> buffer(long timespan, TimeUnit unit, int count) { * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument as measured on the specified {@code scheduler}, or a maximum size specified by - * the {@code count} argument (whichever is reached first). When the source Publisher completes or - * encounters an error, the resulting Publisher emits the current buffer and propagates the notification - * from the source Publisher. + * the {@code count} argument (whichever is reached first). When the source Publisher completes, the resulting + * Publisher emits the current buffer and propagates the notification from the source Publisher. Note that if the + * source Publisher issues an onError notification the event is passed on immediately without first emitting the + * buffer it is in the process of assembling. *

                * *

                @@ -6222,9 +6235,10 @@ public final Flowable> buffer(long timespan, TimeUnit unit, Scheduler sc * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument as measured on the specified {@code scheduler}, or a maximum size specified by - * the {@code count} argument (whichever is reached first). When the source Publisher completes or - * encounters an error, the resulting Publisher emits the current buffer and propagates the notification - * from the source Publisher. + * the {@code count} argument (whichever is reached first). When the source Publisher completes, the resulting + * Publisher emits the current buffer and propagates the notification from the source Publisher. Note that if the + * source Publisher issues an onError notification the event is passed on immediately without first emitting the + * buffer it is in the process of assembling. *

                * *

                @@ -6273,9 +6287,10 @@ public final > Flowable buffer( /** * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits connected, non-overlapping buffers, each of a fixed duration specified by the - * {@code timespan} argument and on the specified {@code scheduler}. When the source Publisher completes or - * encounters an error, the resulting Publisher emits the current buffer and propagates the notification - * from the source Publisher. + * {@code timespan} argument and on the specified {@code scheduler}. When the source Publisher completes, the + * resulting Publisher emits the current buffer and propagates the notification from the source Publisher. Note that + * if the source Publisher issues an onError notification the event is passed on immediately without first emitting + * the buffer it is in the process of assembling. *

                * *

                @@ -6307,7 +6322,9 @@ public final Flowable> buffer(long timespan, TimeUnit unit, Scheduler sc /** * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits buffers that it creates when the specified {@code openingIndicator} Publisher emits an - * item, and closes when the Publisher returned from {@code closingIndicator} emits an item. + * item, and closes when the Publisher returned from {@code closingIndicator} emits an item. If any of the source + * Publisher, {@code openingIndicator} or {@code closingIndicator} issues an onError notification the event is passed + * on immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -6341,7 +6358,9 @@ public final Flowable> buffer( /** * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits buffers that it creates when the specified {@code openingIndicator} Publisher emits an - * item, and closes when the Publisher returned from {@code closingIndicator} emits an item. + * item, and closes when the Publisher returned from {@code closingIndicator} emits an item. If any of the source + * Publisher, {@code openingIndicator} or {@code closingIndicator} issues an onError notification the event is passed + * on immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -6387,7 +6406,8 @@ public final > Flowable b * *

                * Completion of either the source or the boundary Publisher causes the returned Publisher to emit the - * latest buffer and complete. + * latest buffer and complete. If either the source Publisher or the boundary Publisher issues an onError notification + * the event is passed on immediately without first emitting the buffer it is in the process of assembling. *

                *
                Backpressure:
                *
                This operator does not support backpressure as it is instead controlled by the {@code Publisher} @@ -6420,7 +6440,8 @@ public final Flowable> buffer(Publisher boundaryIndicator) { * *

                * Completion of either the source or the boundary Publisher causes the returned Publisher to emit the - * latest buffer and complete. + * latest buffer and complete. If either the source Publisher or the boundary Publisher issues an onError notification + * the event is passed on immediately without first emitting the buffer it is in the process of assembling. *

                *
                Backpressure:
                *
                This operator does not support backpressure as it is instead controlled by the {@code Publisher} @@ -6456,7 +6477,8 @@ public final Flowable> buffer(Publisher boundaryIndicator, final * *

                * Completion of either the source or the boundary Publisher causes the returned Publisher to emit the - * latest buffer and complete. + * latest buffer and complete. If either the source Publisher or the boundary Publisher issues an onError notification + * the event is passed on immediately without first emitting the buffer it is in the process of assembling. *

                *
                Backpressure:
                *
                This operator does not support backpressure as it is instead controlled by the {@code Publisher} @@ -6491,10 +6513,12 @@ public final > Flowable buffer(Publisher * *
                + * If either the source Publisher or the boundary Publisher issues an onError notification the event is passed on + * immediately without first emitting the buffer it is in the process of assembling. *
                Backpressure:
                *
                This operator does not support backpressure as it is instead controlled by the given Publishers and * buffers data. It requests {@code Long.MAX_VALUE} upstream and does not obey downstream requests.
                @@ -6505,7 +6529,7 @@ public final > Flowable buffer(Publisher the value type of the boundary-providing Publisher * @param boundaryIndicatorSupplier * a {@link Callable} that produces a Publisher that governs the boundary between buffers. - * Whenever the source {@code Publisher} emits an item, {@code buffer} emits the current buffer and + * Whenever the supplied {@code Publisher} emits an item, {@code buffer} emits the current buffer and * begins to fill a new one * @return a Flowable that emits a connected, non-overlapping buffer of items from the source Publisher * each time the Publisher created with the {@code closingIndicator} argument emits an item @@ -6522,10 +6546,12 @@ public final Flowable> buffer(Callable> bound /** * Returns a Flowable that emits buffers of items it collects from the source Publisher. The resulting * Publisher emits connected, non-overlapping buffers. It emits the current buffer and replaces it with a - * new buffer whenever the Publisher produced by the specified {@code closingIndicator} emits an item. + * new buffer whenever the Publisher produced by the specified {@code boundaryIndicatorSupplier} emits an item. *

                * *

                + * If either the source Publisher or the boundary Publisher issues an onError notification the event is passed on + * immediately without first emitting the buffer it is in the process of assembling. *
                Backpressure:
                *
                This operator does not support backpressure as it is instead controlled by the given Publishers and * buffers data. It requests {@code Long.MAX_VALUE} upstream and does not obey downstream requests.
                @@ -6537,7 +6563,7 @@ public final Flowable> buffer(Callable> bound * @param the value type of the boundary-providing Publisher * @param boundaryIndicatorSupplier * a {@link Callable} that produces a Publisher that governs the boundary between buffers. - * Whenever the source {@code Publisher} emits an item, {@code buffer} emits the current buffer and + * Whenever the supplied {@code Publisher} emits an item, {@code buffer} emits the current buffer and * begins to fill a new one * @param bufferSupplier * a factory function that returns an instance of the collection subclass to be used and returned diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 423bcef036..9530e8f24d 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -5379,8 +5379,9 @@ public final void blockingSubscribe(Observer subscriber) { /** * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits connected, non-overlapping buffers, each containing {@code count} items. When the source - * ObservableSource completes or encounters an error, the resulting ObservableSource emits the current buffer and - * propagates the notification from the source ObservableSource. + * ObservableSource completes, the resulting ObservableSource emits the current buffer and propagates the notification + * from the source ObservableSource. Note that if the source ObservableSource issues an onError notification + * the event is passed on immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5403,8 +5404,9 @@ public final Observable> buffer(int count) { /** * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits buffers every {@code skip} items, each containing {@code count} items. When the source - * ObservableSource completes or encounters an error, the resulting ObservableSource emits the current buffer and - * propagates the notification from the source ObservableSource. + * ObservableSource completes, the resulting ObservableSource emits the current buffer and propagates the notification + * from the source ObservableSource. Note that if the source ObservableSource issues an onError notification + * the event is passed on immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5431,8 +5433,9 @@ public final Observable> buffer(int count, int skip) { /** * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits buffers every {@code skip} items, each containing {@code count} items. When the source - * ObservableSource completes or encounters an error, the resulting ObservableSource emits the current buffer and - * propagates the notification from the source ObservableSource. + * ObservableSource completes, the resulting ObservableSource emits the current buffer and propagates the notification + * from the source ObservableSource. Note that if the source ObservableSource issues an onError notification + * the event is passed on immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5466,8 +5469,9 @@ public final > Observable buffer(int count, i /** * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits connected, non-overlapping buffers, each containing {@code count} items. When the source - * ObservableSource completes or encounters an error, the resulting ObservableSource emits the current buffer and - * propagates the notification from the source ObservableSource. + * ObservableSource completes, the resulting ObservableSource emits the current buffer and propagates the notification + * from the source ObservableSource. Note that if the source ObservableSource issues an onError notification + * the event is passed on immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5495,8 +5499,9 @@ public final > Observable buffer(int count, C * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource starts a new buffer periodically, as determined by the {@code timeskip} argument. It emits * each buffer after a fixed timespan, specified by the {@code timespan} argument. When the source - * ObservableSource completes or encounters an error, the resulting ObservableSource emits the current buffer and - * propagates the notification from the source ObservableSource. + * ObservableSource completes, the resulting ObservableSource emits the current buffer and propagates the notification + * from the source ObservableSource. Note that if the source ObservableSource issues an onError notification + * the event is passed on immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5524,8 +5529,10 @@ public final Observable> buffer(long timespan, long timeskip, TimeUnit u * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource starts a new buffer periodically, as determined by the {@code timeskip} argument, and on the * specified {@code scheduler}. It emits each buffer after a fixed timespan, specified by the - * {@code timespan} argument. When the source ObservableSource completes or encounters an error, the resulting - * ObservableSource emits the current buffer and propagates the notification from the source ObservableSource. + * {@code timespan} argument. When the source ObservableSource completes, the resulting ObservableSource emits the + * current buffer and propagates the notification from the source ObservableSource. Note that if the source + * ObservableSource issues an onError notification the event is passed on immediately without first emitting the + * buffer it is in the process of assembling. *

                * *

                @@ -5555,8 +5562,10 @@ public final Observable> buffer(long timespan, long timeskip, TimeUnit u * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource starts a new buffer periodically, as determined by the {@code timeskip} argument, and on the * specified {@code scheduler}. It emits each buffer after a fixed timespan, specified by the - * {@code timespan} argument. When the source ObservableSource completes or encounters an error, the resulting - * ObservableSource emits the current buffer and propagates the notification from the source ObservableSource. + * {@code timespan} argument. When the source ObservableSource completes, the resulting ObservableSource emits the + * current buffer and propagates the notification from the source ObservableSource. Note that if the source + * ObservableSource issues an onError notification the event is passed on immediately without first emitting the + * buffer it is in the process of assembling. *

                * *

                @@ -5592,8 +5601,10 @@ public final > Observable buffer(long timespa /** * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits connected, non-overlapping buffers, each of a fixed duration specified by the - * {@code timespan} argument. When the source ObservableSource completes or encounters an error, the resulting - * ObservableSource emits the current buffer and propagates the notification from the source ObservableSource. + * {@code timespan} argument. When the source ObservableSource completes, the resulting ObservableSource emits the + * current buffer and propagates the notification from the source ObservableSource. Note that if the source + * ObservableSource issues an onError notification the event is passed on immediately without first emitting the + * buffer it is in the process of assembling. *

                * *

                @@ -5620,8 +5631,10 @@ public final Observable> buffer(long timespan, TimeUnit unit) { * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument or a maximum size specified by the {@code count} argument (whichever is reached - * first). When the source ObservableSource completes or encounters an error, the resulting ObservableSource emits the - * current buffer and propagates the notification from the source ObservableSource. + * first). When the source ObservableSource completes, the resulting ObservableSource emits the current buffer and + * propagates the notification from the source ObservableSource. Note that if the source ObservableSource issues an + * onError notification the event is passed on immediately without first emitting the buffer it is in the process of + * assembling. *

                * *

                @@ -5651,9 +5664,10 @@ public final Observable> buffer(long timespan, TimeUnit unit, int count) * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument as measured on the specified {@code scheduler}, or a maximum size specified by - * the {@code count} argument (whichever is reached first). When the source ObservableSource completes or - * encounters an error, the resulting ObservableSource emits the current buffer and propagates the notification - * from the source ObservableSource. + * the {@code count} argument (whichever is reached first). When the source ObservableSource completes, the resulting + * ObservableSource emits the current buffer and propagates the notification from the source ObservableSource. Note + * that if the source ObservableSource issues an onError notification the event is passed on immediately without + * first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5685,9 +5699,10 @@ public final Observable> buffer(long timespan, TimeUnit unit, Scheduler * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument as measured on the specified {@code scheduler}, or a maximum size specified by - * the {@code count} argument (whichever is reached first). When the source ObservableSource completes or - * encounters an error, the resulting ObservableSource emits the current buffer and propagates the notification - * from the source ObservableSource. + * the {@code count} argument (whichever is reached first). When the source ObservableSource completes, the resulting + * ObservableSource emits the current buffer and propagates the notification from the source ObservableSource. Note + * that if the source ObservableSource issues an onError notification the event is passed on immediately without + * first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5732,9 +5747,10 @@ public final > Observable buffer( /** * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits connected, non-overlapping buffers, each of a fixed duration specified by the - * {@code timespan} argument and on the specified {@code scheduler}. When the source ObservableSource completes or - * encounters an error, the resulting ObservableSource emits the current buffer and propagates the notification - * from the source ObservableSource. + * {@code timespan} argument and on the specified {@code scheduler}. When the source ObservableSource completes, + * the resulting ObservableSource emits the current buffer and propagates the notification from the source + * ObservableSource. Note that if the source ObservableSource issues an onError notification the event is passed on + * immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5762,7 +5778,9 @@ public final Observable> buffer(long timespan, TimeUnit unit, Scheduler /** * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits buffers that it creates when the specified {@code openingIndicator} ObservableSource emits an - * item, and closes when the ObservableSource returned from {@code closingIndicator} emits an item. + * item, and closes when the ObservableSource returned from {@code closingIndicator} emits an item. If any of the + * source ObservableSource, {@code openingIndicator} or {@code closingIndicator} issues an onError notification the + * event is passed on immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5792,7 +5810,9 @@ public final Observable> buffer( /** * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits buffers that it creates when the specified {@code openingIndicator} ObservableSource emits an - * item, and closes when the ObservableSource returned from {@code closingIndicator} emits an item. + * item, and closes when the ObservableSource returned from {@code closingIndicator} emits an item. If any of the + * source ObservableSource, {@code openingIndicator} or {@code closingIndicator} issues an onError notification the + * event is passed on immediately without first emitting the buffer it is in the process of assembling. *

                * *

                @@ -5834,7 +5854,9 @@ public final > Observable * *

                * Completion of either the source or the boundary ObservableSource causes the returned ObservableSource to emit the - * latest buffer and complete. + * latest buffer and complete. If either the source ObservableSource or the boundary ObservableSource issues an + * onError notification the event is passed on immediately without first emitting the buffer it is in the process of + * assembling. *

                *
                Scheduler:
                *
                This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.
                @@ -5862,7 +5884,9 @@ public final Observable> buffer(ObservableSource boundary) { * *

                * Completion of either the source or the boundary ObservableSource causes the returned ObservableSource to emit the - * latest buffer and complete. + * latest buffer and complete. If either the source ObservableSource or the boundary ObservableSource issues an + * onError notification the event is passed on immediately without first emitting the buffer it is in the process of + * assembling. *

                *
                Scheduler:
                *
                This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.
                @@ -5893,7 +5917,9 @@ public final Observable> buffer(ObservableSource boundary, final * *

                * Completion of either the source or the boundary ObservableSource causes the returned ObservableSource to emit the - * latest buffer and complete. + * latest buffer and complete. If either the source ObservableSource or the boundary ObservableSource issues an + * onError notification the event is passed on immediately without first emitting the buffer it is in the process of + * assembling. *

                *
                Scheduler:
                *
                This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.
                @@ -5923,10 +5949,12 @@ public final > Observable buffer(Observabl /** * Returns an Observable that emits buffers of items it collects from the source ObservableSource. The resulting * ObservableSource emits connected, non-overlapping buffers. It emits the current buffer and replaces it with a - * new buffer whenever the ObservableSource produced by the specified {@code closingIndicator} emits an item. + * new buffer whenever the ObservableSource produced by the specified {@code boundarySupplier} emits an item. *

                * *

                + * If either the source ObservableSource or the boundary ObservableSource issues an onError notification the event + * is passed on immediately without first emitting the buffer it is in the process of assembling. *
                Scheduler:
                *
                This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -5934,7 +5962,7 @@ public final > Observable buffer(Observabl * @param the value type of the boundary-providing ObservableSource * @param boundarySupplier * a {@link Callable} that produces an ObservableSource that governs the boundary between buffers. - * Whenever the source {@code ObservableSource} emits an item, {@code buffer} emits the current buffer and + * Whenever the supplied {@code ObservableSource} emits an item, {@code buffer} emits the current buffer and * begins to fill a new one * @return an Observable that emits a connected, non-overlapping buffer of items from the source ObservableSource * each time the ObservableSource created with the {@code closingIndicator} argument emits an item @@ -5950,10 +5978,12 @@ public final Observable> buffer(Callable * *
                + * If either the source ObservableSource or the boundary ObservableSource issues an onError notification the event + * is passed on immediately without first emitting the buffer it is in the process of assembling. *
                Scheduler:
                *
                This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -5962,7 +5992,7 @@ public final Observable> buffer(Callable the value type of the boundary-providing ObservableSource * @param boundarySupplier * a {@link Callable} that produces an ObservableSource that governs the boundary between buffers. - * Whenever the source {@code ObservableSource} emits an item, {@code buffer} emits the current buffer and + * Whenever the supplied {@code ObservableSource} emits an item, {@code buffer} emits the current buffer and * begins to fill a new one * @param bufferSupplier * a factory function that returns an instance of the collection subclass to be used and returned From 95dde6fbfd95517e31b896257e3a4db50ae686c2 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 7 Mar 2018 12:06:48 +0100 Subject: [PATCH 125/417] 2.x: clarify dematerialize() and terminal items/signals (#5897) --- src/main/java/io/reactivex/Flowable.java | 19 +++++++++++++++++++ src/main/java/io/reactivex/Observable.java | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 13cef7fc07..445487ab7d 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -8276,6 +8276,25 @@ public final Flowable delaySubscription(long delay, TimeUnit unit, Scheduler * represent. *

                * + *

                + * When the upstream signals an {@link Notification#createOnError(Throwable) onError} or + * {@link Notification#createOnComplete() onComplete} item, the + * returned Flowable cancels the flow and terminates with that type of terminal event: + *

                
                +     * Flowable.just(createOnNext(1), createOnComplete(), createOnNext(2))
                +     * .doOnCancel(() -> System.out.println("Cancelled!"));
                +     * .test()
                +     * .assertResult(1);
                +     * 
                + * If the upstream signals {@code onError} or {@code onComplete} directly, the flow is terminated + * with the same event. + *
                
                +     * Flowable.just(createOnNext(1), createOnNext(2))
                +     * .test()
                +     * .assertResult(1, 2);
                +     * 
                + * If this behavior is not desired, the completion can be suppressed by applying {@link #concatWith(Publisher)} + * with a {@link #never()} source. *
                *
                Backpressure:
                *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 9530e8f24d..5337cdbb3b 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7490,6 +7490,25 @@ public final Observable delaySubscription(long delay, TimeUnit unit, Schedule * represent. *

                * + *

                + * When the upstream signals an {@link Notification#createOnError(Throwable) onError} or + * {@link Notification#createOnComplete() onComplete} item, the + * returned Observable cancels the flow and terminates with that type of terminal event: + *

                
                +     * Observable.just(createOnNext(1), createOnComplete(), createOnNext(2))
                +     * .doOnCancel(() -> System.out.println("Cancelled!"));
                +     * .test()
                +     * .assertResult(1);
                +     * 
                + * If the upstream signals {@code onError} or {@code onComplete} directly, the flow is terminated + * with the same event. + *
                
                +     * Observable.just(createOnNext(1), createOnNext(2))
                +     * .test()
                +     * .assertResult(1, 2);
                +     * 
                + * If this behavior is not desired, the completion can be suppressed by applying {@link #concatWith(ObservableSource)} + * with a {@link #never()} source. *
                *
                Scheduler:
                *
                {@code dematerialize} does not operate by default on a particular {@link Scheduler}.
                From 2edea6b8c8349dc06355d9c0182ba537978d6191 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 7 Mar 2018 12:21:53 +0100 Subject: [PATCH 126/417] 2.x: Fix the extra retention problem in ReplaySubject (#5892) * 2.x: Fix the extra retention problem in ReplaySubject * Cover the already-trimmed case. --- .../io/reactivex/subjects/ReplaySubject.java | 83 +++++++++++++++-- .../reactivex/subjects/ReplaySubjectTest.java | 89 +++++++++++++++++++ 2 files changed, 166 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java index 29634ff1c4..271a1f7b56 100644 --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java @@ -13,7 +13,6 @@ package io.reactivex.subjects; -import io.reactivex.annotations.Nullable; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.TimeUnit; @@ -21,7 +20,7 @@ import io.reactivex.Observer; import io.reactivex.Scheduler; -import io.reactivex.annotations.CheckReturnValue; +import io.reactivex.annotations.*; import io.reactivex.disposables.Disposable; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.util.NotificationLite; @@ -94,8 +93,9 @@ * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()}, * {@link #getValues()} or {@link #getValues(Object[])}. *

                - * Note that due to concurrency requirements, a size-bounded {@code ReplaySubject} may hold strong references to more - * source emissions than specified. + * Note that due to concurrency requirements, a size- and time-bounded {@code ReplaySubject} may hold strong references to more + * source emissions than specified while it isn't terminated yet. Use the {@link #cleanupBuffer()} to allow + * such inaccessible items to be cleaned up by GC once no consumer references it anymore. *

                *
                Scheduler:
                *
                {@code ReplaySubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and @@ -415,6 +415,24 @@ public T getValue() { return buffer.getValue(); } + /** + * Makes sure the item cached by the head node in a bounded + * ReplaySubject is released (as it is never part of a replay). + *

                + * By default, live bounded buffers will remember one item before + * the currently receivable one to ensure subscribers can always + * receive a continuous sequence of items. A terminated ReplaySubject + * automatically releases this inaccessible item. + *

                + * The method must be called sequentially, similar to the standard + * {@code onXXX} methods. + * @since 2.1.11 - experimental + */ + @Experimental + public void cleanupBuffer() { + buffer.trimHead(); + } + /** An empty array to avoid allocation in getValues(). */ private static final Object[] EMPTY_ARRAY = new Object[0]; @@ -563,6 +581,12 @@ interface ReplayBuffer { * @return true if successful */ boolean compareAndSet(Object expected, Object next); + + /** + * Make sure an old inaccessible head value is released + * in a bounded buffer. + */ + void trimHead(); } static final class ReplayDisposable extends AtomicInteger implements Disposable { @@ -619,10 +643,16 @@ public void add(T value) { @Override public void addFinal(Object notificationLite) { buffer.add(notificationLite); + trimHead(); size++; done = true; } + @Override + public void trimHead() { + // no-op in this type of buffer + } + @Override @Nullable @SuppressWarnings("unchecked") @@ -839,9 +869,24 @@ public void addFinal(Object notificationLite) { size++; t.lazySet(n); // releases both the tail and size + trimHead(); done = true; } + /** + * Replace a non-empty head node with an empty one to + * allow the GC of the inaccessible old value. + */ + @Override + public void trimHead() { + Node h = head; + if (h.value != null) { + Node n = new Node(null); + n.lazySet(h.get()); + head = n; + } + } + @Override @Nullable @SuppressWarnings("unchecked") @@ -1047,12 +1092,24 @@ void trimFinal() { for (;;) { TimedNode next = h.get(); if (next.get() == null) { - head = h; + if (h.value != null) { + TimedNode lasth = new TimedNode(null, 0L); + lasth.lazySet(h.get()); + head = lasth; + } else { + head = h; + } break; } if (next.time > limit) { - head = h; + if (h.value != null) { + TimedNode lasth = new TimedNode(null, 0L); + lasth.lazySet(h.get()); + head = lasth; + } else { + head = h; + } break; } @@ -1085,6 +1142,20 @@ public void addFinal(Object notificationLite) { done = true; } + /** + * Replace a non-empty head node with an empty one to + * allow the GC of the inaccessible old value. + */ + @Override + public void trimHead() { + TimedNode h = head; + if (h.value != null) { + TimedNode n = new TimedNode(null, 0); + n.lazySet(h.get()); + head = n; + } + } + @Override @Nullable @SuppressWarnings("unchecked") diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java index 7331edf615..ccb5047cff 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java @@ -30,6 +30,7 @@ import io.reactivex.functions.Function; import io.reactivex.observers.*; import io.reactivex.schedulers.*; +import io.reactivex.subjects.ReplaySubject.*; public class ReplaySubjectTest extends SubjectTest { @@ -1184,4 +1185,92 @@ public void timedNoOutdatedData() { source.test().assertResult(); } + + @Test + public void noHeadRetentionCompleteSize() { + ReplaySubject source = ReplaySubject.createWithSize(1); + + source.onNext(1); + source.onNext(2); + source.onComplete(); + + SizeBoundReplayBuffer buf = (SizeBoundReplayBuffer)source.buffer; + + assertNull(buf.head.value); + + Object o = buf.head; + + source.cleanupBuffer(); + + assertSame(o, buf.head); + } + + + @Test + public void noHeadRetentionSize() { + ReplaySubject source = ReplaySubject.createWithSize(1); + + source.onNext(1); + source.onNext(2); + + SizeBoundReplayBuffer buf = (SizeBoundReplayBuffer)source.buffer; + + assertNotNull(buf.head.value); + + source.cleanupBuffer(); + + assertNull(buf.head.value); + + Object o = buf.head; + + source.cleanupBuffer(); + + assertSame(o, buf.head); + } + + @Test + public void noHeadRetentionCompleteTime() { + ReplaySubject source = ReplaySubject.createWithTime(1, TimeUnit.MINUTES, Schedulers.computation()); + + source.onNext(1); + source.onNext(2); + source.onComplete(); + + SizeAndTimeBoundReplayBuffer buf = (SizeAndTimeBoundReplayBuffer)source.buffer; + + assertNull(buf.head.value); + + Object o = buf.head; + + source.cleanupBuffer(); + + assertSame(o, buf.head); + } + + @Test + public void noHeadRetentionTime() { + TestScheduler sch = new TestScheduler(); + + ReplaySubject source = ReplaySubject.createWithTime(1, TimeUnit.MILLISECONDS, sch); + + source.onNext(1); + + sch.advanceTimeBy(2, TimeUnit.MILLISECONDS); + + source.onNext(2); + + SizeAndTimeBoundReplayBuffer buf = (SizeAndTimeBoundReplayBuffer)source.buffer; + + assertNotNull(buf.head.value); + + source.cleanupBuffer(); + + assertNull(buf.head.value); + + Object o = buf.head; + + source.cleanupBuffer(); + + assertSame(o, buf.head); + } } From 3aae12e3cece8679ff82524104442c16980a0ad5 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 7 Mar 2018 18:15:25 +0100 Subject: [PATCH 127/417] 2.x: Fix Observable.flatMap scalar maxConcurrency overflow (#5900) --- .../observable/ObservableFlatMap.java | 33 ++++++--- .../observable/ObservableConcatMapTest.java | 69 ++++++++++++++++++- .../observable/ObservableFlatMapTest.java | 67 ++++++++++++++++++ 3 files changed, 157 insertions(+), 12 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java index d67a850783..6df47ffa87 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java @@ -143,16 +143,19 @@ public void onNext(T t) { void subscribeInner(ObservableSource p) { for (;;) { if (p instanceof Callable) { - tryEmitScalar(((Callable)p)); - - if (maxConcurrency != Integer.MAX_VALUE) { + if (tryEmitScalar(((Callable)p)) && maxConcurrency != Integer.MAX_VALUE) { + boolean empty = false; synchronized (this) { p = sources.poll(); if (p == null) { wip--; - break; + empty = true; } } + if (empty) { + drain(); + break; + } } else { break; } @@ -214,7 +217,7 @@ void removeInner(InnerObserver inner) { } } - void tryEmitScalar(Callable value) { + boolean tryEmitScalar(Callable value) { U u; try { u = value.call(); @@ -222,18 +225,18 @@ void tryEmitScalar(Callable value) { Exceptions.throwIfFatal(ex); errors.addThrowable(ex); drain(); - return; + return true; } if (u == null) { - return; + return true; } if (get() == 0 && compareAndSet(0, 1)) { actual.onNext(u); if (decrementAndGet() == 0) { - return; + return true; } } else { SimplePlainQueue q = queue; @@ -248,13 +251,14 @@ void tryEmitScalar(Callable value) { if (!q.offer(u)) { onError(new IllegalStateException("Scalar queue full?!")); - return; + return true; } if (getAndIncrement() != 0) { - return; + return false; } } drainLoop(); + return true; } void tryEmit(U value, InnerObserver inner) { @@ -360,7 +364,14 @@ void drainLoop() { InnerObserver[] inner = observers.get(); int n = inner.length; - if (d && (svq == null || svq.isEmpty()) && n == 0) { + int nSources = 0; + if (maxConcurrency != Integer.MAX_VALUE) { + synchronized (this) { + nSources = sources.size(); + } + } + + if (d && (svq == null || svq.isEmpty()) && n == 0 && nSources == 0) { Throwable ex = errors.terminate(); if (ex != ExceptionHelper.TERMINATED) { if (ex == null) { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java index ecff867fdb..5c2681a79d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java @@ -22,7 +22,7 @@ import io.reactivex.*; import io.reactivex.disposables.*; -import io.reactivex.exceptions.TestException; +import io.reactivex.exceptions.*; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; @@ -431,4 +431,71 @@ public void onComplete() { assertTrue(disposable[0].isDisposed()); } + + @Test + public void reentrantNoOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + TestObserver to = ps.concatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.just(v + 1); + } + }, 1) + .subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + for (int i = 1; i < 10; i++) { + ps.onNext(i); + } + ps.onComplete(); + } + } + }); + + ps.onNext(0); + + if (!errors.isEmpty()) { + to.onError(new CompositeException(errors)); + } + + to.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void reentrantNoOverflowHidden() { + final PublishSubject ps = PublishSubject.create(); + + TestObserver to = ps.concatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.just(v + 1).hide(); + } + }, 1) + .subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + for (int i = 1; i < 10; i++) { + ps.onNext(i); + } + ps.onComplete(); + } + } + }); + + ps.onNext(0); + + to.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index 1771e1d5f4..70daea3fd9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -938,4 +938,71 @@ public void remove() { assertEquals(1, counter.get()); } + + @Test + public void scalarQueueNoOverflow() { + List errors = TestHelper.trackPluginErrors(); + try { + final PublishSubject ps = PublishSubject.create(); + + TestObserver to = ps.flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.just(v + 1); + } + }, 1) + .subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + for (int i = 1; i < 10; i++) { + ps.onNext(i); + } + ps.onComplete(); + } + } + }); + + ps.onNext(0); + + if (!errors.isEmpty()) { + to.onError(new CompositeException(errors)); + } + + to.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void scalarQueueNoOverflowHidden() { + final PublishSubject ps = PublishSubject.create(); + + TestObserver to = ps.flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.just(v + 1).hide(); + } + }, 1) + .subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + for (int i = 1; i < 10; i++) { + ps.onNext(i); + } + ps.onComplete(); + } + } + }); + + ps.onNext(0); + + to.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } } From 92812812a20db2b5b1c40d0a733ad5bfa320e7da Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 7 Mar 2018 18:32:47 +0100 Subject: [PATCH 128/417] 2.x: Fix publish(-|Function) subscriber swap possible data loss (#5893) --- .../operators/flowable/FlowablePublish.java | 78 ++-- .../flowable/FlowablePublishMulticast.java | 38 +- .../flowable/FlowablePublishTest.java | 363 +++++++++++++++++- 3 files changed, 439 insertions(+), 40 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java index 147f9ecc11..9bc0d63b65 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java @@ -148,7 +148,7 @@ static final class PublishSubscriber final int bufferSize; /** Tracks the subscribed InnerSubscribers. */ - final AtomicReference subscribers; + final AtomicReference[]> subscribers; /** * Atomically changed from false to true by connect to make sure the * connection is only performed by one thread. @@ -165,8 +165,9 @@ static final class PublishSubscriber /** Holds notifications from upstream. */ volatile SimpleQueue queue; + @SuppressWarnings("unchecked") PublishSubscriber(AtomicReference> current, int bufferSize) { - this.subscribers = new AtomicReference(EMPTY); + this.subscribers = new AtomicReference[]>(EMPTY); this.current = current; this.shouldConnect = new AtomicBoolean(); this.bufferSize = bufferSize; @@ -175,6 +176,7 @@ static final class PublishSubscriber @Override public void dispose() { if (subscribers.get() != TERMINATED) { + @SuppressWarnings("unchecked") InnerSubscriber[] ps = subscribers.getAndSet(TERMINATED); if (ps != TERMINATED) { current.compareAndSet(PublishSubscriber.this, null); @@ -263,7 +265,7 @@ boolean add(InnerSubscriber producer) { // the state can change so we do a CAS loop to achieve atomicity for (;;) { // get the current producer array - InnerSubscriber[] c = subscribers.get(); + InnerSubscriber[] c = subscribers.get(); // if this subscriber-to-source reached a terminal state by receiving // an onError or onComplete, just refuse to add the new producer if (c == TERMINATED) { @@ -271,7 +273,8 @@ boolean add(InnerSubscriber producer) { } // we perform a copy-on-write logic int len = c.length; - InnerSubscriber[] u = new InnerSubscriber[len + 1]; + @SuppressWarnings("unchecked") + InnerSubscriber[] u = new InnerSubscriber[len + 1]; System.arraycopy(c, 0, u, 0, len); u[len] = producer; // try setting the subscribers array @@ -287,11 +290,12 @@ boolean add(InnerSubscriber producer) { * Atomically removes the given InnerSubscriber from the subscribers array. * @param producer the producer to remove */ + @SuppressWarnings("unchecked") void remove(InnerSubscriber producer) { // the state can change so we do a CAS loop to achieve atomicity for (;;) { // let's read the current subscribers array - InnerSubscriber[] c = subscribers.get(); + InnerSubscriber[] c = subscribers.get(); int len = c.length; // if it is either empty or terminated, there is nothing to remove so we quit if (len == 0) { @@ -311,7 +315,7 @@ void remove(InnerSubscriber producer) { return; } // we do copy-on-write logic here - InnerSubscriber[] u; + InnerSubscriber[] u; // we don't create a new empty array if producer was the single inhabitant // but rather reuse an empty array if (len == 1) { @@ -340,6 +344,7 @@ void remove(InnerSubscriber producer) { * @param empty set to true if the queue is empty * @return true if there is indeed a terminal condition */ + @SuppressWarnings("unchecked") boolean checkTerminated(Object term, boolean empty) { // first of all, check if there is actually a terminal event if (term != null) { @@ -404,6 +409,17 @@ void dispatch() { return; } int missed = 1; + + // saving a local copy because this will be accessed after every item + // delivered to detect changes in the subscribers due to an onNext + // and thus not dropping items + AtomicReference[]> subscribers = this.subscribers; + + // We take a snapshot of the current child subscribers. + // Concurrent subscribers may miss this iteration, but it is to be expected + InnerSubscriber[] ps = subscribers.get(); + + outer: for (;;) { /* * We need to read terminalEvent before checking the queue for emptiness because @@ -434,10 +450,6 @@ void dispatch() { // this loop is the only one which can turn a non-empty queue into an empty one // and as such, no need to ask the queue itself again for that. if (!empty) { - // We take a snapshot of the current child subscribers. - // Concurrent subscribers may miss this iteration, but it is to be expected - @SuppressWarnings("unchecked") - InnerSubscriber[] ps = subscribers.get(); int len = ps.length; // Let's assume everyone requested the maximum value. @@ -452,14 +464,11 @@ void dispatch() { long r = ip.get(); // if there is one child subscriber that hasn't requested yet // we can't emit anything to anyone - if (r >= 0L) { - maxRequested = Math.min(maxRequested, r); - } else - // cancellation is indicated by a special value - if (r == CANCELLED) { + if (r != CANCELLED) { + maxRequested = Math.min(maxRequested, r - ip.emitted); + } else { cancelled++; } - // we ignore those with NOT_REQUESTED as if they aren't even there } // it may happen everyone has cancelled between here and subscribers.get() @@ -518,20 +527,36 @@ void dispatch() { } // we need to unwrap potential nulls T value = NotificationLite.getValue(v); + + boolean subscribersChanged = false; + // let's emit this value to all child subscribers for (InnerSubscriber ip : ps) { // if ip.get() is negative, the child has either cancelled in the // meantime or hasn't requested anything yet // this eager behavior will skip cancelled children in case // multiple values are available in the queue - if (ip.get() > 0L) { + long ipr = ip.get(); + if (ipr != CANCELLED) { + if (ipr != Long.MAX_VALUE) { + // indicate this child has received 1 element + ip.emitted++; + } ip.child.onNext(value); - // indicate this child has received 1 element - ip.produced(1); + } else { + subscribersChanged = true; } } // indicate we emitted one element d++; + + // see if the array of subscribers changed as a consequence + // of emission or concurrent activity + InnerSubscriber[] freshArray = subscribers.get(); + if (subscribersChanged || freshArray != ps) { + ps = freshArray; + continue outer; + } } // if we did emit at least one element, request more to replenish the queue @@ -552,6 +577,9 @@ void dispatch() { if (missed == 0) { break; } + + // get a fresh copy of the current subscribers + ps = subscribers.get(); } } } @@ -571,6 +599,9 @@ static final class InnerSubscriber extends AtomicLong implements Subscription */ volatile PublishSubscriber parent; + /** Track the number of emitted items (avoids decrementing the request counter). */ + long emitted; + InnerSubscriber(Subscriber child) { this.child = child; } @@ -586,15 +617,6 @@ public void request(long n) { } } - /** - * Indicate that values have been emitted to this child subscriber by the dispatch() method. - * @param n the number of items emitted - * @return the updated request value (may indicate how much can be produced or a terminal state) - */ - public long produced(long n) { - return BackpressureHelper.producedCancel(this, n); - } - @Override public void cancel() { long r = get(); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java index d7cd85d716..079ef019c6 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java @@ -153,8 +153,6 @@ static final class MulticastProcessor extends Flowable implements Flowable int consumed; - long emitted; - @SuppressWarnings("unchecked") MulticastProcessor(int prefetch, boolean delayError) { this.prefetch = prefetch; @@ -325,10 +323,12 @@ void drain() { int upstreamConsumed = consumed; int localLimit = limit; boolean canRequest = sourceMode != QueueSubscription.SYNC; - long e = emitted; + AtomicReference[]> subs = subscribers; + + MulticastSubscription[] array = subs.get(); + outer: for (;;) { - MulticastSubscription[] array = subscribers.get(); int n = array.length; @@ -336,7 +336,7 @@ void drain() { long r = Long.MAX_VALUE; for (MulticastSubscription ms : array) { - long u = ms.get(); + long u = ms.get() - ms.emitted; if (u != Long.MIN_VALUE) { if (r > u) { r = u; @@ -347,10 +347,10 @@ void drain() { } if (n == 0) { - r = e; + r = 0; } - while (e != r) { + while (r != 0) { if (isDisposed()) { q.clear(); return; @@ -393,21 +393,35 @@ void drain() { break; } + boolean subscribersChange = false; + for (MulticastSubscription ms : array) { - if (ms.get() != Long.MIN_VALUE) { + long msr = ms.get(); + if (msr != Long.MIN_VALUE) { + if (msr != Long.MAX_VALUE) { + ms.emitted++; + } ms.actual.onNext(v); + } else { + subscribersChange = true; } } - e++; + r--; if (canRequest && ++upstreamConsumed == localLimit) { upstreamConsumed = 0; s.get().request(localLimit); } + + MulticastSubscription[] freshArray = subs.get(); + if (subscribersChange || freshArray != array) { + array = freshArray; + continue outer; + } } - if (e == r) { + if (r == 0) { if (isDisposed()) { q.clear(); return; @@ -435,7 +449,6 @@ void drain() { } } - emitted = e; consumed = upstreamConsumed; missed = wip.addAndGet(-missed); if (missed == 0) { @@ -444,6 +457,7 @@ void drain() { if (q == null) { q = queue; } + array = subs.get(); } } @@ -476,6 +490,8 @@ static final class MulticastSubscription final MulticastProcessor parent; + long emitted; + MulticastSubscription(Subscriber actual, MulticastProcessor parent) { this.actual = actual; this.parent = parent; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java index 432f5231c4..866e8de378 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java @@ -19,7 +19,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; -import org.junit.Test; +import org.junit.*; import org.reactivestreams.*; import io.reactivex.*; @@ -941,4 +941,365 @@ protected void subscribeActual(Subscriber s) { ref.get().add(new InnerSubscriber(new TestSubscriber())); ref.get().remove(null); } + + @Test + @Ignore("publish() keeps consuming the upstream if there are no subscribers, 3.x should change this") + public void subscriberSwap() { + final ConnectableFlowable co = Flowable.range(1, 5).publish(); + + co.connect(); + + TestSubscriber ts1 = new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + cancel(); + onComplete(); + } + }; + + co.subscribe(ts1); + + ts1.assertResult(1); + + TestSubscriber ts2 = new TestSubscriber(0); + co.subscribe(ts2); + + ts2 + .assertEmpty() + .requestMore(4) + .assertResult(2, 3, 4, 5); + } + + @Test + public void subscriberLiveSwap() { + final ConnectableFlowable co = Flowable.range(1, 5).publish(); + + final TestSubscriber ts2 = new TestSubscriber(0); + + TestSubscriber ts1 = new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + cancel(); + onComplete(); + co.subscribe(ts2); + } + }; + + co.subscribe(ts1); + + co.connect(); + + ts1.assertResult(1); + + ts2 + .assertEmpty() + .requestMore(4) + .assertResult(2, 3, 4, 5); + } + + @Test + public void selectorSubscriberSwap() { + final AtomicReference> ref = new AtomicReference>(); + + Flowable.range(1, 5).publish(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) throws Exception { + ref.set(f); + return Flowable.never(); + } + }).test(); + + ref.get().take(2).test().assertResult(1, 2); + + ref.get() + .test(0) + .assertEmpty() + .requestMore(2) + .assertValuesOnly(3, 4) + .requestMore(1) + .assertResult(3, 4, 5); + } + + @Test + public void leavingSubscriberOverrequests() { + final AtomicReference> ref = new AtomicReference>(); + + PublishProcessor pp = PublishProcessor.create(); + + pp.publish(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) throws Exception { + ref.set(f); + return Flowable.never(); + } + }).test(); + + TestSubscriber ts1 = ref.get().take(2).test(); + + pp.onNext(1); + pp.onNext(2); + + ts1.assertResult(1, 2); + + pp.onNext(3); + pp.onNext(4); + + TestSubscriber ts2 = ref.get().test(0L); + + ts2.assertEmpty(); + + ts2.requestMore(2); + + ts2.assertValuesOnly(3, 4); + } + + // call a transformer only if the input is non-empty + @Test + public void composeIfNotEmpty() { + final FlowableTransformer transformer = new FlowableTransformer() { + @Override + public Publisher apply(Flowable g) { + return g.map(new Function() { + @Override + public Integer apply(Integer v) throws Exception { + return v + 1; + } + }); + } + }; + + final AtomicInteger calls = new AtomicInteger(); + Flowable.range(1, 5) + .publish(new Function, Publisher>() { + @Override + public Publisher apply(final Flowable shared) + throws Exception { + return shared.take(1).concatMap(new Function>() { + @Override + public Publisher apply(Integer first) + throws Exception { + calls.incrementAndGet(); + return transformer.apply(Flowable.just(first).concatWith(shared)); + } + }); + } + }) + .test() + .assertResult(2, 3, 4, 5, 6); + + assertEquals(1, calls.get()); + } + + // call a transformer only if the input is non-empty + @Test + public void composeIfNotEmptyNotFused() { + final FlowableTransformer transformer = new FlowableTransformer() { + @Override + public Publisher apply(Flowable g) { + return g.map(new Function() { + @Override + public Integer apply(Integer v) throws Exception { + return v + 1; + } + }); + } + }; + + final AtomicInteger calls = new AtomicInteger(); + Flowable.range(1, 5).hide() + .publish(new Function, Publisher>() { + @Override + public Publisher apply(final Flowable shared) + throws Exception { + return shared.take(1).concatMap(new Function>() { + @Override + public Publisher apply(Integer first) + throws Exception { + calls.incrementAndGet(); + return transformer.apply(Flowable.just(first).concatWith(shared)); + } + }); + } + }) + .test() + .assertResult(2, 3, 4, 5, 6); + + assertEquals(1, calls.get()); + } + + // call a transformer only if the input is non-empty + @Test + public void composeIfNotEmptyIsEmpty() { + final FlowableTransformer transformer = new FlowableTransformer() { + @Override + public Publisher apply(Flowable g) { + return g.map(new Function() { + @Override + public Integer apply(Integer v) throws Exception { + return v + 1; + } + }); + } + }; + + final AtomicInteger calls = new AtomicInteger(); + Flowable.empty().hide() + .publish(new Function, Publisher>() { + @Override + public Publisher apply(final Flowable shared) + throws Exception { + return shared.take(1).concatMap(new Function>() { + @Override + public Publisher apply(Integer first) + throws Exception { + calls.incrementAndGet(); + return transformer.apply(Flowable.just(first).concatWith(shared)); + } + }); + } + }) + .test() + .assertResult(); + + assertEquals(0, calls.get()); + } + + @Test + public void publishFunctionCancelOuterAfterOneInner() { + final AtomicReference> ref = new AtomicReference>(); + + PublishProcessor pp = PublishProcessor.create(); + + final TestSubscriber ts = pp.publish(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) throws Exception { + ref.set(f); + return Flowable.never(); + } + }).test(); + + ref.get().subscribe(new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + onComplete(); + ts.cancel(); + } + }); + + pp.onNext(1); + } + + @Test + public void publishFunctionCancelOuterAfterOneInnerBackpressured() { + final AtomicReference> ref = new AtomicReference>(); + + PublishProcessor pp = PublishProcessor.create(); + + final TestSubscriber ts = pp.publish(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) throws Exception { + ref.set(f); + return Flowable.never(); + } + }).test(); + + ref.get().subscribe(new TestSubscriber(1L) { + @Override + public void onNext(Integer t) { + super.onNext(t); + onComplete(); + ts.cancel(); + } + }); + + pp.onNext(1); + } + + @Test + public void publishCancelOneAsync() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final PublishProcessor pp = PublishProcessor.create(); + + final AtomicReference> ref = new AtomicReference>(); + + pp.publish(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) throws Exception { + ref.set(f); + return Flowable.never(); + } + }).test(); + + final TestSubscriber ts1 = ref.get().test(); + TestSubscriber ts2 = ref.get().test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts1.cancel(); + } + }; + + TestHelper.race(r1, r2); + + ts2.assertValuesOnly(1); + } + } + + @Test + public void publishCancelOneAsync2() { + final PublishProcessor pp = PublishProcessor.create(); + + ConnectableFlowable co = pp.publish(); + + final TestSubscriber ts1 = new TestSubscriber(); + + final AtomicReference> ref = new AtomicReference>(); + + co.subscribe(new FlowableSubscriber() { + @SuppressWarnings("unchecked") + @Override + public void onSubscribe(Subscription s) { + ts1.onSubscribe(new BooleanSubscription()); + // pretend to be cancelled without removing it from the subscriber list + ref.set((InnerSubscriber)s); + } + + @Override + public void onNext(Integer t) { + ts1.onNext(t); + } + + @Override + public void onError(Throwable t) { + ts1.onError(t); + } + + @Override + public void onComplete() { + ts1.onComplete(); + } + }); + TestSubscriber ts2 = co.test(); + + co.connect(); + + ref.get().set(Long.MIN_VALUE); + + pp.onNext(1); + + ts1.assertEmpty(); + ts2.assertValuesOnly(1); + } } From 5e5d5a27aa7b250ef1626dddf291c9243da2cc61 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 7 Mar 2018 18:49:09 +0100 Subject: [PATCH 129/417] 2.x: Fix excess item retention in the other replay components (#5898) --- .../operators/flowable/FlowableReplay.java | 11 +- .../observable/ObservableReplay.java | 12 +- .../reactivex/processors/ReplayProcessor.java | 66 ++++++- .../flowable/FlowableReplayTest.java | 170 +++++++++++++++++- .../observable/ObservableReplayTest.java | 155 ++++++++++++++++ .../processors/ReplayProcessorTest.java | 142 ++++++++++++++- 6 files changed, 548 insertions(+), 8 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java index 3005eb11c8..7574a93d4b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java @@ -806,6 +806,15 @@ public final void complete() { truncateFinal(); } + final void trimHead() { + Node head = get(); + if (head.value != null) { + Node n = new Node(null, 0L); + n.lazySet(head.get()); + set(n); + } + } + @Override public final void replay(InnerSubscription output) { synchronized (output) { @@ -909,7 +918,7 @@ void truncate() { * based on its properties (i.e., truncate but the very last node). */ void truncateFinal() { - + trimHead(); } /* test */ final void collect(Collection output) { Node n = getHead(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java index c48e83b74b..26efd9be5a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java @@ -619,6 +619,16 @@ final void removeFirst() { // can't null out the head's value because of late replayers would see null setFirst(next); } + + final void trimHead() { + Node head = get(); + if (head.value != null) { + Node n = new Node(null); + n.lazySet(head.get()); + set(n); + } + } + /* test */ final void removeSome(int n) { Node head = get(); while (n > 0) { @@ -733,7 +743,7 @@ Object leaveTransform(Object value) { * based on its properties (i.e., truncate but the very last node). */ void truncateFinal() { - + trimHead(); } /* test */ final void collect(Collection output) { Node n = getHead(); diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index cdfcb0a3af..069e6628fd 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -21,7 +21,7 @@ import org.reactivestreams.*; import io.reactivex.Scheduler; -import io.reactivex.annotations.CheckReturnValue; +import io.reactivex.annotations.*; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.*; @@ -362,6 +362,24 @@ public Throwable getThrowable() { return null; } + /** + * Makes sure the item cached by the head node in a bounded + * ReplayProcessor is released (as it is never part of a replay). + *

                + * By default, live bounded buffers will remember one item before + * the currently receivable one to ensure subscribers can always + * receive a continuous sequence of items. A terminated ReplayProcessor + * automatically releases this inaccessible item. + *

                + * The method must be called sequentially, similar to the standard + * {@code onXXX} methods. + * @since 2.1.11 - experimental + */ + @Experimental + public void cleanupBuffer() { + buffer.trimHead(); + } + /** * Returns a single value the Subject currently has or null if no such value exists. *

                The method is thread-safe. @@ -499,6 +517,12 @@ interface ReplayBuffer { boolean isDone(); Throwable getError(); + + /** + * Make sure an old inaccessible head value is released + * in a bounded buffer. + */ + void trimHead(); } static final class ReplaySubscription extends AtomicInteger implements Subscription { @@ -568,6 +592,11 @@ public void complete() { done = true; } + @Override + public void trimHead() { + // not applicable for an unbounded buffer + } + @Override public T getValue() { int s = size; @@ -771,14 +800,25 @@ public void next(T value) { @Override public void error(Throwable ex) { error = ex; + trimHead(); done = true; } @Override public void complete() { + trimHead(); done = true; } + @Override + public void trimHead() { + if (head.value != null) { + Node n = new Node(null); + n.lazySet(head.get()); + head = n; + } + } + @Override public boolean isDone() { return done; @@ -992,12 +1032,22 @@ void trimFinal() { for (;;) { TimedNode next = h.get(); if (next == null) { - head = h; + if (h.value != null) { + head = new TimedNode(null, 0L); + } else { + head = h; + } break; } if (next.time > limit) { - head = h; + if (h.value != null) { + TimedNode n = new TimedNode(null, 0L); + n.lazySet(h.get()); + head = n; + } else { + head = h; + } break; } @@ -1005,6 +1055,16 @@ void trimFinal() { } } + + @Override + public void trimHead() { + if (head.value != null) { + TimedNode n = new TimedNode(null, 0L); + n.lazySet(head.get()); + head = n; + } + } + @Override public void next(T value) { TimedNode n = new TimedNode(value, scheduler.now(unit)); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index 3c0c1ffc22..d081ea1099 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -21,13 +21,13 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; -import io.reactivex.annotations.NonNull; import org.junit.*; import org.mockito.InOrder; import org.reactivestreams.*; import io.reactivex.*; import io.reactivex.Scheduler.Worker; +import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; import io.reactivex.flowables.ConnectableFlowable; @@ -1775,4 +1775,172 @@ public void badRequest() { .replay() ); } + + @Test + public void noHeadRetentionCompleteSize() { + PublishProcessor source = PublishProcessor.create(); + + FlowableReplay co = (FlowableReplay)source + .replay(1); + + // the backpressure coordination would not accept items from source otherwise + co.test(); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + source.onNext(2); + source.onComplete(); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } + + @Test + public void noHeadRetentionErrorSize() { + PublishProcessor source = PublishProcessor.create(); + + FlowableReplay co = (FlowableReplay)source + .replay(1); + + co.test(); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + source.onNext(2); + source.onError(new TestException()); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } + + @Test + public void noHeadRetentionSize() { + PublishProcessor source = PublishProcessor.create(); + + FlowableReplay co = (FlowableReplay)source + .replay(1); + + co.test(); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + source.onNext(2); + + assertNotNull(buf.get().value); + + buf.trimHead(); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } + + @Test + public void noHeadRetentionCompleteTime() { + PublishProcessor source = PublishProcessor.create(); + + FlowableReplay co = (FlowableReplay)source + .replay(1, TimeUnit.MINUTES, Schedulers.computation()); + + co.test(); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + source.onNext(2); + source.onComplete(); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } + + @Test + public void noHeadRetentionErrorTime() { + PublishProcessor source = PublishProcessor.create(); + + FlowableReplay co = (FlowableReplay)source + .replay(1, TimeUnit.MINUTES, Schedulers.computation()); + + co.test(); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + source.onNext(2); + source.onError(new TestException()); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } + + @Test + public void noHeadRetentionTime() { + TestScheduler sch = new TestScheduler(); + + PublishProcessor source = PublishProcessor.create(); + + FlowableReplay co = (FlowableReplay)source + .replay(1, TimeUnit.MILLISECONDS, sch); + + co.test(); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + + sch.advanceTimeBy(2, TimeUnit.MILLISECONDS); + + source.onNext(2); + + assertNotNull(buf.get().value); + + buf.trimHead(); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java index d8b9c75ef2..0d64c4308f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java @@ -1561,4 +1561,159 @@ public void replaySelectorConnectableReturnsNull() { .test() .assertFailureAndMessage(NullPointerException.class, "The connectableFactory returned a null ConnectableObservable"); } + + @Test + public void noHeadRetentionCompleteSize() { + PublishSubject source = PublishSubject.create(); + + ObservableReplay co = (ObservableReplay)source + .replay(1); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + source.onNext(2); + source.onComplete(); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } + + @Test + public void noHeadRetentionErrorSize() { + PublishSubject source = PublishSubject.create(); + + ObservableReplay co = (ObservableReplay)source + .replay(1); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + source.onNext(2); + source.onError(new TestException()); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } + + @Test + public void noHeadRetentionSize() { + PublishSubject source = PublishSubject.create(); + + ObservableReplay co = (ObservableReplay)source + .replay(1); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + source.onNext(2); + + assertNotNull(buf.get().value); + + buf.trimHead(); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } + + @Test + public void noHeadRetentionCompleteTime() { + PublishSubject source = PublishSubject.create(); + + ObservableReplay co = (ObservableReplay)source + .replay(1, TimeUnit.MINUTES, Schedulers.computation()); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + source.onNext(2); + source.onComplete(); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } + + @Test + public void noHeadRetentionErrorTime() { + PublishSubject source = PublishSubject.create(); + + ObservableReplay co = (ObservableReplay)source + .replay(1, TimeUnit.MINUTES, Schedulers.computation()); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + source.onNext(2); + source.onError(new TestException()); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } + + @Test + public void noHeadRetentionTime() { + TestScheduler sch = new TestScheduler(); + + PublishSubject source = PublishSubject.create(); + + ObservableReplay co = (ObservableReplay)source + .replay(1, TimeUnit.MILLISECONDS, sch); + + co.connect(); + + BoundedReplayBuffer buf = (BoundedReplayBuffer)(co.current.get().buffer); + + source.onNext(1); + + sch.advanceTimeBy(2, TimeUnit.MILLISECONDS); + + source.onNext(2); + + assertNotNull(buf.get().value); + + buf.trimHead(); + + assertNull(buf.get().value); + + Object o = buf.get(); + + buf.trimHead(); + + assertSame(o, buf.get()); + } } diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index cd8f6de326..a80d1d0b83 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -30,6 +30,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.processors.ReplayProcessor.*; import io.reactivex.schedulers.*; import io.reactivex.subscribers.*; @@ -539,7 +540,7 @@ public void testReplayTimestampedDirectly() { // FIXME RS subscribers can't throw // @Test // public void testOnErrorThrowsDoesntPreventDelivery() { -// ReplaySubject ps = ReplaySubject.create(); +// ReplayProcessor ps = ReplayProcessor.create(); // // ps.subscribe(); // TestSubscriber ts = new TestSubscriber(); @@ -561,7 +562,7 @@ public void testReplayTimestampedDirectly() { // */ // @Test // public void testOnErrorThrowsDoesntPreventDelivery2() { -// ReplaySubject ps = ReplaySubject.create(); +// ReplayProcessor ps = ReplayProcessor.create(); // // ps.subscribe(); // ps.subscribe(); @@ -1540,4 +1541,141 @@ public void timeAndSizeBoundCancelAfterOne() { source.subscribeWith(take1AndCancel()) .assertResult(1); } + + @Test + public void noHeadRetentionCompleteSize() { + ReplayProcessor source = ReplayProcessor.createWithSize(1); + + source.onNext(1); + source.onNext(2); + source.onComplete(); + + SizeBoundReplayBuffer buf = (SizeBoundReplayBuffer)source.buffer; + + assertNull(buf.head.value); + + Object o = buf.head; + + source.cleanupBuffer(); + + assertSame(o, buf.head); + } + + @Test + public void noHeadRetentionErrorSize() { + ReplayProcessor source = ReplayProcessor.createWithSize(1); + + source.onNext(1); + source.onNext(2); + source.onError(new TestException()); + + SizeBoundReplayBuffer buf = (SizeBoundReplayBuffer)source.buffer; + + assertNull(buf.head.value); + + Object o = buf.head; + + source.cleanupBuffer(); + + assertSame(o, buf.head); + } + + @Test + public void unboundedCleanupBufferNoOp() { + ReplayProcessor source = ReplayProcessor.create(1); + + source.onNext(1); + source.onNext(2); + + source.cleanupBuffer(); + + source.test().assertValuesOnly(1, 2); + } + + @Test + public void noHeadRetentionSize() { + ReplayProcessor source = ReplayProcessor.createWithSize(1); + + source.onNext(1); + source.onNext(2); + + SizeBoundReplayBuffer buf = (SizeBoundReplayBuffer)source.buffer; + + assertNotNull(buf.head.value); + + source.cleanupBuffer(); + + assertNull(buf.head.value); + + Object o = buf.head; + + source.cleanupBuffer(); + + assertSame(o, buf.head); + } + + @Test + public void noHeadRetentionCompleteTime() { + ReplayProcessor source = ReplayProcessor.createWithTime(1, TimeUnit.MINUTES, Schedulers.computation()); + + source.onNext(1); + source.onNext(2); + source.onComplete(); + + SizeAndTimeBoundReplayBuffer buf = (SizeAndTimeBoundReplayBuffer)source.buffer; + + assertNull(buf.head.value); + + Object o = buf.head; + + source.cleanupBuffer(); + + assertSame(o, buf.head); + } + + @Test + public void noHeadRetentionErrorTime() { + ReplayProcessor source = ReplayProcessor.createWithTime(1, TimeUnit.MINUTES, Schedulers.computation()); + + source.onNext(1); + source.onNext(2); + source.onError(new TestException()); + + SizeAndTimeBoundReplayBuffer buf = (SizeAndTimeBoundReplayBuffer)source.buffer; + + assertNull(buf.head.value); + + Object o = buf.head; + + source.cleanupBuffer(); + + assertSame(o, buf.head); + } + + @Test + public void noHeadRetentionTime() { + TestScheduler sch = new TestScheduler(); + + ReplayProcessor source = ReplayProcessor.createWithTime(1, TimeUnit.MILLISECONDS, sch); + + source.onNext(1); + + sch.advanceTimeBy(2, TimeUnit.MILLISECONDS); + + source.onNext(2); + + SizeAndTimeBoundReplayBuffer buf = (SizeAndTimeBoundReplayBuffer)source.buffer; + + assertNotNull(buf.head.value); + + source.cleanupBuffer(); + + assertNull(buf.head.value); + + Object o = buf.head; + + source.cleanupBuffer(); + + assertSame(o, buf.head); + } } From 7bdcb594806db8dce8a5ed1ad8f149269905731f Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 9 Mar 2018 09:43:45 +0100 Subject: [PATCH 130/417] 2.x: Fix Flowable.singleOrError().toFlowable() not signalling NSEE (#5904) --- .../operators/flowable/FlowableSingle.java | 20 +++++++++++++++---- .../flowable/FlowableSingleMaybe.java | 2 +- .../flowable/FlowableSingleSingle.java | 2 +- .../flowable/FlowableSingleTest.java | 9 +++++++++ .../observable/ObservableSingleTest.java | 9 +++++++++ 5 files changed, 36 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingle.java index a18505404f..70d29e7ad5 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingle.java @@ -13,6 +13,8 @@ package io.reactivex.internal.operators.flowable; +import java.util.NoSuchElementException; + import org.reactivestreams.*; import io.reactivex.*; @@ -23,14 +25,17 @@ public final class FlowableSingle extends AbstractFlowableWithUpstream final T defaultValue; - public FlowableSingle(Flowable source, T defaultValue) { + final boolean failOnEmpty; + + public FlowableSingle(Flowable source, T defaultValue, boolean failOnEmpty) { super(source); this.defaultValue = defaultValue; + this.failOnEmpty = failOnEmpty; } @Override protected void subscribeActual(Subscriber s) { - source.subscribe(new SingleElementSubscriber(s, defaultValue)); + source.subscribe(new SingleElementSubscriber(s, defaultValue, failOnEmpty)); } static final class SingleElementSubscriber extends DeferredScalarSubscription @@ -40,13 +45,16 @@ static final class SingleElementSubscriber extends DeferredScalarSubscription final T defaultValue; + final boolean failOnEmpty; + Subscription s; boolean done; - SingleElementSubscriber(Subscriber actual, T defaultValue) { + SingleElementSubscriber(Subscriber actual, T defaultValue, boolean failOnEmpty) { super(actual); this.defaultValue = defaultValue; + this.failOnEmpty = failOnEmpty; } @Override @@ -94,7 +102,11 @@ public void onComplete() { v = defaultValue; } if (v == null) { - actual.onComplete(); + if (failOnEmpty) { + actual.onError(new NoSuchElementException()); + } else { + actual.onComplete(); + } } else { complete(v); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java index 20608cd430..28ac5bcda1 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java @@ -36,7 +36,7 @@ protected void subscribeActual(MaybeObserver s) { @Override public Flowable fuseToFlowable() { - return RxJavaPlugins.onAssembly(new FlowableSingle(source, null)); + return RxJavaPlugins.onAssembly(new FlowableSingle(source, null, false)); } static final class SingleElementSubscriber diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java index 44df823067..cb33706362 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java @@ -41,7 +41,7 @@ protected void subscribeActual(SingleObserver s) { @Override public Flowable fuseToFlowable() { - return RxJavaPlugins.onAssembly(new FlowableSingle(source, defaultValue)); + return RxJavaPlugins.onAssembly(new FlowableSingle(source, defaultValue, true)); } static final class SingleElementSubscriber diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java index 2aff36bc6a..8be75e36e1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java @@ -796,4 +796,13 @@ public void cancelAsFlowable() { assertFalse(pp.hasSubscribers()); } + + @Test + public void singleOrError() { + Flowable.empty() + .singleOrError() + .toFlowable() + .test() + .assertFailure(NoSuchElementException.class); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSingleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSingleTest.java index 597ac731c2..9407cf4969 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSingleTest.java @@ -556,4 +556,13 @@ public MaybeSource apply(Observable o) throws Exception { } }); } + + @Test + public void singleOrError() { + Observable.empty() + .singleOrError() + .toObservable() + .test() + .assertFailure(NoSuchElementException.class); + } } From 4e50ea491b88680244e41af153c0efce2fecbfc9 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 9 Mar 2018 10:02:23 +0100 Subject: [PATCH 131/417] 2.x: Perf measure of Flowable flatMap & flatMapCompletable (#5902) --- build.gradle | 3 +- .../FlowableFlatMapCompletablePerf.java | 73 +++++++++++++++++++ .../FlowableFlatMapCompletableSyncPerf.java | 63 ++++++++++++++++ .../java/io/reactivex/PerfAsyncConsumer.java | 4 +- .../FlowableFlatMapCompletableTest.java | 18 +++++ 5 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 src/jmh/java/io/reactivex/FlowableFlatMapCompletablePerf.java create mode 100644 src/jmh/java/io/reactivex/FlowableFlatMapCompletableSyncPerf.java diff --git a/build.gradle b/build.gradle index 9da4ae5757..f3f16d4eb4 100644 --- a/build.gradle +++ b/build.gradle @@ -54,7 +54,7 @@ targetCompatibility = JavaVersion.VERSION_1_6 def junitVersion = "4.12" def reactiveStreamsVersion = "1.0.2" def mockitoVersion = "2.1.0" -def jmhLibVersion = "1.19" +def jmhLibVersion = "1.20" def testNgVersion = "6.11" def guavaVersion = "24.0-jre" def jacocoVersion = "0.8.0" @@ -201,6 +201,7 @@ jmh { jmhVersion = jmhLibVersion humanOutputFile = null includeTests = false + jvmArgsAppend = ["-Djmh.separateClasspathJAR=true"] if (project.hasProperty("jmh")) { include = ".*" + project.jmh + ".*" diff --git a/src/jmh/java/io/reactivex/FlowableFlatMapCompletablePerf.java b/src/jmh/java/io/reactivex/FlowableFlatMapCompletablePerf.java new file mode 100644 index 0000000000..ec846d35eb --- /dev/null +++ b/src/jmh/java/io/reactivex/FlowableFlatMapCompletablePerf.java @@ -0,0 +1,73 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.functions.Action; +import io.reactivex.internal.functions.Functions; +import io.reactivex.schedulers.Schedulers; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableFlatMapCompletablePerf implements Action { + + @Param({"1", "10", "100", "1000", "10000", "100000", "1000000"}) + int items; + + @Param({"1", "8", "32", "128", "256"}) + int maxConcurrency; + + @Param({"1", "10", "100", "1000"}) + int work; + + Completable flatMapCompletable; + + Flowable flatMap; + + @Override + public void run() throws Exception { + Blackhole.consumeCPU(work); + } + + @Setup + public void setup() { + Integer[] array = new Integer[items]; + Arrays.fill(array, 777); + + flatMapCompletable = Flowable.fromArray(array) + .flatMapCompletable(Functions.justFunction(Completable.fromAction(this).subscribeOn(Schedulers.computation())), false, maxConcurrency); + + flatMap = Flowable.fromArray(array) + .flatMap(Functions.justFunction(Completable.fromAction(this).subscribeOn(Schedulers.computation()).toFlowable()), false, maxConcurrency); + } + +// @Benchmark + public Object flatMap(Blackhole bh) { + return flatMap.subscribeWith(new PerfAsyncConsumer(bh)).await(items); + } + + @Benchmark + public Object flatMapCompletable(Blackhole bh) { + return flatMapCompletable.subscribeWith(new PerfAsyncConsumer(bh)).await(items); + } +} diff --git a/src/jmh/java/io/reactivex/FlowableFlatMapCompletableSyncPerf.java b/src/jmh/java/io/reactivex/FlowableFlatMapCompletableSyncPerf.java new file mode 100644 index 0000000000..047bad30a3 --- /dev/null +++ b/src/jmh/java/io/reactivex/FlowableFlatMapCompletableSyncPerf.java @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.internal.functions.Functions; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableFlatMapCompletableSyncPerf { + + @Param({"1", "10", "100", "1000", "10000", "100000", "1000000"}) + int items; + + @Param({"1", "8", "32", "128", "256"}) + int maxConcurrency; + + Completable flatMapCompletable; + + Flowable flatMap; + + @Setup + public void setup() { + Integer[] array = new Integer[items]; + Arrays.fill(array, 777); + + flatMapCompletable = Flowable.fromArray(array) + .flatMapCompletable(Functions.justFunction(Completable.complete()), false, maxConcurrency); + + flatMap = Flowable.fromArray(array) + .flatMap(Functions.justFunction(Completable.complete().toFlowable()), false, maxConcurrency); + } + + @Benchmark + public Object flatMap(Blackhole bh) { + return flatMap.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flatMapCompletable(Blackhole bh) { + return flatMapCompletable.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/PerfAsyncConsumer.java b/src/jmh/java/io/reactivex/PerfAsyncConsumer.java index 8db609b4b5..0b99202afc 100644 --- a/src/jmh/java/io/reactivex/PerfAsyncConsumer.java +++ b/src/jmh/java/io/reactivex/PerfAsyncConsumer.java @@ -68,8 +68,9 @@ public void onComplete() { /** * Wait for the terminal signal. * @param count if less than 1001, a spin-wait is used + * @return this */ - public void await(int count) { + public PerfAsyncConsumer await(int count) { if (count <= 1000) { while (getCount() != 0) { } } else { @@ -79,6 +80,7 @@ public void await(int count) { throw new RuntimeException(ex); } } + return this; } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java index c91e7b8ef9..d132f56f7b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java @@ -25,6 +25,7 @@ import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; +import io.reactivex.internal.functions.Functions; import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; import io.reactivex.processors.PublishProcessor; @@ -523,4 +524,21 @@ public CompletableSource apply(Integer v) throws Exception { .test() .assertFailure(TestException.class); } + + @Test + public void asyncMaxConcurrency() { + for (int itemCount = 1; itemCount <= 100000; itemCount *= 10) { + for (int concurrency = 1; concurrency <= 256; concurrency *= 2) { + Flowable.range(1, itemCount) + .flatMapCompletable( + Functions.justFunction(Completable.complete() + .subscribeOn(Schedulers.computation())) + , false, concurrency) + .test() + .withTag("itemCount=" + itemCount + ", concurrency=" + concurrency) + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(); + } + } + } } From 7646371a4960be54f015467a628dca6010026773 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 9 Mar 2018 10:29:56 +0100 Subject: [PATCH 132/417] 2.x: Coverage improvements, logical fixes and cleanups 03/08 (#5905) --- .../operators/flowable/FlowableCache.java | 59 ++++---- .../flowable/FlowableFlattenIterable.java | 6 +- .../operators/flowable/FlowableReplay.java | 3 +- .../observable/ObservablePublish.java | 10 +- .../operators/flowable/FlowableCacheTest.java | 120 +++++++++++++++ .../flowable/FlowableFlattenIterableTest.java | 142 +++++++++++++++++- .../flowable/FlowableReplayTest.java | 36 +++++ .../observable/ObservableObserveOnTest.java | 26 +++- .../observable/ObservablePublishTest.java | 19 +++ .../observers/SerializedObserverTest.java | 16 ++ .../subjects/SerializedSubjectTest.java | 16 ++ 11 files changed, 411 insertions(+), 42 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java index 24cad0d2f7..ad4de6050f 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java @@ -50,16 +50,24 @@ public FlowableCache(Flowable source, int capacityHint) { protected void subscribeActual(Subscriber t) { // we can connect first because we replay everything anyway ReplaySubscription rp = new ReplaySubscription(t, state); - state.addChild(rp); - t.onSubscribe(rp); + boolean doReplay = true; + if (state.addChild(rp)) { + if (rp.requested.get() == ReplaySubscription.CANCELLED) { + state.removeChild(rp); + doReplay = false; + } + } + // we ensure a single connection here to save an instance field of AtomicBoolean in state. if (!once.get() && once.compareAndSet(false, true)) { state.connect(); } - // no need to call rp.replay() here because the very first request will trigger it anyway + if (doReplay) { + rp.replay(); + } } /** @@ -122,14 +130,15 @@ static final class CacheState extends LinkedArrayList implements FlowableSubs /** * Adds a ReplaySubscription to the subscribers array atomically. * @param p the target ReplaySubscription wrapping a downstream Subscriber with state + * @return true if the ReplaySubscription was added or false if the cache is already terminated */ - public void addChild(ReplaySubscription p) { + public boolean addChild(ReplaySubscription p) { // guarding by connection to save on allocating another object // thus there are two distinct locks guarding the value-addition and child come-and-go for (;;) { ReplaySubscription[] a = subscribers.get(); if (a == TERMINATED) { - return; + return false; } int n = a.length; @SuppressWarnings("unchecked") @@ -137,7 +146,7 @@ public void addChild(ReplaySubscription p) { System.arraycopy(a, 0, b, 0, n); b[n] = p; if (subscribers.compareAndSet(a, b)) { - return; + return true; } } } @@ -240,12 +249,16 @@ static final class ReplaySubscription extends AtomicInteger implements Subscription { private static final long serialVersionUID = -2557562030197141021L; - private static final long CANCELLED = -1; + private static final long CANCELLED = Long.MIN_VALUE; /** The actual child subscriber. */ final Subscriber child; /** The cache state object. */ final CacheState state; + /** + * Number of items requested and also the cancelled indicator if + * it contains {@link #CANCELLED}. + */ final AtomicLong requested; /** @@ -263,6 +276,9 @@ static final class ReplaySubscription */ int index; + /** Number of items emitted so far. */ + long emitted; + ReplaySubscription(Subscriber child, CacheState state) { this.child = child; this.state = state; @@ -271,17 +287,8 @@ static final class ReplaySubscription @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { - for (;;) { - long r = requested.get(); - if (r == CANCELLED) { - return; - } - long u = BackpressureHelper.addCap(r, n); - if (requested.compareAndSet(r, u)) { - replay(); - return; - } - } + BackpressureHelper.addCancel(requested, n); + replay(); } } @@ -303,12 +310,13 @@ public void replay() { int missed = 1; final Subscriber child = this.child; AtomicLong rq = requested; + long e = emitted; for (;;) { long r = rq.get(); - if (r < 0L) { + if (r == CANCELLED) { return; } @@ -326,9 +334,8 @@ public void replay() { final int n = b.length - 1; int j = index; int k = currentIndexInBuffer; - int valuesProduced = 0; - while (j < s && r > 0) { + while (j < s && e != r) { if (rq.get() == CANCELLED) { return; } @@ -344,15 +351,14 @@ public void replay() { k++; j++; - r--; - valuesProduced++; + e++; } if (rq.get() == CANCELLED) { return; } - if (r == 0) { + if (r == e) { Object o = b[k]; if (NotificationLite.isComplete(o)) { child.onComplete(); @@ -364,15 +370,12 @@ public void replay() { } } - if (valuesProduced != 0) { - BackpressureHelper.producedCancel(rq, valuesProduced); - } - index = j; currentIndexInBuffer = k; currentBuffer = b; } + emitted = e; missed = addAndGet(-missed); if (missed == 0) { break; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java index 48a9d75333..12b1095fa8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java @@ -411,11 +411,7 @@ public void clear() { @Override public boolean isEmpty() { - Iterator it = current; - if (it == null) { - return queue.isEmpty(); - } - return !it.hasNext(); + return current == null && queue.isEmpty(); } @Nullable diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java index 7574a93d4b..f32b58dfbc 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java @@ -1215,7 +1215,8 @@ public void subscribe(Subscriber child) { buf = bufferFactory.call(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - throw ExceptionHelper.wrapOrThrow(ex); + EmptySubscription.error(ex, child); + return; } // create a new subscriber to source ReplaySubscriber u = new ReplaySubscriber(buf); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java index b8c5206c2b..d5fa94eb76 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java @@ -148,13 +148,11 @@ static final class PublishObserver @SuppressWarnings("unchecked") @Override public void dispose() { - if (observers.get() != TERMINATED) { - InnerDisposable[] ps = observers.getAndSet(TERMINATED); - if (ps != TERMINATED) { - current.compareAndSet(PublishObserver.this, null); + InnerDisposable[] ps = observers.getAndSet(TERMINATED); + if (ps != TERMINATED) { + current.compareAndSet(PublishObserver.this, null); - DisposableHelper.dispose(s); - } + DisposableHelper.dispose(s); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java index 7cec7d4c33..50b9d69d05 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java @@ -419,4 +419,124 @@ public void error() { .test(0L) .assertFailure(TestException.class); } + + @Test + public void cancelledUpFrontConnectAnyway() { + final AtomicInteger call = new AtomicInteger(); + Flowable.fromCallable(new Callable() { + @Override + public Object call() throws Exception { + return call.incrementAndGet(); + } + }) + .cache() + .test(1L, true) + .assertNoValues(); + + assertEquals(1, call.get()); + } + + @Test + public void cancelledUpFront() { + final AtomicInteger call = new AtomicInteger(); + Flowable f = Flowable.fromCallable(new Callable() { + @Override + public Object call() throws Exception { + return call.incrementAndGet(); + } + }).concatWith(Flowable.never()) + .cache(); + + f.test().assertValuesOnly(1); + + f.test(1L, true) + .assertEmpty(); + + assertEquals(1, call.get()); + } + + @Test + public void subscribeSubscribeRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final Flowable cache = Flowable.range(1, 500).cache(); + + final TestSubscriber to1 = new TestSubscriber(); + final TestSubscriber to2 = new TestSubscriber(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + cache.subscribe(to1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cache.subscribe(to2); + } + }; + + TestHelper.race(r1, r2); + + to1 + .awaitDone(5, TimeUnit.SECONDS) + .assertSubscribed() + .assertValueCount(500) + .assertComplete() + .assertNoErrors(); + + to2 + .awaitDone(5, TimeUnit.SECONDS) + .assertSubscribed() + .assertValueCount(500) + .assertComplete() + .assertNoErrors(); + } + } + + @Test + public void subscribeCompleteRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final PublishProcessor ps = PublishProcessor.create(); + + final Flowable cache = ps.cache(); + + cache.test(); + + final TestSubscriber to = new TestSubscriber(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + cache.subscribe(to); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ps.onComplete(); + } + }; + + TestHelper.race(r1, r2); + + to + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(); + } + } + + @Test + public void backpressure() { + Flowable.range(1, 5) + .cache() + .test(0) + .assertEmpty() + .requestMore(2) + .assertValuesOnly(1, 2) + .requestMore(3) + .assertResult(1, 2, 3, 4, 5); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java index ebfe899488..b4cb5b5f5f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java @@ -17,7 +17,7 @@ import java.util.*; import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.*; import org.junit.*; import org.reactivestreams.*; @@ -27,8 +27,10 @@ import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.operators.flowable.FlowableFlattenIterable.FlattenIterableSubscriber; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.internal.util.ExceptionHelper; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.subscribers.*; @@ -957,4 +959,142 @@ public void remove() { assertEquals(1, counter.get()); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) + throws Exception { + return f.flatMapIterable(Functions.justFunction(Collections.emptyList())); + } + }); + } + + @Test + public void upstreamFusionRejected() { + TestSubscriber ts = new TestSubscriber(); + FlattenIterableSubscriber f = new FlattenIterableSubscriber(ts, + Functions.justFunction(Collections.emptyList()), 128); + + final AtomicLong requested = new AtomicLong(); + + f.onSubscribe(new QueueSubscription() { + + @Override + public int requestFusion(int mode) { + return 0; + } + + @Override + public boolean offer(Integer value) { + return false; + } + + @Override + public boolean offer(Integer v1, Integer v2) { + return false; + } + + @Override + public Integer poll() throws Exception { + return null; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public void clear() { + } + + @Override + public void request(long n) { + requested.set(n); + } + + @Override + public void cancel() { + } + }); + + assertEquals(128, requested.get()); + assertNotNull(f.queue); + + ts.assertEmpty(); + } + + @Test + public void onErrorLate() { + List errors = TestHelper.trackPluginErrors(); + try { + TestSubscriber ts = new TestSubscriber(); + FlattenIterableSubscriber f = new FlattenIterableSubscriber(ts, + Functions.justFunction(Collections.emptyList()), 128); + + f.onSubscribe(new BooleanSubscription()); + + f.onError(new TestException("first")); + + ts.assertFailureAndMessage(TestException.class, "first"); + + assertTrue(errors.isEmpty()); + + f.done = false; + f.onError(new TestException("second")); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void badRequest() { + TestHelper.assertBadRequestReported(Flowable.never().flatMapIterable(Functions.justFunction(Collections.emptyList()))); + } + + @Test + public void fusedCurrentIteratorEmpty() throws Exception { + TestSubscriber ts = new TestSubscriber(0); + FlattenIterableSubscriber f = new FlattenIterableSubscriber(ts, + Functions.justFunction(Arrays.asList(1, 2)), 128); + + f.onSubscribe(new BooleanSubscription()); + + f.onNext(1); + + assertFalse(f.isEmpty()); + + assertEquals(1, f.poll().intValue()); + + assertFalse(f.isEmpty()); + + assertEquals(2, f.poll().intValue()); + + assertTrue(f.isEmpty()); + } + + @Test + public void fusionRequestedState() throws Exception { + TestSubscriber ts = new TestSubscriber(0); + FlattenIterableSubscriber f = new FlattenIterableSubscriber(ts, + Functions.justFunction(Arrays.asList(1, 2)), 128); + + f.onSubscribe(new BooleanSubscription()); + + f.fusionMode = QueueSubscription.NONE; + + assertEquals(QueueSubscription.NONE, f.requestFusion(QueueSubscription.SYNC)); + + assertEquals(QueueSubscription.NONE, f.requestFusion(QueueSubscription.ASYNC)); + + f.fusionMode = QueueSubscription.SYNC; + + assertEquals(QueueSubscription.SYNC, f.requestFusion(QueueSubscription.SYNC)); + + assertEquals(QueueSubscription.NONE, f.requestFusion(QueueSubscription.ASYNC)); +} } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index d081ea1099..72a65fe1d3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -1943,4 +1943,40 @@ public void noHeadRetentionTime() { assertSame(o, buf.get()); } + + @Test(expected = TestException.class) + public void createBufferFactoryCrash() { + FlowableReplay.create(Flowable.just(1), new Callable>() { + @Override + public ReplayBuffer call() throws Exception { + throw new TestException(); + } + }) + .connect(); + } + + @Test + public void createBufferFactoryCrashOnSubscribe() { + FlowableReplay.create(Flowable.just(1), new Callable>() { + @Override + public ReplayBuffer call() throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void currentDisposedWhenConnecting() { + FlowableReplay fr = (FlowableReplay)FlowableReplay.create(Flowable.never(), 16); + fr.connect(); + + fr.current.get().dispose(); + assertTrue(fr.current.get().isDisposed()); + + fr.connect(); + + assertFalse(fr.current.get().isDisposed()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java index 21460f2b21..8b0dedc22b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java @@ -21,13 +21,13 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; -import io.reactivex.annotations.Nullable; import org.junit.Test; import org.mockito.InOrder; import io.reactivex.*; import io.reactivex.Observable; import io.reactivex.Observer; +import io.reactivex.annotations.Nullable; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; @@ -719,4 +719,28 @@ public void clear() { .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } + + @Test + public void outputFusedOneSignal() { + final BehaviorSubject bs = BehaviorSubject.createDefault(1); + + bs.observeOn(ImmediateThinScheduler.INSTANCE) + .concatMap(new Function>() { + @Override + public ObservableSource apply(Integer v) + throws Exception { + return Observable.just(v + 1); + } + }) + .subscribeWith(new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 2) { + bs.onNext(2); + } + } + }) + .assertValuesOnly(2, 3); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java index 9005371fe2..90a78db347 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java @@ -738,4 +738,23 @@ public ObservableSource apply(Observable v) } ); } + + @Test + public void disposedUpfront() { + ConnectableObservable co = Observable.just(1) + .concatWith(Observable.never()) + .publish(); + + TestObserver to1 = co.test(); + + TestObserver to2 = co.test(true); + + co.connect(); + + to1.assertValuesOnly(1); + + to2.assertEmpty(); + + ((ObservablePublish)co).current.get().remove(null); + } } diff --git a/src/test/java/io/reactivex/observers/SerializedObserverTest.java b/src/test/java/io/reactivex/observers/SerializedObserverTest.java index 0fb3526df9..ee50af3730 100644 --- a/src/test/java/io/reactivex/observers/SerializedObserverTest.java +++ b/src/test/java/io/reactivex/observers/SerializedObserverTest.java @@ -1227,4 +1227,20 @@ public void run() { } } + + @Test + public void nullOnNext() { + + TestObserver ts = new TestObserver(); + + final SerializedObserver so = new SerializedObserver(ts); + + Disposable d = Disposables.empty(); + + so.onSubscribe(d); + + so.onNext(null); + + ts.assertFailureAndMessage(NullPointerException.class, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); + } } diff --git a/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java b/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java index 523e375ea0..b3d22d83c5 100644 --- a/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java @@ -23,8 +23,10 @@ import io.reactivex.TestHelper; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; +import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subscribers.*; public class SerializedSubjectTest { @@ -672,4 +674,18 @@ public void run() { ts.assertEmpty(); } } + + @Test + public void nullOnNext() { + + TestSubscriber ts = new TestSubscriber(); + + final SerializedSubscriber so = new SerializedSubscriber(ts); + + so.onSubscribe(new BooleanSubscription()); + + so.onNext(null); + + ts.assertFailureAndMessage(NullPointerException.class, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); + } } From 5f4daa9e6894c7aa8be3ed144dc95ad25bd5c962 Mon Sep 17 00:00:00 2001 From: Niklas Baudy Date: Fri, 9 Mar 2018 14:22:53 +0100 Subject: [PATCH 133/417] 2.x: Add public constructor for TestScheduler that takes the time. (#5906) * 2.x: Add public constructor for TestScheduler that takes the time. * Wording. --- .../reactivex/schedulers/TestScheduler.java | 19 +++++++++++++++++++ .../schedulers/TestSchedulerTest.java | 7 ++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/schedulers/TestScheduler.java b/src/main/java/io/reactivex/schedulers/TestScheduler.java index b2ca366978..44272ffc25 100644 --- a/src/main/java/io/reactivex/schedulers/TestScheduler.java +++ b/src/main/java/io/reactivex/schedulers/TestScheduler.java @@ -35,6 +35,25 @@ public final class TestScheduler extends Scheduler { // Storing time in nanoseconds internally. volatile long time; + /** + * Creates a new TestScheduler with initial virtual time of zero. + */ + public TestScheduler() { + // No-op. + } + + /** + * Creates a new TestScheduler with the specified initial virtual time. + * + * @param delayTime + * the point in time to move the Scheduler's clock to + * @param unit + * the units of time that {@code delayTime} is expressed in + */ + public TestScheduler(long delayTime, TimeUnit unit) { + time = unit.toNanos(delayTime); + } + static final class TimedRunnable implements Comparable { final long time; diff --git a/src/test/java/io/reactivex/schedulers/TestSchedulerTest.java b/src/test/java/io/reactivex/schedulers/TestSchedulerTest.java index 803bd50522..2d5484cbb3 100644 --- a/src/test/java/io/reactivex/schedulers/TestSchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/TestSchedulerTest.java @@ -253,5 +253,10 @@ public void workerDisposed() { assertTrue(w.isDisposed()); } - + @Test + public void constructorTimeSetsTime() { + TestScheduler ts = new TestScheduler(5, TimeUnit.SECONDS); + assertEquals(5, ts.now(TimeUnit.SECONDS)); + assertEquals(5000, ts.now(TimeUnit.MILLISECONDS)); + } } From ab520503925bc9cdff47d6a4ceaf8b2209b61250 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 9 Mar 2018 14:56:08 +0100 Subject: [PATCH 134/417] 2.x: Cleanup test local variable names (#5907) * 2.x: Cleanup test local variable names * Check for Observable c --- src/main/java/io/reactivex/Completable.java | 14 +- src/main/java/io/reactivex/Maybe.java | 14 +- src/main/java/io/reactivex/Observable.java | 14 +- src/main/java/io/reactivex/Single.java | 14 +- .../operators/flowable/FlowableReplay.java | 24 +- .../io/reactivex/observers/TestObserver.java | 10 +- .../reactivex/CheckLocalVariablesInTests.java | 191 ++++++ src/test/java/io/reactivex/TestHelper.java | 72 +- src/test/java/io/reactivex/XFlatMapTest.java | 112 ++-- .../completable/CompletableTest.java | 188 +++--- .../flowable/FlowableFuseableTest.java | 28 +- .../flowable/FlowableSubscriberTest.java | 12 +- .../disposables/EmptyDisposableTest.java | 7 +- .../observers/DeferredScalarObserverTest.java | 33 +- .../completable/CompletableCacheTest.java | 84 +-- .../completable/CompletableConcatTest.java | 14 +- .../CompletableSubscribeOnTest.java | 4 +- .../completable/CompletableTimerTest.java | 4 +- .../operators/flowable/FlowableAllTest.java | 34 +- .../operators/flowable/FlowableAmbTest.java | 64 +- .../operators/flowable/FlowableAnyTest.java | 34 +- .../flowable/FlowableAutoConnectTest.java | 6 +- .../flowable/FlowableBlockingTest.java | 24 +- .../flowable/FlowableBufferTest.java | 94 +-- .../operators/flowable/FlowableCacheTest.java | 48 +- .../operators/flowable/FlowableCastTest.java | 10 +- .../flowable/FlowableCombineLatestTest.java | 26 +- .../flowable/FlowableConcatMapEagerTest.java | 46 +- .../flowable/FlowableCreateTest.java | 4 +- .../flowable/FlowableDebounceTest.java | 18 +- .../operators/flowable/FlowableDelayTest.java | 26 +- .../flowable/FlowableDistinctTest.java | 12 +- .../FlowableDistinctUntilChangedTest.java | 32 +- .../flowable/FlowableDoAfterNextTest.java | 26 +- .../flowable/FlowableDoFinallyTest.java | 46 +- .../flowable/FlowableDoOnEachTest.java | 64 +- .../flowable/FlowableFilterTest.java | 60 +- .../FlowableFlatMapCompletableTest.java | 64 +- .../flowable/FlowableFlatMapMaybeTest.java | 118 ++-- .../flowable/FlowableFlatMapSingleTest.java | 84 +-- .../flowable/FlowableFlatMapTest.java | 54 +- .../flowable/FlowableFlattenIterableTest.java | 46 +- .../flowable/FlowableFromIterableTest.java | 26 +- .../flowable/FlowableGroupByTest.java | 56 +- .../flowable/FlowableGroupJoinTest.java | 56 +- .../flowable/FlowableIgnoreElementsTest.java | 30 +- .../operators/flowable/FlowableJoinTest.java | 22 +- .../flowable/FlowableMapNotificationTest.java | 12 +- .../operators/flowable/FlowableMapTest.java | 44 +- .../flowable/FlowableMergeDelayErrorTest.java | 44 +- .../operators/flowable/FlowableMergeTest.java | 30 +- .../flowable/FlowableObserveOnTest.java | 78 +-- .../FlowableOnBackpressureBufferTest.java | 14 +- ...wableOnErrorResumeNextViaFlowableTest.java | 10 +- ...wableOnErrorResumeNextViaFunctionTest.java | 10 +- .../flowable/FlowableOnErrorReturnTest.java | 10 +- ...eOnExceptionResumeNextViaFlowableTest.java | 10 +- .../flowable/FlowablePublishFunctionTest.java | 56 +- .../flowable/FlowablePublishTest.java | 154 ++--- .../flowable/FlowableRangeLongTest.java | 14 +- .../operators/flowable/FlowableRangeTest.java | 20 +- .../flowable/FlowableRefCountTest.java | 10 +- .../flowable/FlowableReplayTest.java | 182 ++--- .../FlowableRetryWithPredicateTest.java | 28 +- .../flowable/FlowableScalarXMapTest.java | 14 +- .../flowable/FlowableSequenceEqualTest.java | 24 +- .../flowable/FlowableSkipLastTimedTest.java | 8 +- .../flowable/FlowableSwitchTest.java | 86 +-- .../flowable/FlowableTakeLastTimedTest.java | 22 +- .../flowable/FlowableTimeoutTests.java | 24 +- .../FlowableTimeoutWithSelectorTest.java | 20 +- .../flowable/FlowableToListTest.java | 38 +- .../flowable/FlowableToSortedListTest.java | 34 +- .../operators/flowable/FlowableUsingTest.java | 8 +- .../FlowableWindowWithFlowableTest.java | 76 +-- ...lowableWindowWithStartEndFlowableTest.java | 18 +- .../flowable/FlowableWindowWithTimeTest.java | 28 +- .../flowable/FlowableWithLatestFromTest.java | 76 +-- .../operators/maybe/MaybeCacheTest.java | 26 +- .../maybe/MaybeConcatIterableTest.java | 4 +- .../operators/maybe/MaybeContainsTest.java | 4 +- .../operators/maybe/MaybeCountTest.java | 4 +- .../operators/maybe/MaybeDelayOtherTest.java | 56 +- .../maybe/MaybeDelaySubscriptionTest.java | 14 +- .../operators/maybe/MaybeDelayTest.java | 10 +- .../maybe/MaybeDoAfterSuccessTest.java | 14 +- .../MaybeFlatMapIterableFlowableTest.java | 20 +- .../MaybeFlatMapIterableObservableTest.java | 15 +- .../operators/maybe/MaybeMergeArrayTest.java | 16 +- .../operators/maybe/MaybeOfTypeTest.java | 16 +- .../maybe/MaybeSwitchIfEmptySingleTest.java | 8 +- .../maybe/MaybeSwitchIfEmptyTest.java | 8 +- .../operators/maybe/MaybeTimerTest.java | 4 +- .../mixed/ObservableConcatMapMaybeTest.java | 34 +- .../mixed/ObservableConcatMapSingleTest.java | 30 +- .../mixed/ObservableSwitchMapMaybeTest.java | 86 +-- .../mixed/ObservableSwitchMapSingleTest.java | 86 +-- .../observable/ObservableAllTest.java | 24 +- .../observable/ObservableAmbTest.java | 12 +- .../observable/ObservableAnyTest.java | 24 +- .../observable/ObservableBufferTest.java | 52 +- .../observable/ObservableCacheTest.java | 102 +-- .../ObservableCombineLatestTest.java | 10 +- .../ObservableConcatMapEagerTest.java | 260 ++++---- .../observable/ObservableConcatTest.java | 38 +- .../ObservableConcatWithCompletableTest.java | 34 +- .../ObservableConcatWithMaybeTest.java | 40 +- .../ObservableConcatWithSingleTest.java | 28 +- .../ObservableDelaySubscriptionOtherTest.java | 80 +-- .../observable/ObservableDelayTest.java | 104 +-- .../ObservableDematerializeTest.java | 6 +- .../observable/ObservableDetachTest.java | 72 +- .../observable/ObservableDistinctTest.java | 10 +- .../ObservableDistinctUntilChangedTest.java | 42 +- .../observable/ObservableDoAfterNextTest.java | 58 +- .../observable/ObservableDoFinallyTest.java | 66 +- .../observable/ObservableDoOnEachTest.java | 74 +-- .../observable/ObservableFilterTest.java | 14 +- .../ObservableFlatMapCompletableTest.java | 10 +- .../observable/ObservableFlatMapTest.java | 112 ++-- .../ObservableFromIterableTest.java | 26 +- .../observable/ObservableFromTest.java | 4 +- .../observable/ObservableGroupByTest.java | 82 +-- .../ObservableIgnoreElementsTest.java | 56 +- .../observable/ObservableIntervalTest.java | 8 +- .../ObservableMapNotificationTest.java | 16 +- .../observable/ObservableMapTest.java | 17 +- .../observable/ObservableMaterializeTest.java | 10 +- .../ObservableMergeDelayErrorTest.java | 20 +- .../ObservableMergeMaxConcurrentTest.java | 50 +- .../observable/ObservableMergeTest.java | 250 +++---- .../observable/ObservableObserveOnTest.java | 50 +- ...vableOnErrorResumeNextViaFunctionTest.java | 34 +- ...bleOnErrorResumeNextViaObservableTest.java | 14 +- .../ObservableOnErrorReturnTest.java | 14 +- ...nExceptionResumeNextViaObservableTest.java | 8 +- .../observable/ObservablePublishTest.java | 102 +-- .../observable/ObservableRangeLongTest.java | 28 +- .../observable/ObservableRangeTest.java | 25 +- .../observable/ObservableRefCountTest.java | 40 +- .../observable/ObservableRepeatTest.java | 20 +- .../observable/ObservableReplayTest.java | 102 +-- .../observable/ObservableRetryTest.java | 38 +- .../ObservableRetryWithPredicateTest.java | 8 +- .../observable/ObservableSampleTest.java | 30 +- .../observable/ObservableScalarXMapTest.java | 36 +- .../observable/ObservableScanTest.java | 16 +- .../observable/ObservableSkipLastTest.java | 10 +- .../observable/ObservableSkipTest.java | 12 +- .../observable/ObservableSubscribeOnTest.java | 26 +- .../observable/ObservableSwitchTest.java | 46 +- .../observable/ObservableTakeLastTest.java | 20 +- .../observable/ObservableTakeTest.java | 28 +- .../ObservableTakeUntilPredicateTest.java | 10 +- .../observable/ObservableTakeUntilTest.java | 36 +- .../observable/ObservableTakeWhileTest.java | 18 +- .../observable/ObservableTimeoutTests.java | 102 +-- .../ObservableTimeoutWithSelectorTest.java | 24 +- .../observable/ObservableTimerTest.java | 164 ++--- .../observable/ObservableToFutureTest.java | 38 +- .../ObservableWindowWithObservableTest.java | 62 +- .../ObservableWindowWithSizeTest.java | 50 +- ...vableWindowWithStartEndObservableTest.java | 16 +- .../ObservableWindowWithTimeTest.java | 108 +-- .../ObservableWithLatestFromTest.java | 230 +++---- .../observable/ObservableZipTest.java | 50 +- .../operators/single/SingleAmbTest.java | 16 +- .../operators/single/SingleCacheTest.java | 8 +- .../single/SingleDoAfterSuccessTest.java | 10 +- .../single/SingleDoAfterTerminateTest.java | 10 +- .../SingleFlatMapIterableFlowableTest.java | 20 +- .../SingleFlatMapIterableObservableTest.java | 12 +- .../single/SingleFromPublisherTest.java | 4 +- .../single/SingleSubscribeOnTest.java | 4 +- .../operators/single/SingleTakeUntilTest.java | 66 +- .../operators/single/SingleTimerTest.java | 4 +- .../operators/single/SingleUsingTest.java | 16 +- .../DeferredScalarSubscriberTest.java | 8 +- .../subscribers/LambdaSubscriberTest.java | 16 +- .../DeferredScalarSubscriptionTest.java | 4 +- .../util/HalfSerializerObserverTest.java | 26 +- .../internal/util/QueueDrainHelperTest.java | 48 +- .../java/io/reactivex/maybe/MaybeTest.java | 144 ++-- .../observable/ObservableCovarianceTest.java | 10 +- .../observable/ObservableFuseableTest.java | 26 +- .../observable/ObservableNullTests.java | 10 +- .../observable/ObservableSubscriberTest.java | 6 +- .../reactivex/observable/ObservableTest.java | 28 +- .../reactivex/observers/ObserverFusion.java | 50 +- .../reactivex/observers/SafeObserverTest.java | 46 +- .../observers/SerializedObserverTest.java | 76 +-- .../reactivex/observers/TestObserverTest.java | 622 +++++++++--------- .../parallel/ParallelFromPublisherTest.java | 6 +- .../processors/AsyncProcessorTest.java | 10 +- .../processors/PublishProcessorTest.java | 12 +- .../processors/UnicastProcessorTest.java | 38 +- .../io/reactivex/single/SingleCacheTest.java | 18 +- .../reactivex/subjects/AsyncSubjectTest.java | 102 +-- .../subjects/BehaviorSubjectTest.java | 48 +- .../subjects/PublishSubjectTest.java | 166 ++--- .../ReplaySubjectBoundedConcurrencyTest.java | 10 +- .../ReplaySubjectConcurrencyTest.java | 10 +- .../reactivex/subjects/ReplaySubjectTest.java | 58 +- .../subjects/SerializedSubjectTest.java | 70 +- .../subjects/UnicastSubjectTest.java | 98 +-- .../subscribers/SerializedSubscriberTest.java | 71 +- .../subscribers/SubscriberFusion.java | 22 +- .../subscribers/TestSubscriberTest.java | 40 +- 208 files changed, 4706 insertions(+), 4515 deletions(-) create mode 100644 src/test/java/io/reactivex/CheckLocalVariablesInTests.java diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 134119fa08..f0e57a6a11 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -2286,9 +2286,9 @@ public final Completable unsubscribeOn(final Scheduler scheduler) { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final TestObserver test() { - TestObserver ts = new TestObserver(); - subscribe(ts); - return ts; + TestObserver to = new TestObserver(); + subscribe(to); + return to; } /** @@ -2305,12 +2305,12 @@ public final TestObserver test() { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final TestObserver test(boolean cancelled) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); if (cancelled) { - ts.cancel(); + to.cancel(); } - subscribe(ts); - return ts; + subscribe(to); + return to; } } diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index f3d8cec1a6..cb3b18145d 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -4496,9 +4496,9 @@ public final Maybe zipWith(MaybeSource other, BiFunction< @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final TestObserver test() { - TestObserver ts = new TestObserver(); - subscribe(ts); - return ts; + TestObserver to = new TestObserver(); + subscribe(to); + return to; } /** @@ -4514,13 +4514,13 @@ public final TestObserver test() { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final TestObserver test(boolean cancelled) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); if (cancelled) { - ts.cancel(); + to.cancel(); } - subscribe(ts); - return ts; + subscribe(to); + return to; } } diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 5337cdbb3b..f4a5412a64 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -15079,9 +15079,9 @@ public final Observable zipWith(ObservableSource other, @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final TestObserver test() { // NoPMD - TestObserver ts = new TestObserver(); - subscribe(ts); - return ts; + TestObserver to = new TestObserver(); + subscribe(to); + return to; } /** @@ -15099,11 +15099,11 @@ public final TestObserver test() { // NoPMD @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final TestObserver test(boolean dispose) { // NoPMD - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); if (dispose) { - ts.dispose(); + to.dispose(); } - subscribe(ts); - return ts; + subscribe(to); + return to; } } diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 2ef5a5d63e..d3c1bf6aca 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -3654,9 +3654,9 @@ public final Single zipWith(SingleSource other, BiFunction test() { - TestObserver ts = new TestObserver(); - subscribe(ts); - return ts; + TestObserver to = new TestObserver(); + subscribe(to); + return to; } /** @@ -3673,14 +3673,14 @@ public final TestObserver test() { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final TestObserver test(boolean cancelled) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); if (cancelled) { - ts.cancel(); + to.cancel(); } - subscribe(ts); - return ts; + subscribe(to); + return to; } private static Single toSingle(Flowable source) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java index f32b58dfbc..64853d362b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java @@ -64,13 +64,13 @@ public static Flowable multicastSelector( * Child Subscribers will observe the events of the ConnectableObservable on the * specified scheduler. * @param the value type - * @param co the ConnectableFlowable to wrap + * @param cf the ConnectableFlowable to wrap * @param scheduler the target scheduler * @return the new ConnectableObservable instance */ - public static ConnectableFlowable observeOn(final ConnectableFlowable co, final Scheduler scheduler) { - final Flowable observable = co.observeOn(scheduler); - return RxJavaPlugins.onAssembly(new ConnectableFlowableReplay(co, observable)); + public static ConnectableFlowable observeOn(final ConnectableFlowable cf, final Scheduler scheduler) { + final Flowable observable = cf.observeOn(scheduler); + return RxJavaPlugins.onAssembly(new ConnectableFlowableReplay(cf, observable)); } /** @@ -1100,9 +1100,9 @@ static final class MulticastFlowable extends Flowable { @Override protected void subscribeActual(Subscriber child) { - ConnectableFlowable co; + ConnectableFlowable cf; try { - co = ObjectHelper.requireNonNull(connectableFactory.call(), "The connectableFactory returned null"); + cf = ObjectHelper.requireNonNull(connectableFactory.call(), "The connectableFactory returned null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); EmptySubscription.error(e, child); @@ -1111,7 +1111,7 @@ protected void subscribeActual(Subscriber child) { Publisher observable; try { - observable = ObjectHelper.requireNonNull(selector.apply(co), "The selector returned a null Publisher"); + observable = ObjectHelper.requireNonNull(selector.apply(cf), "The selector returned a null Publisher"); } catch (Throwable e) { Exceptions.throwIfFatal(e); EmptySubscription.error(e, child); @@ -1122,7 +1122,7 @@ protected void subscribeActual(Subscriber child) { observable.subscribe(srw); - co.connect(new DisposableConsumer(srw)); + cf.connect(new DisposableConsumer(srw)); } final class DisposableConsumer implements Consumer { @@ -1140,17 +1140,17 @@ public void accept(Disposable r) { } static final class ConnectableFlowableReplay extends ConnectableFlowable { - private final ConnectableFlowable co; + private final ConnectableFlowable cf; private final Flowable observable; - ConnectableFlowableReplay(ConnectableFlowable co, Flowable observable) { - this.co = co; + ConnectableFlowableReplay(ConnectableFlowable cf, Flowable observable) { + this.cf = cf; this.observable = observable; } @Override public void connect(Consumer connection) { - co.connect(connection); + cf.connect(connection); } @Override diff --git a/src/main/java/io/reactivex/observers/TestObserver.java b/src/main/java/io/reactivex/observers/TestObserver.java index 761414de01..18d9b41faf 100644 --- a/src/main/java/io/reactivex/observers/TestObserver.java +++ b/src/main/java/io/reactivex/observers/TestObserver.java @@ -18,8 +18,8 @@ import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import io.reactivex.internal.disposables.DisposableHelper; -import io.reactivex.internal.fuseable.QueueDisposable; -import io.reactivex.internal.util.*; +import io.reactivex.internal.fuseable.*; +import io.reactivex.internal.util.ExceptionHelper; /** * An Observer that records events and allows making assertions about them. @@ -309,9 +309,9 @@ final TestObserver assertFusionMode(int mode) { static String fusionModeToString(int mode) { switch (mode) { - case QueueDisposable.NONE : return "NONE"; - case QueueDisposable.SYNC : return "SYNC"; - case QueueDisposable.ASYNC : return "ASYNC"; + case QueueFuseable.NONE : return "NONE"; + case QueueFuseable.SYNC : return "SYNC"; + case QueueFuseable.ASYNC : return "ASYNC"; default: return "Unknown(" + mode + ")"; } } diff --git a/src/test/java/io/reactivex/CheckLocalVariablesInTests.java b/src/test/java/io/reactivex/CheckLocalVariablesInTests.java new file mode 100644 index 0000000000..9139738b9f --- /dev/null +++ b/src/test/java/io/reactivex/CheckLocalVariablesInTests.java @@ -0,0 +1,191 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import java.io.*; +import java.util.*; +import java.util.regex.Pattern; + +import org.junit.Test; + +/** + * Checks for commonly copy-pasted but not-renamed local variables in unit tests. + *
                  + *
                • {@code TestSubscriber} named as {@code to*}
                • + *
                • {@code TestObserver} named as {@code ts*}
                • + *
                • {@code PublishProcessor} named as {@code ps*}
                • + *
                • {@code PublishSubject} named as {@code pp*}
                • + *
                + */ +public class CheckLocalVariablesInTests { + + static void findPattern(String pattern) throws Exception { + File f = MaybeNo2Dot0Since.findSource("Flowable"); + if (f == null) { + System.out.println("Unable to find sources of RxJava"); + return; + } + + Queue dirs = new ArrayDeque(); + + StringBuilder fail = new StringBuilder(); + fail.append("The following code pattern was found: ").append(pattern).append("\n"); + + File parent = f.getParentFile(); + + dirs.offer(new File(parent.getAbsolutePath().replace('\\', '/').replace("src/main/java", "src/test/java"))); + + Pattern p = Pattern.compile(pattern); + + int total = 0; + + while (!dirs.isEmpty()) { + f = dirs.poll(); + + File[] list = f.listFiles(); + if (list != null && list.length != 0) { + + for (File u : list) { + if (u.isDirectory()) { + dirs.offer(u); + } else { + String fname = u.getName(); + if (fname.endsWith(".java")) { + + int lineNum = 0; + BufferedReader in = new BufferedReader(new FileReader(u)); + try { + for (;;) { + String line = in.readLine(); + if (line != null) { + lineNum++; + + line = line.trim(); + + if (!line.startsWith("//") && !line.startsWith("*")) { + if (p.matcher(line).find()) { + fail + .append(fname) + .append("#L").append(lineNum) + .append(" ").append(line) + .append("\n"); + total++; + } + } + } else { + break; + } + } + } finally { + in.close(); + } + } + } + } + } + } + if (total != 0) { + fail.append("Found ") + .append(total) + .append(" instances"); + System.out.println(fail); + throw new AssertionError(fail.toString()); + } + } + + @Test + public void testSubscriberAsTo() throws Exception { + findPattern("TestSubscriber<.*>\\s+to"); + } + + @Test + public void testObserverAsTs() throws Exception { + findPattern("TestObserver<.*>\\s+ts"); + } + + @Test + public void publishSubjectAsPp() throws Exception { + findPattern("PublishSubject<.*>\\s+pp"); + } + + @Test + public void publishProcessorAsPs() throws Exception { + findPattern("PublishProcessor<.*>\\s+ps"); + } + + @Test + public void behaviorProcessorAsBs() throws Exception { + findPattern("BehaviorProcessor<.*>\\s+bs"); + } + + @Test + public void behaviorSubjectAsBp() throws Exception { + findPattern("BehaviorSubject<.*>\\s+bp"); + } + + @Test + public void connectableFlowableAsCo() throws Exception { + findPattern("ConnectableFlowable<.*>\\s+co(0-9|\\b)"); + } + + @Test + public void connectableObservableAsCf() throws Exception { + findPattern("ConnectableObservable<.*>\\s+cf(0-9|\\b)"); + } + + @Test + public void queueDisposableInsteadOfQueueFuseable() throws Exception { + findPattern("QueueDisposable\\.(NONE|SYNC|ASYNC|ANY|BOUNDARY)"); + } + + @Test + public void queueSubscriptionInsteadOfQueueFuseable() throws Exception { + findPattern("QueueSubscription\\.(NONE|SYNC|ASYNC|ANY|BOUNDARY)"); + } + + @Test + public void singleSourceAsMs() throws Exception { + findPattern("SingleSource<.*>\\s+ms"); + } + + @Test + public void singleSourceAsCs() throws Exception { + findPattern("SingleSource<.*>\\s+cs"); + } + + @Test + public void maybeSourceAsSs() throws Exception { + findPattern("MaybeSource<.*>\\s+ss"); + } + + @Test + public void maybeSourceAsCs() throws Exception { + findPattern("MaybeSource<.*>\\s+cs"); + } + + @Test + public void completableSourceAsSs() throws Exception { + findPattern("CompletableSource<.*>\\s+ss"); + } + + @Test + public void completableSourceAsMs() throws Exception { + findPattern("CompletableSource<.*>\\s+ms"); + } + + @Test + public void observableAsC() throws Exception { + findPattern("Observable<.*>\\s+c\\b"); + } +} diff --git a/src/test/java/io/reactivex/TestHelper.java b/src/test/java/io/reactivex/TestHelper.java index b6660c19d6..2a4ac1ee58 100644 --- a/src/test/java/io/reactivex/TestHelper.java +++ b/src/test/java/io/reactivex/TestHelper.java @@ -217,8 +217,8 @@ public static void assertUndeliverable(List list, int index, Class ts, int index, Class clazz) { - Throwable ex = ts.errors().get(0); + public static void assertError(TestObserver to, int index, Class clazz) { + Throwable ex = to.errors().get(0); try { if (ex instanceof CompositeException) { CompositeException ce = (CompositeException) ex; @@ -244,8 +244,8 @@ public static void assertError(TestSubscriber ts, int index, Class ts, int index, Class clazz, String message) { - Throwable ex = ts.errors().get(0); + public static void assertError(TestObserver to, int index, Class clazz, String message) { + Throwable ex = to.errors().get(0); if (ex instanceof CompositeException) { CompositeException ce = (CompositeException) ex; List cel = ce.getExceptions(); @@ -514,14 +514,14 @@ public void accept(TestSubscriber ts) throws Exception { public static Consumer> observerSingleNot(final T value) { return new Consumer>() { @Override - public void accept(TestObserver ts) throws Exception { - ts + public void accept(TestObserver to) throws Exception { + to .assertSubscribed() .assertValueCount(1) .assertNoErrors() .assertComplete(); - T v = ts.values().get(0); + T v = to.values().get(0); assertNotEquals(value, v); } }; @@ -2271,16 +2271,16 @@ public static void assertCompositeExceptions(TestSubscriber ts, Object... cla /** * Check if the TestSubscriber has a CompositeException with the specified class * of Throwables in the given order. - * @param ts the TestSubscriber instance + * @param to the TestSubscriber instance * @param classes the array of expected Throwables inside the Composite */ - public static void assertCompositeExceptions(TestObserver ts, Class... classes) { - ts + public static void assertCompositeExceptions(TestObserver to, Class... classes) { + to .assertSubscribed() .assertError(CompositeException.class) .assertNotComplete(); - List list = compositeList(ts.errors().get(0)); + List list = compositeList(to.errors().get(0)); assertEquals(classes.length, list.size()); @@ -2292,18 +2292,18 @@ public static void assertCompositeExceptions(TestObserver ts, Class ts, Object... classes) { - ts + public static void assertCompositeExceptions(TestObserver to, Object... classes) { + to .assertSubscribed() .assertError(CompositeException.class) .assertNotComplete(); - List list = compositeList(ts.errors().get(0)); + List list = compositeList(to.errors().get(0)); assertEquals(classes.length, list.size()); @@ -2357,9 +2357,9 @@ public void onSubscribe(Disposable d) { QueueDisposable qd = (QueueDisposable) d; state[0] = true; - int m = qd.requestFusion(QueueDisposable.ANY); + int m = qd.requestFusion(QueueFuseable.ANY); - if (m != QueueDisposable.NONE) { + if (m != QueueFuseable.NONE) { state[1] = true; state[2] = qd.isEmpty(); @@ -2423,9 +2423,9 @@ public void onSubscribe(Subscription d) { QueueSubscription qd = (QueueSubscription) d; state[0] = true; - int m = qd.requestFusion(QueueSubscription.ANY); + int m = qd.requestFusion(QueueFuseable.ANY); - if (m != QueueSubscription.NONE) { + if (m != QueueFuseable.NONE) { state[1] = true; state[2] = qd.isEmpty(); @@ -2481,11 +2481,11 @@ public static List errorList(TestObserver to) { /** * Returns an expanded error list of the given test consumer. - * @param to the test consumer instance + * @param ts the test consumer instance * @return the list */ - public static List errorList(TestSubscriber to) { - return compositeList(to.errors().get(0)); + public static List errorList(TestSubscriber ts) { + return compositeList(ts.errors().get(0)); } /** @@ -2557,23 +2557,23 @@ protected void subscribeActual(Observer observer) { if (o instanceof Publisher) { Publisher os = (Publisher) o; - TestSubscriber to = new TestSubscriber(); + TestSubscriber ts = new TestSubscriber(); - os.subscribe(to); + os.subscribe(ts); - to.awaitDone(5, TimeUnit.SECONDS); + ts.awaitDone(5, TimeUnit.SECONDS); - to.assertSubscribed(); + ts.assertSubscribed(); if (expected != null) { - to.assertValues(expected); + ts.assertValues(expected); } if (error) { - to.assertError(TestException.class) + ts.assertError(TestException.class) .assertErrorMessage("error") .assertNotComplete(); } else { - to.assertNoErrors().assertComplete(); + ts.assertNoErrors().assertComplete(); } } @@ -2716,23 +2716,23 @@ protected void subscribeActual(Subscriber observer) { if (o instanceof Publisher) { Publisher os = (Publisher) o; - TestSubscriber to = new TestSubscriber(); + TestSubscriber ts = new TestSubscriber(); - os.subscribe(to); + os.subscribe(ts); - to.awaitDone(5, TimeUnit.SECONDS); + ts.awaitDone(5, TimeUnit.SECONDS); - to.assertSubscribed(); + ts.assertSubscribed(); if (expected != null) { - to.assertValues(expected); + ts.assertValues(expected); } if (error) { - to.assertError(TestException.class) + ts.assertError(TestException.class) .assertErrorMessage("error") .assertNotComplete(); } else { - to.assertNoErrors().assertComplete(); + ts.assertNoErrors().assertComplete(); } } diff --git a/src/test/java/io/reactivex/XFlatMapTest.java b/src/test/java/io/reactivex/XFlatMapTest.java index 028814e5ec..8a6ec939c5 100644 --- a/src/test/java/io/reactivex/XFlatMapTest.java +++ b/src/test/java/io/reactivex/XFlatMapTest.java @@ -154,7 +154,7 @@ public Maybe apply(Integer v) throws Exception { public void flowableCompletable() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Flowable.just(1) + TestObserver to = Flowable.just(1) .subscribeOn(Schedulers.io()) .flatMapCompletable(new Function() { @Override @@ -167,13 +167,13 @@ public Completable apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -217,7 +217,7 @@ public Completable apply(Integer v) throws Exception { public void observableFlowable() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Observable.just(1) + TestObserver to = Observable.just(1) .subscribeOn(Schedulers.io()) .flatMap(new Function>() { @Override @@ -230,13 +230,13 @@ public Observable apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -248,7 +248,7 @@ public Observable apply(Integer v) throws Exception { public void observerSingle() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Observable.just(1) + TestObserver to = Observable.just(1) .subscribeOn(Schedulers.io()) .flatMapSingle(new Function>() { @Override @@ -261,13 +261,13 @@ public Single apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -279,7 +279,7 @@ public Single apply(Integer v) throws Exception { public void observerMaybe() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Observable.just(1) + TestObserver to = Observable.just(1) .subscribeOn(Schedulers.io()) .flatMapMaybe(new Function>() { @Override @@ -292,13 +292,13 @@ public Maybe apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -310,7 +310,7 @@ public Maybe apply(Integer v) throws Exception { public void observerCompletable() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Observable.just(1) + TestObserver to = Observable.just(1) .subscribeOn(Schedulers.io()) .flatMapCompletable(new Function() { @Override @@ -323,13 +323,13 @@ public Completable apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -341,7 +341,7 @@ public Completable apply(Integer v) throws Exception { public void observerCompletable2() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Observable.just(1) + TestObserver to = Observable.just(1) .subscribeOn(Schedulers.io()) .flatMapCompletable(new Function() { @Override @@ -355,13 +355,13 @@ public Completable apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -373,7 +373,7 @@ public Completable apply(Integer v) throws Exception { public void singleSingle() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Single.just(1) + TestObserver to = Single.just(1) .subscribeOn(Schedulers.io()) .flatMap(new Function>() { @Override @@ -386,13 +386,13 @@ public Single apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -404,7 +404,7 @@ public Single apply(Integer v) throws Exception { public void singleMaybe() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Single.just(1) + TestObserver to = Single.just(1) .subscribeOn(Schedulers.io()) .flatMapMaybe(new Function>() { @Override @@ -417,13 +417,13 @@ public Maybe apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -435,7 +435,7 @@ public Maybe apply(Integer v) throws Exception { public void singleCompletable() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Single.just(1) + TestObserver to = Single.just(1) .subscribeOn(Schedulers.io()) .flatMapCompletable(new Function() { @Override @@ -448,13 +448,13 @@ public Completable apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -466,7 +466,7 @@ public Completable apply(Integer v) throws Exception { public void singleCompletable2() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Single.just(1) + TestObserver to = Single.just(1) .subscribeOn(Schedulers.io()) .flatMapCompletable(new Function() { @Override @@ -480,13 +480,13 @@ public Completable apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -498,7 +498,7 @@ public Completable apply(Integer v) throws Exception { public void maybeSingle() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Maybe.just(1) + TestObserver to = Maybe.just(1) .subscribeOn(Schedulers.io()) .flatMapSingle(new Function>() { @Override @@ -511,13 +511,13 @@ public Single apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -529,7 +529,7 @@ public Single apply(Integer v) throws Exception { public void maybeMaybe() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Maybe.just(1) + TestObserver to = Maybe.just(1) .subscribeOn(Schedulers.io()) .flatMap(new Function>() { @Override @@ -542,13 +542,13 @@ public Maybe apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -560,7 +560,7 @@ public Maybe apply(Integer v) throws Exception { public void maybeCompletable() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Maybe.just(1) + TestObserver to = Maybe.just(1) .subscribeOn(Schedulers.io()) .flatMapCompletable(new Function() { @Override @@ -573,13 +573,13 @@ public Completable apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { @@ -591,7 +591,7 @@ public Completable apply(Integer v) throws Exception { public void maybeCompletable2() throws Exception { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = Maybe.just(1) + TestObserver to = Maybe.just(1) .subscribeOn(Schedulers.io()) .flatMapCompletable(new Function() { @Override @@ -605,13 +605,13 @@ public Completable apply(Integer v) throws Exception { cb.await(); - beforeCancelSleep(ts); + beforeCancelSleep(to); - ts.cancel(); + to.cancel(); Thread.sleep(SLEEP_AFTER_CANCEL); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(errors.toString(), errors.isEmpty()); } finally { diff --git a/src/test/java/io/reactivex/completable/CompletableTest.java b/src/test/java/io/reactivex/completable/CompletableTest.java index 9b0b914a66..010ba0c619 100644 --- a/src/test/java/io/reactivex/completable/CompletableTest.java +++ b/src/test/java/io/reactivex/completable/CompletableTest.java @@ -2599,24 +2599,24 @@ public void run() { } @Test(timeout = 5000) public void subscribeObserverNormal() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - normal.completable.toObservable().subscribe(ts); + normal.completable.toObservable().subscribe(to); - ts.assertComplete(); - ts.assertNoValues(); - ts.assertNoErrors(); + to.assertComplete(); + to.assertNoValues(); + to.assertNoErrors(); } @Test(timeout = 5000) public void subscribeObserverError() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - error.completable.toObservable().subscribe(ts); + error.completable.toObservable().subscribe(to); - ts.assertNotComplete(); - ts.assertNoValues(); - ts.assertError(TestException.class); + to.assertNotComplete(); + to.assertNoValues(); + to.assertError(TestException.class); } @Test(timeout = 5000) @@ -2978,12 +2978,12 @@ public void ambArraySingleError() { @Test(timeout = 5000) public void ambArrayOneFires() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Completable c1 = Completable.fromPublisher(ps1); + Completable c1 = Completable.fromPublisher(pp1); - Completable c2 = Completable.fromPublisher(ps2); + Completable c2 = Completable.fromPublisher(pp2); Completable c = Completable.ambArray(c1, c2); @@ -2996,25 +2996,25 @@ public void run() { } }); - Assert.assertTrue("First subject no subscribers", ps1.hasSubscribers()); - Assert.assertTrue("Second subject no subscribers", ps2.hasSubscribers()); + Assert.assertTrue("First subject no subscribers", pp1.hasSubscribers()); + Assert.assertTrue("Second subject no subscribers", pp2.hasSubscribers()); - ps1.onComplete(); + pp1.onComplete(); - Assert.assertFalse("First subject has subscribers", ps1.hasSubscribers()); - Assert.assertFalse("Second subject has subscribers", ps2.hasSubscribers()); + Assert.assertFalse("First subject has subscribers", pp1.hasSubscribers()); + Assert.assertFalse("Second subject has subscribers", pp2.hasSubscribers()); Assert.assertTrue("Not completed", complete.get()); } @Test(timeout = 5000) public void ambArrayOneFiresError() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Completable c1 = Completable.fromPublisher(ps1); + Completable c1 = Completable.fromPublisher(pp1); - Completable c2 = Completable.fromPublisher(ps2); + Completable c2 = Completable.fromPublisher(pp2); Completable c = Completable.ambArray(c1, c2); @@ -3027,25 +3027,25 @@ public void accept(Throwable v) { } }); - Assert.assertTrue("First subject no subscribers", ps1.hasSubscribers()); - Assert.assertTrue("Second subject no subscribers", ps2.hasSubscribers()); + Assert.assertTrue("First subject no subscribers", pp1.hasSubscribers()); + Assert.assertTrue("Second subject no subscribers", pp2.hasSubscribers()); - ps1.onError(new TestException()); + pp1.onError(new TestException()); - Assert.assertFalse("First subject has subscribers", ps1.hasSubscribers()); - Assert.assertFalse("Second subject has subscribers", ps2.hasSubscribers()); + Assert.assertFalse("First subject has subscribers", pp1.hasSubscribers()); + Assert.assertFalse("Second subject has subscribers", pp2.hasSubscribers()); Assert.assertTrue("Not completed", complete.get() instanceof TestException); } @Test(timeout = 5000) public void ambArraySecondFires() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Completable c1 = Completable.fromPublisher(ps1); + Completable c1 = Completable.fromPublisher(pp1); - Completable c2 = Completable.fromPublisher(ps2); + Completable c2 = Completable.fromPublisher(pp2); Completable c = Completable.ambArray(c1, c2); @@ -3058,25 +3058,25 @@ public void run() { } }); - Assert.assertTrue("First subject no subscribers", ps1.hasSubscribers()); - Assert.assertTrue("Second subject no subscribers", ps2.hasSubscribers()); + Assert.assertTrue("First subject no subscribers", pp1.hasSubscribers()); + Assert.assertTrue("Second subject no subscribers", pp2.hasSubscribers()); - ps2.onComplete(); + pp2.onComplete(); - Assert.assertFalse("First subject has subscribers", ps1.hasSubscribers()); - Assert.assertFalse("Second subject has subscribers", ps2.hasSubscribers()); + Assert.assertFalse("First subject has subscribers", pp1.hasSubscribers()); + Assert.assertFalse("Second subject has subscribers", pp2.hasSubscribers()); Assert.assertTrue("Not completed", complete.get()); } @Test(timeout = 5000) public void ambArraySecondFiresError() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Completable c1 = Completable.fromPublisher(ps1); + Completable c1 = Completable.fromPublisher(pp1); - Completable c2 = Completable.fromPublisher(ps2); + Completable c2 = Completable.fromPublisher(pp2); Completable c = Completable.ambArray(c1, c2); @@ -3089,13 +3089,13 @@ public void accept(Throwable v) { } }); - Assert.assertTrue("First subject no subscribers", ps1.hasSubscribers()); - Assert.assertTrue("Second subject no subscribers", ps2.hasSubscribers()); + Assert.assertTrue("First subject no subscribers", pp1.hasSubscribers()); + Assert.assertTrue("Second subject no subscribers", pp2.hasSubscribers()); - ps2.onError(new TestException()); + pp2.onError(new TestException()); - Assert.assertFalse("First subject has subscribers", ps1.hasSubscribers()); - Assert.assertFalse("Second subject has subscribers", ps2.hasSubscribers()); + Assert.assertFalse("First subject has subscribers", pp1.hasSubscribers()); + Assert.assertFalse("Second subject has subscribers", pp2.hasSubscribers()); Assert.assertTrue("Not completed", complete.get() instanceof TestException); } @@ -3199,12 +3199,12 @@ public void ambWithNull() { @Test(timeout = 5000) public void ambWithArrayOneFires() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Completable c1 = Completable.fromPublisher(ps1); + Completable c1 = Completable.fromPublisher(pp1); - Completable c2 = Completable.fromPublisher(ps2); + Completable c2 = Completable.fromPublisher(pp2); Completable c = c1.ambWith(c2); @@ -3217,25 +3217,25 @@ public void run() { } }); - Assert.assertTrue("First subject no subscribers", ps1.hasSubscribers()); - Assert.assertTrue("Second subject no subscribers", ps2.hasSubscribers()); + Assert.assertTrue("First subject no subscribers", pp1.hasSubscribers()); + Assert.assertTrue("Second subject no subscribers", pp2.hasSubscribers()); - ps1.onComplete(); + pp1.onComplete(); - Assert.assertFalse("First subject has subscribers", ps1.hasSubscribers()); - Assert.assertFalse("Second subject has subscribers", ps2.hasSubscribers()); + Assert.assertFalse("First subject has subscribers", pp1.hasSubscribers()); + Assert.assertFalse("Second subject has subscribers", pp2.hasSubscribers()); Assert.assertTrue("Not completed", complete.get()); } @Test(timeout = 5000) public void ambWithArrayOneFiresError() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Completable c1 = Completable.fromPublisher(ps1); + Completable c1 = Completable.fromPublisher(pp1); - Completable c2 = Completable.fromPublisher(ps2); + Completable c2 = Completable.fromPublisher(pp2); Completable c = c1.ambWith(c2); @@ -3248,25 +3248,25 @@ public void accept(Throwable v) { } }); - Assert.assertTrue("First subject no subscribers", ps1.hasSubscribers()); - Assert.assertTrue("Second subject no subscribers", ps2.hasSubscribers()); + Assert.assertTrue("First subject no subscribers", pp1.hasSubscribers()); + Assert.assertTrue("Second subject no subscribers", pp2.hasSubscribers()); - ps1.onError(new TestException()); + pp1.onError(new TestException()); - Assert.assertFalse("First subject has subscribers", ps1.hasSubscribers()); - Assert.assertFalse("Second subject has subscribers", ps2.hasSubscribers()); + Assert.assertFalse("First subject has subscribers", pp1.hasSubscribers()); + Assert.assertFalse("Second subject has subscribers", pp2.hasSubscribers()); Assert.assertTrue("Not completed", complete.get() instanceof TestException); } @Test(timeout = 5000) public void ambWithArraySecondFires() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Completable c1 = Completable.fromPublisher(ps1); + Completable c1 = Completable.fromPublisher(pp1); - Completable c2 = Completable.fromPublisher(ps2); + Completable c2 = Completable.fromPublisher(pp2); Completable c = c1.ambWith(c2); @@ -3279,25 +3279,25 @@ public void run() { } }); - Assert.assertTrue("First subject no subscribers", ps1.hasSubscribers()); - Assert.assertTrue("Second subject no subscribers", ps2.hasSubscribers()); + Assert.assertTrue("First subject no subscribers", pp1.hasSubscribers()); + Assert.assertTrue("Second subject no subscribers", pp2.hasSubscribers()); - ps2.onComplete(); + pp2.onComplete(); - Assert.assertFalse("First subject has subscribers", ps1.hasSubscribers()); - Assert.assertFalse("Second subject has subscribers", ps2.hasSubscribers()); + Assert.assertFalse("First subject has subscribers", pp1.hasSubscribers()); + Assert.assertFalse("Second subject has subscribers", pp2.hasSubscribers()); Assert.assertTrue("Not completed", complete.get()); } @Test(timeout = 5000) public void ambWithArraySecondFiresError() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Completable c1 = Completable.fromPublisher(ps1); + Completable c1 = Completable.fromPublisher(pp1); - Completable c2 = Completable.fromPublisher(ps2); + Completable c2 = Completable.fromPublisher(pp2); Completable c = c1.ambWith(c2); @@ -3310,13 +3310,13 @@ public void accept(Throwable v) { } }); - Assert.assertTrue("First subject no subscribers", ps1.hasSubscribers()); - Assert.assertTrue("Second subject no subscribers", ps2.hasSubscribers()); + Assert.assertTrue("First subject no subscribers", pp1.hasSubscribers()); + Assert.assertTrue("Second subject no subscribers", pp2.hasSubscribers()); - ps2.onError(new TestException()); + pp2.onError(new TestException()); - Assert.assertFalse("First subject has subscribers", ps1.hasSubscribers()); - Assert.assertFalse("Second subject has subscribers", ps2.hasSubscribers()); + Assert.assertFalse("First subject has subscribers", pp1.hasSubscribers()); + Assert.assertFalse("Second subject has subscribers", pp2.hasSubscribers()); Assert.assertTrue("Not completed", complete.get() instanceof TestException); } @@ -3395,7 +3395,7 @@ public void startWithFlowableError() { @Test(timeout = 5000) public void startWithObservableNormal() { final AtomicBoolean run = new AtomicBoolean(); - Observable c = normal.completable + Observable o = normal.completable .startWith(Observable.fromCallable(new Callable() { @Override public Object call() throws Exception { @@ -3404,32 +3404,32 @@ public Object call() throws Exception { } })); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - c.subscribe(ts); + o.subscribe(to); Assert.assertTrue("Did not start with other", run.get()); normal.assertSubscriptions(1); - ts.assertValue(1); - ts.assertComplete(); - ts.assertNoErrors(); + to.assertValue(1); + to.assertComplete(); + to.assertNoErrors(); } @Test(timeout = 5000) public void startWithObservableError() { - Observable c = normal.completable + Observable o = normal.completable .startWith(Observable.error(new TestException())); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - c.subscribe(ts); + o.subscribe(to); normal.assertSubscriptions(0); - ts.assertNoValues(); - ts.assertError(TestException.class); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertError(TestException.class); + to.assertNotComplete(); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/io/reactivex/flowable/FlowableFuseableTest.java b/src/test/java/io/reactivex/flowable/FlowableFuseableTest.java index 64e886e614..f9594a6220 100644 --- a/src/test/java/io/reactivex/flowable/FlowableFuseableTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableFuseableTest.java @@ -17,8 +17,8 @@ import org.junit.Test; import io.reactivex.Flowable; -import io.reactivex.internal.fuseable.QueueSubscription; -import io.reactivex.subscribers.*; +import io.reactivex.internal.fuseable.*; +import io.reactivex.subscribers.SubscriberFusion; public class FlowableFuseableTest { @@ -26,8 +26,8 @@ public class FlowableFuseableTest { public void syncRange() { Flowable.range(1, 10) - .to(SubscriberFusion.test(Long.MAX_VALUE, QueueSubscription.ANY, false)) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .to(SubscriberFusion.test(Long.MAX_VALUE, QueueFuseable.ANY, false)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); @@ -37,8 +37,8 @@ public void syncRange() { public void syncArray() { Flowable.fromArray(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) - .to(SubscriberFusion.test(Long.MAX_VALUE, QueueSubscription.ANY, false)) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .to(SubscriberFusion.test(Long.MAX_VALUE, QueueFuseable.ANY, false)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); @@ -48,8 +48,8 @@ public void syncArray() { public void syncIterable() { Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) - .to(SubscriberFusion.test(Long.MAX_VALUE, QueueSubscription.ANY, false)) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .to(SubscriberFusion.test(Long.MAX_VALUE, QueueFuseable.ANY, false)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); @@ -59,9 +59,9 @@ public void syncIterable() { public void syncRangeHidden() { Flowable.range(1, 10).hide() - .to(SubscriberFusion.test(Long.MAX_VALUE, QueueSubscription.ANY, false)) + .to(SubscriberFusion.test(Long.MAX_VALUE, QueueFuseable.ANY, false)) .assertOf(SubscriberFusion.assertNotFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.NONE)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); @@ -71,9 +71,9 @@ public void syncRangeHidden() { public void syncArrayHidden() { Flowable.fromArray(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) .hide() - .to(SubscriberFusion.test(Long.MAX_VALUE, QueueSubscription.ANY, false)) + .to(SubscriberFusion.test(Long.MAX_VALUE, QueueFuseable.ANY, false)) .assertOf(SubscriberFusion.assertNotFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.NONE)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); @@ -83,9 +83,9 @@ public void syncArrayHidden() { public void syncIterableHidden() { Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) .hide() - .to(SubscriberFusion.test(Long.MAX_VALUE, QueueSubscription.ANY, false)) + .to(SubscriberFusion.test(Long.MAX_VALUE, QueueFuseable.ANY, false)) .assertOf(SubscriberFusion.assertNotFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.NONE)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); diff --git a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java index e9e0da5159..c944d63092 100644 --- a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java @@ -749,11 +749,11 @@ public void accept(Throwable e) throws Exception { @Test public void methodTestCancelled() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.test(Long.MAX_VALUE, true); + pp.test(Long.MAX_VALUE, true); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test @@ -767,11 +767,11 @@ public void safeSubscriberAlreadySafe() { @Test public void methodTestNoCancel() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.test(Long.MAX_VALUE, false); + pp.test(Long.MAX_VALUE, false); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); } @Test diff --git a/src/test/java/io/reactivex/internal/disposables/EmptyDisposableTest.java b/src/test/java/io/reactivex/internal/disposables/EmptyDisposableTest.java index 7e25cbcd4f..d373560413 100644 --- a/src/test/java/io/reactivex/internal/disposables/EmptyDisposableTest.java +++ b/src/test/java/io/reactivex/internal/disposables/EmptyDisposableTest.java @@ -14,10 +14,11 @@ package io.reactivex.internal.disposables; import static org.junit.Assert.*; + import org.junit.Test; import io.reactivex.TestHelper; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; public class EmptyDisposableTest { @@ -28,8 +29,8 @@ public void noOffer() { @Test public void asyncFusion() { - assertEquals(QueueDisposable.NONE, EmptyDisposable.INSTANCE.requestFusion(QueueDisposable.SYNC)); - assertEquals(QueueDisposable.ASYNC, EmptyDisposable.INSTANCE.requestFusion(QueueDisposable.ASYNC)); + assertEquals(QueueFuseable.NONE, EmptyDisposable.INSTANCE.requestFusion(QueueFuseable.SYNC)); + assertEquals(QueueFuseable.ASYNC, EmptyDisposable.INSTANCE.requestFusion(QueueFuseable.ASYNC)); } @Test diff --git a/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java b/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java index ff0dc18984..75918d345a 100644 --- a/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java @@ -20,8 +20,7 @@ import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; -import io.reactivex.internal.fuseable.QueueDisposable; -import io.reactivex.internal.observers.DeferredScalarObserver; +import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; public class DeferredScalarObserverTest { @@ -106,7 +105,7 @@ public void dispose() { @Test public void fused() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); TakeFirst source = new TakeFirst(to); @@ -115,7 +114,7 @@ public void fused() { source.onSubscribe(d); to.assertOf(ObserverFusion.assertFuseable()); - to.assertOf(ObserverFusion.assertFusionMode(QueueDisposable.ASYNC)); + to.assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)); source.onNext(1); source.onNext(1); @@ -129,7 +128,7 @@ public void fused() { @Test public void fusedReject() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.SYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC); TakeFirst source = new TakeFirst(to); @@ -138,7 +137,7 @@ public void fusedReject() { source.onSubscribe(d); to.assertOf(ObserverFusion.assertFuseable()); - to.assertOf(ObserverFusion.assertFusionMode(QueueDisposable.NONE)); + to.assertOf(ObserverFusion.assertFusionMode(QueueFuseable.NONE)); source.onNext(1); source.onNext(1); @@ -168,7 +167,7 @@ public void onNext(Integer value) { @Test public void nonfusedTerminateMore() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.NONE); + TestObserver to = ObserverFusion.newTest(QueueFuseable.NONE); TakeLast source = new TakeLast(to); @@ -186,7 +185,7 @@ public void nonfusedTerminateMore() { @Test public void nonfusedError() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.NONE); + TestObserver to = ObserverFusion.newTest(QueueFuseable.NONE); TakeLast source = new TakeLast(to); @@ -204,7 +203,7 @@ public void nonfusedError() { @Test public void fusedTerminateMore() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); TakeLast source = new TakeLast(to); @@ -222,7 +221,7 @@ public void fusedTerminateMore() { @Test public void fusedError() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); TakeLast source = new TakeLast(to); @@ -240,7 +239,7 @@ public void fusedError() { @Test public void disposed() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.NONE); + TestObserver to = ObserverFusion.newTest(QueueFuseable.NONE); TakeLast source = new TakeLast(to); @@ -295,7 +294,7 @@ public void onComplete() { @Test public void fusedEmpty() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); TakeLast source = new TakeLast(to); @@ -310,7 +309,7 @@ public void fusedEmpty() { @Test public void nonfusedEmpty() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.NONE); + TestObserver to = ObserverFusion.newTest(QueueFuseable.NONE); TakeLast source = new TakeLast(to); @@ -335,7 +334,7 @@ public void customFusion() { public void onSubscribe(Disposable d) { this.d = (QueueDisposable)d; to.onSubscribe(d); - this.d.requestFusion(QueueDisposable.ANY); + this.d.requestFusion(QueueFuseable.ANY); } @Override @@ -385,7 +384,7 @@ public void customFusionClear() { public void onSubscribe(Disposable d) { this.d = (QueueDisposable)d; to.onSubscribe(d); - this.d.requestFusion(QueueDisposable.ANY); + this.d.requestFusion(QueueFuseable.ANY); } @Override @@ -414,7 +413,7 @@ public void onComplete() { @Test public void offerThrow() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.NONE); + TestObserver to = ObserverFusion.newTest(QueueFuseable.NONE); TakeLast source = new TakeLast(to); @@ -433,7 +432,7 @@ public void customFusionDontConsume() { public void onSubscribe(Disposable d) { this.d = (QueueDisposable)d; to.onSubscribe(d); - this.d.requestFusion(QueueDisposable.ANY); + this.d.requestFusion(QueueFuseable.ANY); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableCacheTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableCacheTest.java index 0a20999b98..c32ea2c9ba 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableCacheTest.java @@ -85,50 +85,50 @@ public void error() { public void crossDispose() { PublishSubject ps = PublishSubject.create(); - final TestObserver ts1 = new TestObserver(); + final TestObserver to1 = new TestObserver(); - final TestObserver ts2 = new TestObserver() { + final TestObserver to2 = new TestObserver() { @Override public void onComplete() { super.onComplete(); - ts1.cancel(); + to1.cancel(); } }; Completable c = ps.ignoreElements().cache(); - c.subscribe(ts2); - c.subscribe(ts1); + c.subscribe(to2); + c.subscribe(to1); ps.onComplete(); - ts1.assertEmpty(); - ts2.assertResult(); + to1.assertEmpty(); + to2.assertResult(); } @Test public void crossDisposeOnError() { PublishSubject ps = PublishSubject.create(); - final TestObserver ts1 = new TestObserver(); + final TestObserver to1 = new TestObserver(); - final TestObserver ts2 = new TestObserver() { + final TestObserver to2 = new TestObserver() { @Override public void onError(Throwable ex) { super.onError(ex); - ts1.cancel(); + to1.cancel(); } }; Completable c = ps.ignoreElements().cache(); - c.subscribe(ts2); - c.subscribe(ts1); + c.subscribe(to2); + c.subscribe(to1); ps.onError(new TestException()); - ts1.assertEmpty(); - ts2.assertFailure(TestException.class); + to1.assertEmpty(); + to2.assertFailure(TestException.class); } @Test @@ -139,31 +139,31 @@ public void dispose() { assertFalse(ps.hasObservers()); - TestObserver ts1 = c.test(); + TestObserver to1 = c.test(); assertTrue(ps.hasObservers()); - ts1.cancel(); + to1.cancel(); assertTrue(ps.hasObservers()); - TestObserver ts2 = c.test(); + TestObserver to2 = c.test(); - TestObserver ts3 = c.test(); - ts3.cancel(); + TestObserver to3 = c.test(); + to3.cancel(); - TestObserver ts4 = c.test(true); - ts3.cancel(); + TestObserver to4 = c.test(true); + to3.cancel(); ps.onComplete(); - ts1.assertEmpty(); + to1.assertEmpty(); - ts2.assertResult(); + to2.assertResult(); - ts3.assertEmpty(); + to3.assertEmpty(); - ts4.assertEmpty(); + to4.assertEmpty(); } @Test @@ -173,20 +173,20 @@ public void subscribeRace() { final Completable c = ps.ignoreElements().cache(); - final TestObserver ts1 = new TestObserver(); + final TestObserver to1 = new TestObserver(); - final TestObserver ts2 = new TestObserver(); + final TestObserver to2 = new TestObserver(); Runnable r1 = new Runnable() { @Override public void run() { - c.subscribe(ts1); + c.subscribe(to1); } }; Runnable r2 = new Runnable() { @Override public void run() { - c.subscribe(ts2); + c.subscribe(to2); } }; @@ -194,8 +194,8 @@ public void run() { ps.onComplete(); - ts1.assertResult(); - ts2.assertResult(); + to1.assertResult(); + to2.assertResult(); } } @@ -206,20 +206,20 @@ public void subscribeDisposeRace() { final Completable c = ps.ignoreElements().cache(); - final TestObserver ts1 = c.test(); + final TestObserver to1 = c.test(); - final TestObserver ts2 = new TestObserver(); + final TestObserver to2 = new TestObserver(); Runnable r1 = new Runnable() { @Override public void run() { - ts1.cancel(); + to1.cancel(); } }; Runnable r2 = new Runnable() { @Override public void run() { - c.subscribe(ts2); + c.subscribe(to2); } }; @@ -227,8 +227,8 @@ public void run() { ps.onComplete(); - ts1.assertEmpty(); - ts2.assertResult(); + to1.assertEmpty(); + to2.assertResult(); } } @@ -236,31 +236,31 @@ public void run() { public void doubleDispose() { PublishSubject ps = PublishSubject.create(); - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); ps.ignoreElements().cache() .subscribe(new CompletableObserver() { @Override public void onSubscribe(Disposable d) { - ts.onSubscribe(EmptyDisposable.INSTANCE); + to.onSubscribe(EmptyDisposable.INSTANCE); d.dispose(); d.dispose(); } @Override public void onComplete() { - ts.onComplete(); + to.onComplete(); } @Override public void onError(Throwable e) { - ts.onError(e); + to.onError(e); } }); ps.onComplete(); - ts.assertEmpty(); + to.assertEmpty(); } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java index a72faf078b..218180b4a7 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java @@ -73,30 +73,30 @@ public void errorRace() { List errors = TestHelper.trackPluginErrors(); try { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); - TestObserver to = Completable.concat(ps1.map(new Function() { + TestObserver to = Completable.concat(pp1.map(new Function() { @Override public Completable apply(Integer v) throws Exception { - return ps2.ignoreElements(); + return pp2.ignoreElements(); } })).test(); - ps1.onNext(1); + pp1.onNext(1); final TestException ex = new TestException(); Runnable r1 = new Runnable() { @Override public void run() { - ps1.onError(ex); + pp1.onError(ex); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps2.onError(ex); + pp2.onError(ex); } }; diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableSubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableSubscribeOnTest.java index fdb64a94c5..cfbc1e6a00 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableSubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableSubscribeOnTest.java @@ -35,13 +35,13 @@ public void normal() { try { TestScheduler scheduler = new TestScheduler(); - TestObserver ts = Completable.complete() + TestObserver to = Completable.complete() .subscribeOn(scheduler) .test(); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ts.assertResult(); + to.assertResult(); assertTrue(list.toString(), list.isEmpty()); } finally { diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableTimerTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableTimerTest.java index 1d611a6287..6bd5afd62b 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableTimerTest.java @@ -38,7 +38,7 @@ public void timerInterruptible() throws Exception { try { for (Scheduler s : new Scheduler[] { Schedulers.single(), Schedulers.computation(), Schedulers.newThread(), Schedulers.io(), Schedulers.from(exec) }) { final AtomicBoolean interrupted = new AtomicBoolean(); - TestObserver ts = Completable.timer(1, TimeUnit.MILLISECONDS, s) + TestObserver to = Completable.timer(1, TimeUnit.MILLISECONDS, s) .doOnComplete(new Action() { @Override public void run() throws Exception { @@ -53,7 +53,7 @@ public void run() throws Exception { Thread.sleep(500); - ts.cancel(); + to.cancel(); Thread.sleep(500); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java index 8f184a92ec..9f578b2d2d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java @@ -146,40 +146,40 @@ public Publisher apply(Boolean t1) { @Test @Ignore("No backpressure in Single") public void testBackpressureIfNoneRequestedNoneShouldBeDelivered() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Flowable.empty().all(new Predicate() { @Override public boolean test(Object t1) { return false; } - }).subscribe(ts); + }).subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertNotComplete(); } @Test public void testBackpressureIfOneRequestedOneShouldBeDelivered() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Flowable.empty().all(new Predicate() { @Override public boolean test(Object t) { return false; } - }).subscribe(ts); + }).subscribe(to); - ts.assertTerminated(); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertTerminated(); + to.assertNoErrors(); + to.assertComplete(); - ts.assertValue(true); + to.assertValue(true); } @Test public void testPredicateThrowsExceptionAndValueInCauseMessage() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final IllegalArgumentException ex = new IllegalArgumentException(); @@ -189,12 +189,12 @@ public boolean test(String v) { throw ex; } }) - .subscribe(ts); + .subscribe(to); - ts.assertTerminated(); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(ex); + to.assertTerminated(); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(ex); // FIXME need to decide about adding the value that probably caused the crash in some way // assertTrue(ex.getCause().getMessage().contains("Boo!")); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java index 7a1fcdf2ce..839d04e3e1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java @@ -353,20 +353,20 @@ public void testMultipleUse() { @SuppressWarnings("unchecked") @Test public void ambIterable() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); TestSubscriber ts = TestSubscriber.create(); - Flowable.amb(Arrays.asList(ps1, ps2)).subscribe(ts); + Flowable.amb(Arrays.asList(pp1, pp2)).subscribe(ts); ts.assertNoValues(); - ps1.onNext(1); - ps1.onComplete(); + pp1.onNext(1); + pp1.onComplete(); - assertFalse(ps1.hasSubscribers()); - assertFalse(ps2.hasSubscribers()); + assertFalse(pp1.hasSubscribers()); + assertFalse(pp2.hasSubscribers()); ts.assertValue(1); ts.assertNoErrors(); @@ -376,20 +376,20 @@ public void ambIterable() { @SuppressWarnings("unchecked") @Test public void ambIterable2() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); TestSubscriber ts = TestSubscriber.create(); - Flowable.amb(Arrays.asList(ps1, ps2)).subscribe(ts); + Flowable.amb(Arrays.asList(pp1, pp2)).subscribe(ts); ts.assertNoValues(); - ps2.onNext(2); - ps2.onComplete(); + pp2.onNext(2); + pp2.onComplete(); - assertFalse(ps1.hasSubscribers()); - assertFalse(ps2.hasSubscribers()); + assertFalse(pp1.hasSubscribers()); + assertFalse(pp2.hasSubscribers()); ts.assertValue(2); ts.assertNoErrors(); @@ -568,28 +568,28 @@ public void singleIterable() { @Test public void onNextRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); @SuppressWarnings("unchecked") - TestSubscriber to = Flowable.ambArray(ps1, ps2).test(); + TestSubscriber ts = Flowable.ambArray(pp1, pp2).test(); Runnable r1 = new Runnable() { @Override public void run() { - ps1.onNext(1); + pp1.onNext(1); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps2.onNext(1); + pp2.onNext(1); } }; TestHelper.race(r1, r2); - to.assertSubscribed().assertNoErrors() + ts.assertSubscribed().assertNoErrors() .assertNotComplete().assertValueCount(1); } } @@ -597,52 +597,52 @@ public void run() { @Test public void onCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); @SuppressWarnings("unchecked") - TestSubscriber to = Flowable.ambArray(ps1, ps2).test(); + TestSubscriber ts = Flowable.ambArray(pp1, pp2).test(); Runnable r1 = new Runnable() { @Override public void run() { - ps1.onComplete(); + pp1.onComplete(); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps2.onComplete(); + pp2.onComplete(); } }; TestHelper.race(r1, r2); - to.assertResult(); + ts.assertResult(); } } @Test public void onErrorRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); @SuppressWarnings("unchecked") - TestSubscriber to = Flowable.ambArray(ps1, ps2).test(); + TestSubscriber ts = Flowable.ambArray(pp1, pp2).test(); final Throwable ex = new TestException(); Runnable r1 = new Runnable() { @Override public void run() { - ps1.onError(ex); + pp1.onError(ex); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps2.onError(ex); + pp2.onError(ex); } }; @@ -653,7 +653,7 @@ public void run() { RxJavaPlugins.reset(); } - to.assertFailure(TestException.class); + ts.assertFailure(TestException.class); if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java index 7484568ac2..90d05f7ac1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java @@ -239,7 +239,7 @@ public Publisher apply(Boolean t1) { @Test @Ignore("Single doesn't do backpressure") public void testBackpressureIfNoneRequestedNoneShouldBeDelivered() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Flowable.just(1).any(new Predicate() { @Override @@ -247,32 +247,32 @@ public boolean test(Integer t) { return true; } }) - .subscribe(ts); + .subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertNotComplete(); } @Test public void testBackpressureIfOneRequestedOneShouldBeDelivered() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Flowable.just(1).any(new Predicate() { @Override public boolean test(Integer v) { return true; } - }).subscribe(ts); + }).subscribe(to); - ts.assertTerminated(); - ts.assertNoErrors(); - ts.assertComplete(); - ts.assertValue(true); + to.assertTerminated(); + to.assertNoErrors(); + to.assertComplete(); + to.assertValue(true); } @Test public void testPredicateThrowsExceptionAndValueInCauseMessage() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final IllegalArgumentException ex = new IllegalArgumentException(); Flowable.just("Boo!").any(new Predicate() { @@ -280,12 +280,12 @@ public void testPredicateThrowsExceptionAndValueInCauseMessage() { public boolean test(String v) { throw ex; } - }).subscribe(ts); + }).subscribe(to); - ts.assertTerminated(); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(ex); + to.assertTerminated(); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(ex); // FIXME value as last cause? // assertTrue(ex.getCause().getMessage().contains("Boo!")); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAutoConnectTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAutoConnectTest.java index be92d5ac56..0e70a5070e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAutoConnectTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAutoConnectTest.java @@ -23,10 +23,10 @@ public class FlowableAutoConnectTest { @Test public void autoConnectImmediately() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.publish().autoConnect(0); + pp.publish().autoConnect(0); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java index 50edb0ac6d..09c246016a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java @@ -291,12 +291,12 @@ public void blockingSingleEmpty() { @Test public void onCompleteDelayed() { - TestSubscriber to = new TestSubscriber(); + TestSubscriber ts = new TestSubscriber(); Flowable.empty().delay(100, TimeUnit.MILLISECONDS) - .blockingSubscribe(to); + .blockingSubscribe(ts); - to.assertResult(); + ts.assertResult(); } @Test @@ -306,24 +306,24 @@ public void utilityClass() { @Test public void disposeUpFront() { - TestSubscriber to = new TestSubscriber(); - to.dispose(); - Flowable.just(1).blockingSubscribe(to); + TestSubscriber ts = new TestSubscriber(); + ts.dispose(); + Flowable.just(1).blockingSubscribe(ts); - to.assertEmpty(); + ts.assertEmpty(); } @SuppressWarnings("rawtypes") @Test public void delayed() throws Exception { - final TestSubscriber to = new TestSubscriber(); + final TestSubscriber ts = new TestSubscriber(); final Subscriber[] s = { null }; Schedulers.single().scheduleDirect(new Runnable() { @SuppressWarnings("unchecked") @Override public void run() { - to.dispose(); + ts.dispose(); s[0].onNext(1); } }, 200, TimeUnit.MILLISECONDS); @@ -334,13 +334,13 @@ protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); s[0] = observer; } - }.blockingSubscribe(to); + }.blockingSubscribe(ts); - while (!to.isDisposed()) { + while (!ts.isDisposed()) { Thread.sleep(100); } - to.assertEmpty(); + ts.assertEmpty(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index a65442a895..3a32a81c38 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -1100,29 +1100,29 @@ public void testPostCompleteBackpressure() { @Test public void timeAndSkipOverlap() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); TestSubscriber> ts = TestSubscriber.create(); - ps.buffer(2, 1, TimeUnit.SECONDS, scheduler).subscribe(ts); + pp.buffer(2, 1, TimeUnit.SECONDS, scheduler).subscribe(ts); - ps.onNext(1); + pp.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(2); + pp.onNext(2); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(3); + pp.onNext(3); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(4); + pp.onNext(4); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onComplete(); + pp.onComplete(); ts.assertValues( Arrays.asList(1, 2), @@ -1140,29 +1140,29 @@ public void timeAndSkipOverlap() { @Test public void timeAndSkipSkip() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); TestSubscriber> ts = TestSubscriber.create(); - ps.buffer(2, 3, TimeUnit.SECONDS, scheduler).subscribe(ts); + pp.buffer(2, 3, TimeUnit.SECONDS, scheduler).subscribe(ts); - ps.onNext(1); + pp.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(2); + pp.onNext(2); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(3); + pp.onNext(3); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(4); + pp.onNext(4); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onComplete(); + pp.onComplete(); ts.assertValues( Arrays.asList(1, 2), @@ -1185,29 +1185,29 @@ public Scheduler apply(Scheduler t) { }); try { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); TestSubscriber> ts = TestSubscriber.create(); - ps.buffer(2, 1, TimeUnit.SECONDS).subscribe(ts); + pp.buffer(2, 1, TimeUnit.SECONDS).subscribe(ts); - ps.onNext(1); + pp.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(2); + pp.onNext(2); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(3); + pp.onNext(3); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(4); + pp.onNext(4); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onComplete(); + pp.onComplete(); ts.assertValues( Arrays.asList(1, 2), @@ -1236,29 +1236,29 @@ public Scheduler apply(Scheduler t) { try { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); TestSubscriber> ts = TestSubscriber.create(); - ps.buffer(2, 3, TimeUnit.SECONDS).subscribe(ts); + pp.buffer(2, 3, TimeUnit.SECONDS).subscribe(ts); - ps.onNext(1); + pp.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(2); + pp.onNext(2); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(3); + pp.onNext(3); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onNext(4); + pp.onNext(4); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ps.onComplete(); + pp.onComplete(); ts.assertValues( Arrays.asList(1, 2), @@ -1849,9 +1849,9 @@ public void bufferTimedOverlapEmpty() { public void bufferTimedExactSupplierCrash() { TestScheduler scheduler = new TestScheduler(); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber> to = ps + TestSubscriber> ts = pp .buffer(1, TimeUnit.MILLISECONDS, scheduler, 1, new Callable>() { int calls; @Override @@ -1864,13 +1864,13 @@ public List call() throws Exception { }, true) .test(); - ps.onNext(1); + pp.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); - ps.onNext(2); + pp.onNext(2); - to + ts .assertFailure(TestException.class, Arrays.asList(1)); } @@ -1879,15 +1879,15 @@ public List call() throws Exception { public void bufferTimedExactBoundedError() { TestScheduler scheduler = new TestScheduler(); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber> to = ps + TestSubscriber> ts = pp .buffer(1, TimeUnit.MILLISECONDS, scheduler, 1, Functions.createArrayList(16), true) .test(); - ps.onError(new TestException()); + pp.onError(new TestException()); - to + ts .assertFailure(TestException.class); } @@ -1981,19 +1981,19 @@ public void withTimeAndSizeCapacityRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler scheduler = new TestScheduler(); - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber> ts = ps.buffer(1, TimeUnit.SECONDS, scheduler, 5).test(); + TestSubscriber> ts = pp.buffer(1, TimeUnit.SECONDS, scheduler, 5).test(); - ps.onNext(1); - ps.onNext(2); - ps.onNext(3); - ps.onNext(4); + pp.onNext(1); + pp.onNext(2); + pp.onNext(3); + pp.onNext(4); Runnable r1 = new Runnable() { @Override public void run() { - ps.onNext(5); + pp.onNext(5); } }; @@ -2006,7 +2006,7 @@ public void run() { TestHelper.race(r1, r2); - ps.onComplete(); + pp.onComplete(); int items = 0; for (List o : ts.values()) { @@ -2456,7 +2456,7 @@ public void bufferExactBoundarySecondBufferCrash() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor b = PublishProcessor.create(); - TestSubscriber> to = pp.buffer(b, new Callable>() { + TestSubscriber> ts = pp.buffer(b, new Callable>() { int calls; @Override public List call() throws Exception { @@ -2469,7 +2469,7 @@ public List call() throws Exception { b.onNext(1); - to.assertFailure(TestException.class); + ts.assertFailure(TestException.class); } @SuppressWarnings("unchecked") diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java index 50b9d69d05..2524d5eb28 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java @@ -316,18 +316,18 @@ public void disposeOnArrival2() { @Test public void subscribeEmitRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final Flowable cache = ps.cache(); + final Flowable cache = pp.cache(); cache.test(); - final TestSubscriber to = new TestSubscriber(); + final TestSubscriber ts = new TestSubscriber(); Runnable r1 = new Runnable() { @Override public void run() { - cache.subscribe(to); + cache.subscribe(ts); } }; @@ -335,15 +335,15 @@ public void run() { @Override public void run() { for (int j = 0; j < 500; j++) { - ps.onNext(j); + pp.onNext(j); } - ps.onComplete(); + pp.onComplete(); } }; TestHelper.race(r1, r2); - to + ts .awaitDone(5, TimeUnit.SECONDS) .assertSubscribed().assertValueCount(500).assertComplete().assertNoErrors(); } @@ -351,22 +351,22 @@ public void run() { @Test public void observers() { - PublishProcessor ps = PublishProcessor.create(); - FlowableCache cache = (FlowableCache)Flowable.range(1, 5).concatWith(ps).cache(); + PublishProcessor pp = PublishProcessor.create(); + FlowableCache cache = (FlowableCache)Flowable.range(1, 5).concatWith(pp).cache(); assertFalse(cache.hasSubscribers()); assertEquals(0, cache.cachedEventCount()); - TestSubscriber to = cache.test(); + TestSubscriber ts = cache.test(); assertTrue(cache.hasSubscribers()); assertEquals(5, cache.cachedEventCount()); - ps.onComplete(); + pp.onComplete(); - to.assertResult(1, 2, 3, 4, 5); + ts.assertResult(1, 2, 3, 4, 5); } @Test @@ -460,33 +460,33 @@ public void subscribeSubscribeRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Flowable cache = Flowable.range(1, 500).cache(); - final TestSubscriber to1 = new TestSubscriber(); - final TestSubscriber to2 = new TestSubscriber(); + final TestSubscriber ts1 = new TestSubscriber(); + final TestSubscriber ts2 = new TestSubscriber(); Runnable r1 = new Runnable() { @Override public void run() { - cache.subscribe(to1); + cache.subscribe(ts1); } }; Runnable r2 = new Runnable() { @Override public void run() { - cache.subscribe(to2); + cache.subscribe(ts2); } }; TestHelper.race(r1, r2); - to1 + ts1 .awaitDone(5, TimeUnit.SECONDS) .assertSubscribed() .assertValueCount(500) .assertComplete() .assertNoErrors(); - to2 + ts2 .awaitDone(5, TimeUnit.SECONDS) .assertSubscribed() .assertValueCount(500) @@ -498,31 +498,31 @@ public void run() { @Test public void subscribeCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final Flowable cache = ps.cache(); + final Flowable cache = pp.cache(); cache.test(); - final TestSubscriber to = new TestSubscriber(); + final TestSubscriber ts = new TestSubscriber(); Runnable r1 = new Runnable() { @Override public void run() { - cache.subscribe(to); + cache.subscribe(ts); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps.onComplete(); + pp.onComplete(); } }; TestHelper.race(r1, r2); - to + ts .awaitDone(5, TimeUnit.SECONDS) .assertResult(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCastTest.java index 02928041fb..370f32d18a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCastTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCastTest.java @@ -56,17 +56,17 @@ public void testCastWithWrongType() { @Test public void castCrashUnsubscribes() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); TestSubscriber ts = TestSubscriber.create(); - ps.cast(String.class).subscribe(ts); + pp.cast(String.class).subscribe(ts); - Assert.assertTrue("Not subscribed?", ps.hasSubscribers()); + Assert.assertTrue("Not subscribed?", pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - Assert.assertFalse("Subscribed?", ps.hasSubscribers()); + Assert.assertFalse("Subscribed?", pp.hasSubscribers()); ts.assertError(ClassCastException.class); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java index 1abc20903f..dd95488500 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java @@ -1242,14 +1242,14 @@ public Object apply(Object a, Object b) throws Exception { @Test public void cancelWhileSubscribing() { - final TestSubscriber to = new TestSubscriber(); + final TestSubscriber ts = new TestSubscriber(); Flowable.combineLatest( Flowable.just(1) .doOnNext(new Consumer() { @Override public void accept(Integer v) throws Exception { - to.cancel(); + ts.cancel(); } }), Flowable.never(), @@ -1259,7 +1259,7 @@ public Object apply(Object a, Object b) throws Exception { return a; } }) - .subscribe(to); + .subscribe(ts); } @Test @@ -1267,10 +1267,10 @@ public void onErrorRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); - TestSubscriber to = Flowable.combineLatest(ps1, ps2, new BiFunction() { + TestSubscriber ts = Flowable.combineLatest(pp1, pp2, new BiFunction() { @Override public Integer apply(Integer a, Integer b) throws Exception { return a; @@ -1283,30 +1283,30 @@ public Integer apply(Integer a, Integer b) throws Exception { Runnable r1 = new Runnable() { @Override public void run() { - ps1.onError(ex1); + pp1.onError(ex1); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps2.onError(ex2); + pp2.onError(ex2); } }; TestHelper.race(r1, r2); - if (to.errorCount() != 0) { - if (to.errors().get(0) instanceof CompositeException) { - to.assertSubscribed() + if (ts.errorCount() != 0) { + if (ts.errors().get(0) instanceof CompositeException) { + ts.assertSubscribed() .assertNotComplete() .assertNoValues(); - for (Throwable e : TestHelper.errorList(to)) { + for (Throwable e : TestHelper.errorList(ts)) { assertTrue(e.toString(), e instanceof TestException); } } else { - to.assertFailure(TestException.class); + ts.assertFailure(TestException.class); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java index 37cd8bf3d6..90c0c59691 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java @@ -859,46 +859,46 @@ public void innerOuterRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { List errors = TestHelper.trackPluginErrors(); try { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); - TestSubscriber to = ps1.concatMapEager(new Function>() { + TestSubscriber ts = pp1.concatMapEager(new Function>() { @Override public Flowable apply(Integer v) throws Exception { - return ps2; + return pp2; } }).test(); final TestException ex1 = new TestException(); final TestException ex2 = new TestException(); - ps1.onNext(1); + pp1.onNext(1); Runnable r1 = new Runnable() { @Override public void run() { - ps1.onError(ex1); + pp1.onError(ex1); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps2.onError(ex2); + pp2.onError(ex2); } }; TestHelper.race(r1, r2); - to.assertSubscribed().assertNoValues().assertNotComplete(); + ts.assertSubscribed().assertNoValues().assertNotComplete(); - Throwable ex = to.errors().get(0); + Throwable ex = ts.errors().get(0); if (ex instanceof CompositeException) { - List es = TestHelper.errorList(to); + List es = TestHelper.errorList(ts); TestHelper.assertError(es, 0, TestException.class); TestHelper.assertError(es, 1, TestException.class); } else { - to.assertError(TestException.class); + ts.assertError(TestException.class); if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); } @@ -943,7 +943,7 @@ public void innerErrorAfterPoll() { final UnicastProcessor us = UnicastProcessor.create(); us.onNext(1); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); @@ -958,18 +958,18 @@ public Flowable apply(Integer v) throws Exception { return us; } }, 1, 128) - .subscribe(to); + .subscribe(ts); - to + ts .assertFailure(TestException.class, 1); } @Test public void nextCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps1 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); - final TestSubscriber to = ps1.concatMapEager(new Function>() { + final TestSubscriber ts = pp1.concatMapEager(new Function>() { @Override public Flowable apply(Integer v) throws Exception { return Flowable.never(); @@ -979,37 +979,37 @@ public Flowable apply(Integer v) throws Exception { Runnable r1 = new Runnable() { @Override public void run() { - ps1.onNext(1); + pp1.onNext(1); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; TestHelper.race(r1, r2); - to.assertEmpty(); + ts.assertEmpty(); } } @Test public void mapperCancels() { - final TestSubscriber to = new TestSubscriber(); + final TestSubscriber ts = new TestSubscriber(); Flowable.just(1).hide() .concatMapEager(new Function>() { @Override public Flowable apply(Integer v) throws Exception { - to.cancel(); + ts.cancel(); return Flowable.never(); } }, 1, 128) - .subscribe(to); + .subscribe(ts); - to.assertEmpty(); + ts.assertEmpty(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java index de6e10417c..786dd5cb1e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java @@ -800,7 +800,7 @@ public void run() { @Test public void serializedConcurrentOnNextOnComplete() { for (BackpressureStrategy m : BackpressureStrategy.values()) { - TestSubscriber to = Flowable.create(new FlowableOnSubscribe() { + TestSubscriber ts = Flowable.create(new FlowableOnSubscribe() { @Override public void subscribe(FlowableEmitter e) throws Exception { final FlowableEmitter f = e.serialize(); @@ -831,7 +831,7 @@ public void run() { .assertSubscribed().assertComplete() .assertNoErrors(); - int c = to.valueCount(); + int c = ts.valueCount(); assertTrue("" + c, c >= 100); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java index b87cd59fbf..fbd14694f0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java @@ -422,36 +422,36 @@ public Flowable apply(Flowable o) throws Exception { @Test public void disposeInOnNext() { - final TestSubscriber to = new TestSubscriber(); + final TestSubscriber ts = new TestSubscriber(); BehaviorProcessor.createDefault(1) .debounce(new Function>() { @Override public Flowable apply(Integer o) throws Exception { - to.cancel(); + ts.cancel(); return Flowable.never(); } }) - .subscribeWith(to) + .subscribeWith(ts) .assertEmpty(); - assertTrue(to.isDisposed()); + assertTrue(ts.isDisposed()); } @Test public void disposedInOnComplete() { - final TestSubscriber to = new TestSubscriber(); + final TestSubscriber ts = new TestSubscriber(); new Flowable() { @Override protected void subscribeActual(Subscriber subscriber) { subscriber.onSubscribe(new BooleanSubscription()); - to.cancel(); + ts.cancel(); subscriber.onComplete(); } } .debounce(Functions.justFunction(Flowable.never())) - .subscribeWith(to) + .subscribeWith(ts) .assertEmpty(); } @@ -459,7 +459,7 @@ protected void subscribeActual(Subscriber subscriber) { public void emitLate() { final AtomicReference> ref = new AtomicReference>(); - TestSubscriber to = Flowable.range(1, 2) + TestSubscriber ts = Flowable.range(1, 2) .debounce(new Function>() { @Override public Flowable apply(Integer o) throws Exception { @@ -479,7 +479,7 @@ protected void subscribeActual(Subscriber subscriber) { ref.get().onNext(1); - to + ts .assertResult(2); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java index 40e6ff58fb..d86f5f5469 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java @@ -768,17 +768,17 @@ public Integer apply(Integer t) { public void testErrorRunsBeforeOnNext() { TestScheduler test = new TestScheduler(); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); TestSubscriber ts = new TestSubscriber(); - ps.delay(1, TimeUnit.SECONDS, test).subscribe(ts); + pp.delay(1, TimeUnit.SECONDS, test).subscribe(ts); - ps.onNext(1); + pp.onNext(1); test.advanceTimeBy(500, TimeUnit.MILLISECONDS); - ps.onError(new TestException()); + pp.onError(new TestException()); test.advanceTimeBy(1, TimeUnit.SECONDS); @@ -789,7 +789,7 @@ public void testErrorRunsBeforeOnNext() { @Test public void testDelaySupplierSimple() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); Flowable source = Flowable.range(1, 5); @@ -798,7 +798,7 @@ public void testDelaySupplierSimple() { source.delaySubscription(Flowable.defer(new Callable>() { @Override public Publisher call() { - return ps; + return pp; } })).subscribe(ts); @@ -806,7 +806,7 @@ public Publisher call() { ts.assertNoErrors(); ts.assertNotComplete(); - ps.onNext(1); + pp.onNext(1); ts.assertValues(1, 2, 3, 4, 5); ts.assertComplete(); @@ -815,7 +815,7 @@ public Publisher call() { @Test public void testDelaySupplierCompletes() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); Flowable source = Flowable.range(1, 5); @@ -824,7 +824,7 @@ public void testDelaySupplierCompletes() { source.delaySubscription(Flowable.defer(new Callable>() { @Override public Publisher call() { - return ps; + return pp; } })).subscribe(ts); @@ -833,7 +833,7 @@ public Publisher call() { ts.assertNotComplete(); // FIXME should this complete the source instead of consuming it? - ps.onComplete(); + pp.onComplete(); ts.assertValues(1, 2, 3, 4, 5); ts.assertComplete(); @@ -842,7 +842,7 @@ public Publisher call() { @Test public void testDelaySupplierErrors() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); Flowable source = Flowable.range(1, 5); @@ -851,7 +851,7 @@ public void testDelaySupplierErrors() { source.delaySubscription(Flowable.defer(new Callable>() { @Override public Publisher call() { - return ps; + return pp; } })).subscribe(ts); @@ -859,7 +859,7 @@ public Publisher call() { ts.assertNoErrors(); ts.assertNotComplete(); - ps.onError(new TestException()); + pp.onError(new TestException()); ts.assertNoValues(); ts.assertNotComplete(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java index 0404682e9d..3584224000 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java @@ -143,29 +143,29 @@ public void error() { @Test public void fusedSync() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.just(1, 1, 2, 1, 3, 2, 4, 5, 4) .distinct() - .subscribe(to); + .subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.SYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); } @Test public void fusedAsync() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor us = UnicastProcessor.create(); us .distinct() - .subscribe(to); + .subscribe(ts); TestHelper.emit(us, 1, 1, 2, 1, 3, 2, 4, 5, 4); - SubscriberFusion.assertFusion(to, QueueDisposable.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java index f63ded514c..2e5e97bb67 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java @@ -182,9 +182,9 @@ public boolean test(Integer a, Integer b) { return a.equals(b); } }) - .to(SubscriberFusion.test(Long.MAX_VALUE, QueueSubscription.ANY, false)) + .to(SubscriberFusion.test(Long.MAX_VALUE, QueueFuseable.ANY, false)) .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(1, 2, 3, 2, 4, 1, 2); } @@ -203,9 +203,9 @@ public boolean test(Integer v) { return true; } }) - .to(SubscriberFusion.test(Long.MAX_VALUE, QueueSubscription.ANY, false)) + .to(SubscriberFusion.test(Long.MAX_VALUE, QueueFuseable.ANY, false)) .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(1, 2, 3, 2, 4, 1, 2); } @@ -272,7 +272,7 @@ public boolean test(String a, String b) { @Test public void fused() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.just(1, 2, 2, 3, 3, 4, 5) .distinctUntilChanged(new BiPredicate() { @@ -281,17 +281,17 @@ public boolean test(Integer a, Integer b) throws Exception { return a.equals(b); } }) - .subscribe(to); + .subscribe(ts); - to.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueDisposable.SYNC)) + ts.assertOf(SubscriberFusion.assertFuseable()) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(1, 2, 3, 4, 5) ; } @Test public void fusedAsync() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor up = UnicastProcessor.create(); @@ -302,12 +302,12 @@ public boolean test(Integer a, Integer b) throws Exception { return a.equals(b); } }) - .subscribe(to); + .subscribe(ts); TestHelper.emit(up, 1, 2, 2, 3, 3, 4, 5); - to.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueDisposable.ASYNC)) + ts.assertOf(SubscriberFusion.assertFuseable()) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2, 3, 4, 5) ; } @@ -438,7 +438,7 @@ public boolean test(Integer v) throws Exception { @Test public void conditionalFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.just(1, 2, 1, 3, 3, 4, 3, 5, 5) .distinctUntilChanged() @@ -450,13 +450,13 @@ public boolean test(Integer v) throws Exception { }) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.SYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.SYNC) .assertResult(2, 4); } @Test public void conditionalAsyncFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor up = UnicastProcessor.create(); up @@ -472,7 +472,7 @@ public boolean test(Integer v) throws Exception { TestHelper.emit(up, 1, 2, 1, 3, 3, 4, 3, 5, 5); - SubscriberFusion.assertFusion(ts, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .assertResult(2, 4); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNextTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNextTest.java index 78b9f05f7d..338d0b0f50 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNextTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNextTest.java @@ -23,7 +23,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.Consumer; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.processors.UnicastProcessor; import io.reactivex.subscribers.*; @@ -88,13 +88,13 @@ public void empty() { @Test public void syncFused() { - TestSubscriber ts0 = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts0 = SubscriberFusion.newTest(QueueFuseable.SYNC); Flowable.range(1, 5) .doAfterNext(afterNext) .subscribe(ts0); - SubscriberFusion.assertFusion(ts0, QueueSubscription.SYNC) + SubscriberFusion.assertFusion(ts0, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -102,13 +102,13 @@ public void syncFused() { @Test public void asyncFusedRejected() { - TestSubscriber ts0 = SubscriberFusion.newTest(QueueSubscription.ASYNC); + TestSubscriber ts0 = SubscriberFusion.newTest(QueueFuseable.ASYNC); Flowable.range(1, 5) .doAfterNext(afterNext) .subscribe(ts0); - SubscriberFusion.assertFusion(ts0, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts0, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -116,7 +116,7 @@ public void asyncFusedRejected() { @Test public void asyncFused() { - TestSubscriber ts0 = SubscriberFusion.newTest(QueueSubscription.ASYNC); + TestSubscriber ts0 = SubscriberFusion.newTest(QueueFuseable.ASYNC); UnicastProcessor up = UnicastProcessor.create(); @@ -126,7 +126,7 @@ public void asyncFused() { .doAfterNext(afterNext) .subscribe(ts0); - SubscriberFusion.assertFusion(ts0, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts0, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -183,14 +183,14 @@ public void emptyConditional() { @Test public void syncFusedConditional() { - TestSubscriber ts0 = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts0 = SubscriberFusion.newTest(QueueFuseable.SYNC); Flowable.range(1, 5) .doAfterNext(afterNext) .filter(Functions.alwaysTrue()) .subscribe(ts0); - SubscriberFusion.assertFusion(ts0, QueueSubscription.SYNC) + SubscriberFusion.assertFusion(ts0, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -198,14 +198,14 @@ public void syncFusedConditional() { @Test public void asyncFusedRejectedConditional() { - TestSubscriber ts0 = SubscriberFusion.newTest(QueueSubscription.ASYNC); + TestSubscriber ts0 = SubscriberFusion.newTest(QueueFuseable.ASYNC); Flowable.range(1, 5) .doAfterNext(afterNext) .filter(Functions.alwaysTrue()) .subscribe(ts0); - SubscriberFusion.assertFusion(ts0, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts0, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -213,7 +213,7 @@ public void asyncFusedRejectedConditional() { @Test public void asyncFusedConditional() { - TestSubscriber ts0 = SubscriberFusion.newTest(QueueSubscription.ASYNC); + TestSubscriber ts0 = SubscriberFusion.newTest(QueueFuseable.ASYNC); UnicastProcessor up = UnicastProcessor.create(); @@ -224,7 +224,7 @@ public void asyncFusedConditional() { .filter(Functions.alwaysTrue()) .subscribe(ts0); - SubscriberFusion.assertFusion(ts0, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts0, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoFinallyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoFinallyTest.java index 8a775ea310..943d92ff03 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoFinallyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoFinallyTest.java @@ -24,7 +24,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.UnicastProcessor; import io.reactivex.subscribers.*; @@ -97,13 +97,13 @@ public Publisher apply(Flowable f) throws Exception { @Test public void syncFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Flowable.range(1, 5) .doFinally(this) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.SYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -111,13 +111,13 @@ public void syncFused() { @Test public void syncFusedBoundary() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.SYNC | QueueSubscription.BOUNDARY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC | QueueFuseable.BOUNDARY); Flowable.range(1, 5) .doFinally(this) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -125,7 +125,7 @@ public void syncFusedBoundary() { @Test public void asyncFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ASYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ASYNC); UnicastProcessor up = UnicastProcessor.create(); TestHelper.emit(up, 1, 2, 3, 4, 5); @@ -134,7 +134,7 @@ public void asyncFused() { .doFinally(this) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -142,7 +142,7 @@ public void asyncFused() { @Test public void asyncFusedBoundary() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ASYNC | QueueSubscription.BOUNDARY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ASYNC | QueueFuseable.BOUNDARY); UnicastProcessor up = UnicastProcessor.create(); TestHelper.emit(up, 1, 2, 3, 4, 5); @@ -151,7 +151,7 @@ public void asyncFusedBoundary() { .doFinally(this) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -205,14 +205,14 @@ public void normalTakeConditional() { @Test public void syncFusedConditional() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Flowable.range(1, 5) .doFinally(this) .filter(Functions.alwaysTrue()) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.SYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -220,13 +220,13 @@ public void syncFusedConditional() { @Test public void nonFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Flowable.range(1, 5).hide() .doFinally(this) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -234,14 +234,14 @@ public void nonFused() { @Test public void nonFusedConditional() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Flowable.range(1, 5).hide() .doFinally(this) .filter(Functions.alwaysTrue()) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -249,14 +249,14 @@ public void nonFusedConditional() { @Test public void syncFusedBoundaryConditional() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.SYNC | QueueSubscription.BOUNDARY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC | QueueFuseable.BOUNDARY); Flowable.range(1, 5) .doFinally(this) .filter(Functions.alwaysTrue()) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -264,7 +264,7 @@ public void syncFusedBoundaryConditional() { @Test public void asyncFusedConditional() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ASYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ASYNC); UnicastProcessor up = UnicastProcessor.create(); TestHelper.emit(up, 1, 2, 3, 4, 5); @@ -274,7 +274,7 @@ public void asyncFusedConditional() { .filter(Functions.alwaysTrue()) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -282,7 +282,7 @@ public void asyncFusedConditional() { @Test public void asyncFusedBoundaryConditional() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ASYNC | QueueSubscription.BOUNDARY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ASYNC | QueueFuseable.BOUNDARY); UnicastProcessor up = UnicastProcessor.create(); TestHelper.emit(up, 1, 2, 3, 4, 5); @@ -292,7 +292,7 @@ public void asyncFusedBoundaryConditional() { .filter(Functions.alwaysTrue()) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -357,7 +357,7 @@ public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") QueueSubscription qs = (QueueSubscription)s; - qs.requestFusion(QueueSubscription.ANY); + qs.requestFusion(QueueFuseable.ANY); assertFalse(qs.isEmpty()); @@ -404,7 +404,7 @@ public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") QueueSubscription qs = (QueueSubscription)s; - qs.requestFusion(QueueSubscription.ANY); + qs.requestFusion(QueueFuseable.ANY); assertFalse(qs.isEmpty()); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java index d55c6be3a9..225859575e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java @@ -504,7 +504,7 @@ public void accept(Throwable e) throws Exception { @Test public void fused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); final int[] call = { 0, 0 }; @@ -524,7 +524,7 @@ public void run() throws Exception { .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(1, 2, 3, 4, 5); assertEquals(5, call[0]); @@ -533,7 +533,7 @@ public void run() throws Exception { @Test public void fusedOnErrorCrash() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); final int[] call = { 0 }; @@ -553,7 +553,7 @@ public void run() throws Exception { .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertFailure(TestException.class); assertEquals(0, call[0]); @@ -561,7 +561,7 @@ public void run() throws Exception { @Test public void fusedConditional() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); final int[] call = { 0, 0 }; @@ -582,7 +582,7 @@ public void run() throws Exception { .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(1, 2, 3, 4, 5); assertEquals(5, call[0]); @@ -591,7 +591,7 @@ public void run() throws Exception { @Test public void fusedOnErrorCrashConditional() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); final int[] call = { 0 }; @@ -612,7 +612,7 @@ public void run() throws Exception { .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertFailure(TestException.class); assertEquals(0, call[0]); @@ -620,7 +620,7 @@ public void run() throws Exception { @Test public void fusedAsync() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); final int[] call = { 0, 0 }; @@ -644,7 +644,7 @@ public void run() throws Exception { TestHelper.emit(up, 1, 2, 3, 4, 5); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2, 3, 4, 5); assertEquals(5, call[0]); @@ -653,7 +653,7 @@ public void run() throws Exception { @Test public void fusedAsyncConditional() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); final int[] call = { 0, 0 }; @@ -678,7 +678,7 @@ public void run() throws Exception { TestHelper.emit(up, 1, 2, 3, 4, 5); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2, 3, 4, 5); assertEquals(5, call[0]); @@ -687,7 +687,7 @@ public void run() throws Exception { @Test public void fusedAsyncConditional2() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); final int[] call = { 0, 0 }; @@ -712,7 +712,7 @@ public void run() throws Exception { TestHelper.emit(up, 1, 2, 3, 4, 5); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.NONE)) .assertResult(1, 2, 3, 4, 5); assertEquals(5, call[0]); @@ -736,7 +736,7 @@ public Flowable apply(Flowable o) throws Exception { @Test public void doOnNextDoOnErrorFused() { - ConnectableFlowable co = Flowable.just(1) + ConnectableFlowable cf = Flowable.just(1) .doOnNext(new Consumer() { @Override public void accept(Integer v) throws Exception { @@ -751,8 +751,8 @@ public void accept(Throwable e) throws Exception { }) .publish(); - TestSubscriber ts = co.test(); - co.connect(); + TestSubscriber ts = cf.test(); + cf.connect(); ts.assertFailure(CompositeException.class); @@ -762,7 +762,7 @@ public void accept(Throwable e) throws Exception { @Test public void doOnNextDoOnErrorCombinedFused() { - ConnectableFlowable co = Flowable.just(1) + ConnectableFlowable cf = Flowable.just(1) .compose(new FlowableTransformer() { @Override public Publisher apply(Flowable v) { @@ -787,8 +787,8 @@ public void accept(Throwable e) throws Exception { }) .publish(); - TestSubscriber ts = co.test(); - co.connect(); + TestSubscriber ts = cf.test(); + cf.connect(); ts.assertFailure(CompositeException.class); @@ -798,7 +798,7 @@ public void accept(Throwable e) throws Exception { @Test public void doOnNextDoOnErrorFused2() { - ConnectableFlowable co = Flowable.just(1) + ConnectableFlowable cf = Flowable.just(1) .doOnNext(new Consumer() { @Override public void accept(Integer v) throws Exception { @@ -819,8 +819,8 @@ public void accept(Throwable e) throws Exception { }) .publish(); - TestSubscriber ts = co.test(); - co.connect(); + TestSubscriber ts = cf.test(); + cf.connect(); ts.assertFailure(CompositeException.class); @@ -831,7 +831,7 @@ public void accept(Throwable e) throws Exception { @Test public void doOnNextDoOnErrorFusedConditional() { - ConnectableFlowable co = Flowable.just(1) + ConnectableFlowable cf = Flowable.just(1) .doOnNext(new Consumer() { @Override public void accept(Integer v) throws Exception { @@ -847,8 +847,8 @@ public void accept(Throwable e) throws Exception { .filter(Functions.alwaysTrue()) .publish(); - TestSubscriber ts = co.test(); - co.connect(); + TestSubscriber ts = cf.test(); + cf.connect(); ts.assertFailure(CompositeException.class); @@ -858,7 +858,7 @@ public void accept(Throwable e) throws Exception { @Test public void doOnNextDoOnErrorFusedConditional2() { - ConnectableFlowable co = Flowable.just(1) + ConnectableFlowable cf = Flowable.just(1) .doOnNext(new Consumer() { @Override public void accept(Integer v) throws Exception { @@ -880,8 +880,8 @@ public void accept(Throwable e) throws Exception { .filter(Functions.alwaysTrue()) .publish(); - TestSubscriber ts = co.test(); - co.connect(); + TestSubscriber ts = cf.test(); + cf.connect(); ts.assertFailure(CompositeException.class); @@ -892,7 +892,7 @@ public void accept(Throwable e) throws Exception { @Test public void doOnNextDoOnErrorCombinedFusedConditional() { - ConnectableFlowable co = Flowable.just(1) + ConnectableFlowable cf = Flowable.just(1) .compose(new FlowableTransformer() { @Override public Publisher apply(Flowable v) { @@ -918,8 +918,8 @@ public void accept(Throwable e) throws Exception { .filter(Functions.alwaysTrue()) .publish(); - TestSubscriber ts = co.test(); - co.connect(); + TestSubscriber ts = cf.test(); + cf.connect(); ts.assertFailure(CompositeException.class); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java index bda46e6ac1..836ead8bca 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java @@ -181,22 +181,22 @@ public void testFatalError() { @Test public void functionCrashUnsubscribes() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); TestSubscriber ts = new TestSubscriber(); - ps.filter(new Predicate() { + pp.filter(new Predicate() { @Override public boolean test(Integer v) { throw new TestException(); } }).subscribe(ts); - Assert.assertTrue("Not subscribed?", ps.hasSubscribers()); + Assert.assertTrue("Not subscribed?", pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - Assert.assertFalse("Subscribed?", ps.hasSubscribers()); + Assert.assertFalse("Subscribed?", pp.hasSubscribers()); ts.assertError(TestException.class); } @@ -245,7 +245,7 @@ public void conditionalNone2() { @Test public void conditionalFusedSync() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5) .filter(Functions.alwaysTrue()) @@ -253,13 +253,13 @@ public void conditionalFusedSync() { .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(1, 2, 3, 4, 5); } @Test public void conditionalFusedSync2() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5) .filter(Functions.alwaysFalse()) @@ -267,13 +267,13 @@ public void conditionalFusedSync2() { .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(); } @Test public void conditionalFusedAsync() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor up = UnicastProcessor.create(); @@ -290,13 +290,13 @@ public void conditionalFusedAsync() { up.onComplete(); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2, 3, 4, 5); } @Test public void conditionalFusedNoneAsync() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor up = UnicastProcessor.create(); @@ -313,13 +313,13 @@ public void conditionalFusedNoneAsync() { up.onComplete(); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(); } @Test public void conditionalFusedNoneAsync2() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor up = UnicastProcessor.create(); @@ -336,7 +336,7 @@ public void conditionalFusedNoneAsync2() { up.onComplete(); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(); } @@ -415,33 +415,33 @@ public boolean test(Integer v) throws Exception { @Test public void syncFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5) .filter(Functions.alwaysTrue()) .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(1, 2, 3, 4, 5); } @Test public void syncNoneFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5) .filter(Functions.alwaysFalse()) .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(); } @Test public void syncNoneFused2() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5) .filter(Functions.alwaysFalse()) @@ -449,7 +449,7 @@ public void syncNoneFused2() { .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(); } @@ -563,7 +563,7 @@ public Flowable apply(Flowable o) throws Exception { @Test public void fusedSync() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5) .filter(new Predicate() { @@ -572,15 +572,15 @@ public boolean test(Integer v) throws Exception { return v % 2 == 0; } }) - .subscribe(to); + .subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.SYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.SYNC) .assertResult(2, 4); } @Test public void fusedAsync() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor us = UnicastProcessor.create(); @@ -591,17 +591,17 @@ public boolean test(Integer v) throws Exception { return v % 2 == 0; } }) - .subscribe(to); + .subscribe(ts); TestHelper.emit(us, 1, 2, 3, 4, 5); - SubscriberFusion.assertFusion(to, QueueDisposable.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .assertResult(2, 4); } @Test public void fusedReject() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY | QueueDisposable.BOUNDARY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY | QueueFuseable.BOUNDARY); Flowable.range(1, 5) .filter(new Predicate() { @@ -610,9 +610,9 @@ public boolean test(Integer v) throws Exception { return v % 2 == 0; } }) - .subscribe(to); + .subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(2, 4); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java index d132f56f7b..3e7ea75c66 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java @@ -49,9 +49,9 @@ public CompletableSource apply(Integer v) throws Exception { @Test public void mapperThrowsFlowable() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber ts = pp .flatMapCompletable(new Function() { @Override public CompletableSource apply(Integer v) throws Exception { @@ -60,20 +60,20 @@ public CompletableSource apply(Integer v) throws Exception { }).toFlowable() .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - to.assertFailure(TestException.class); + ts.assertFailure(TestException.class); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test public void mapperReturnsNullFlowable() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber ts = pp .flatMapCompletable(new Function() { @Override public CompletableSource apply(Integer v) throws Exception { @@ -82,13 +82,13 @@ public CompletableSource apply(Integer v) throws Exception { }).toFlowable() .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - to.assertFailure(NullPointerException.class); + ts.assertFailure(NullPointerException.class); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test @@ -134,7 +134,7 @@ public CompletableSource apply(Integer v) throws Exception { @Test public void normalDelayErrorAllFlowable() { - TestSubscriber to = Flowable.range(1, 10).concatWith(Flowable.error(new TestException())) + TestSubscriber ts = Flowable.range(1, 10).concatWith(Flowable.error(new TestException())) .flatMapCompletable(new Function() { @Override public CompletableSource apply(Integer v) throws Exception { @@ -144,7 +144,7 @@ public CompletableSource apply(Integer v) throws Exception { .test() .assertFailure(CompositeException.class); - List errors = TestHelper.compositeList(to.errors().get(0)); + List errors = TestHelper.compositeList(ts.errors().get(0)); for (int i = 0; i < 11; i++) { TestHelper.assertError(errors, i, TestException.class); @@ -153,7 +153,7 @@ public CompletableSource apply(Integer v) throws Exception { @Test public void normalDelayInnerErrorAllFlowable() { - TestSubscriber to = Flowable.range(1, 10) + TestSubscriber ts = Flowable.range(1, 10) .flatMapCompletable(new Function() { @Override public CompletableSource apply(Integer v) throws Exception { @@ -163,7 +163,7 @@ public CompletableSource apply(Integer v) throws Exception { .test() .assertFailure(CompositeException.class); - List errors = TestHelper.compositeList(to.errors().get(0)); + List errors = TestHelper.compositeList(ts.errors().get(0)); for (int i = 0; i < 10; i++) { TestHelper.assertError(errors, i, TestException.class); @@ -186,7 +186,7 @@ public CompletableSource apply(Integer v) throws Exception { @Test public void fusedFlowable() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 10) .flatMapCompletable(new Function() { @@ -195,11 +195,11 @@ public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }).toFlowable() - .subscribe(to); + .subscribe(ts); - to + ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueDisposable.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(); } @@ -218,9 +218,9 @@ public CompletableSource apply(Integer v) throws Exception { @Test public void mapperThrows() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestObserver to = ps + TestObserver to = pp .flatMapCompletable(new Function() { @Override public CompletableSource apply(Integer v) throws Exception { @@ -229,20 +229,20 @@ public CompletableSource apply(Integer v) throws Exception { }) .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); to.assertFailure(TestException.class); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test public void mapperReturnsNull() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestObserver to = ps + TestObserver to = pp .flatMapCompletable(new Function() { @Override public CompletableSource apply(Integer v) throws Exception { @@ -251,13 +251,13 @@ public CompletableSource apply(Integer v) throws Exception { }) .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); to.assertFailure(NullPointerException.class); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test @@ -341,7 +341,7 @@ public CompletableSource apply(Integer v) throws Exception { @Test public void fused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 10) .flatMapCompletable(new Function() { @@ -355,7 +355,7 @@ public CompletableSource apply(Integer v) throws Exception { ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueDisposable.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java index 26762e7e4d..cee2e89628 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java @@ -123,9 +123,9 @@ public MaybeSource apply(Integer v) throws Exception { @Test public void mapperThrowsFlowable() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber ts = pp .flatMapMaybe(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -134,20 +134,20 @@ public MaybeSource apply(Integer v) throws Exception { }) .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - to.assertFailure(TestException.class); + ts.assertFailure(TestException.class); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test public void mapperReturnsNullFlowable() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber ts = pp .flatMapMaybe(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -156,18 +156,18 @@ public MaybeSource apply(Integer v) throws Exception { }) .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - to.assertFailure(NullPointerException.class); + ts.assertFailure(NullPointerException.class); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test public void normalDelayErrorAll() { - TestSubscriber to = Flowable.range(1, 10).concatWith(Flowable.error(new TestException())) + TestSubscriber ts = Flowable.range(1, 10).concatWith(Flowable.error(new TestException())) .flatMapMaybe(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -177,7 +177,7 @@ public MaybeSource apply(Integer v) throws Exception { .test() .assertFailure(CompositeException.class); - List errors = TestHelper.compositeList(to.errors().get(0)); + List errors = TestHelper.compositeList(ts.errors().get(0)); for (int i = 0; i < 11; i++) { TestHelper.assertError(errors, i, TestException.class); @@ -352,46 +352,46 @@ public MaybeSource apply(Integer v) throws Exception { @Test public void successError() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = Flowable.range(1, 2) + TestSubscriber ts = Flowable.range(1, 2) .flatMapMaybe(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { if (v == 2) { - return ps.singleElement(); + return pp.singleElement(); } return Maybe.error(new TestException()); } }, true, Integer.MAX_VALUE) .test(); - ps.onNext(1); - ps.onComplete(); + pp.onNext(1); + pp.onComplete(); - to + ts .assertFailure(TestException.class, 1); } @Test public void completeError() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = Flowable.range(1, 2) + TestSubscriber ts = Flowable.range(1, 2) .flatMapMaybe(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { if (v == 2) { - return ps.singleElement(); + return pp.singleElement(); } return Maybe.error(new TestException()); } }, true, Integer.MAX_VALUE) .test(); - ps.onComplete(); + pp.onComplete(); - to + ts .assertFailure(TestException.class); } @@ -451,72 +451,72 @@ protected void subscribeActual(MaybeObserver observer) { @Test public void emissionQueueTrigger() { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { - ps2.onNext(2); - ps2.onComplete(); + pp2.onNext(2); + pp2.onComplete(); } } }; - Flowable.just(ps1, ps2) + Flowable.just(pp1, pp2) .flatMapMaybe(new Function, MaybeSource>() { @Override public MaybeSource apply(PublishProcessor v) throws Exception { return v.singleElement(); } }) - .subscribe(to); + .subscribe(ts); - ps1.onNext(1); - ps1.onComplete(); + pp1.onNext(1); + pp1.onComplete(); - to.assertResult(1, 2); + ts.assertResult(1, 2); } @Test public void emissionQueueTrigger2() { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); - final PublishProcessor ps3 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); + final PublishProcessor pp3 = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { - ps2.onNext(2); - ps2.onComplete(); + pp2.onNext(2); + pp2.onComplete(); } } }; - Flowable.just(ps1, ps2, ps3) + Flowable.just(pp1, pp2, pp3) .flatMapMaybe(new Function, MaybeSource>() { @Override public MaybeSource apply(PublishProcessor v) throws Exception { return v.singleElement(); } }) - .subscribe(to); + .subscribe(ts); - ps1.onNext(1); - ps1.onComplete(); + pp1.onNext(1); + pp1.onComplete(); - ps3.onComplete(); + pp3.onComplete(); - to.assertResult(1, 2); + ts.assertResult(1, 2); } @Test public void disposeInner() { - final TestSubscriber to = new TestSubscriber(); + final TestSubscriber ts = new TestSubscriber(); Flowable.just(1).flatMapMaybe(new Function>() { @Override @@ -528,30 +528,30 @@ protected void subscribeActual(MaybeObserver observer) { assertFalse(((Disposable)observer).isDisposed()); - to.dispose(); + ts.dispose(); assertTrue(((Disposable)observer).isDisposed()); } }; } }) - .subscribe(to); + .subscribe(ts); - to + ts .assertEmpty(); } @Test public void innerSuccessCompletesAfterMain() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = Flowable.just(1).flatMapMaybe(Functions.justFunction(ps.singleElement())) + TestSubscriber ts = Flowable.just(1).flatMapMaybe(Functions.justFunction(pp.singleElement())) .test(); - ps.onNext(2); - ps.onComplete(); + pp.onNext(2); + pp.onComplete(); - to + ts .assertResult(2); } @@ -585,19 +585,19 @@ public void errorDelayed() { @Test public void requestCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final TestSubscriber to = Flowable.just(1).concatWith(Flowable.never()) + final TestSubscriber ts = Flowable.just(1).concatWith(Flowable.never()) .flatMapMaybe(Functions.justFunction(Maybe.just(2))).test(0); Runnable r1 = new Runnable() { @Override public void run() { - to.request(1); + ts.request(1); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java index 14a0dfa569..78217c9330 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java @@ -110,9 +110,9 @@ public SingleSource apply(Integer v) throws Exception { @Test public void mapperThrowsFlowable() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber ts = pp .flatMapSingle(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -121,20 +121,20 @@ public SingleSource apply(Integer v) throws Exception { }) .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - to.assertFailure(TestException.class); + ts.assertFailure(TestException.class); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test public void mapperReturnsNullFlowable() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps + TestSubscriber ts = pp .flatMapSingle(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -143,18 +143,18 @@ public SingleSource apply(Integer v) throws Exception { }) .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - to.assertFailure(NullPointerException.class); + ts.assertFailure(NullPointerException.class); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test public void normalDelayErrorAll() { - TestSubscriber to = Flowable.range(1, 10).concatWith(Flowable.error(new TestException())) + TestSubscriber ts = Flowable.range(1, 10).concatWith(Flowable.error(new TestException())) .flatMapSingle(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -164,7 +164,7 @@ public SingleSource apply(Integer v) throws Exception { .test() .assertFailure(CompositeException.class); - List errors = TestHelper.compositeList(to.errors().get(0)); + List errors = TestHelper.compositeList(ts.errors().get(0)); for (int i = 0; i < 11; i++) { TestHelper.assertError(errors, i, TestException.class); @@ -284,24 +284,24 @@ public SingleSource apply(Integer v) throws Exception { @Test public void successError() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = Flowable.range(1, 2) + TestSubscriber ts = Flowable.range(1, 2) .flatMapSingle(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { if (v == 2) { - return ps.singleOrError(); + return pp.singleOrError(); } return Single.error(new TestException()); } }, true, Integer.MAX_VALUE) .test(); - ps.onNext(1); - ps.onComplete(); + pp.onNext(1); + pp.onComplete(); - to + ts .assertFailure(TestException.class, 1); } @@ -371,38 +371,38 @@ protected void subscribeActual(SingleObserver observer) { @Test public void emissionQueueTrigger() { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { - ps2.onNext(2); - ps2.onComplete(); + pp2.onNext(2); + pp2.onComplete(); } } }; - Flowable.just(ps1, ps2) + Flowable.just(pp1, pp2) .flatMapSingle(new Function, SingleSource>() { @Override public SingleSource apply(PublishProcessor v) throws Exception { return v.singleOrError(); } }) - .subscribe(to); + .subscribe(ts); - ps1.onNext(1); - ps1.onComplete(); + pp1.onNext(1); + pp1.onComplete(); - to.assertResult(1, 2); + ts.assertResult(1, 2); } @Test public void disposeInner() { - final TestSubscriber to = new TestSubscriber(); + final TestSubscriber ts = new TestSubscriber(); Flowable.just(1).flatMapSingle(new Function>() { @Override @@ -414,30 +414,30 @@ protected void subscribeActual(SingleObserver observer) { assertFalse(((Disposable)observer).isDisposed()); - to.dispose(); + ts.dispose(); assertTrue(((Disposable)observer).isDisposed()); } }; } }) - .subscribe(to); + .subscribe(ts); - to + ts .assertEmpty(); } @Test public void innerSuccessCompletesAfterMain() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = Flowable.just(1).flatMapSingle(Functions.justFunction(ps.singleOrError())) + TestSubscriber ts = Flowable.just(1).flatMapSingle(Functions.justFunction(pp.singleOrError())) .test(); - ps.onNext(2); - ps.onComplete(); + pp.onNext(2); + pp.onComplete(); - to + ts .assertResult(2); } @@ -471,19 +471,19 @@ public void errorDelayed() { @Test public void requestCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final TestSubscriber to = Flowable.just(1).concatWith(Flowable.never()) + final TestSubscriber ts = Flowable.just(1).concatWith(Flowable.never()) .flatMapSingle(Functions.justFunction(Single.just(2))).test(0); Runnable r1 = new Runnable() { @Override public void run() { - to.request(1); + ts.request(1); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index 9e53cbe70a..9b3037a4c2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -656,11 +656,11 @@ public Flowable apply(Integer v) { @Test public void castCrashUnsubscribes() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); TestSubscriber ts = TestSubscriber.create(); - ps.flatMap(new Function>() { + pp.flatMap(new Function>() { @Override public Publisher apply(Integer t) { throw new TestException(); @@ -672,11 +672,11 @@ public Integer apply(Integer t1, Integer t2) { } }).subscribe(ts); - Assert.assertTrue("Not subscribed?", ps.hasSubscribers()); + Assert.assertTrue("Not subscribed?", pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - Assert.assertFalse("Subscribed?", ps.hasSubscribers()); + Assert.assertFalse("Subscribed?", pp.hasSubscribers()); ts.assertError(TestException.class); } @@ -780,68 +780,68 @@ public Object call() throws Exception { @Test public void scalarReentrant() { - final PublishProcessor> ps = PublishProcessor.create(); + final PublishProcessor> pp = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { - ps.onNext(Flowable.just(2)); + pp.onNext(Flowable.just(2)); } } }; - Flowable.merge(ps) - .subscribe(to); + Flowable.merge(pp) + .subscribe(ts); - ps.onNext(Flowable.just(1)); - ps.onComplete(); + pp.onNext(Flowable.just(1)); + pp.onComplete(); - to.assertResult(1, 2); + ts.assertResult(1, 2); } @Test public void scalarReentrant2() { - final PublishProcessor> ps = PublishProcessor.create(); + final PublishProcessor> pp = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { - ps.onNext(Flowable.just(2)); + pp.onNext(Flowable.just(2)); } } }; - Flowable.merge(ps, 2) - .subscribe(to); + Flowable.merge(pp, 2) + .subscribe(ts); - ps.onNext(Flowable.just(1)); - ps.onComplete(); + pp.onNext(Flowable.just(1)); + pp.onComplete(); - to.assertResult(1, 2); + ts.assertResult(1, 2); } @Test public void innerCompleteCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final TestSubscriber to = Flowable.merge(Flowable.just(ps)).test(); + final TestSubscriber ts = Flowable.merge(Flowable.just(pp)).test(); Runnable r1 = new Runnable() { @Override public void run() { - ps.onComplete(); + pp.onComplete(); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; @@ -870,7 +870,7 @@ public Object apply(Integer w) throws Exception { @Test public void fusedInnerThrows2() { - TestSubscriber to = Flowable.range(1, 2).hide() + TestSubscriber ts = Flowable.range(1, 2).hide() .flatMap(new Function>() { @Override public Flowable apply(Integer v) throws Exception { @@ -885,7 +885,7 @@ public Integer apply(Integer w) throws Exception { .test() .assertFailure(CompositeException.class); - List errors = TestHelper.errorList(to); + List errors = TestHelper.errorList(ts); TestHelper.assertError(errors, 0, TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java index b4cb5b5f5f..8448e1db06 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java @@ -26,7 +26,7 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.operators.flowable.FlowableFlattenIterable.FlattenIterableSubscriber; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.internal.util.ExceptionHelper; @@ -395,9 +395,9 @@ public void remove() { } }; - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps + pp .concatMapIterable(new Function>() { @Override public Iterable apply(Integer v) { @@ -406,13 +406,13 @@ public Iterable apply(Integer v) { }) .subscribe(ts); - ps.onNext(1); + pp.onNext(1); ts.assertNoValues(); ts.assertError(TestException.class); ts.assertNotComplete(); - Assert.assertFalse("PublishProcessor has Subscribers?!", ps.hasSubscribers()); + Assert.assertFalse("PublishProcessor has Subscribers?!", pp.hasSubscribers()); } @Test @@ -498,9 +498,9 @@ public void remove() { } }; - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps + pp .concatMapIterable(new Function>() { @Override public Iterable apply(Integer v) { @@ -510,13 +510,13 @@ public Iterable apply(Integer v) { .take(1) .subscribe(ts); - ps.onNext(1); + pp.onNext(1); ts.assertValue(1); ts.assertNoErrors(); ts.assertComplete(); - Assert.assertFalse("PublishProcessor has Subscribers?!", ps.hasSubscribers()); + Assert.assertFalse("PublishProcessor has Subscribers?!", pp.hasSubscribers()); Assert.assertEquals(1, counter.get()); } @@ -617,7 +617,7 @@ public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") QueueSubscription qs = (QueueSubscription)s; - assertEquals(QueueSubscription.SYNC, qs.requestFusion(QueueSubscription.ANY)); + assertEquals(QueueFuseable.SYNC, qs.requestFusion(QueueFuseable.ANY)); try { assertFalse("Source reports being empty!", qs.isEmpty()); @@ -672,7 +672,7 @@ public void smallPrefetch2() { @Test public void mixedInnerSource() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.just(1, 2, 3) .flatMapIterable(new Function>() { @@ -686,13 +686,13 @@ public Iterable apply(Integer v) throws Exception { }) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.SYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.SYNC) .assertResult(1, 2, 1, 2); } @Test public void mixedInnerSource2() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.just(1, 2, 3) .flatMapIterable(new Function>() { @@ -706,13 +706,13 @@ public Iterable apply(Integer v) throws Exception { }) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.SYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.SYNC) .assertResult(1, 2); } @Test public void fusionRejected() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.just(1, 2, 3).hide() .flatMapIterable(new Function>() { @@ -723,7 +723,7 @@ public Iterable apply(Integer v) throws Exception { }) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2, 1, 2, 1, 2); } @@ -745,7 +745,7 @@ public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") QueueSubscription qs = (QueueSubscription)s; - assertEquals(QueueSubscription.SYNC, qs.requestFusion(QueueSubscription.ANY)); + assertEquals(QueueFuseable.SYNC, qs.requestFusion(QueueFuseable.ANY)); try { assertFalse("Source reports being empty!", qs.isEmpty()); @@ -1085,16 +1085,16 @@ public void fusionRequestedState() throws Exception { f.onSubscribe(new BooleanSubscription()); - f.fusionMode = QueueSubscription.NONE; + f.fusionMode = QueueFuseable.NONE; - assertEquals(QueueSubscription.NONE, f.requestFusion(QueueSubscription.SYNC)); + assertEquals(QueueFuseable.NONE, f.requestFusion(QueueFuseable.SYNC)); - assertEquals(QueueSubscription.NONE, f.requestFusion(QueueSubscription.ASYNC)); + assertEquals(QueueFuseable.NONE, f.requestFusion(QueueFuseable.ASYNC)); - f.fusionMode = QueueSubscription.SYNC; + f.fusionMode = QueueFuseable.SYNC; - assertEquals(QueueSubscription.SYNC, f.requestFusion(QueueSubscription.SYNC)); + assertEquals(QueueFuseable.SYNC, f.requestFusion(QueueFuseable.SYNC)); - assertEquals(QueueSubscription.NONE, f.requestFusion(QueueSubscription.ASYNC)); + assertEquals(QueueFuseable.NONE, f.requestFusion(QueueFuseable.ASYNC)); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java index 7a23049928..f606ee6eb4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java @@ -551,7 +551,7 @@ public void remove() { @Test public void fusionWithConcatMap() { - TestSubscriber to = new TestSubscriber(); + TestSubscriber ts = new TestSubscriber(); Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)).concatMap( new Function>() { @@ -559,11 +559,11 @@ public void fusionWithConcatMap() { public Flowable apply(Integer v) { return Flowable.range(v, 2); } - }).subscribe(to); + }).subscribe(ts); - to.assertValues(1, 2, 2, 3, 3, 4, 4, 5); - to.assertNoErrors(); - to.assertComplete(); + ts.assertValues(1, 2, 2, 3, 3, 4, 4, 5); + ts.assertNoErrors(); + ts.assertComplete(); } @Test @@ -868,12 +868,12 @@ public void run() { @Test public void fusionRejected() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ASYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ASYNC); Flowable.fromIterable(Arrays.asList(1, 2, 3)) - .subscribe(to); + .subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2, 3); } @@ -886,7 +886,7 @@ public void onSubscribe(Subscription d) { @SuppressWarnings("unchecked") QueueSubscription qd = (QueueSubscription)d; - qd.requestFusion(QueueSubscription.ANY); + qd.requestFusion(QueueFuseable.ANY); try { assertEquals(1, qd.poll().intValue()); @@ -932,7 +932,7 @@ public void hasNext2Throws() { @Test public void hasNextCancels() { - final TestSubscriber to = new TestSubscriber(); + final TestSubscriber ts = new TestSubscriber(); Flowable.fromIterable(new Iterable() { @Override @@ -943,7 +943,7 @@ public Iterator iterator() { @Override public boolean hasNext() { if (++count == 2) { - to.cancel(); + ts.cancel(); } return true; } @@ -960,9 +960,9 @@ public void remove() { }; } }) - .subscribe(to); + .subscribe(ts); - to.assertValue(1) + ts.assertValue(1) .assertNoErrors() .assertNotComplete(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index e5a18c80af..3e6dcca7ac 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -22,24 +22,22 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; -import io.reactivex.subjects.PublishSubject; import org.junit.Test; import org.mockito.Mockito; import org.reactivestreams.*; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.RemovalListener; -import com.google.common.cache.RemovalNotification; +import com.google.common.cache.*; import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.flowables.GroupedFlowable; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; +import io.reactivex.subjects.PublishSubject; import io.reactivex.subscribers.*; public class FlowableGroupByTest { @@ -1604,9 +1602,9 @@ public void accept(GroupedFlowable g) { @Test public void outerInnerFusion() { - final TestSubscriber ts1 = SubscriberFusion.newTest(QueueSubscription.ANY); + final TestSubscriber ts1 = SubscriberFusion.newTest(QueueFuseable.ANY); - final TestSubscriber> ts2 = SubscriberFusion.newTest(QueueSubscription.ANY); + final TestSubscriber> ts2 = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 10).groupBy(new Function() { @Override @@ -1628,13 +1626,13 @@ public void accept(GroupedFlowable g) { .subscribe(ts2); ts1 - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertValues(2, 3, 4, 5, 6, 7, 8, 9, 10, 11) .assertNoErrors() .assertComplete(); ts2 - .assertOf(SubscriberFusion.>assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.>assertFusionMode(QueueFuseable.ASYNC)) .assertValueCount(1) .assertNoErrors() .assertComplete(); @@ -1686,47 +1684,47 @@ public void accept(GroupedFlowable g) throws Exception { @Test public void reentrantComplete() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { - ps.onComplete(); + pp.onComplete(); } } }; - Flowable.merge(ps.groupBy(Functions.justFunction(1))) - .subscribe(to); + Flowable.merge(pp.groupBy(Functions.justFunction(1))) + .subscribe(ts); - ps.onNext(1); + pp.onNext(1); - to.assertResult(1); + ts.assertResult(1); } @Test public void reentrantCompleteCancel() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { - ps.onComplete(); + pp.onComplete(); dispose(); } } }; - Flowable.merge(ps.groupBy(Functions.justFunction(1))) - .subscribe(to); + Flowable.merge(pp.groupBy(Functions.justFunction(1))) + .subscribe(ts); - ps.onNext(1); + pp.onNext(1); - to.assertSubscribed().assertValue(1).assertNoErrors().assertNotComplete(); + ts.assertSubscribed().assertValue(1).assertNoErrors().assertNotComplete(); } @Test @@ -1740,13 +1738,13 @@ public void delayErrorSimpleComplete() { @Test public void mainFusionRejected() { - TestSubscriber> ts = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber> ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Flowable.just(1) .groupBy(Functions.justFunction(1)) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertValueCount(1) .assertComplete() .assertNoErrors(); @@ -1799,25 +1797,25 @@ public Publisher apply(GroupedFlowable g) throws Excep @Test public void errorFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.error(new TestException()) .groupBy(Functions.justFunction(1)) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .assertFailure(TestException.class); } @Test public void errorFusedDelayed() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.error(new TestException()) .groupBy(Functions.justFunction(1), true) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .assertFailure(TestException.class); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java index 9bc958c730..0d27bc2280 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java @@ -508,25 +508,25 @@ public Flowable apply(Integer r, Flowable l) throws Exception @Test public void innerErrorRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); List errors = TestHelper.trackPluginErrors(); try { - TestSubscriber> to = Flowable.just(1) + TestSubscriber> ts = Flowable.just(1) .groupJoin( Flowable.just(2).concatWith(Flowable.never()), new Function>() { @Override public Flowable apply(Integer left) throws Exception { - return ps1; + return pp1; } }, new Function>() { @Override public Flowable apply(Integer right) throws Exception { - return ps2; + return pp2; } }, new BiFunction, Flowable>() { @@ -544,28 +544,28 @@ public Flowable apply(Integer r, Flowable l) throws Exception Runnable r1 = new Runnable() { @Override public void run() { - ps1.onError(ex1); + pp1.onError(ex1); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps2.onError(ex2); + pp2.onError(ex2); } }; TestHelper.race(r1, r2); - to.assertError(Throwable.class).assertSubscribed().assertNotComplete().assertValueCount(1); + ts.assertError(Throwable.class).assertSubscribed().assertNotComplete().assertValueCount(1); - Throwable exc = to.errors().get(0); + Throwable exc = ts.errors().get(0); if (exc instanceof CompositeException) { List es = TestHelper.compositeList(exc); TestHelper.assertError(es, 0, TestException.class); TestHelper.assertError(es, 1, TestException.class); } else { - to.assertError(TestException.class); + ts.assertError(TestException.class); } if (!errors.isEmpty()) { @@ -580,15 +580,15 @@ public void run() { @Test public void outerErrorRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); List errors = TestHelper.trackPluginErrors(); try { - TestSubscriber to = ps1 + TestSubscriber ts = pp1 .groupJoin( - ps2, + pp2, new Function>() { @Override public Flowable apply(Object left) throws Exception { @@ -617,28 +617,28 @@ public Flowable apply(Object r, Flowable l) throws Exception { Runnable r1 = new Runnable() { @Override public void run() { - ps1.onError(ex1); + pp1.onError(ex1); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps2.onError(ex2); + pp2.onError(ex2); } }; TestHelper.race(r1, r2); - to.assertError(Throwable.class).assertSubscribed().assertNotComplete().assertNoValues(); + ts.assertError(Throwable.class).assertSubscribed().assertNotComplete().assertNoValues(); - Throwable exc = to.errors().get(0); + Throwable exc = ts.errors().get(0); if (exc instanceof CompositeException) { List es = TestHelper.compositeList(exc); TestHelper.assertError(es, 0, TestException.class); TestHelper.assertError(es, 1, TestException.class); } else { - to.assertError(TestException.class); + ts.assertError(TestException.class); } if (!errors.isEmpty()) { @@ -652,12 +652,12 @@ public void run() { @Test public void rightEmission() { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); - TestSubscriber to = ps1 + TestSubscriber ts = pp1 .groupJoin( - ps2, + pp2, new Function>() { @Override public Flowable apply(Object left) throws Exception { @@ -680,14 +680,14 @@ public Flowable apply(Object r, Flowable l) throws Exception { .flatMap(Functions.>identity()) .test(); - ps2.onNext(2); + pp2.onNext(2); - ps1.onNext(1); - ps1.onComplete(); + pp1.onNext(1); + pp1.onComplete(); - ps2.onComplete(); + pp2.onComplete(); - to.assertResult(2); + ts.assertResult(2); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java index 4c07e86ffb..6d2d42aeaf 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java @@ -18,12 +18,12 @@ import java.util.concurrent.atomic.*; import org.junit.Test; -import org.reactivestreams.*; +import org.reactivestreams.Subscription; import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; import io.reactivex.processors.PublishProcessor; import io.reactivex.subscribers.*; @@ -174,22 +174,22 @@ public void accept(Integer t) { @Test public void testCompletedOk() { - TestObserver ts = new TestObserver(); - Flowable.range(1, 10).ignoreElements().subscribe(ts); - ts.assertNoErrors(); - ts.assertNoValues(); - ts.assertTerminated(); + TestObserver to = new TestObserver(); + Flowable.range(1, 10).ignoreElements().subscribe(to); + to.assertNoErrors(); + to.assertNoValues(); + to.assertTerminated(); } @Test public void testErrorReceived() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); TestException ex = new TestException("boo"); - Flowable.error(ex).ignoreElements().subscribe(ts); - ts.assertNoValues(); - ts.assertTerminated(); - ts.assertError(TestException.class); - ts.assertErrorMessage("boo"); + Flowable.error(ex).ignoreElements().subscribe(to); + to.assertNoValues(); + to.assertTerminated(); + to.assertError(TestException.class); + to.assertErrorMessage("boo"); } @Test @@ -252,13 +252,13 @@ public void cancel() { @Test public void fused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.just(1).hide().ignoreElements().toFlowable() .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java index a1512f577b..a44b07608f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java @@ -339,9 +339,9 @@ public Integer apply(Integer a, Integer b) throws Exception { @Test public void rightClose() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps.join(Flowable.just(2), + TestSubscriber ts = pp.join(Flowable.just(2), Functions.justFunction(Flowable.never()), Functions.justFunction(Flowable.empty()), new BiFunction() { @@ -353,16 +353,16 @@ public Integer apply(Integer a, Integer b) throws Exception { .test() .assertEmpty(); - ps.onNext(1); + pp.onNext(1); - to.assertEmpty(); + ts.assertEmpty(); } @Test public void resultSelectorThrows2() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps.join( + TestSubscriber ts = pp.join( Flowable.just(2), Functions.justFunction(Flowable.never()), Functions.justFunction(Flowable.never()), @@ -374,10 +374,10 @@ public Integer apply(Integer a, Integer b) throws Exception { }) .test(); - ps.onNext(1); - ps.onComplete(); + pp.onNext(1); + pp.onComplete(); - to.assertFailure(TestException.class); + ts.assertFailure(TestException.class); } @Test @@ -417,7 +417,7 @@ public void badEndSource() { @SuppressWarnings("rawtypes") final Subscriber[] o = { null }; - TestSubscriber to = Flowable.just(1) + TestSubscriber ts = Flowable.just(1) .join(Flowable.just(2), Functions.justFunction(Flowable.never()), Functions.justFunction(new Flowable() { @@ -438,7 +438,7 @@ public Integer apply(Integer a, Integer b) throws Exception { o[0].onError(new TestException("Second")); - to + ts .assertFailureAndMessage(TestException.class, "First"); TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second"); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapNotificationTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapNotificationTest.java index 287b83fb59..245fb9b581 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapNotificationTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapNotificationTest.java @@ -104,9 +104,9 @@ public Integer call() { public void noBackpressure() { TestSubscriber ts = TestSubscriber.create(0L); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - new FlowableMapNotification(ps, + new FlowableMapNotification(pp, new Function() { @Override public Integer apply(Integer item) { @@ -131,10 +131,10 @@ public Integer call() { ts.assertNoErrors(); ts.assertNotComplete(); - ps.onNext(1); - ps.onNext(2); - ps.onNext(3); - ps.onComplete(); + pp.onNext(1); + pp.onNext(2); + pp.onNext(3); + pp.onComplete(); ts.assertNoValues(); ts.assertNoErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java index e74f5bc961..20022bf843 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java @@ -339,22 +339,22 @@ public void verifyExceptionIsThrownIfThereIsNoExceptionHandler() { @Test public void functionCrashUnsubscribes() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); TestSubscriber ts = new TestSubscriber(); - ps.map(new Function() { + pp.map(new Function() { @Override public Integer apply(Integer v) { throw new TestException(); } }).subscribe(ts); - Assert.assertTrue("Not subscribed?", ps.hasSubscribers()); + Assert.assertTrue("Not subscribed?", pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - Assert.assertFalse("Subscribed?", ps.hasSubscribers()); + Assert.assertFalse("Subscribed?", pp.hasSubscribers()); ts.assertError(TestException.class); } @@ -418,7 +418,7 @@ public boolean test(Integer v) throws Exception { @Test public void mapFilterFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 2) .map(new Function() { @@ -436,13 +436,13 @@ public boolean test(Integer v) throws Exception { .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(2, 3); } @Test public void mapFilterFusedHidden() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 2).hide() .map(new Function() { @@ -460,7 +460,7 @@ public boolean test(Integer v) throws Exception { .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.NONE)) .assertResult(2, 3); } @@ -496,7 +496,7 @@ public Object apply(Integer v) throws Exception { @Test public void mapFilterMapperCrashFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 2).hide() .map(new Function() { @@ -514,7 +514,7 @@ public boolean test(Integer v) throws Exception { .subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.NONE)) .assertFailure(TestException.class); } @@ -556,7 +556,7 @@ public boolean test(Integer v) throws Exception { @Test public void mapFilterFused2() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor up = UnicastProcessor.create(); @@ -580,7 +580,7 @@ public boolean test(Integer v) throws Exception { up.onComplete(); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(2, 3); } @@ -638,41 +638,41 @@ public Flowable apply(Flowable o) throws Exception { @Test public void fusedSync() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5) .map(Functions.identity()) - .subscribe(to); + .subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.SYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); } @Test public void fusedAsync() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor us = UnicastProcessor.create(); us .map(Functions.identity()) - .subscribe(to); + .subscribe(ts); TestHelper.emit(us, 1, 2, 3, 4, 5); - SubscriberFusion.assertFusion(to, QueueDisposable.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); } @Test public void fusedReject() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY | QueueDisposable.BOUNDARY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY | QueueFuseable.BOUNDARY); Flowable.range(1, 5) .map(Functions.identity()) - .subscribe(to); + .subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java index fd4a8a9a21..d9be86f909 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java @@ -604,22 +604,22 @@ public void mergeIterable() { public void iterableMaxConcurrent() { TestSubscriber ts = TestSubscriber.create(); - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Flowable.mergeDelayError(Arrays.asList(ps1, ps2), 1).subscribe(ts); + Flowable.mergeDelayError(Arrays.asList(pp1, pp2), 1).subscribe(ts); - assertTrue("ps1 has no subscribers?!", ps1.hasSubscribers()); - assertFalse("ps2 has subscribers?!", ps2.hasSubscribers()); + assertTrue("ps1 has no subscribers?!", pp1.hasSubscribers()); + assertFalse("ps2 has subscribers?!", pp2.hasSubscribers()); - ps1.onNext(1); - ps1.onComplete(); + pp1.onNext(1); + pp1.onComplete(); - assertFalse("ps1 has subscribers?!", ps1.hasSubscribers()); - assertTrue("ps2 has no subscribers?!", ps2.hasSubscribers()); + assertFalse("ps1 has subscribers?!", pp1.hasSubscribers()); + assertTrue("ps2 has no subscribers?!", pp2.hasSubscribers()); - ps2.onNext(2); - ps2.onComplete(); + pp2.onNext(2); + pp2.onComplete(); ts.assertValues(1, 2); ts.assertNoErrors(); @@ -631,22 +631,22 @@ public void iterableMaxConcurrent() { public void iterableMaxConcurrentError() { TestSubscriber ts = TestSubscriber.create(); - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Flowable.mergeDelayError(Arrays.asList(ps1, ps2), 1).subscribe(ts); + Flowable.mergeDelayError(Arrays.asList(pp1, pp2), 1).subscribe(ts); - assertTrue("ps1 has no subscribers?!", ps1.hasSubscribers()); - assertFalse("ps2 has subscribers?!", ps2.hasSubscribers()); + assertTrue("ps1 has no subscribers?!", pp1.hasSubscribers()); + assertFalse("ps2 has subscribers?!", pp2.hasSubscribers()); - ps1.onNext(1); - ps1.onError(new TestException()); + pp1.onNext(1); + pp1.onError(new TestException()); - assertFalse("ps1 has subscribers?!", ps1.hasSubscribers()); - assertTrue("ps2 has no subscribers?!", ps2.hasSubscribers()); + assertFalse("ps1 has subscribers?!", pp1.hasSubscribers()); + assertTrue("ps2 has no subscribers?!", pp2.hasSubscribers()); - ps2.onNext(2); - ps2.onError(new TestException()); + pp2.onNext(2); + pp2.onError(new TestException()); ts.assertValues(1, 2); ts.assertError(CompositeException.class); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java index e4e68f3922..085b9d1720 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java @@ -1494,22 +1494,22 @@ public void mergeMany() throws Exception { public void mergeArrayMaxConcurrent() { TestSubscriber ts = TestSubscriber.create(); - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); - Flowable.mergeArray(1, 128, new Flowable[] { ps1, ps2 }).subscribe(ts); + Flowable.mergeArray(1, 128, new Flowable[] { pp1, pp2 }).subscribe(ts); - assertTrue("ps1 has no subscribers?!", ps1.hasSubscribers()); - assertFalse("ps2 has subscribers?!", ps2.hasSubscribers()); + assertTrue("ps1 has no subscribers?!", pp1.hasSubscribers()); + assertFalse("ps2 has subscribers?!", pp2.hasSubscribers()); - ps1.onNext(1); - ps1.onComplete(); + pp1.onNext(1); + pp1.onComplete(); - assertFalse("ps1 has subscribers?!", ps1.hasSubscribers()); - assertTrue("ps2 has no subscribers?!", ps2.hasSubscribers()); + assertFalse("ps1 has subscribers?!", pp1.hasSubscribers()); + assertTrue("ps2 has no subscribers?!", pp2.hasSubscribers()); - ps2.onNext(2); - ps2.onComplete(); + pp2.onNext(2); + pp2.onComplete(); ts.assertValues(1, 2); ts.assertNoErrors(); @@ -1571,15 +1571,15 @@ public void noInnerReordering() { new FlowableFlatMap.MergeSubscriber, Integer>(ts, Functions.>identity(), false, 128, 128); ms.onSubscribe(new BooleanSubscription()); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ms.onNext(ps); + ms.onNext(pp); - ps.onNext(1); + pp.onNext(1); BackpressureHelper.add(ms.requested, 2); - ps.onNext(2); + pp.onNext(2); ms.drain(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java index dab9f09e72..3344a30a65 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java @@ -1006,7 +1006,7 @@ public void cancelCleanup() { @Test public void conditionalConsumerFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5) .observeOn(Schedulers.single()) @@ -1020,14 +1020,14 @@ public boolean test(Integer v) throws Exception { ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .awaitDone(5, TimeUnit.SECONDS) .assertResult(2, 4); } @Test public void conditionalConsumerFusedReject() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Flowable.range(1, 5) .observeOn(Schedulers.single()) @@ -1041,7 +1041,7 @@ public boolean test(Integer v) throws Exception { ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.NONE)) .awaitDone(5, TimeUnit.SECONDS) .assertResult(2, 4); } @@ -1071,7 +1071,7 @@ public void requestOneConditional() throws Exception { @Test public void conditionalConsumerFusedAsync() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor up = UnicastProcessor.create(); @@ -1094,14 +1094,14 @@ public boolean test(Integer v) throws Exception { ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .awaitDone(5, TimeUnit.SECONDS) .assertResult(2, 4); } @Test public void conditionalConsumerHidden() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5).hide() .observeOn(Schedulers.single()) @@ -1115,14 +1115,14 @@ public boolean test(Integer v) throws Exception { ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .awaitDone(5, TimeUnit.SECONDS) .assertResult(2, 4); } @Test public void conditionalConsumerBarrier() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5) .map(Functions.identity()) @@ -1137,7 +1137,7 @@ public boolean test(Integer v) throws Exception { ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .awaitDone(5, TimeUnit.SECONDS) .assertResult(2, 4); } @@ -1162,7 +1162,7 @@ public void badSource() { List errors = TestHelper.trackPluginErrors(); try { TestScheduler scheduler = new TestScheduler(); - TestSubscriber to = new Flowable() { + TestSubscriber ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -1177,7 +1177,7 @@ protected void subscribeActual(Subscriber observer) { scheduler.triggerActions(); - to.assertResult(); + ts.assertResult(); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { @@ -1198,11 +1198,11 @@ public void inputSyncFused() { public void inputAsyncFused() { UnicastProcessor us = UnicastProcessor.create(); - TestSubscriber to = us.observeOn(Schedulers.single()).test(); + TestSubscriber ts = us.observeOn(Schedulers.single()).test(); TestHelper.emit(us, 1, 2, 3, 4, 5); - to + ts .awaitDone(5, TimeUnit.SECONDS) .assertResult(1, 2, 3, 4, 5); } @@ -1211,11 +1211,11 @@ public void inputAsyncFused() { public void inputAsyncFusedError() { UnicastProcessor us = UnicastProcessor.create(); - TestSubscriber to = us.observeOn(Schedulers.single()).test(); + TestSubscriber ts = us.observeOn(Schedulers.single()).test(); us.onError(new TestException()); - to + ts .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @@ -1224,77 +1224,77 @@ public void inputAsyncFusedError() { public void inputAsyncFusedErrorDelayed() { UnicastProcessor us = UnicastProcessor.create(); - TestSubscriber to = us.observeOn(Schedulers.single(), true).test(); + TestSubscriber ts = us.observeOn(Schedulers.single(), true).test(); us.onError(new TestException()); - to + ts .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test public void outputFused() { - TestSubscriber to = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 5).hide() .observeOn(Schedulers.single()) - .subscribe(to); + .subscribe(ts); - SubscriberFusion.assertFusion(to, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .awaitDone(5, TimeUnit.SECONDS) .assertResult(1, 2, 3, 4, 5); } @Test public void outputFusedReject() { - TestSubscriber to = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Flowable.range(1, 5).hide() .observeOn(Schedulers.single()) - .subscribe(to); + .subscribe(ts); - SubscriberFusion.assertFusion(to, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .awaitDone(5, TimeUnit.SECONDS) .assertResult(1, 2, 3, 4, 5); } @Test public void inputOutputAsyncFusedError() { - TestSubscriber to = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor us = UnicastProcessor.create(); us.observeOn(Schedulers.single()) - .subscribe(to); + .subscribe(ts); us.onError(new TestException()); - to + ts .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); - SubscriberFusion.assertFusion(to, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test public void inputOutputAsyncFusedErrorDelayed() { - TestSubscriber to = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); UnicastProcessor us = UnicastProcessor.create(); us.observeOn(Schedulers.single(), true) - .subscribe(to); + .subscribe(ts); us.onError(new TestException()); - to + ts .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); - SubscriberFusion.assertFusion(to, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @@ -1312,7 +1312,7 @@ public void outputFusedCancelReentrant() throws Exception { @Override public void onSubscribe(Subscription d) { this.d = d; - ((QueueSubscription)d).requestFusion(QueueSubscription.ANY); + ((QueueSubscription)d).requestFusion(QueueFuseable.ANY); } @Override @@ -1712,14 +1712,14 @@ public void request1Conditional() { @Test public void backFusedConditional() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 100).hide() .observeOn(ImmediateThinScheduler.INSTANCE) .filter(Functions.alwaysTrue()) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .assertValueCount(100) .assertComplete() .assertNoErrors(); @@ -1727,21 +1727,21 @@ public void backFusedConditional() { @Test public void backFusedErrorConditional() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.error(new TestException()) .observeOn(ImmediateThinScheduler.INSTANCE) .filter(Functions.alwaysTrue()) .subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.ASYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) .assertFailure(TestException.class); } @Test public void backFusedCancelConditional() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + final TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); final TestScheduler scheduler = new TestScheduler(); @@ -1766,7 +1766,7 @@ public void run() { TestHelper.race(r1, r2); - SubscriberFusion.assertFusion(ts, QueueSubscription.ASYNC); + SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC); if (ts.valueCount() != 0) { ts.assertResult(1); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java index 672b94cb1b..84793d3136 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java @@ -24,7 +24,7 @@ import io.reactivex.Flowable; import io.reactivex.exceptions.*; import io.reactivex.functions.*; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.*; @@ -249,23 +249,23 @@ public void delayErrorBuffer() { @Test public void fusedNormal() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.range(1, 10).onBackpressureBuffer().subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } @Test public void fusedError() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Flowable.error(new TestException()).onBackpressureBuffer().subscribe(ts); ts.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertFailure(TestException.class); } @@ -300,11 +300,11 @@ public void emptyDelayError() { @Test public void fusionRejected() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Flowable.never().onBackpressureBuffer().subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertEmpty(); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java index aeae4de368..86c12e3304 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java @@ -222,15 +222,15 @@ public Integer apply(Integer t1) { public void normalBackpressure() { TestSubscriber ts = TestSubscriber.create(0); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.onErrorResumeNext(Flowable.range(3, 2)).subscribe(ts); + pp.onErrorResumeNext(Flowable.range(3, 2)).subscribe(ts); ts.request(2); - ps.onNext(1); - ps.onNext(2); - ps.onError(new TestException("Forced failure")); + pp.onNext(1); + pp.onNext(2); + pp.onError(new TestException("Forced failure")); ts.assertValues(1, 2); ts.assertNoErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java index 68f7737943..8d55d06f96 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java @@ -352,9 +352,9 @@ public Integer apply(Integer t1) { public void normalBackpressure() { TestSubscriber ts = TestSubscriber.create(0); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.onErrorResumeNext(new Function>() { + pp.onErrorResumeNext(new Function>() { @Override public Flowable apply(Throwable v) { return Flowable.range(3, 2); @@ -363,9 +363,9 @@ public Flowable apply(Throwable v) { ts.request(2); - ps.onNext(1); - ps.onNext(2); - ps.onError(new TestException("Forced failure")); + pp.onNext(1); + pp.onNext(2); + pp.onError(new TestException("Forced failure")); ts.assertValues(1, 2); ts.assertNoErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java index 676318f7fe..a22c4055e2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java @@ -218,9 +218,9 @@ public void run() { public void normalBackpressure() { TestSubscriber ts = TestSubscriber.create(0); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.onErrorReturn(new Function() { + pp.onErrorReturn(new Function() { @Override public Integer apply(Throwable e) { return 3; @@ -229,9 +229,9 @@ public Integer apply(Throwable e) { ts.request(2); - ps.onNext(1); - ps.onNext(2); - ps.onError(new TestException("Forced failure")); + pp.onNext(1); + pp.onNext(2); + pp.onError(new TestException("Forced failure")); ts.assertValues(1, 2); ts.assertNoErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java index 102c564024..6c6b8c9962 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java @@ -267,15 +267,15 @@ public void run() { public void normalBackpressure() { TestSubscriber ts = TestSubscriber.create(0); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.onExceptionResumeNext(Flowable.range(3, 2)).subscribe(ts); + pp.onExceptionResumeNext(Flowable.range(3, 2)).subscribe(ts); ts.request(2); - ps.onNext(1); - ps.onNext(2); - ps.onError(new TestException("Forced failure")); + pp.onNext(1); + pp.onNext(2); + pp.onError(new TestException("Forced failure")); ts.assertValues(1, 2); ts.assertNoErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java index c05899bdc3..8dfb7584aa 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java @@ -84,17 +84,17 @@ public Flowable apply(Flowable o) { public void canBeCancelled() { TestSubscriber ts = TestSubscriber.create(); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.publish(new Function, Flowable>() { + pp.publish(new Function, Flowable>() { @Override public Flowable apply(Flowable o) { return Flowable.concat(o.take(5), o.takeLast(5)); } }).subscribe(ts); - ps.onNext(1); - ps.onNext(2); + pp.onNext(1); + pp.onNext(2); ts.assertValues(1, 2); ts.assertNoErrors(); @@ -102,7 +102,7 @@ public Flowable apply(Flowable o) { ts.cancel(); - Assert.assertFalse("Source has subscribers?", ps.hasSubscribers()); + Assert.assertFalse("Source has subscribers?", pp.hasSubscribers()); } @Test @@ -120,22 +120,22 @@ public void invalidPrefetch() { public void takeCompletes() { TestSubscriber ts = TestSubscriber.create(); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.publish(new Function, Flowable>() { + pp.publish(new Function, Flowable>() { @Override public Flowable apply(Flowable o) { return o.take(1); } }).subscribe(ts); - ps.onNext(1); + pp.onNext(1); ts.assertValues(1); ts.assertNoErrors(); ts.assertComplete(); - Assert.assertFalse("Source has subscribers?", ps.hasSubscribers()); + Assert.assertFalse("Source has subscribers?", pp.hasSubscribers()); } @@ -151,9 +151,9 @@ public void onStart() { } }; - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.publish(new Function, Flowable>() { + pp.publish(new Function, Flowable>() { @Override public Flowable apply(Flowable o) { return o.take(1); @@ -167,54 +167,54 @@ public Flowable apply(Flowable o) { public void takeCompletesUnsafe() { TestSubscriber ts = TestSubscriber.create(); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.publish(new Function, Flowable>() { + pp.publish(new Function, Flowable>() { @Override public Flowable apply(Flowable o) { return o.take(1); } }).subscribe(ts); - ps.onNext(1); + pp.onNext(1); ts.assertValues(1); ts.assertNoErrors(); ts.assertComplete(); - Assert.assertFalse("Source has subscribers?", ps.hasSubscribers()); + Assert.assertFalse("Source has subscribers?", pp.hasSubscribers()); } @Test public void directCompletesUnsafe() { TestSubscriber ts = TestSubscriber.create(); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.publish(new Function, Flowable>() { + pp.publish(new Function, Flowable>() { @Override public Flowable apply(Flowable o) { return o; } }).subscribe(ts); - ps.onNext(1); - ps.onComplete(); + pp.onNext(1); + pp.onComplete(); ts.assertValues(1); ts.assertNoErrors(); ts.assertComplete(); - Assert.assertFalse("Source has subscribers?", ps.hasSubscribers()); + Assert.assertFalse("Source has subscribers?", pp.hasSubscribers()); } @Test public void overflowMissingBackpressureException() { TestSubscriber ts = TestSubscriber.create(0); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.publish(new Function, Flowable>() { + pp.publish(new Function, Flowable>() { @Override public Flowable apply(Flowable o) { return o; @@ -222,7 +222,7 @@ public Flowable apply(Flowable o) { }).subscribe(ts); for (int i = 0; i < Flowable.bufferSize() * 2; i++) { - ps.onNext(i); + pp.onNext(i); } ts.assertNoValues(); @@ -231,16 +231,16 @@ public Flowable apply(Flowable o) { Assert.assertEquals("Could not emit value due to lack of requests", ts.errors().get(0).getMessage()); - Assert.assertFalse("Source has subscribers?", ps.hasSubscribers()); + Assert.assertFalse("Source has subscribers?", pp.hasSubscribers()); } @Test public void overflowMissingBackpressureExceptionDelayed() { TestSubscriber ts = TestSubscriber.create(0); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - new FlowablePublishMulticast(ps, new Function, Flowable>() { + new FlowablePublishMulticast(pp, new Function, Flowable>() { @Override public Flowable apply(Flowable o) { return o; @@ -248,7 +248,7 @@ public Flowable apply(Flowable o) { }, Flowable.bufferSize(), true).subscribe(ts); for (int i = 0; i < Flowable.bufferSize() * 2; i++) { - ps.onNext(i); + pp.onNext(i); } ts.request(Flowable.bufferSize()); @@ -258,7 +258,7 @@ public Flowable apply(Flowable o) { ts.assertNotComplete(); Assert.assertEquals("Could not emit value due to lack of requests", ts.errors().get(0).getMessage()); - Assert.assertFalse("Source has subscribers?", ps.hasSubscribers()); + Assert.assertFalse("Source has subscribers?", pp.hasSubscribers()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java index 866e8de378..4c65265cb1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java @@ -254,12 +254,12 @@ public void run() { @Test public void testConnectWithNoSubscriber() { TestScheduler scheduler = new TestScheduler(); - ConnectableFlowable co = Flowable.interval(10, 10, TimeUnit.MILLISECONDS, scheduler).take(3).publish(); - co.connect(); + ConnectableFlowable cf = Flowable.interval(10, 10, TimeUnit.MILLISECONDS, scheduler).take(3).publish(); + cf.connect(); // Emit 0 scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); TestSubscriber subscriber = new TestSubscriber(); - co.subscribe(subscriber); + cf.subscribe(subscriber); // Emit 1 and 2 scheduler.advanceTimeBy(50, TimeUnit.MILLISECONDS); subscriber.assertValues(1L, 2L); @@ -401,8 +401,8 @@ public void subscribe(Subscriber t) { @Test public void syncFusedObserveOn() { - ConnectableFlowable co = Flowable.range(0, 1000).publish(); - Flowable obs = co.observeOn(Schedulers.computation()); + ConnectableFlowable cf = Flowable.range(0, 1000).publish(); + Flowable obs = cf.observeOn(Schedulers.computation()); for (int i = 0; i < 1000; i++) { for (int j = 1; j < 6; j++) { List> tss = new ArrayList>(); @@ -412,7 +412,7 @@ public void syncFusedObserveOn() { obs.subscribe(ts); } - Disposable s = co.connect(); + Disposable s = cf.connect(); for (TestSubscriber ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) @@ -428,8 +428,8 @@ public void syncFusedObserveOn() { @Test public void syncFusedObserveOn2() { - ConnectableFlowable co = Flowable.range(0, 1000).publish(); - Flowable obs = co.observeOn(ImmediateThinScheduler.INSTANCE); + ConnectableFlowable cf = Flowable.range(0, 1000).publish(); + Flowable obs = cf.observeOn(ImmediateThinScheduler.INSTANCE); for (int i = 0; i < 1000; i++) { for (int j = 1; j < 6; j++) { List> tss = new ArrayList>(); @@ -439,7 +439,7 @@ public void syncFusedObserveOn2() { obs.subscribe(ts); } - Disposable s = co.connect(); + Disposable s = cf.connect(); for (TestSubscriber ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) @@ -455,17 +455,17 @@ public void syncFusedObserveOn2() { @Test public void asyncFusedObserveOn() { - ConnectableFlowable co = Flowable.range(0, 1000).observeOn(ImmediateThinScheduler.INSTANCE).publish(); + ConnectableFlowable cf = Flowable.range(0, 1000).observeOn(ImmediateThinScheduler.INSTANCE).publish(); for (int i = 0; i < 1000; i++) { for (int j = 1; j < 6; j++) { List> tss = new ArrayList>(); for (int k = 1; k < j; k++) { TestSubscriber ts = new TestSubscriber(); tss.add(ts); - co.subscribe(ts); + cf.subscribe(ts); } - Disposable s = co.connect(); + Disposable s = cf.connect(); for (TestSubscriber ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) @@ -481,8 +481,8 @@ public void asyncFusedObserveOn() { @Test public void testObserveOn() { - ConnectableFlowable co = Flowable.range(0, 1000).hide().publish(); - Flowable obs = co.observeOn(Schedulers.computation()); + ConnectableFlowable cf = Flowable.range(0, 1000).hide().publish(); + Flowable obs = cf.observeOn(Schedulers.computation()); for (int i = 0; i < 1000; i++) { for (int j = 1; j < 6; j++) { List> tss = new ArrayList>(); @@ -492,7 +492,7 @@ public void testObserveOn() { obs.subscribe(ts); } - Disposable s = co.connect(); + Disposable s = cf.connect(); for (TestSubscriber ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) @@ -515,9 +515,9 @@ public void source() { @Test public void connectThrows() { - ConnectableFlowable co = Flowable.empty().publish(); + ConnectableFlowable cf = Flowable.empty().publish(); try { - co.connect(new Consumer() { + cf.connect(new Consumer() { @Override public void accept(Disposable s) throws Exception { throw new TestException(); @@ -532,23 +532,23 @@ public void accept(Disposable s) throws Exception { public void addRemoveRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final ConnectableFlowable co = Flowable.empty().publish(); + final ConnectableFlowable cf = Flowable.empty().publish(); - final TestSubscriber to = co.test(); + final TestSubscriber ts = cf.test(); - final TestSubscriber to2 = new TestSubscriber(); + final TestSubscriber ts2 = new TestSubscriber(); Runnable r1 = new Runnable() { @Override public void run() { - co.subscribe(to2); + cf.subscribe(ts2); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; @@ -558,9 +558,9 @@ public void run() { @Test public void disposeOnArrival() { - ConnectableFlowable co = Flowable.empty().publish(); + ConnectableFlowable cf = Flowable.empty().publish(); - co.test(Long.MAX_VALUE, true).assertEmpty(); + cf.test(Long.MAX_VALUE, true).assertEmpty(); } @Test @@ -579,65 +579,65 @@ public void dispose() { @Test public void empty() { - ConnectableFlowable co = Flowable.empty().publish(); + ConnectableFlowable cf = Flowable.empty().publish(); - co.connect(); + cf.connect(); } @Test public void take() { - ConnectableFlowable co = Flowable.range(1, 2).publish(); + ConnectableFlowable cf = Flowable.range(1, 2).publish(); - TestSubscriber to = co.take(1).test(); + TestSubscriber ts = cf.take(1).test(); - co.connect(); + cf.connect(); - to.assertResult(1); + ts.assertResult(1); } @Test public void just() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - ConnectableFlowable co = ps.publish(); + ConnectableFlowable cf = pp.publish(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); - ps.onComplete(); + pp.onComplete(); } }; - co.subscribe(to); - co.connect(); + cf.subscribe(ts); + cf.connect(); - ps.onNext(1); + pp.onNext(1); - to.assertResult(1); + ts.assertResult(1); } @Test public void nextCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final ConnectableFlowable co = ps.publish(); + final ConnectableFlowable cf = pp.publish(); - final TestSubscriber to = co.test(); + final TestSubscriber ts = cf.test(); Runnable r1 = new Runnable() { @Override public void run() { - ps.onNext(1); + pp.onNext(1); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; @@ -675,9 +675,9 @@ protected void subscribeActual(Subscriber observer) { public void noErrorLoss() { List errors = TestHelper.trackPluginErrors(); try { - ConnectableFlowable co = Flowable.error(new TestException()).publish(); + ConnectableFlowable cf = Flowable.error(new TestException()).publish(); - co.connect(); + cf.connect(); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { @@ -689,12 +689,12 @@ public void noErrorLoss() { public void subscribeDisconnectRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final ConnectableFlowable co = ps.publish(); + final ConnectableFlowable cf = pp.publish(); - final Disposable d = co.connect(); - final TestSubscriber to = new TestSubscriber(); + final Disposable d = cf.connect(); + final TestSubscriber ts = new TestSubscriber(); Runnable r1 = new Runnable() { @Override @@ -706,7 +706,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - co.subscribe(to); + cf.subscribe(ts); } }; @@ -716,9 +716,9 @@ public void run() { @Test public void selectorDisconnectsIndependentSource() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.publish(new Function, Flowable>() { + pp.publish(new Function, Flowable>() { @Override public Flowable apply(Flowable v) throws Exception { return Flowable.range(1, 2); @@ -727,7 +727,7 @@ public Flowable apply(Flowable v) throws Exception { .test() .assertResult(1, 2); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test(timeout = 5000) @@ -753,9 +753,9 @@ public void mainError() { @Test public void selectorInnerError() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.publish(new Function, Flowable>() { + pp.publish(new Function, Flowable>() { @Override public Flowable apply(Flowable v) throws Exception { return Flowable.error(new TestException()); @@ -764,21 +764,21 @@ public Flowable apply(Flowable v) throws Exception { .test() .assertFailure(TestException.class); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); } @Test public void preNextConnect() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final ConnectableFlowable co = Flowable.empty().publish(); + final ConnectableFlowable cf = Flowable.empty().publish(); - co.connect(); + cf.connect(); Runnable r1 = new Runnable() { @Override public void run() { - co.test(); + cf.test(); } }; @@ -790,12 +790,12 @@ public void run() { public void connectRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final ConnectableFlowable co = Flowable.empty().publish(); + final ConnectableFlowable cf = Flowable.empty().publish(); Runnable r1 = new Runnable() { @Override public void run() { - co.connect(); + cf.connect(); } }; @@ -902,7 +902,7 @@ public void disposeRace() { final AtomicReference ref = new AtomicReference(); - final ConnectableFlowable co = new Flowable() { + final ConnectableFlowable cf = new Flowable() { @Override protected void subscribeActual(Subscriber s) { s.onSubscribe(new BooleanSubscription()); @@ -910,7 +910,7 @@ protected void subscribeActual(Subscriber s) { } }.publish(); - co.connect(); + cf.connect(); Runnable r1 = new Runnable() { @Override @@ -927,7 +927,7 @@ public void run() { public void removeNotPresent() { final AtomicReference> ref = new AtomicReference>(); - final ConnectableFlowable co = new Flowable() { + final ConnectableFlowable cf = new Flowable() { @Override @SuppressWarnings("unchecked") protected void subscribeActual(Subscriber s) { @@ -936,7 +936,7 @@ protected void subscribeActual(Subscriber s) { } }.publish(); - co.connect(); + cf.connect(); ref.get().add(new InnerSubscriber(new TestSubscriber())); ref.get().remove(null); @@ -945,9 +945,9 @@ protected void subscribeActual(Subscriber s) { @Test @Ignore("publish() keeps consuming the upstream if there are no subscribers, 3.x should change this") public void subscriberSwap() { - final ConnectableFlowable co = Flowable.range(1, 5).publish(); + final ConnectableFlowable cf = Flowable.range(1, 5).publish(); - co.connect(); + cf.connect(); TestSubscriber ts1 = new TestSubscriber() { @Override @@ -958,12 +958,12 @@ public void onNext(Integer t) { } }; - co.subscribe(ts1); + cf.subscribe(ts1); ts1.assertResult(1); TestSubscriber ts2 = new TestSubscriber(0); - co.subscribe(ts2); + cf.subscribe(ts2); ts2 .assertEmpty() @@ -973,7 +973,7 @@ public void onNext(Integer t) { @Test public void subscriberLiveSwap() { - final ConnectableFlowable co = Flowable.range(1, 5).publish(); + final ConnectableFlowable cf = Flowable.range(1, 5).publish(); final TestSubscriber ts2 = new TestSubscriber(0); @@ -983,13 +983,13 @@ public void onNext(Integer t) { super.onNext(t); cancel(); onComplete(); - co.subscribe(ts2); + cf.subscribe(ts2); } }; - co.subscribe(ts1); + cf.subscribe(ts1); - co.connect(); + cf.connect(); ts1.assertResult(1); @@ -1261,13 +1261,13 @@ public void run() { public void publishCancelOneAsync2() { final PublishProcessor pp = PublishProcessor.create(); - ConnectableFlowable co = pp.publish(); + ConnectableFlowable cf = pp.publish(); final TestSubscriber ts1 = new TestSubscriber(); final AtomicReference> ref = new AtomicReference>(); - co.subscribe(new FlowableSubscriber() { + cf.subscribe(new FlowableSubscriber() { @SuppressWarnings("unchecked") @Override public void onSubscribe(Subscription s) { @@ -1291,9 +1291,9 @@ public void onComplete() { ts1.onComplete(); } }); - TestSubscriber ts2 = co.test(); + TestSubscriber ts2 = cf.test(); - co.connect(); + cf.connect(); ref.get().set(Long.MIN_VALUE); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java index 2fbd1be6c3..bf6130b027 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java @@ -26,7 +26,7 @@ import io.reactivex.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.subscribers.*; public class FlowableRangeLongTest { @@ -290,21 +290,21 @@ public void countOne() { @Test public void fused() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); - Flowable.rangeLong(1, 2).subscribe(to); + Flowable.rangeLong(1, 2).subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.SYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.SYNC) .assertResult(1L, 2L); } @Test public void fusedReject() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ASYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ASYNC); - Flowable.rangeLong(1, 2).subscribe(to); + Flowable.rangeLong(1, 2).subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1L, 2L); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java index 86dd5dbb58..d6e2821d84 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java @@ -26,7 +26,7 @@ import io.reactivex.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.subscribers.*; public class FlowableRangeTest { @@ -283,12 +283,12 @@ public void negativeCount() { @Test public void requestWrongFusion() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ASYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ASYNC); Flowable.range(1, 5) - .subscribe(to); + .subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); } @@ -301,21 +301,21 @@ public void countOne() { @Test public void fused() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); - Flowable.range(1, 2).subscribe(to); + Flowable.range(1, 2).subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.SYNC) + SubscriberFusion.assertFusion(ts, QueueFuseable.SYNC) .assertResult(1, 2); } @Test public void fusedReject() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ASYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ASYNC); - Flowable.range(1, 2).subscribe(to); + Flowable.range(1, 2).subscribe(ts); - SubscriberFusion.assertFusion(to, QueueDisposable.NONE) + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertResult(1, 2); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index 9de049a90d..eafd7873f8 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -775,18 +775,18 @@ public Object call() throws Exception { @Test public void replayIsUnsubscribed() { - ConnectableFlowable co = Flowable.just(1) + ConnectableFlowable cf = Flowable.just(1) .replay(); - assertTrue(((Disposable)co).isDisposed()); + assertTrue(((Disposable)cf).isDisposed()); - Disposable s = co.connect(); + Disposable s = cf.connect(); - assertFalse(((Disposable)co).isDisposed()); + assertFalse(((Disposable)cf).isDisposed()); s.dispose(); - assertTrue(((Disposable)co).isDisposed()); + assertTrue(((Disposable)cf).isDisposed()); } static final class BadFlowableSubscribe extends ConnectableFlowable { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index 72a65fe1d3..5941a8f4e2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -46,14 +46,14 @@ public class FlowableReplayTest { public void testBufferedReplay() { PublishProcessor source = PublishProcessor.create(); - ConnectableFlowable co = source.replay(3); - co.connect(); + ConnectableFlowable cf = source.replay(3); + cf.connect(); { Subscriber observer1 = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(observer1); - co.subscribe(observer1); + cf.subscribe(observer1); source.onNext(1); source.onNext(2); @@ -76,7 +76,7 @@ public void testBufferedReplay() { Subscriber observer1 = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(observer1); - co.subscribe(observer1); + cf.subscribe(observer1); inOrder.verify(observer1, times(1)).onNext(2); inOrder.verify(observer1, times(1)).onNext(3); @@ -91,14 +91,14 @@ public void testBufferedReplay() { public void testBufferedWindowReplay() { PublishProcessor source = PublishProcessor.create(); TestScheduler scheduler = new TestScheduler(); - ConnectableFlowable co = source.replay(3, 100, TimeUnit.MILLISECONDS, scheduler); - co.connect(); + ConnectableFlowable cf = source.replay(3, 100, TimeUnit.MILLISECONDS, scheduler); + cf.connect(); { Subscriber observer1 = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(observer1); - co.subscribe(observer1); + cf.subscribe(observer1); source.onNext(1); scheduler.advanceTimeBy(10, TimeUnit.MILLISECONDS); @@ -128,7 +128,7 @@ public void testBufferedWindowReplay() { Subscriber observer1 = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(observer1); - co.subscribe(observer1); + cf.subscribe(observer1); inOrder.verify(observer1, times(1)).onNext(4); inOrder.verify(observer1, times(1)).onNext(5); @@ -143,14 +143,14 @@ public void testWindowedReplay() { PublishProcessor source = PublishProcessor.create(); - ConnectableFlowable co = source.replay(100, TimeUnit.MILLISECONDS, scheduler); - co.connect(); + ConnectableFlowable cf = source.replay(100, TimeUnit.MILLISECONDS, scheduler); + cf.connect(); { Subscriber observer1 = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(observer1); - co.subscribe(observer1); + cf.subscribe(observer1); source.onNext(1); scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); @@ -174,7 +174,7 @@ public void testWindowedReplay() { Subscriber observer1 = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(observer1); - co.subscribe(observer1); + cf.subscribe(observer1); inOrder.verify(observer1, never()).onNext(3); inOrder.verify(observer1, times(1)).onComplete(); @@ -371,14 +371,14 @@ public Flowable apply(Flowable t1) { public void testBufferedReplayError() { PublishProcessor source = PublishProcessor.create(); - ConnectableFlowable co = source.replay(3); - co.connect(); + ConnectableFlowable cf = source.replay(3); + cf.connect(); { Subscriber observer1 = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(observer1); - co.subscribe(observer1); + cf.subscribe(observer1); source.onNext(1); source.onNext(2); @@ -402,7 +402,7 @@ public void testBufferedReplayError() { Subscriber observer1 = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(observer1); - co.subscribe(observer1); + cf.subscribe(observer1); inOrder.verify(observer1, times(1)).onNext(2); inOrder.verify(observer1, times(1)).onNext(3); @@ -419,14 +419,14 @@ public void testWindowedReplayError() { PublishProcessor source = PublishProcessor.create(); - ConnectableFlowable co = source.replay(100, TimeUnit.MILLISECONDS, scheduler); - co.connect(); + ConnectableFlowable cf = source.replay(100, TimeUnit.MILLISECONDS, scheduler); + cf.connect(); { Subscriber observer1 = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(observer1); - co.subscribe(observer1); + cf.subscribe(observer1); source.onNext(1); scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); @@ -450,7 +450,7 @@ public void testWindowedReplayError() { Subscriber observer1 = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(observer1); - co.subscribe(observer1); + cf.subscribe(observer1); inOrder.verify(observer1, never()).onNext(3); inOrder.verify(observer1, times(1)).onError(any(RuntimeException.class)); @@ -807,17 +807,17 @@ public void accept(long t) { requested.addAndGet(t); } }); - ConnectableFlowable co = source.replay(); + ConnectableFlowable cf = source.replay(); TestSubscriber ts1 = new TestSubscriber(10L); TestSubscriber ts2 = new TestSubscriber(90L); - co.subscribe(ts1); - co.subscribe(ts2); + cf.subscribe(ts1); + cf.subscribe(ts2); ts2.request(10); - co.connect(); + cf.connect(); ts1.assertValueCount(10); ts1.assertNotTerminated(); @@ -838,17 +838,17 @@ public void accept(long t) { requested.addAndGet(t); } }); - ConnectableFlowable co = source.replay(50); + ConnectableFlowable cf = source.replay(50); TestSubscriber ts1 = new TestSubscriber(10L); TestSubscriber ts2 = new TestSubscriber(90L); - co.subscribe(ts1); - co.subscribe(ts2); + cf.subscribe(ts1); + cf.subscribe(ts2); ts2.request(10); - co.connect(); + cf.connect(); ts1.assertValueCount(10); ts1.assertNotTerminated(); @@ -1306,12 +1306,12 @@ public void source() { @Test public void connectRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final ConnectableFlowable co = Flowable.range(1, 3).replay(); + final ConnectableFlowable cf = Flowable.range(1, 3).replay(); Runnable r = new Runnable() { @Override public void run() { - co.connect(); + cf.connect(); } }; @@ -1322,22 +1322,22 @@ public void run() { @Test public void subscribeRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final ConnectableFlowable co = Flowable.range(1, 3).replay(); + final ConnectableFlowable cf = Flowable.range(1, 3).replay(); - final TestSubscriber to1 = new TestSubscriber(); - final TestSubscriber to2 = new TestSubscriber(); + final TestSubscriber ts1 = new TestSubscriber(); + final TestSubscriber ts2 = new TestSubscriber(); Runnable r1 = new Runnable() { @Override public void run() { - co.subscribe(to1); + cf.subscribe(ts1); } }; Runnable r2 = new Runnable() { @Override public void run() { - co.subscribe(to2); + cf.subscribe(ts2); } }; @@ -1348,24 +1348,24 @@ public void run() { @Test public void addRemoveRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final ConnectableFlowable co = Flowable.range(1, 3).replay(); + final ConnectableFlowable cf = Flowable.range(1, 3).replay(); - final TestSubscriber to1 = new TestSubscriber(); - final TestSubscriber to2 = new TestSubscriber(); + final TestSubscriber ts1 = new TestSubscriber(); + final TestSubscriber ts2 = new TestSubscriber(); - co.subscribe(to1); + cf.subscribe(ts1); Runnable r1 = new Runnable() { @Override public void run() { - to1.cancel(); + ts1.cancel(); } }; Runnable r2 = new Runnable() { @Override public void run() { - co.subscribe(to2); + cf.subscribe(ts2); } }; @@ -1384,12 +1384,12 @@ public void cancelOnArrival() { @Test public void cancelOnArrival2() { - ConnectableFlowable co = PublishProcessor.create() + ConnectableFlowable cf = PublishProcessor.create() .replay(Integer.MAX_VALUE); - co.test(); + cf.test(); - co + cf .autoConnect() .test(Long.MAX_VALUE, true) .assertEmpty(); @@ -1397,11 +1397,11 @@ public void cancelOnArrival2() { @Test public void connectConsumerThrows() { - ConnectableFlowable co = Flowable.range(1, 2) + ConnectableFlowable cf = Flowable.range(1, 2) .replay(); try { - co.connect(new Consumer() { + cf.connect(new Consumer() { @Override public void accept(Disposable t) throws Exception { throw new TestException(); @@ -1412,11 +1412,11 @@ public void accept(Disposable t) throws Exception { // expected } - co.test().assertEmpty().cancel(); + cf.test().assertEmpty().cancel(); - co.connect(); + cf.connect(); - co.test().assertResult(1, 2); + cf.test().assertResult(1, 2); } @Test @@ -1446,16 +1446,16 @@ protected void subscribeActual(Subscriber observer) { @Test public void subscribeOnNextRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final ConnectableFlowable co = ps.replay(); + final ConnectableFlowable cf = pp.replay(); - final TestSubscriber to1 = new TestSubscriber(); + final TestSubscriber ts1 = new TestSubscriber(); Runnable r1 = new Runnable() { @Override public void run() { - co.subscribe(to1); + cf.subscribe(ts1); } }; @@ -1463,7 +1463,7 @@ public void run() { @Override public void run() { for (int j = 0; j < 1000; j++) { - ps.onNext(j); + pp.onNext(j); } } }; @@ -1475,18 +1475,18 @@ public void run() { @Test public void unsubscribeOnNextRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final ConnectableFlowable co = ps.replay(); + final ConnectableFlowable cf = pp.replay(); - final TestSubscriber to1 = new TestSubscriber(); + final TestSubscriber ts1 = new TestSubscriber(); - co.subscribe(to1); + cf.subscribe(ts1); Runnable r1 = new Runnable() { @Override public void run() { - to1.dispose(); + ts1.dispose(); } }; @@ -1494,7 +1494,7 @@ public void run() { @Override public void run() { for (int j = 0; j < 1000; j++) { - ps.onNext(j); + pp.onNext(j); } } }; @@ -1506,23 +1506,23 @@ public void run() { @Test public void unsubscribeReplayRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final ConnectableFlowable co = Flowable.range(1, 1000).replay(); + final ConnectableFlowable cf = Flowable.range(1, 1000).replay(); - final TestSubscriber to1 = new TestSubscriber(); + final TestSubscriber ts1 = new TestSubscriber(); - co.connect(); + cf.connect(); Runnable r1 = new Runnable() { @Override public void run() { - co.subscribe(to1); + cf.subscribe(ts1); } }; Runnable r2 = new Runnable() { @Override public void run() { - to1.dispose(); + ts1.dispose(); } }; @@ -1532,90 +1532,90 @@ public void run() { @Test public void reentrantOnNext() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { if (t == 1) { - ps.onNext(2); - ps.onComplete(); + pp.onNext(2); + pp.onComplete(); } super.onNext(t); } }; - ps.replay().autoConnect().subscribe(to); + pp.replay().autoConnect().subscribe(ts); - ps.onNext(1); + pp.onNext(1); - to.assertResult(1, 2); + ts.assertResult(1, 2); } @Test public void reentrantOnNextBound() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { if (t == 1) { - ps.onNext(2); - ps.onComplete(); + pp.onNext(2); + pp.onComplete(); } super.onNext(t); } }; - ps.replay(10).autoConnect().subscribe(to); + pp.replay(10).autoConnect().subscribe(ts); - ps.onNext(1); + pp.onNext(1); - to.assertResult(1, 2); + ts.assertResult(1, 2); } @Test public void reentrantOnNextCancel() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { if (t == 1) { - ps.onNext(2); + pp.onNext(2); cancel(); } super.onNext(t); } }; - ps.replay().autoConnect().subscribe(to); + pp.replay().autoConnect().subscribe(ts); - ps.onNext(1); + pp.onNext(1); - to.assertValues(1); + ts.assertValues(1); } @Test public void reentrantOnNextCancelBounded() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { if (t == 1) { - ps.onNext(2); + pp.onNext(2); cancel(); } super.onNext(t); } }; - ps.replay(10).autoConnect().subscribe(to); + pp.replay(10).autoConnect().subscribe(ts); - ps.onNext(1); + pp.onNext(1); - to.assertValues(1); + ts.assertValues(1); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java index 9f94cc267c..72a9f518ce 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java @@ -392,7 +392,7 @@ public boolean test(Integer t1, Throwable t2) { @Test public void predicateThrows() { - TestSubscriber to = Flowable.error(new TestException("Outer")) + TestSubscriber ts = Flowable.error(new TestException("Outer")) .retry(new Predicate() { @Override public boolean test(Throwable e) throws Exception { @@ -402,7 +402,7 @@ public boolean test(Throwable e) throws Exception { .test() .assertFailure(CompositeException.class); - List errors = TestHelper.compositeList(to.errors().get(0)); + List errors = TestHelper.compositeList(ts.errors().get(0)); TestHelper.assertError(errors, 0, TestException.class, "Outer"); TestHelper.assertError(errors, 1, TestException.class, "Inner"); @@ -419,36 +419,36 @@ public void dontRetry() { @Test public void retryDisposeRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final TestSubscriber to = ps.retry(Functions.alwaysTrue()).test(); + final TestSubscriber ts = pp.retry(Functions.alwaysTrue()).test(); final TestException ex = new TestException(); Runnable r1 = new Runnable() { @Override public void run() { - ps.onError(ex); + pp.onError(ex); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; TestHelper.race(r1, r2); - to.assertEmpty(); + ts.assertEmpty(); } } @Test public void bipredicateThrows() { - TestSubscriber to = Flowable.error(new TestException("Outer")) + TestSubscriber ts = Flowable.error(new TestException("Outer")) .retry(new BiPredicate() { @Override public boolean test(Integer n, Throwable e) throws Exception { @@ -458,7 +458,7 @@ public boolean test(Integer n, Throwable e) throws Exception { .test() .assertFailure(CompositeException.class); - List errors = TestHelper.compositeList(to.errors().get(0)); + List errors = TestHelper.compositeList(ts.errors().get(0)); TestHelper.assertError(errors, 0, TestException.class, "Outer"); TestHelper.assertError(errors, 1, TestException.class, "Inner"); @@ -467,9 +467,9 @@ public boolean test(Integer n, Throwable e) throws Exception { @Test public void retryBiPredicateDisposeRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final TestSubscriber to = ps.retry(new BiPredicate() { + final TestSubscriber ts = pp.retry(new BiPredicate() { @Override public boolean test(Object t1, Object t2) throws Exception { return true; @@ -481,20 +481,20 @@ public boolean test(Object t1, Object t2) throws Exception { Runnable r1 = new Runnable() { @Override public void run() { - ps.onError(ex); + pp.onError(ex); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; TestHelper.race(r1, r2); - to.assertEmpty(); + ts.assertEmpty(); } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableScalarXMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableScalarXMapTest.java index 191f90bbea..14f98a6c76 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableScalarXMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableScalarXMapTest.java @@ -178,9 +178,9 @@ public Publisher apply(Integer v) throws Exception { @Test public void scalarDisposableStateCheck() { - TestSubscriber to = new TestSubscriber(); - ScalarSubscription sd = new ScalarSubscription(to, 1); - to.onSubscribe(sd); + TestSubscriber ts = new TestSubscriber(); + ScalarSubscription sd = new ScalarSubscription(ts, 1); + ts.onSubscribe(sd); assertFalse(sd.isCancelled()); @@ -192,7 +192,7 @@ public void scalarDisposableStateCheck() { assertTrue(sd.isEmpty()); - to.assertResult(1); + ts.assertResult(1); try { sd.offer(1); @@ -212,9 +212,9 @@ public void scalarDisposableStateCheck() { @Test public void scalarDisposableRunDisposeRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - TestSubscriber to = new TestSubscriber(); - final ScalarSubscription sd = new ScalarSubscription(to, 1); - to.onSubscribe(sd); + TestSubscriber ts = new TestSubscriber(); + final ScalarSubscription sd = new ScalarSubscription(ts, 1); + ts.onSubscribe(sd); Runnable r1 = new Runnable() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java index f4dc1441d0..a71e68f696 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java @@ -313,9 +313,9 @@ public void simpleInequalObservable() { @Test public void onNextCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final TestObserver to = Flowable.sequenceEqual(Flowable.never(), ps).test(); + final TestObserver to = Flowable.sequenceEqual(Flowable.never(), pp).test(); Runnable r1 = new Runnable() { @Override @@ -327,7 +327,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ps.onNext(1); + pp.onNext(1); } }; @@ -340,27 +340,27 @@ public void run() { @Test public void onNextCancelRaceObservable() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final TestSubscriber to = Flowable.sequenceEqual(Flowable.never(), ps).toFlowable().test(); + final TestSubscriber ts = Flowable.sequenceEqual(Flowable.never(), pp).toFlowable().test(); Runnable r1 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps.onNext(1); + pp.onNext(1); } }; TestHelper.race(r1, r2); - to.assertEmpty(); + ts.assertEmpty(); } } @@ -519,14 +519,14 @@ protected void subscribeActual(Subscriber s) { }; for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); final PublishProcessor pp = PublishProcessor.create(); boolean swap = (i & 1) == 0; Flowable.sequenceEqual(swap ? pp : neverNever, swap ? neverNever : pp) - .subscribe(ts); + .subscribe(to); Runnable r1 = new Runnable() { @Override @@ -538,13 +538,13 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; TestHelper.race(r1, r2); - ts.assertEmpty(); + to.assertEmpty(); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java index 23d5a7b987..f82e172f23 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java @@ -197,21 +197,21 @@ public Flowable apply(Flowable o) throws Exception { public void onNextDisposeRace() { TestScheduler scheduler = new TestScheduler(); for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final TestSubscriber to = ps.skipLast(1, TimeUnit.DAYS, scheduler).test(); + final TestSubscriber ts = pp.skipLast(1, TimeUnit.DAYS, scheduler).test(); Runnable r1 = new Runnable() { @Override public void run() { - ps.onComplete(); + pp.onComplete(); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java index 41a13caa60..8aeda04f47 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java @@ -723,27 +723,27 @@ public void accept(Integer v) throws Exception { @Test public void switchOnNextDelayErrorWithError() { - PublishProcessor> ps = PublishProcessor.create(); + PublishProcessor> pp = PublishProcessor.create(); - TestSubscriber ts = Flowable.switchOnNextDelayError(ps).test(); + TestSubscriber ts = Flowable.switchOnNextDelayError(pp).test(); - ps.onNext(Flowable.just(1)); - ps.onNext(Flowable.error(new TestException())); - ps.onNext(Flowable.range(2, 4)); - ps.onComplete(); + pp.onNext(Flowable.just(1)); + pp.onNext(Flowable.error(new TestException())); + pp.onNext(Flowable.range(2, 4)); + pp.onComplete(); ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); } @Test public void switchOnNextDelayErrorBufferSize() { - PublishProcessor> ps = PublishProcessor.create(); + PublishProcessor> pp = PublishProcessor.create(); - TestSubscriber ts = Flowable.switchOnNextDelayError(ps, 2).test(); + TestSubscriber ts = Flowable.switchOnNextDelayError(pp, 2).test(); - ps.onNext(Flowable.just(1)); - ps.onNext(Flowable.range(2, 4)); - ps.onComplete(); + pp.onNext(Flowable.just(1)); + pp.onNext(Flowable.range(2, 4)); + pp.onComplete(); ts.assertResult(1, 2, 3, 4, 5); } @@ -825,14 +825,14 @@ public void nextSourceErrorRace() { List errors = TestHelper.trackPluginErrors(); try { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); - ps1.switchMap(new Function>() { + pp1.switchMap(new Function>() { @Override public Flowable apply(Integer v) throws Exception { if (v == 1) { - return ps2; + return pp2; } return Flowable.never(); } @@ -842,7 +842,7 @@ public Flowable apply(Integer v) throws Exception { Runnable r1 = new Runnable() { @Override public void run() { - ps1.onNext(2); + pp1.onNext(2); } }; @@ -851,7 +851,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ps2.onError(ex); + pp2.onError(ex); } }; @@ -872,14 +872,14 @@ public void outerInnerErrorRace() { List errors = TestHelper.trackPluginErrors(); try { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); - ps1.switchMap(new Function>() { + pp1.switchMap(new Function>() { @Override public Flowable apply(Integer v) throws Exception { if (v == 1) { - return ps2; + return pp2; } return Flowable.never(); } @@ -891,7 +891,7 @@ public Flowable apply(Integer v) throws Exception { Runnable r1 = new Runnable() { @Override public void run() { - ps1.onError(ex1); + pp1.onError(ex1); } }; @@ -900,7 +900,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ps2.onError(ex2); + pp2.onError(ex2); } }; @@ -918,9 +918,9 @@ public void run() { @Test public void nextCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps1 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); - final TestSubscriber to = ps1.switchMap(new Function>() { + final TestSubscriber ts = pp1.switchMap(new Function>() { @Override public Flowable apply(Integer v) throws Exception { return Flowable.never(); @@ -931,14 +931,14 @@ public Flowable apply(Integer v) throws Exception { Runnable r1 = new Runnable() { @Override public void run() { - ps1.onNext(2); + pp1.onNext(2); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; @@ -1024,44 +1024,44 @@ protected void subscribeActual(Subscriber observer) { @Test public void innerCompletesReentrant() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); - ps.onComplete(); + pp.onComplete(); } }; Flowable.just(1).hide() - .switchMap(Functions.justFunction(ps)) - .subscribe(to); + .switchMap(Functions.justFunction(pp)) + .subscribe(ts); - ps.onNext(1); + pp.onNext(1); - to.assertResult(1); + ts.assertResult(1); } @Test public void innerErrorsReentrant() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); - ps.onError(new TestException()); + pp.onError(new TestException()); } }; Flowable.just(1).hide() - .switchMap(Functions.justFunction(ps)) - .subscribe(to); + .switchMap(Functions.justFunction(pp)) + .subscribe(ts); - ps.onNext(1); + pp.onNext(1); - to.assertFailure(TestException.class, 1); + ts.assertFailure(TestException.class, 1); } @Test @@ -1159,7 +1159,7 @@ public void innerCancelledOnMainError() { final PublishProcessor main = PublishProcessor.create(); final PublishProcessor inner = PublishProcessor.create(); - TestSubscriber to = main.switchMap(Functions.justFunction(inner)) + TestSubscriber ts = main.switchMap(Functions.justFunction(inner)) .test(); assertTrue(main.hasSubscribers()); @@ -1172,6 +1172,6 @@ public void innerCancelledOnMainError() { assertFalse(inner.hasSubscribers()); - to.assertFailure(TestException.class); + ts.assertFailure(TestException.class); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java index f27411ef0e..a0bce236de 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java @@ -208,19 +208,19 @@ public void testContinuousDelivery() { TestSubscriber ts = new TestSubscriber(0L); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - ps.takeLast(1000, TimeUnit.MILLISECONDS, scheduler).subscribe(ts); + pp.takeLast(1000, TimeUnit.MILLISECONDS, scheduler).subscribe(ts); - ps.onNext(1); + pp.onNext(1); scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); - ps.onNext(2); + pp.onNext(2); scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); - ps.onNext(3); + pp.onNext(3); scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); - ps.onNext(4); + pp.onNext(4); scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); - ps.onComplete(); + pp.onComplete(); scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); ts.assertNoValues(); @@ -292,21 +292,21 @@ public void observeOn() { @Test public void cancelCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); - final TestSubscriber to = ps.takeLast(1, TimeUnit.DAYS).test(); + final TestSubscriber ts = pp.takeLast(1, TimeUnit.DAYS).test(); Runnable r1 = new Runnable() { @Override public void run() { - ps.onComplete(); + pp.onComplete(); } }; Runnable r2 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java index b95a03d7be..b119bd00e4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java @@ -480,36 +480,36 @@ protected void subscribeActual(Subscriber observer) { @Test public void timedTake() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps.timeout(1, TimeUnit.DAYS) + TestSubscriber ts = pp.timeout(1, TimeUnit.DAYS) .take(1) .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); - to.assertResult(1); + ts.assertResult(1); } @Test public void timedFallbackTake() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = ps.timeout(1, TimeUnit.DAYS, Flowable.just(2)) + TestSubscriber ts = pp.timeout(1, TimeUnit.DAYS, Flowable.just(2)) .take(1) .test(); - assertTrue(ps.hasSubscribers()); + assertTrue(pp.hasSubscribers()); - ps.onNext(1); + pp.onNext(1); - assertFalse(ps.hasSubscribers()); + assertFalse(pp.hasSubscribers()); - to.assertResult(1); + ts.assertResult(1); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java index 3641de632c..b1667e1e56 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java @@ -416,13 +416,13 @@ public void error() { public void emptyInner() { PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = pp + TestSubscriber ts = pp .timeout(Functions.justFunction(Flowable.empty())) .test(); pp.onNext(1); - to.assertFailure(TimeoutException.class, 1); + ts.assertFailure(TimeoutException.class, 1); } @Test @@ -431,7 +431,7 @@ public void badInnerSource() { try { PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = pp + TestSubscriber ts = pp .timeout(Functions.justFunction(new Flowable() { @Override protected void subscribeActual(Subscriber observer) { @@ -446,7 +446,7 @@ protected void subscribeActual(Subscriber observer) { pp.onNext(1); - to.assertFailureAndMessage(TestException.class, "First", 1); + ts.assertFailureAndMessage(TestException.class, "First", 1); TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second"); } finally { @@ -460,7 +460,7 @@ public void badInnerSourceOther() { try { PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = pp + TestSubscriber ts = pp .timeout(Functions.justFunction(new Flowable() { @Override protected void subscribeActual(Subscriber observer) { @@ -475,7 +475,7 @@ protected void subscribeActual(Subscriber observer) { pp.onNext(1); - to.assertFailureAndMessage(TestException.class, "First", 1); + ts.assertFailureAndMessage(TestException.class, "First", 1); TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second"); } finally { @@ -515,7 +515,7 @@ protected void subscribeActual(Subscriber observer) { public void selectorTake() { PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = pp + TestSubscriber ts = pp .timeout(Functions.justFunction(Flowable.never())) .take(1) .test(); @@ -526,14 +526,14 @@ public void selectorTake() { assertFalse(pp.hasSubscribers()); - to.assertResult(1); + ts.assertResult(1); } @Test public void selectorFallbackTake() { PublishProcessor pp = PublishProcessor.create(); - TestSubscriber to = pp + TestSubscriber ts = pp .timeout(Functions.justFunction(Flowable.never()), Flowable.just(2)) .take(1) .test(); @@ -544,7 +544,7 @@ public void selectorFallbackTake() { assertFalse(pp.hasSubscribers()); - to.assertResult(1); + ts.assertResult(1); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java index 6babda3c89..4c18a1ce29 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java @@ -231,25 +231,25 @@ public void testListWithBlockingFirst() { @Ignore("Single doesn't do backpressure") public void testBackpressureHonored() { Single> w = Flowable.just(1, 2, 3, 4, 5).toList(); - TestObserver> ts = new TestObserver>(); + TestObserver> to = new TestObserver>(); - w.subscribe(ts); + w.subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertNotComplete(); // ts.request(1); - ts.assertValue(Arrays.asList(1, 2, 3, 4, 5)); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(Arrays.asList(1, 2, 3, 4, 5)); + to.assertNoErrors(); + to.assertComplete(); // ts.request(1); - ts.assertValue(Arrays.asList(1, 2, 3, 4, 5)); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(Arrays.asList(1, 2, 3, 4, 5)); + to.assertNoErrors(); + to.assertComplete(); } @Test(timeout = 2000) @Ignore("PublishProcessor no longer emits without requests so this test fails due to the race of onComplete and request") @@ -264,8 +264,8 @@ public void testAsyncRequested() { Single> sorted = source.toList(); final CyclicBarrier cb = new CyclicBarrier(2); - final TestObserver> ts = new TestObserver>(); - sorted.subscribe(ts); + final TestObserver> to = new TestObserver>(); + sorted.subscribe(to); w.schedule(new Runnable() { @Override @@ -277,10 +277,10 @@ public void run() { source.onNext(1); await(cb); source.onComplete(); - ts.awaitTerminalEvent(1, TimeUnit.SECONDS); - ts.assertTerminated(); - ts.assertNoErrors(); - ts.assertValue(Arrays.asList(1)); + to.awaitTerminalEvent(1, TimeUnit.SECONDS); + to.assertTerminated(); + to.assertNoErrors(); + to.assertValue(Arrays.asList(1)); } } finally { w.dispose(); @@ -395,7 +395,7 @@ public Collection call() throws Exception { public void onNextCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); - final TestObserver> ts = pp.toList().test(); + final TestObserver> to = pp.toList().test(); Runnable r1 = new Runnable() { @Override @@ -406,7 +406,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java index 8a840f4b30..db118e2ab1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java @@ -204,25 +204,25 @@ public void testWithFollowingFirst() { @Ignore("Single doesn't do backpressure") public void testBackpressureHonored() { Single> w = Flowable.just(1, 3, 2, 5, 4).toSortedList(); - TestObserver> ts = new TestObserver>(); + TestObserver> to = new TestObserver>(); - w.subscribe(ts); + w.subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertNotComplete(); // ts.request(1); - ts.assertValue(Arrays.asList(1, 2, 3, 4, 5)); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(Arrays.asList(1, 2, 3, 4, 5)); + to.assertNoErrors(); + to.assertComplete(); // ts.request(1); - ts.assertValue(Arrays.asList(1, 2, 3, 4, 5)); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(Arrays.asList(1, 2, 3, 4, 5)); + to.assertNoErrors(); + to.assertComplete(); } @Test(timeout = 2000) @@ -238,8 +238,8 @@ public void testAsyncRequested() { Single> sorted = source.toSortedList(); final CyclicBarrier cb = new CyclicBarrier(2); - final TestObserver> ts = new TestObserver>(); - sorted.subscribe(ts); + final TestObserver> to = new TestObserver>(); + sorted.subscribe(to); w.schedule(new Runnable() { @Override public void run() { @@ -250,10 +250,10 @@ public void run() { source.onNext(1); await(cb); source.onComplete(); - ts.awaitTerminalEvent(1, TimeUnit.SECONDS); - ts.assertTerminated(); - ts.assertNoErrors(); - ts.assertValue(Arrays.asList(1)); + to.awaitTerminalEvent(1, TimeUnit.SECONDS); + to.assertTerminated(); + to.assertNoErrors(); + to.assertValue(Arrays.asList(1)); } } finally { w.dispose(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java index ebb7a9722b..4638086065 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java @@ -525,7 +525,7 @@ public Flowable apply(Object v) throws Exception { @Test public void supplierDisposerCrash() { - TestSubscriber to = Flowable.using(new Callable() { + TestSubscriber ts = Flowable.using(new Callable() { @Override public Object call() throws Exception { return 1; @@ -544,7 +544,7 @@ public void accept(Object e) throws Exception { .test() .assertFailure(CompositeException.class); - List errors = TestHelper.compositeList(to.errors().get(0)); + List errors = TestHelper.compositeList(ts.errors().get(0)); TestHelper.assertError(errors, 0, TestException.class, "First"); TestHelper.assertError(errors, 1, TestException.class, "Second"); @@ -552,7 +552,7 @@ public void accept(Object e) throws Exception { @Test public void eagerOnErrorDisposerCrash() { - TestSubscriber to = Flowable.using(new Callable() { + TestSubscriber ts = Flowable.using(new Callable() { @Override public Object call() throws Exception { return 1; @@ -571,7 +571,7 @@ public void accept(Object e) throws Exception { .test() .assertFailure(CompositeException.class); - List errors = TestHelper.compositeList(to.errors().get(0)); + List errors = TestHelper.compositeList(ts.errors().get(0)); TestHelper.assertError(errors, 0, TestException.class, "First"); TestHelper.assertError(errors, 1, TestException.class, "Second"); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java index d9912f0b01..1bdb7a95e6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java @@ -474,13 +474,13 @@ public void boundaryDispose2() { @Test public void boundaryOnError() { - TestSubscriber to = Flowable.error(new TestException()) + TestSubscriber ts = Flowable.error(new TestException()) .window(Flowable.never()) .flatMap(Functions.>identity(), true) .test() .assertFailure(CompositeException.class); - List errors = TestHelper.compositeList(to.errors().get(0)); + List errors = TestHelper.compositeList(ts.errors().get(0)); TestHelper.assertError(errors, 0, TestException.class); } @@ -534,7 +534,7 @@ public Flowable apply(Flowable v) throws Exception { public void reentrant() { final FlowableProcessor ps = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); @@ -552,11 +552,11 @@ public Flowable apply(Flowable v) throws Exception { return v; } }) - .subscribe(to); + .subscribe(ts); ps.onNext(1); - to + ts .awaitDone(1, TimeUnit.SECONDS) .assertResult(1, 2); } @@ -565,7 +565,7 @@ public Flowable apply(Flowable v) throws Exception { public void reentrantCallable() { final FlowableProcessor ps = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); @@ -593,11 +593,11 @@ public Flowable apply(Flowable v) throws Exception { return v; } }) - .subscribe(to); + .subscribe(ts); ps.onNext(1); - to + ts .awaitDone(1, TimeUnit.SECONDS) .assertResult(1, 2); } @@ -738,7 +738,7 @@ public void upstreamDisposedWhenOutputsDisposed() { PublishProcessor source = PublishProcessor.create(); PublishProcessor boundary = PublishProcessor.create(); - TestSubscriber to = source.window(boundary) + TestSubscriber ts = source.window(boundary) .take(1) .flatMap(new Function, Flowable>() { @Override @@ -754,7 +754,7 @@ public Flowable apply( assertFalse("source not disposed", source.hasSubscribers()); assertFalse("boundary not disposed", boundary.hasSubscribers()); - to.assertResult(1); + ts.assertResult(1); } @@ -764,7 +764,7 @@ public void mainAndBoundaryBothError() { try { final AtomicReference> ref = new AtomicReference>(); - TestSubscriber> to = Flowable.error(new TestException("main")) + TestSubscriber> ts = Flowable.error(new TestException("main")) .window(new Flowable() { @Override protected void subscribeActual(Subscriber observer) { @@ -774,7 +774,7 @@ protected void subscribeActual(Subscriber observer) { }) .test(); - to + ts .assertValueCount(1) .assertError(TestException.class) .assertErrorMessage("main") @@ -798,7 +798,7 @@ public void mainCompleteBoundaryErrorRace() { final AtomicReference> refMain = new AtomicReference>(); final AtomicReference> ref = new AtomicReference>(); - TestSubscriber> to = new Flowable() { + TestSubscriber> ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -829,7 +829,7 @@ public void run() { TestHelper.race(r1, r2); - to + ts .assertValueCount(1) .assertTerminated(); @@ -848,7 +848,7 @@ public void mainNextBoundaryNextRace() { final AtomicReference> refMain = new AtomicReference>(); final AtomicReference> ref = new AtomicReference>(); - TestSubscriber> to = new Flowable() { + TestSubscriber> ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -879,7 +879,7 @@ public void run() { TestHelper.race(r1, r2); - to + ts .assertValueCount(2) .assertNotComplete() .assertNoErrors(); @@ -891,7 +891,7 @@ public void takeOneAnotherBoundary() { final AtomicReference> refMain = new AtomicReference>(); final AtomicReference> ref = new AtomicReference>(); - TestSubscriber> to = new Flowable() { + TestSubscriber> ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -907,13 +907,13 @@ protected void subscribeActual(Subscriber observer) { }) .test(); - to.assertValueCount(1) + ts.assertValueCount(1) .assertNotTerminated() .cancel(); ref.get().onNext(1); - to.assertValueCount(1) + ts.assertValueCount(1) .assertNotTerminated(); } @@ -923,7 +923,7 @@ public void disposeMainBoundaryCompleteRace() { final AtomicReference> refMain = new AtomicReference>(); final AtomicReference> ref = new AtomicReference>(); - final TestSubscriber> to = new Flowable() { + final TestSubscriber> ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -956,7 +956,7 @@ public void request(long n) { Runnable r1 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; Runnable r2 = new Runnable() { @@ -980,7 +980,7 @@ public void disposeMainBoundaryErrorRace() { final AtomicReference> refMain = new AtomicReference>(); final AtomicReference> ref = new AtomicReference>(); - final TestSubscriber> to = new Flowable() { + final TestSubscriber> ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -1013,7 +1013,7 @@ public void request(long n) { Runnable r1 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; Runnable r2 = new Runnable() { @@ -1045,7 +1045,7 @@ public void selectorUpstreamDisposedWhenOutputsDisposed() { PublishProcessor source = PublishProcessor.create(); PublishProcessor boundary = PublishProcessor.create(); - TestSubscriber to = source.window(Functions.justCallable(boundary)) + TestSubscriber ts = source.window(Functions.justCallable(boundary)) .take(1) .flatMap(new Function, Flowable>() { @Override @@ -1061,7 +1061,7 @@ public Flowable apply( assertFalse("source not disposed", source.hasSubscribers()); assertFalse("boundary not disposed", boundary.hasSubscribers()); - to.assertResult(1); + ts.assertResult(1); } @Test @@ -1070,7 +1070,7 @@ public void supplierMainAndBoundaryBothError() { try { final AtomicReference> ref = new AtomicReference>(); - TestSubscriber> to = Flowable.error(new TestException("main")) + TestSubscriber> ts = Flowable.error(new TestException("main")) .window(Functions.justCallable(new Flowable() { @Override protected void subscribeActual(Subscriber observer) { @@ -1080,7 +1080,7 @@ protected void subscribeActual(Subscriber observer) { })) .test(); - to + ts .assertValueCount(1) .assertError(TestException.class) .assertErrorMessage("main") @@ -1104,7 +1104,7 @@ public void supplierMainCompleteBoundaryErrorRace() { final AtomicReference> refMain = new AtomicReference>(); final AtomicReference> ref = new AtomicReference>(); - TestSubscriber> to = new Flowable() { + TestSubscriber> ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -1135,7 +1135,7 @@ public void run() { TestHelper.race(r1, r2); - to + ts .assertValueCount(1) .assertTerminated(); @@ -1154,7 +1154,7 @@ public void supplierMainNextBoundaryNextRace() { final AtomicReference> refMain = new AtomicReference>(); final AtomicReference> ref = new AtomicReference>(); - TestSubscriber> to = new Flowable() { + TestSubscriber> ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -1185,7 +1185,7 @@ public void run() { TestHelper.race(r1, r2); - to + ts .assertValueCount(2) .assertNotComplete() .assertNoErrors(); @@ -1197,7 +1197,7 @@ public void supplierTakeOneAnotherBoundary() { final AtomicReference> refMain = new AtomicReference>(); final AtomicReference> ref = new AtomicReference>(); - TestSubscriber> to = new Flowable() { + TestSubscriber> ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -1213,13 +1213,13 @@ protected void subscribeActual(Subscriber observer) { })) .test(); - to.assertValueCount(1) + ts.assertValueCount(1) .assertNotTerminated() .cancel(); ref.get().onNext(1); - to.assertValueCount(1) + ts.assertValueCount(1) .assertNotTerminated(); } @@ -1229,7 +1229,7 @@ public void supplierDisposeMainBoundaryCompleteRace() { final AtomicReference> refMain = new AtomicReference>(); final AtomicReference> ref = new AtomicReference>(); - final TestSubscriber> to = new Flowable() { + final TestSubscriber> ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -1262,7 +1262,7 @@ public void request(long n) { Runnable r1 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; Runnable r2 = new Runnable() { @@ -1288,7 +1288,7 @@ public void supplierDisposeMainBoundaryErrorRace() { final AtomicReference> refMain = new AtomicReference>(); final AtomicReference> ref = new AtomicReference>(); - final TestSubscriber> to = new Flowable() { + final TestSubscriber> ts = new Flowable() { @Override protected void subscribeActual(Subscriber observer) { observer.onSubscribe(new BooleanSubscription()); @@ -1330,7 +1330,7 @@ public void request(long n) { Runnable r1 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; Runnable r2 = new Runnable() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java index 73535ff5c2..561deaf7bb 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java @@ -269,7 +269,7 @@ public void dispose() { public void reentrant() { final FlowableProcessor ps = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); @@ -287,11 +287,11 @@ public Flowable apply(Flowable v) throws Exception { return v; } }) - .subscribe(to); + .subscribe(ts); ps.onNext(1); - to + ts .awaitDone(1, TimeUnit.SECONDS) .assertResult(1, 2); } @@ -312,7 +312,7 @@ public void boundarySelectorNormal() { PublishProcessor start = PublishProcessor.create(); final PublishProcessor end = PublishProcessor.create(); - TestSubscriber to = source.window(start, new Function>() { + TestSubscriber ts = source.window(start, new Function>() { @Override public Flowable apply(Integer v) throws Exception { return end; @@ -339,7 +339,7 @@ public Flowable apply(Integer v) throws Exception { TestHelper.emit(source, 7, 8); - to.assertResult(1, 2, 3, 4, 5, 5, 6, 6, 7, 8); + ts.assertResult(1, 2, 3, 4, 5, 5, 6, 6, 7, 8); } @Test @@ -348,7 +348,7 @@ public void startError() { PublishProcessor start = PublishProcessor.create(); final PublishProcessor end = PublishProcessor.create(); - TestSubscriber to = source.window(start, new Function>() { + TestSubscriber ts = source.window(start, new Function>() { @Override public Flowable apply(Integer v) throws Exception { return end; @@ -359,7 +359,7 @@ public Flowable apply(Integer v) throws Exception { start.onError(new TestException()); - to.assertFailure(TestException.class); + ts.assertFailure(TestException.class); assertFalse("Source has observers!", source.hasSubscribers()); assertFalse("Start has observers!", start.hasSubscribers()); @@ -372,7 +372,7 @@ public void endError() { PublishProcessor start = PublishProcessor.create(); final PublishProcessor end = PublishProcessor.create(); - TestSubscriber to = source.window(start, new Function>() { + TestSubscriber ts = source.window(start, new Function>() { @Override public Flowable apply(Integer v) throws Exception { return end; @@ -384,7 +384,7 @@ public Flowable apply(Integer v) throws Exception { start.onNext(1); end.onError(new TestException()); - to.assertFailure(TestException.class); + ts.assertFailure(TestException.class); assertFalse("Source has observers!", source.hasSubscribers()); assertFalse("Start has observers!", start.hasSubscribers()); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java index 6d48c40f49..019c2d101f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java @@ -561,7 +561,7 @@ public void exactUnboundedReentrant() { final FlowableProcessor ps = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); @@ -579,11 +579,11 @@ public Flowable apply(Flowable v) throws Exception { return v; } }) - .subscribe(to); + .subscribe(ts); ps.onNext(1); - to + ts .awaitDone(1, TimeUnit.SECONDS) .assertResult(1, 2); } @@ -594,7 +594,7 @@ public void exactBoundedReentrant() { final FlowableProcessor ps = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); @@ -612,11 +612,11 @@ public Flowable apply(Flowable v) throws Exception { return v; } }) - .subscribe(to); + .subscribe(ts); ps.onNext(1); - to + ts .awaitDone(1, TimeUnit.SECONDS) .assertResult(1, 2); } @@ -627,7 +627,7 @@ public void exactBoundedReentrant2() { final FlowableProcessor ps = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); @@ -645,11 +645,11 @@ public Flowable apply(Flowable v) throws Exception { return v; } }) - .subscribe(to); + .subscribe(ts); ps.onNext(1); - to + ts .awaitDone(1, TimeUnit.SECONDS) .assertResult(1, 2); } @@ -660,7 +660,7 @@ public void skipReentrant() { final FlowableProcessor ps = PublishProcessor.create(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { super.onNext(t); @@ -678,11 +678,11 @@ public Flowable apply(Flowable v) throws Exception { return v; } }) - .subscribe(to); + .subscribe(ts); ps.onNext(1); - to + ts .awaitDone(1, TimeUnit.SECONDS) .assertResult(1, 2); } @@ -690,9 +690,9 @@ public Flowable apply(Flowable v) throws Exception { @Test public void sizeTimeTimeout() { TestScheduler scheduler = new TestScheduler(); - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); - TestSubscriber> ts = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 100) + TestSubscriber> ts = pp.window(5, TimeUnit.MILLISECONDS, scheduler, 100) .test() .assertValueCount(1); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java index 0151fbbe90..360aa9c3bc 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java @@ -313,36 +313,36 @@ public String apply(Object[] args) { @Test public void manySources() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); - PublishProcessor ps3 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); + PublishProcessor pp3 = PublishProcessor.create(); PublishProcessor main = PublishProcessor.create(); TestSubscriber ts = new TestSubscriber(); - main.withLatestFrom(new Flowable[] { ps1, ps2, ps3 }, toArray) + main.withLatestFrom(new Flowable[] { pp1, pp2, pp3 }, toArray) .subscribe(ts); main.onNext("1"); ts.assertNoValues(); - ps1.onNext("a"); + pp1.onNext("a"); ts.assertNoValues(); - ps2.onNext("A"); + pp2.onNext("A"); ts.assertNoValues(); - ps3.onNext("="); + pp3.onNext("="); ts.assertNoValues(); main.onNext("2"); ts.assertValues("[2, a, A, =]"); - ps2.onNext("B"); + pp2.onNext("B"); ts.assertValues("[2, a, A, =]"); - ps3.onComplete(); + pp3.onComplete(); ts.assertValues("[2, a, A, =]"); - ps1.onNext("b"); + pp1.onNext("b"); main.onNext("3"); @@ -353,43 +353,43 @@ public void manySources() { ts.assertNoErrors(); ts.assertComplete(); - assertFalse("ps1 has subscribers?", ps1.hasSubscribers()); - assertFalse("ps2 has subscribers?", ps2.hasSubscribers()); - assertFalse("ps3 has subscribers?", ps3.hasSubscribers()); + assertFalse("ps1 has subscribers?", pp1.hasSubscribers()); + assertFalse("ps2 has subscribers?", pp2.hasSubscribers()); + assertFalse("ps3 has subscribers?", pp3.hasSubscribers()); } @Test public void manySourcesIterable() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); - PublishProcessor ps3 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); + PublishProcessor pp3 = PublishProcessor.create(); PublishProcessor main = PublishProcessor.create(); TestSubscriber ts = new TestSubscriber(); - main.withLatestFrom(Arrays.>asList(ps1, ps2, ps3), toArray) + main.withLatestFrom(Arrays.>asList(pp1, pp2, pp3), toArray) .subscribe(ts); main.onNext("1"); ts.assertNoValues(); - ps1.onNext("a"); + pp1.onNext("a"); ts.assertNoValues(); - ps2.onNext("A"); + pp2.onNext("A"); ts.assertNoValues(); - ps3.onNext("="); + pp3.onNext("="); ts.assertNoValues(); main.onNext("2"); ts.assertValues("[2, a, A, =]"); - ps2.onNext("B"); + pp2.onNext("B"); ts.assertValues("[2, a, A, =]"); - ps3.onComplete(); + pp3.onComplete(); ts.assertValues("[2, a, A, =]"); - ps1.onNext("b"); + pp1.onNext("b"); main.onNext("3"); @@ -400,9 +400,9 @@ public void manySourcesIterable() { ts.assertNoErrors(); ts.assertComplete(); - assertFalse("ps1 has subscribers?", ps1.hasSubscribers()); - assertFalse("ps2 has subscribers?", ps2.hasSubscribers()); - assertFalse("ps3 has subscribers?", ps3.hasSubscribers()); + assertFalse("ps1 has subscribers?", pp1.hasSubscribers()); + assertFalse("ps2 has subscribers?", pp2.hasSubscribers()); + assertFalse("ps3 has subscribers?", pp3.hasSubscribers()); } @Test @@ -439,12 +439,12 @@ public void manySourcesIterableSweep() { @Test public void backpressureNoSignal() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); TestSubscriber ts = new TestSubscriber(0); - Flowable.range(1, 10).withLatestFrom(new Flowable[] { ps1, ps2 }, toArray) + Flowable.range(1, 10).withLatestFrom(new Flowable[] { pp1, pp2 }, toArray) .subscribe(ts); ts.assertNoValues(); @@ -455,24 +455,24 @@ public void backpressureNoSignal() { ts.assertNoErrors(); ts.assertComplete(); - assertFalse("ps1 has subscribers?", ps1.hasSubscribers()); - assertFalse("ps2 has subscribers?", ps2.hasSubscribers()); + assertFalse("ps1 has subscribers?", pp1.hasSubscribers()); + assertFalse("ps2 has subscribers?", pp2.hasSubscribers()); } @Test public void backpressureWithSignal() { - PublishProcessor ps1 = PublishProcessor.create(); - PublishProcessor ps2 = PublishProcessor.create(); + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); TestSubscriber ts = new TestSubscriber(0); - Flowable.range(1, 3).withLatestFrom(new Flowable[] { ps1, ps2 }, toArray) + Flowable.range(1, 3).withLatestFrom(new Flowable[] { pp1, pp2 }, toArray) .subscribe(ts); ts.assertNoValues(); - ps1.onNext("1"); - ps2.onNext("1"); + pp1.onNext("1"); + pp2.onNext("1"); ts.request(1); @@ -488,8 +488,8 @@ public void backpressureWithSignal() { ts.assertNoErrors(); ts.assertComplete(); - assertFalse("ps1 has subscribers?", ps1.hasSubscribers()); - assertFalse("ps2 has subscribers?", ps2.hasSubscribers()); + assertFalse("ps1 has subscribers?", pp1.hasSubscribers()); + assertFalse("ps2 has subscribers?", pp2.hasSubscribers()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java index 652ddf6e0a..57c856b472 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java @@ -73,7 +73,7 @@ public void onlineSuccess() { assertNotNull(((MaybeCache)source).source.get()); - TestObserver ts = source.test(); + TestObserver to = source.test(); assertNull(((MaybeCache)source).source.get()); @@ -81,12 +81,12 @@ public void onlineSuccess() { source.test(true).assertEmpty(); - ts.assertEmpty(); + to.assertEmpty(); pp.onNext(1); pp.onComplete(); - ts.assertResult(1); + to.assertResult(1); source.test().assertResult(1); @@ -103,7 +103,7 @@ public void onlineError() { assertNotNull(((MaybeCache)source).source.get()); - TestObserver ts = source.test(); + TestObserver to = source.test(); assertNull(((MaybeCache)source).source.get()); @@ -111,11 +111,11 @@ public void onlineError() { source.test(true).assertEmpty(); - ts.assertEmpty(); + to.assertEmpty(); pp.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); source.test().assertFailure(TestException.class); @@ -132,7 +132,7 @@ public void onlineComplete() { assertNotNull(((MaybeCache)source).source.get()); - TestObserver ts = source.test(); + TestObserver to = source.test(); assertNull(((MaybeCache)source).source.get()); @@ -140,11 +140,11 @@ public void onlineComplete() { source.test(true).assertEmpty(); - ts.assertEmpty(); + to.assertEmpty(); pp.onComplete(); - ts.assertResult(); + to.assertResult(); source.test().assertResult(); @@ -246,20 +246,20 @@ public void removeRemoveRace() { final Maybe source = pp.singleElement().cache(); - final TestObserver ts1 = source.test(); - final TestObserver ts2 = source.test(); + final TestObserver to1 = source.test(); + final TestObserver to2 = source.test(); Runnable r1 = new Runnable() { @Override public void run() { - ts1.cancel(); + to1.cancel(); } }; Runnable r2 = new Runnable() { @Override public void run() { - ts2.cancel(); + to2.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatIterableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatIterableTest.java index 545c15225f..1ae2ac56bb 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatIterableTest.java @@ -64,7 +64,7 @@ public void successCancelRace() { final PublishProcessor pp = PublishProcessor.create(); - final TestSubscriber to = Maybe.concat(Arrays.asList(pp.singleElement())) + final TestSubscriber ts = Maybe.concat(Arrays.asList(pp.singleElement())) .test(); pp.onNext(1); @@ -72,7 +72,7 @@ public void successCancelRace() { Runnable r1 = new Runnable() { @Override public void run() { - to.cancel(); + ts.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeContainsTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeContainsTest.java index e1172ce5d7..588de845a8 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeContainsTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeContainsTest.java @@ -50,11 +50,11 @@ public void error() { public void dispose() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = pp.singleElement().contains(1).test(); + TestObserver to = pp.singleElement().contains(1).test(); assertTrue(pp.hasSubscribers()); - ts.cancel(); + to.cancel(); assertFalse(pp.hasSubscribers()); } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeCountTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeCountTest.java index be5e117214..3a0d29ab9c 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeCountTest.java @@ -45,11 +45,11 @@ public void error() { public void dispose() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = pp.singleElement().count().test(); + TestObserver to = pp.singleElement().count().test(); assertTrue(pp.hasSubscribers()); - ts.cancel(); + to.cancel(); assertFalse(pp.hasSubscribers()); } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java index ce23150c9a..40cb873836 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java @@ -33,10 +33,10 @@ public class MaybeDelayOtherTest { public void justWithOnNext() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Maybe.just(1) + TestObserver to = Maybe.just(1) .delay(pp).test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp.hasSubscribers()); @@ -44,17 +44,17 @@ public void justWithOnNext() { assertFalse(pp.hasSubscribers()); - ts.assertResult(1); + to.assertResult(1); } @Test public void justWithOnComplete() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Maybe.just(1) + TestObserver to = Maybe.just(1) .delay(pp).test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp.hasSubscribers()); @@ -62,7 +62,7 @@ public void justWithOnComplete() { assertFalse(pp.hasSubscribers()); - ts.assertResult(1); + to.assertResult(1); } @@ -70,10 +70,10 @@ public void justWithOnComplete() { public void justWithOnError() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Maybe.just(1) + TestObserver to = Maybe.just(1) .delay(pp).test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp.hasSubscribers()); @@ -81,17 +81,17 @@ public void justWithOnError() { assertFalse(pp.hasSubscribers()); - ts.assertFailureAndMessage(TestException.class, "Other"); + to.assertFailureAndMessage(TestException.class, "Other"); } @Test public void emptyWithOnNext() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Maybe.empty() + TestObserver to = Maybe.empty() .delay(pp).test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp.hasSubscribers()); @@ -99,7 +99,7 @@ public void emptyWithOnNext() { assertFalse(pp.hasSubscribers()); - ts.assertResult(); + to.assertResult(); } @@ -107,10 +107,10 @@ public void emptyWithOnNext() { public void emptyWithOnComplete() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Maybe.empty() + TestObserver to = Maybe.empty() .delay(pp).test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp.hasSubscribers()); @@ -118,17 +118,17 @@ public void emptyWithOnComplete() { assertFalse(pp.hasSubscribers()); - ts.assertResult(); + to.assertResult(); } @Test public void emptyWithOnError() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Maybe.empty() + TestObserver to = Maybe.empty() .delay(pp).test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp.hasSubscribers()); @@ -136,17 +136,17 @@ public void emptyWithOnError() { assertFalse(pp.hasSubscribers()); - ts.assertFailureAndMessage(TestException.class, "Other"); + to.assertFailureAndMessage(TestException.class, "Other"); } @Test public void errorWithOnNext() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Maybe.error(new TestException("Main")) + TestObserver to = Maybe.error(new TestException("Main")) .delay(pp).test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp.hasSubscribers()); @@ -154,17 +154,17 @@ public void errorWithOnNext() { assertFalse(pp.hasSubscribers()); - ts.assertFailureAndMessage(TestException.class, "Main"); + to.assertFailureAndMessage(TestException.class, "Main"); } @Test public void errorWithOnComplete() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Maybe.error(new TestException("Main")) + TestObserver to = Maybe.error(new TestException("Main")) .delay(pp).test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp.hasSubscribers()); @@ -172,17 +172,17 @@ public void errorWithOnComplete() { assertFalse(pp.hasSubscribers()); - ts.assertFailureAndMessage(TestException.class, "Main"); + to.assertFailureAndMessage(TestException.class, "Main"); } @Test public void errorWithOnError() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Maybe.error(new TestException("Main")) + TestObserver to = Maybe.error(new TestException("Main")) .delay(pp).test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp.hasSubscribers()); @@ -190,9 +190,9 @@ public void errorWithOnError() { assertFalse(pp.hasSubscribers()); - ts.assertFailure(CompositeException.class); + to.assertFailure(CompositeException.class); - List list = TestHelper.compositeList(ts.errors().get(0)); + List list = TestHelper.compositeList(to.errors().get(0)); assertEquals(2, list.size()); TestHelper.assertError(list, 0, TestException.class, "Main"); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionTest.java index a684ff68ff..0b082b5899 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionTest.java @@ -36,18 +36,18 @@ public class MaybeDelaySubscriptionTest { public void normal() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Maybe.just(1).delaySubscription(pp) + TestObserver to = Maybe.just(1).delaySubscription(pp) .test(); assertTrue(pp.hasSubscribers()); - ts.assertEmpty(); + to.assertEmpty(); pp.onNext("one"); assertFalse(pp.hasSubscribers()); - ts.assertResult(1); + to.assertResult(1); } @Test @@ -70,19 +70,19 @@ public void timedEmpty() { public void timedTestScheduler() { TestScheduler scheduler = new TestScheduler(); - TestObserver ts = Maybe.just(1) + TestObserver to = Maybe.just(1) .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler) .test(); - ts.assertEmpty(); + to.assertEmpty(); scheduler.advanceTimeBy(99, TimeUnit.MILLISECONDS); - ts.assertEmpty(); + to.assertEmpty(); scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); - ts.assertResult(1); + to.assertResult(1); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayTest.java index a392f5f11f..c6b9fdbd4c 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayTest.java @@ -66,25 +66,25 @@ public void nullScheduler() { public void disposeDuringDelay() { TestScheduler scheduler = new TestScheduler(); - TestObserver ts = Maybe.just(1).delay(100, TimeUnit.MILLISECONDS, scheduler) + TestObserver to = Maybe.just(1).delay(100, TimeUnit.MILLISECONDS, scheduler) .test(); - ts.cancel(); + to.cancel(); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ts.assertEmpty(); + to.assertEmpty(); } @Test public void dispose() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = pp.singleElement().delay(100, TimeUnit.MILLISECONDS).test(); + TestObserver to = pp.singleElement().delay(100, TimeUnit.MILLISECONDS).test(); assertTrue(pp.hasSubscribers()); - ts.cancel(); + to.cancel(); assertFalse(pp.hasSubscribers()); } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccessTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccessTest.java index cee3a213f2..31e046c41f 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccessTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccessTest.java @@ -38,7 +38,7 @@ public void accept(Integer e) throws Exception { } }; - final TestObserver ts = new TestObserver() { + final TestObserver to = new TestObserver() { @Override public void onNext(Integer t) { super.onNext(t); @@ -50,7 +50,7 @@ public void onNext(Integer t) { public void just() { Maybe.just(1) .doAfterSuccess(afterSuccess) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1); assertEquals(Arrays.asList(1, -1), values); @@ -60,7 +60,7 @@ public void just() { public void error() { Maybe.error(new TestException()) .doAfterSuccess(afterSuccess) - .subscribeWith(ts) + .subscribeWith(to) .assertFailure(TestException.class); assertTrue(values.isEmpty()); @@ -70,7 +70,7 @@ public void error() { public void empty() { Maybe.empty() .doAfterSuccess(afterSuccess) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(); assertTrue(values.isEmpty()); @@ -86,7 +86,7 @@ public void justConditional() { Maybe.just(1) .doAfterSuccess(afterSuccess) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1); assertEquals(Arrays.asList(1, -1), values); @@ -97,7 +97,7 @@ public void errorConditional() { Maybe.error(new TestException()) .doAfterSuccess(afterSuccess) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertFailure(TestException.class); assertTrue(values.isEmpty()); @@ -108,7 +108,7 @@ public void emptyConditional() { Maybe.empty() .doAfterSuccess(afterSuccess) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(); assertTrue(values.isEmpty()); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java index bc9617c293..c44782fa3c 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java @@ -19,7 +19,7 @@ import java.util.concurrent.TimeUnit; import org.junit.Test; -import org.reactivestreams.*; +import org.reactivestreams.Subscription; import io.reactivex.*; import io.reactivex.exceptions.TestException; @@ -121,7 +121,7 @@ public Iterable apply(Integer v) throws Exception { @Test public void fused() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Maybe.just(1).flattenAsFlowable(new Function>() { @Override @@ -129,17 +129,17 @@ public Iterable apply(Integer v) throws Exception { return Arrays.asList(v, v + 1); } }) - .subscribe(to); + .subscribe(ts); - to.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueDisposable.ASYNC)) + ts.assertOf(SubscriberFusion.assertFuseable()) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2); ; } @Test public void fusedNoSync() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Maybe.just(1).flattenAsFlowable(new Function>() { @Override @@ -147,10 +147,10 @@ public Iterable apply(Integer v) throws Exception { return Arrays.asList(v, v + 1); } }) - .subscribe(to); + .subscribe(ts); - to.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueDisposable.NONE)) + ts.assertOf(SubscriberFusion.assertFuseable()) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.NONE)) .assertResult(1, 2); ; } @@ -305,7 +305,7 @@ public Iterable apply(Object v) throws Exception { public void onSubscribe(Subscription d) { qd = (QueueSubscription)d; - assertEquals(QueueSubscription.ASYNC, qd.requestFusion(QueueSubscription.ANY)); + assertEquals(QueueFuseable.ASYNC, qd.requestFusion(QueueFuseable.ANY)); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservableTest.java index 5da9082918..c4648d8331 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservableTest.java @@ -13,10 +13,11 @@ package io.reactivex.internal.operators.maybe; +import static org.junit.Assert.*; + import java.util.*; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.*; import org.junit.Test; import io.reactivex.*; @@ -24,7 +25,7 @@ import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.util.CrashingIterable; import io.reactivex.observers.*; import io.reactivex.schedulers.Schedulers; @@ -98,7 +99,7 @@ public Iterable apply(Integer v) throws Exception { @Test public void fused() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); Maybe.just(1).flattenAsObservable(new Function>() { @Override @@ -109,14 +110,14 @@ public Iterable apply(Integer v) throws Exception { .subscribe(to); to.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.ASYNC)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2); ; } @Test public void fusedNoSync() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.SYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC); Maybe.just(1).flattenAsObservable(new Function>() { @Override @@ -127,7 +128,7 @@ public Iterable apply(Integer v) throws Exception { .subscribe(to); to.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.NONE)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.NONE)) .assertResult(1, 2); ; } @@ -307,7 +308,7 @@ public Iterable apply(Object v) throws Exception { public void onSubscribe(Disposable d) { qd = (QueueDisposable)d; - assertEquals(QueueDisposable.ASYNC, qd.requestFusion(QueueDisposable.ANY)); + assertEquals(QueueFuseable.ASYNC, qd.requestFusion(QueueFuseable.ANY)); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java index 2d65eb5b67..b5833c1941 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java @@ -23,7 +23,7 @@ import io.reactivex.*; import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.TestException; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.operators.maybe.MaybeMergeArray.MergeMaybeObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.PublishSubject; @@ -34,26 +34,26 @@ public class MaybeMergeArrayTest { @SuppressWarnings("unchecked") @Test public void normal() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Maybe.mergeArray(Maybe.just(1), Maybe.just(2)) .subscribe(ts); ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.NONE)) .assertResult(1, 2); } @SuppressWarnings("unchecked") @Test public void fusedPollMixed() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Maybe.mergeArray(Maybe.just(1), Maybe.empty(), Maybe.just(2)) .subscribe(ts); ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2); } @@ -67,7 +67,7 @@ public void fusedEmptyCheck() { public void onSubscribe(Subscription d) { qd = (QueueSubscription)d; - assertEquals(QueueSubscription.ASYNC, qd.requestFusion(QueueSubscription.ANY)); + assertEquals(QueueFuseable.ASYNC, qd.requestFusion(QueueFuseable.ANY)); } @Override @@ -119,13 +119,13 @@ public void firstErrors() { @SuppressWarnings("unchecked") @Test public void errorFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Maybe.mergeArray(Maybe.error(new TestException()), Maybe.just(2)) .subscribe(ts); ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertFailure(TestException.class); } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeOfTypeTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeOfTypeTest.java index ba93e61c6b..814a0c8e16 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeOfTypeTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeOfTypeTest.java @@ -32,38 +32,38 @@ public void normal() { @Test public void normalDowncast() { - TestObserver ts = Maybe.just(1) + TestObserver to = Maybe.just(1) .ofType(Number.class) .test(); // don't make this fluent, target type required! - ts.assertResult((Number)1); + to.assertResult((Number)1); } @Test public void notInstance() { - TestObserver ts = Maybe.just(1) + TestObserver to = Maybe.just(1) .ofType(String.class) .test(); // don't make this fluent, target type required! - ts.assertResult(); + to.assertResult(); } @Test public void error() { - TestObserver ts = Maybe.error(new TestException()) + TestObserver to = Maybe.error(new TestException()) .ofType(Number.class) .test(); // don't make this fluent, target type required! - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test public void errorNotInstance() { - TestObserver ts = Maybe.error(new TestException()) + TestObserver to = Maybe.error(new TestException()) .ofType(String.class) .test(); // don't make this fluent, target type required! - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java index 714ba98272..bacd1c1870 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java @@ -52,11 +52,11 @@ public void errorOther() { public void dispose() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = pp.singleElement().switchIfEmpty(Single.just(2)).test(); + TestObserver to = pp.singleElement().switchIfEmpty(Single.just(2)).test(); assertTrue(pp.hasSubscribers()); - ts.cancel(); + to.cancel(); assertFalse(pp.hasSubscribers()); } @@ -84,7 +84,7 @@ public void emptyCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); - final TestObserver ts = pp.singleElement().switchIfEmpty(Single.just(2)).test(); + final TestObserver to = pp.singleElement().switchIfEmpty(Single.just(2)).test(); Runnable r1 = new Runnable() { @Override @@ -96,7 +96,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java index 2ce1d6b8d7..d2e53a7225 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java @@ -67,11 +67,11 @@ public void emptyOtherToo() { public void dispose() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = pp.singleElement().switchIfEmpty(Maybe.just(2)).test(); + TestObserver to = pp.singleElement().switchIfEmpty(Maybe.just(2)).test(); assertTrue(pp.hasSubscribers()); - ts.cancel(); + to.cancel(); assertFalse(pp.hasSubscribers()); } @@ -99,7 +99,7 @@ public void emptyCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishProcessor pp = PublishProcessor.create(); - final TestObserver ts = pp.singleElement().switchIfEmpty(Maybe.just(2)).test(); + final TestObserver to = pp.singleElement().switchIfEmpty(Maybe.just(2)).test(); Runnable r1 = new Runnable() { @Override @@ -111,7 +111,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimerTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimerTest.java index d588be655b..05d33d7175 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTimerTest.java @@ -38,7 +38,7 @@ public void timerInterruptible() throws Exception { try { for (Scheduler s : new Scheduler[] { Schedulers.single(), Schedulers.computation(), Schedulers.newThread(), Schedulers.io(), Schedulers.from(exec) }) { final AtomicBoolean interrupted = new AtomicBoolean(); - TestObserver ts = Maybe.timer(1, TimeUnit.MILLISECONDS, s) + TestObserver to = Maybe.timer(1, TimeUnit.MILLISECONDS, s) .map(new Function() { @Override public Long apply(Long v) throws Exception { @@ -54,7 +54,7 @@ public Long apply(Long v) throws Exception { Thread.sleep(500); - ts.cancel(); + to.cancel(); Thread.sleep(500); diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java index 154508bcf7..bdedbd2055 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java @@ -114,9 +114,9 @@ public MaybeSource apply(Integer v) .assertComplete() .assertOf(new Consumer>() { @Override - public void accept(TestObserver ts) throws Exception { + public void accept(TestObserver to) throws Exception { for (int i = 0; i < 512; i ++) { - ts.assertValueAt(i, (i + 1) * 2); + to.assertValueAt(i, (i + 1) * 2); } } }); @@ -143,9 +143,9 @@ public void mainBoundaryErrorInnerSuccess() { PublishSubject ps = PublishSubject.create(); MaybeSubject ms = MaybeSubject.create(); - TestObserver ts = ps.concatMapMaybeDelayError(Functions.justFunction(ms), false).test(); + TestObserver to = ps.concatMapMaybeDelayError(Functions.justFunction(ms), false).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); @@ -155,11 +155,11 @@ public void mainBoundaryErrorInnerSuccess() { assertTrue(ms.hasObservers()); - ts.assertEmpty(); + to.assertEmpty(); ms.onSuccess(1); - ts.assertFailure(TestException.class, 1); + to.assertFailure(TestException.class, 1); } @Test @@ -167,9 +167,9 @@ public void mainBoundaryErrorInnerEmpty() { PublishSubject ps = PublishSubject.create(); MaybeSubject ms = MaybeSubject.create(); - TestObserver ts = ps.concatMapMaybeDelayError(Functions.justFunction(ms), false).test(); + TestObserver to = ps.concatMapMaybeDelayError(Functions.justFunction(ms), false).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); @@ -179,11 +179,11 @@ public void mainBoundaryErrorInnerEmpty() { assertTrue(ms.hasObservers()); - ts.assertEmpty(); + to.assertEmpty(); ms.onComplete(); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -264,7 +264,7 @@ public void innerErrorAfterMainError() { final AtomicReference> obs = new AtomicReference>(); - TestObserver ts = ps.concatMapMaybe( + TestObserver to = ps.concatMapMaybe( new Function>() { @Override public MaybeSource apply(Integer v) @@ -286,7 +286,7 @@ protected void subscribeActual( ps.onError(new TestException("outer")); obs.get().onError(new TestException("inner")); - ts.assertFailureAndMessage(TestException.class, "outer"); + to.assertFailureAndMessage(TestException.class, "outer"); TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); } finally { @@ -308,8 +308,8 @@ public MaybeSource apply(Integer v) .assertFailure(CompositeException.class) .assertOf(new Consumer>() { @Override - public void accept(TestObserver ts) throws Exception { - CompositeException ce = (CompositeException)ts.errors().get(0); + public void accept(TestObserver to) throws Exception { + CompositeException ce = (CompositeException)to.errors().get(0); assertEquals(5, ce.getExceptions().size()); } }); @@ -319,7 +319,7 @@ public void accept(TestObserver ts) throws Exception { public void mapperCrash() { final PublishSubject ps = PublishSubject.create(); - TestObserver ts = ps + TestObserver to = ps .concatMapMaybe(new Function>() { @Override public MaybeSource apply(Integer v) @@ -329,13 +329,13 @@ public MaybeSource apply(Integer v) }) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ps.hasObservers()); ps.onNext(1); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); assertFalse(ps.hasObservers()); } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java index 48a35df533..0a1ff4e1be 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java @@ -82,9 +82,9 @@ public void mainBoundaryErrorInnerSuccess() { PublishSubject ps = PublishSubject.create(); SingleSubject ms = SingleSubject.create(); - TestObserver ts = ps.concatMapSingleDelayError(Functions.justFunction(ms), false).test(); + TestObserver to = ps.concatMapSingleDelayError(Functions.justFunction(ms), false).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); @@ -94,11 +94,11 @@ public void mainBoundaryErrorInnerSuccess() { assertTrue(ms.hasObservers()); - ts.assertEmpty(); + to.assertEmpty(); ms.onSuccess(1); - ts.assertFailure(TestException.class, 1); + to.assertFailure(TestException.class, 1); } @Test @@ -179,7 +179,7 @@ public void innerErrorAfterMainError() { final AtomicReference> obs = new AtomicReference>(); - TestObserver ts = ps.concatMapSingle( + TestObserver to = ps.concatMapSingle( new Function>() { @Override public SingleSource apply(Integer v) @@ -201,7 +201,7 @@ protected void subscribeActual( ps.onError(new TestException("outer")); obs.get().onError(new TestException("inner")); - ts.assertFailureAndMessage(TestException.class, "outer"); + to.assertFailureAndMessage(TestException.class, "outer"); TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner"); } finally { @@ -223,8 +223,8 @@ public SingleSource apply(Integer v) .assertFailure(CompositeException.class) .assertOf(new Consumer>() { @Override - public void accept(TestObserver ts) throws Exception { - CompositeException ce = (CompositeException)ts.errors().get(0); + public void accept(TestObserver to) throws Exception { + CompositeException ce = (CompositeException)to.errors().get(0); assertEquals(5, ce.getExceptions().size()); } }); @@ -234,7 +234,7 @@ public void accept(TestObserver ts) throws Exception { public void mapperCrash() { final PublishSubject ps = PublishSubject.create(); - TestObserver ts = ps + TestObserver to = ps .concatMapSingle(new Function>() { @Override public SingleSource apply(Integer v) @@ -244,13 +244,13 @@ public SingleSource apply(Integer v) }) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ps.hasObservers()); ps.onNext(1); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); assertFalse(ps.hasObservers()); } @@ -267,9 +267,9 @@ public void mainCompletesWhileInnerActive() { PublishSubject ps = PublishSubject.create(); SingleSubject ms = SingleSubject.create(); - TestObserver ts = ps.concatMapSingleDelayError(Functions.justFunction(ms), false).test(); + TestObserver to = ps.concatMapSingleDelayError(Functions.justFunction(ms), false).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); ps.onNext(2); @@ -277,10 +277,10 @@ public void mainCompletesWhileInnerActive() { assertTrue(ms.hasObservers()); - ts.assertEmpty(); + to.assertEmpty(); ms.onSuccess(1); - ts.assertResult(1, 1); + to.assertResult(1, 1); } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java index 65f487a14e..4b0046bb61 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java @@ -127,7 +127,7 @@ public void switchOver() { final MaybeSubject ms1 = MaybeSubject.create(); final MaybeSubject ms2 = MaybeSubject.create(); - TestObserver ts = ps.switchMapMaybe(new Function>() { + TestObserver to = ps.switchMapMaybe(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -138,11 +138,11 @@ public MaybeSource apply(Integer v) } }).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ms1.hasObservers()); @@ -155,7 +155,7 @@ public MaybeSource apply(Integer v) assertFalse(ps.hasObservers()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -165,7 +165,7 @@ public void switchOverDelayError() { final MaybeSubject ms1 = MaybeSubject.create(); final MaybeSubject ms2 = MaybeSubject.create(); - TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + TestObserver to = ps.switchMapMaybeDelayError(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -176,11 +176,11 @@ public MaybeSource apply(Integer v) } }).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ms1.hasObservers()); @@ -191,13 +191,13 @@ public MaybeSource apply(Integer v) ms2.onError(new TestException()); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ps.hasObservers()); ps.onComplete(); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -206,7 +206,7 @@ public void mainErrorInnerCompleteDelayError() { final MaybeSubject ms = MaybeSubject.create(); - TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + TestObserver to = ps.switchMapMaybeDelayError(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -214,11 +214,11 @@ public MaybeSource apply(Integer v) } }).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ms.hasObservers()); @@ -226,11 +226,11 @@ public MaybeSource apply(Integer v) assertTrue(ms.hasObservers()); - ts.assertEmpty(); + to.assertEmpty(); ms.onComplete(); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -239,7 +239,7 @@ public void mainErrorInnerSuccessDelayError() { final MaybeSubject ms = MaybeSubject.create(); - TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + TestObserver to = ps.switchMapMaybeDelayError(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -247,11 +247,11 @@ public MaybeSource apply(Integer v) } }).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ms.hasObservers()); @@ -259,11 +259,11 @@ public MaybeSource apply(Integer v) assertTrue(ms.hasObservers()); - ts.assertEmpty(); + to.assertEmpty(); ms.onSuccess(1); - ts.assertFailure(TestException.class, 1); + to.assertFailure(TestException.class, 1); } @Test @@ -282,24 +282,24 @@ public MaybeSource apply(Integer v) @Test public void disposeBeforeSwitchInOnNext() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.just(1) .switchMapMaybe(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { - ts.cancel(); + to.cancel(); return Maybe.just(1); } - }).subscribe(ts); + }).subscribe(to); - ts.assertEmpty(); + to.assertEmpty(); } @Test public void disposeOnNextAfterFirst() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.just(1, 2) .switchMapMaybe(new Function>() { @@ -307,13 +307,13 @@ public void disposeOnNextAfterFirst() { public MaybeSource apply(Integer v) throws Exception { if (v == 2) { - ts.cancel(); + to.cancel(); } return Maybe.just(1); } - }).subscribe(ts); + }).subscribe(to); - ts.assertValue(1) + to.assertValue(1) .assertNoErrors() .assertNotComplete(); } @@ -324,7 +324,7 @@ public void cancel() { final MaybeSubject ms = MaybeSubject.create(); - TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + TestObserver to = ps.switchMapMaybeDelayError(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -332,16 +332,16 @@ public MaybeSource apply(Integer v) } }).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ps.hasObservers()); assertTrue(ms.hasObservers()); - ts.cancel(); + to.cancel(); assertFalse(ps.hasObservers()); assertFalse(ms.hasObservers()); @@ -382,7 +382,7 @@ public void innerErrorAfterTermination() { try { final AtomicReference> moRef = new AtomicReference>(); - TestObserver ts = new Observable() { + TestObserver to = new Observable() { @Override protected void subscribeActual(Observer s) { s.onSubscribe(Disposables.empty()); @@ -406,7 +406,7 @@ protected void subscribeActual( }) .test(); - ts.assertFailureAndMessage(TestException.class, "outer"); + to.assertFailureAndMessage(TestException.class, "outer"); moRef.get().onError(new TestException("inner")); moRef.get().onComplete(); @@ -425,7 +425,7 @@ public void nextCancelRace() { final MaybeSubject ms = MaybeSubject.create(); - final TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + final TestObserver to = ps.switchMapMaybeDelayError(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -443,13 +443,13 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; TestHelper.race(r1, r2); - ts.assertNoErrors() + to.assertNoErrors() .assertNotComplete(); } } @@ -466,7 +466,7 @@ public void nextInnerErrorRace() { final MaybeSubject ms = MaybeSubject.create(); - final TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + final TestObserver to = ps.switchMapMaybeDelayError(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -495,9 +495,9 @@ public void run() { TestHelper.race(r1, r2); - if (ts.errorCount() != 0) { + if (to.errorCount() != 0) { assertTrue(errors.isEmpty()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } else if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); } @@ -520,7 +520,7 @@ public void mainErrorInnerErrorRace() { final MaybeSubject ms = MaybeSubject.create(); - final TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + final TestObserver to = ps.switchMapMaybeDelayError(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -549,7 +549,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertError(new Predicate() { + to.assertError(new Predicate() { @Override public boolean test(Throwable e) throws Exception { return e instanceof TestException || e instanceof CompositeException; @@ -573,7 +573,7 @@ public void nextInnerSuccessRace() { final MaybeSubject ms = MaybeSubject.create(); - final TestObserver ts = ps.switchMapMaybeDelayError(new Function>() { + final TestObserver to = ps.switchMapMaybeDelayError(new Function>() { @Override public MaybeSource apply(Integer v) throws Exception { @@ -602,7 +602,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertNoErrors() + to.assertNoErrors() .assertNotComplete(); } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java index cafbf15e4d..10b3dba8d8 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java @@ -96,7 +96,7 @@ public void switchOver() { final SingleSubject ms1 = SingleSubject.create(); final SingleSubject ms2 = SingleSubject.create(); - TestObserver ts = ps.switchMapSingle(new Function>() { + TestObserver to = ps.switchMapSingle(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -107,11 +107,11 @@ public SingleSource apply(Integer v) } }).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ms1.hasObservers()); @@ -124,7 +124,7 @@ public SingleSource apply(Integer v) assertFalse(ps.hasObservers()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -134,7 +134,7 @@ public void switchOverDelayError() { final SingleSubject ms1 = SingleSubject.create(); final SingleSubject ms2 = SingleSubject.create(); - TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + TestObserver to = ps.switchMapSingleDelayError(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -145,11 +145,11 @@ public SingleSource apply(Integer v) } }).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ms1.hasObservers()); @@ -160,13 +160,13 @@ public SingleSource apply(Integer v) ms2.onError(new TestException()); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ps.hasObservers()); ps.onComplete(); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -175,7 +175,7 @@ public void mainErrorInnerCompleteDelayError() { final SingleSubject ms = SingleSubject.create(); - TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + TestObserver to = ps.switchMapSingleDelayError(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -183,11 +183,11 @@ public SingleSource apply(Integer v) } }).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ms.hasObservers()); @@ -195,11 +195,11 @@ public SingleSource apply(Integer v) assertTrue(ms.hasObservers()); - ts.assertEmpty(); + to.assertEmpty(); ms.onSuccess(1); - ts.assertFailure(TestException.class, 1); + to.assertFailure(TestException.class, 1); } @Test @@ -208,7 +208,7 @@ public void mainErrorInnerSuccessDelayError() { final SingleSubject ms = SingleSubject.create(); - TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + TestObserver to = ps.switchMapSingleDelayError(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -216,11 +216,11 @@ public SingleSource apply(Integer v) } }).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ms.hasObservers()); @@ -228,11 +228,11 @@ public SingleSource apply(Integer v) assertTrue(ms.hasObservers()); - ts.assertEmpty(); + to.assertEmpty(); ms.onSuccess(1); - ts.assertFailure(TestException.class, 1); + to.assertFailure(TestException.class, 1); } @Test @@ -251,24 +251,24 @@ public SingleSource apply(Integer v) @Test public void disposeBeforeSwitchInOnNext() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.just(1) .switchMapSingle(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { - ts.cancel(); + to.cancel(); return Single.just(1); } - }).subscribe(ts); + }).subscribe(to); - ts.assertEmpty(); + to.assertEmpty(); } @Test public void disposeOnNextAfterFirst() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.just(1, 2) .switchMapSingle(new Function>() { @@ -276,13 +276,13 @@ public void disposeOnNextAfterFirst() { public SingleSource apply(Integer v) throws Exception { if (v == 2) { - ts.cancel(); + to.cancel(); } return Single.just(1); } - }).subscribe(ts); + }).subscribe(to); - ts.assertValue(1) + to.assertValue(1) .assertNoErrors() .assertNotComplete(); } @@ -293,7 +293,7 @@ public void cancel() { final SingleSubject ms = SingleSubject.create(); - TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + TestObserver to = ps.switchMapSingleDelayError(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -301,16 +301,16 @@ public SingleSource apply(Integer v) } }).test(); - ts.assertEmpty(); + to.assertEmpty(); ps.onNext(1); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(ps.hasObservers()); assertTrue(ms.hasObservers()); - ts.cancel(); + to.cancel(); assertFalse(ps.hasObservers()); assertFalse(ms.hasObservers()); @@ -351,7 +351,7 @@ public void innerErrorAfterTermination() { try { final AtomicReference> moRef = new AtomicReference>(); - TestObserver ts = new Observable() { + TestObserver to = new Observable() { @Override protected void subscribeActual(Observer s) { s.onSubscribe(Disposables.empty()); @@ -375,7 +375,7 @@ protected void subscribeActual( }) .test(); - ts.assertFailureAndMessage(TestException.class, "outer"); + to.assertFailureAndMessage(TestException.class, "outer"); moRef.get().onError(new TestException("inner")); @@ -393,7 +393,7 @@ public void nextCancelRace() { final SingleSubject ms = SingleSubject.create(); - final TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + final TestObserver to = ps.switchMapSingleDelayError(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -411,13 +411,13 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; TestHelper.race(r1, r2); - ts.assertNoErrors() + to.assertNoErrors() .assertNotComplete(); } } @@ -434,7 +434,7 @@ public void nextInnerErrorRace() { final SingleSubject ms = SingleSubject.create(); - final TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + final TestObserver to = ps.switchMapSingleDelayError(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -463,9 +463,9 @@ public void run() { TestHelper.race(r1, r2); - if (ts.errorCount() != 0) { + if (to.errorCount() != 0) { assertTrue(errors.isEmpty()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } else if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); } @@ -488,7 +488,7 @@ public void mainErrorInnerErrorRace() { final SingleSubject ms = SingleSubject.create(); - final TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + final TestObserver to = ps.switchMapSingleDelayError(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -517,7 +517,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertError(new Predicate() { + to.assertError(new Predicate() { @Override public boolean test(Throwable e) throws Exception { return e instanceof TestException || e instanceof CompositeException; @@ -541,7 +541,7 @@ public void nextInnerSuccessRace() { final SingleSubject ms = SingleSubject.create(); - final TestObserver ts = ps.switchMapSingleDelayError(new Function>() { + final TestObserver to = ps.switchMapSingleDelayError(new Function>() { @Override public SingleSource apply(Integer v) throws Exception { @@ -570,7 +570,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertNoErrors() + to.assertNoErrors() .assertNotComplete(); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java index 29d2f8eff0..d37fc5fb74 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java @@ -146,7 +146,7 @@ public Observable apply(Boolean t1) { @Test public void testPredicateThrowsExceptionAndValueInCauseMessageObservable() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final IllegalArgumentException ex = new IllegalArgumentException(); @@ -156,12 +156,12 @@ public boolean test(String v) { throw ex; } }) - .subscribe(ts); + .subscribe(to); - ts.assertTerminated(); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(ex); + to.assertTerminated(); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(ex); // FIXME need to decide about adding the value that probably caused the crash in some way // assertTrue(ex.getCause().getMessage().contains("Boo!")); } @@ -278,7 +278,7 @@ public Observable apply(Boolean t1) { @Test public void testPredicateThrowsExceptionAndValueInCauseMessage() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final IllegalArgumentException ex = new IllegalArgumentException(); @@ -288,12 +288,12 @@ public boolean test(String v) { throw ex; } }) - .subscribe(ts); + .subscribe(to); - ts.assertTerminated(); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(ex); + to.assertTerminated(); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(ex); // FIXME need to decide about adding the value that probably caused the crash in some way // assertTrue(ex.getCause().getMessage().contains("Boo!")); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java index 932b40187c..497b2894d9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java @@ -176,10 +176,10 @@ public void accept(Disposable s) { //this stream emits second Observable o2 = Observable.just(1).doOnSubscribe(incrementer) .delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation()); - TestObserver ts = new TestObserver(); - Observable.ambArray(o1, o2).subscribe(ts); - ts.awaitTerminalEvent(5, TimeUnit.SECONDS); - ts.assertNoErrors(); + TestObserver to = new TestObserver(); + Observable.ambArray(o1, o2).subscribe(to); + to.awaitTerminalEvent(5, TimeUnit.SECONDS); + to.assertNoErrors(); assertEquals(2, count.get()); } @@ -210,9 +210,9 @@ public void testAmbCancelsOthers() { PublishSubject source2 = PublishSubject.create(); PublishSubject source3 = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.ambArray(source1, source2, source3).subscribe(ts); + Observable.ambArray(source1, source2, source3).subscribe(to); assertTrue("Source 1 doesn't have subscribers!", source1.hasObservers()); assertTrue("Source 2 doesn't have subscribers!", source2.hasObservers()); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java index 3ad9314430..5ada2a774e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java @@ -246,7 +246,7 @@ public Observable apply(Boolean t1) { @Test public void testPredicateThrowsExceptionAndValueInCauseMessageObservable() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final IllegalArgumentException ex = new IllegalArgumentException(); Observable.just("Boo!").any(new Predicate() { @@ -254,12 +254,12 @@ public void testPredicateThrowsExceptionAndValueInCauseMessageObservable() { public boolean test(String v) { throw ex; } - }).subscribe(ts); + }).subscribe(to); - ts.assertTerminated(); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(ex); + to.assertTerminated(); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(ex); // FIXME value as last cause? // assertTrue(ex.getCause().getMessage().contains("Boo!")); } @@ -467,7 +467,7 @@ public Observable apply(Boolean t1) { @Test public void testPredicateThrowsExceptionAndValueInCauseMessage() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final IllegalArgumentException ex = new IllegalArgumentException(); Observable.just("Boo!").any(new Predicate() { @@ -475,12 +475,12 @@ public void testPredicateThrowsExceptionAndValueInCauseMessage() { public boolean test(String v) { throw ex; } - }).subscribe(ts); + }).subscribe(to); - ts.assertTerminated(); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(ex); + to.assertTerminated(); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(ex); // FIXME value as last cause? // assertTrue(ex.getCause().getMessage().contains("Boo!")); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 517a99a3c6..1e7407c121 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -344,7 +344,7 @@ public void testBufferStopsWhenUnsubscribed1() { Observable source = Observable.never(); Observer> o = TestHelper.mockObserver(); - TestObserver> ts = new TestObserver>(o); + TestObserver> to = new TestObserver>(o); source.buffer(100, 200, TimeUnit.MILLISECONDS, scheduler) .doOnNext(new Consumer>() { @@ -353,7 +353,7 @@ public void accept(List pv) { System.out.println(pv); } }) - .subscribe(ts); + .subscribe(to); InOrder inOrder = Mockito.inOrder(o); @@ -361,7 +361,7 @@ public void accept(List pv) { inOrder.verify(o, times(5)).onNext(Arrays. asList()); - ts.dispose(); + to.dispose(); scheduler.advanceTimeBy(999, TimeUnit.MILLISECONDS); @@ -1104,9 +1104,9 @@ public Collection call() throws Exception { @Test public void boundaryCancel() { - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver> ts = pp + TestObserver> to = ps .buffer(Functions.justCallable(Observable.never()), new Callable>() { @Override public Collection call() throws Exception { @@ -1115,11 +1115,11 @@ public Collection call() throws Exception { }) .test(); - assertTrue(pp.hasObservers()); + assertTrue(ps.hasObservers()); - ts.dispose(); + to.dispose(); - assertFalse(pp.hasObservers()); + assertFalse(ps.hasObservers()); } @Test @@ -1173,9 +1173,9 @@ public Collection call() throws Exception { @SuppressWarnings("unchecked") @Test public void boundaryMainError() { - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver> ts = pp + TestObserver> to = ps .buffer(Functions.justCallable(Observable.never()), new Callable>() { @Override public Collection call() throws Exception { @@ -1184,17 +1184,17 @@ public Collection call() throws Exception { }) .test(); - pp.onError(new TestException()); + ps.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @SuppressWarnings("unchecked") @Test public void boundaryBoundaryError() { - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver> ts = pp + TestObserver> to = ps .buffer(Functions.justCallable(Observable.error(new TestException())), new Callable>() { @Override public Collection call() throws Exception { @@ -1203,9 +1203,9 @@ public Collection call() throws Exception { }) .test(); - pp.onError(new TestException()); + ps.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -1409,7 +1409,7 @@ public void withTimeAndSizeCapacityRace() { final PublishSubject ps = PublishSubject.create(); - TestObserver> ts = ps.buffer(1, TimeUnit.SECONDS, scheduler, 5).test(); + TestObserver> to = ps.buffer(1, TimeUnit.SECONDS, scheduler, 5).test(); ps.onNext(1); ps.onNext(2); @@ -1435,7 +1435,7 @@ public void run() { ps.onComplete(); int items = 0; - for (List o : ts.values()) { + for (List o : to.values()) { items += o.size(); } @@ -1512,7 +1512,7 @@ public void boundaryOpenCloseDisposedOnComplete() { PublishSubject closeIndicator = PublishSubject.create(); - TestObserver> ts = source + TestObserver> to = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(); @@ -1527,7 +1527,7 @@ public void boundaryOpenCloseDisposedOnComplete() { source.onComplete(); - ts.assertResult(Collections.emptyList()); + to.assertResult(Collections.emptyList()); assertFalse(openIndicator.hasObservers()); assertFalse(closeIndicator.hasObservers()); @@ -1635,7 +1635,7 @@ public void openCloseOpenCompletes() { PublishSubject closeIndicator = PublishSubject.create(); - TestObserver> ts = source + TestObserver> to = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(); @@ -1652,7 +1652,7 @@ public void openCloseOpenCompletes() { assertFalse(source.hasObservers()); - ts.assertResult(Collections.emptyList()); + to.assertResult(Collections.emptyList()); } @Test @@ -1664,7 +1664,7 @@ public void openCloseOpenCompletesNoBuffers() { PublishSubject closeIndicator = PublishSubject.create(); - TestObserver> ts = source + TestObserver> to = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(); @@ -1681,7 +1681,7 @@ public void openCloseOpenCompletesNoBuffers() { assertFalse(source.hasObservers()); - ts.assertResult(Collections.emptyList()); + to.assertResult(Collections.emptyList()); } @Test @@ -1693,7 +1693,7 @@ public void openCloseTake() { PublishSubject closeIndicator = PublishSubject.create(); - TestObserver> ts = source + TestObserver> to = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .take(1) .test(); @@ -1705,7 +1705,7 @@ public void openCloseTake() { assertFalse(openIndicator.hasObservers()); assertFalse(closeIndicator.hasObservers()); - ts.assertResult(Collections.emptyList()); + to.assertResult(Collections.emptyList()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java index e7d7e35f16..c664c2591c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java @@ -39,16 +39,16 @@ public void testColdReplayNoBackpressure() { assertFalse("Source is connected!", source.isConnected()); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.subscribe(ts); + source.subscribe(to); assertTrue("Source is not connected!", source.isConnected()); assertFalse("Subscribers retained!", source.hasObservers()); - ts.assertNoErrors(); - ts.assertTerminated(); - List onNextEvents = ts.values(); + to.assertNoErrors(); + to.assertTerminated(); + List onNextEvents = to.values(); assertEquals(1000, onNextEvents.size()); for (int i = 0; i < 1000; i++) { @@ -118,14 +118,14 @@ public void testUnsubscribeSource() throws Exception { @Test public void testTake() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); ObservableCache cached = (ObservableCache)ObservableCache.from(Observable.range(1, 100)); - cached.take(10).subscribe(ts); + cached.take(10).subscribe(to); - ts.assertNoErrors(); - ts.assertComplete(); - ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + to.assertNoErrors(); + to.assertComplete(); + to.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // ts.assertUnsubscribed(); // FIXME no longer valid assertFalse(cached.hasObservers()); } @@ -134,24 +134,24 @@ public void testTake() { public void testAsync() { Observable source = Observable.range(1, 10000); for (int i = 0; i < 100; i++) { - TestObserver ts1 = new TestObserver(); + TestObserver to1 = new TestObserver(); ObservableCache cached = (ObservableCache)ObservableCache.from(source); - cached.observeOn(Schedulers.computation()).subscribe(ts1); + cached.observeOn(Schedulers.computation()).subscribe(to1); - ts1.awaitTerminalEvent(2, TimeUnit.SECONDS); - ts1.assertNoErrors(); - ts1.assertComplete(); - assertEquals(10000, ts1.values().size()); + to1.awaitTerminalEvent(2, TimeUnit.SECONDS); + to1.assertNoErrors(); + to1.assertComplete(); + assertEquals(10000, to1.values().size()); - TestObserver ts2 = new TestObserver(); - cached.observeOn(Schedulers.computation()).subscribe(ts2); + TestObserver to2 = new TestObserver(); + cached.observeOn(Schedulers.computation()).subscribe(to2); - ts2.awaitTerminalEvent(2, TimeUnit.SECONDS); - ts2.assertNoErrors(); - ts2.assertComplete(); - assertEquals(10000, ts2.values().size()); + to2.awaitTerminalEvent(2, TimeUnit.SECONDS); + to2.assertNoErrors(); + to2.assertComplete(); + assertEquals(10000, to2.values().size()); } } @Test @@ -165,9 +165,9 @@ public void testAsyncComeAndGo() { List> list = new ArrayList>(100); for (int i = 0; i < 100; i++) { - TestObserver ts = new TestObserver(); - list.add(ts); - output.skip(i * 10).take(10).subscribe(ts); + TestObserver to = new TestObserver(); + list.add(to); + output.skip(i * 10).take(10).subscribe(to); } List expected = new ArrayList(); @@ -175,16 +175,16 @@ public void testAsyncComeAndGo() { expected.add((long)(i - 10)); } int j = 0; - for (TestObserver ts : list) { - ts.awaitTerminalEvent(3, TimeUnit.SECONDS); - ts.assertNoErrors(); - ts.assertComplete(); + for (TestObserver to : list) { + to.awaitTerminalEvent(3, TimeUnit.SECONDS); + to.assertNoErrors(); + to.assertComplete(); for (int i = j * 10; i < j * 10 + 10; i++) { expected.set(i - j * 10, (long)i); } - ts.assertValueSequence(expected); + to.assertValueSequence(expected); j++; } @@ -204,14 +204,14 @@ public void subscribe(Observer t) { } }); - TestObserver ts = new TestObserver(); - firehose.cache().observeOn(Schedulers.computation()).takeLast(100).subscribe(ts); + TestObserver to = new TestObserver(); + firehose.cache().observeOn(Schedulers.computation()).takeLast(100).subscribe(to); - ts.awaitTerminalEvent(3, TimeUnit.SECONDS); - ts.assertNoErrors(); - ts.assertComplete(); + to.awaitTerminalEvent(3, TimeUnit.SECONDS); + to.assertNoErrors(); + to.assertComplete(); - assertEquals(100, ts.values().size()); + assertEquals(100, to.values().size()); } @Test @@ -221,19 +221,19 @@ public void testValuesAndThenError() { .cache(); - TestObserver ts = new TestObserver(); - source.subscribe(ts); + TestObserver to = new TestObserver(); + source.subscribe(to); - ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - ts.assertNotComplete(); - ts.assertError(TestException.class); + to.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + to.assertNotComplete(); + to.assertError(TestException.class); - TestObserver ts2 = new TestObserver(); - source.subscribe(ts2); + TestObserver to2 = new TestObserver(); + source.subscribe(to2); - ts2.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - ts2.assertNotComplete(); - ts2.assertError(TestException.class); + to2.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + to2.assertNotComplete(); + to2.assertError(TestException.class); } @Test @@ -250,20 +250,20 @@ public void accept(Integer t) { }) .cache(); - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { @Override public void onNext(Integer t) { throw new TestException(); } }; - source.subscribe(ts); + source.subscribe(to); Assert.assertEquals(100, count.get()); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(TestException.class); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(TestException.class); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java index 7595a9b893..cee12d300e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java @@ -756,14 +756,14 @@ public void accept(Notification n) { } }).take(SIZE); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.combineLatest(timer, Observable. never(), new BiFunction() { @Override public Long apply(Long t1, Integer t2) { return t1; } - }).subscribe(ts); + }).subscribe(to); if (!latch.await(SIZE + 1000, TimeUnit.MILLISECONDS)) { fail("timed out"); @@ -1170,7 +1170,7 @@ public void eagerDispose() { final PublishSubject ps1 = PublishSubject.create(); final PublishSubject ps2 = PublishSubject.create(); - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { @Override public void onNext(Integer t) { super.onNext(t); @@ -1192,11 +1192,11 @@ public Integer apply(Integer t1, Integer t2) throws Exception { return t1 + t2; } }) - .subscribe(ts); + .subscribe(to); ps1.onNext(1); ps2.onNext(2); - ts.assertResult(3); + to.assertResult(3); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java index 593febc4eb..8874eec137 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java @@ -50,7 +50,7 @@ public ObservableSource apply(Integer t) { @Test @Ignore("Observable doesn't do backpressure") public void normalBackpressured() { -// TestObserver ts = Observable.range(1, 5) +// TestObserver to = Observable.range(1, 5) // .concatMapEager(new Function>() { // @Override // public ObservableSource apply(Integer t) { @@ -59,19 +59,19 @@ public void normalBackpressured() { // }) // .test(3); // -// ts.assertValues(1, 2, 2); +// to.assertValues(1, 2, 2); // -// ts.request(1); +// to.request(1); // -// ts.assertValues(1, 2, 2, 3); +// to.assertValues(1, 2, 2, 3); // -// ts.request(1); +// to.request(1); // -// ts.assertValues(1, 2, 2, 3, 3); +// to.assertValues(1, 2, 2, 3, 3); // -// ts.request(5); +// to.request(5); // -// ts.assertResult(1, 2, 2, 3, 3, 4, 4, 5, 5, 6); +// to.assertResult(1, 2, 2, 3, 3, 4, 4, 5, 5, 6); } @Test @@ -90,7 +90,7 @@ public ObservableSource apply(Integer t) { @Test @Ignore("Observable doesn't do backpressure") public void normalDelayBoundaryBackpressured() { -// TestObserver ts = Observable.range(1, 5) +// TestObserver to = Observable.range(1, 5) // .concatMapEagerDelayError(new Function>() { // @Override // public ObservableSource apply(Integer t) { @@ -99,19 +99,19 @@ public void normalDelayBoundaryBackpressured() { // }, false) // .test(3); // -// ts.assertValues(1, 2, 2); +// to.assertValues(1, 2, 2); // -// ts.request(1); +// to.request(1); // -// ts.assertValues(1, 2, 2, 3); +// to.assertValues(1, 2, 2, 3); // -// ts.request(1); +// to.request(1); // -// ts.assertValues(1, 2, 2, 3, 3); +// to.assertValues(1, 2, 2, 3, 3); // -// ts.request(5); +// to.request(5); // -// ts.assertResult(1, 2, 2, 3, 3, 4, 4, 5, 5, 6); +// to.assertResult(1, 2, 2, 3, 3, 4, 4, 5, 5, 6); } @Test @@ -130,7 +130,7 @@ public ObservableSource apply(Integer t) { @Test @Ignore("Observable doesn't do backpressure") public void normalDelayEndBackpressured() { -// TestObserver ts = Observable.range(1, 5) +// TestObserver to = Observable.range(1, 5) // .concatMapEagerDelayError(new Function>() { // @Override // public ObservableSource apply(Integer t) { @@ -139,19 +139,19 @@ public void normalDelayEndBackpressured() { // }, true) // .test(3); // -// ts.assertValues(1, 2, 2); +// to.assertValues(1, 2, 2); // -// ts.request(1); +// to.request(1); // -// ts.assertValues(1, 2, 2, 3); +// to.assertValues(1, 2, 2, 3); // -// ts.request(1); +// to.request(1); // -// ts.assertValues(1, 2, 2, 3, 3); +// to.assertValues(1, 2, 2, 3, 3); // -// ts.request(5); +// to.request(5); // -// ts.assertResult(1, 2, 2, 3, 3, 4, 4, 5, 5, 6); +// to.assertResult(1, 2, 2, 3, 3, 4, 4, 5, 5, 6); } @Test @@ -159,7 +159,7 @@ public void mainErrorsDelayBoundary() { PublishSubject main = PublishSubject.create(); final PublishSubject inner = PublishSubject.create(); - TestObserver ts = main.concatMapEagerDelayError( + TestObserver to = main.concatMapEagerDelayError( new Function>() { @Override public ObservableSource apply(Integer t) { @@ -171,16 +171,16 @@ public ObservableSource apply(Integer t) { inner.onNext(2); - ts.assertValue(2); + to.assertValue(2); main.onError(new TestException("Forced failure")); - ts.assertNoErrors(); + to.assertNoErrors(); inner.onNext(3); inner.onComplete(); - ts.assertFailureAndMessage(TestException.class, "Forced failure", 2, 3); + to.assertFailureAndMessage(TestException.class, "Forced failure", 2, 3); } @Test @@ -188,7 +188,7 @@ public void mainErrorsDelayEnd() { PublishSubject main = PublishSubject.create(); final PublishSubject inner = PublishSubject.create(); - TestObserver ts = main.concatMapEagerDelayError( + TestObserver to = main.concatMapEagerDelayError( new Function>() { @Override public ObservableSource apply(Integer t) { @@ -201,16 +201,16 @@ public ObservableSource apply(Integer t) { inner.onNext(2); - ts.assertValue(2); + to.assertValue(2); main.onError(new TestException("Forced failure")); - ts.assertNoErrors(); + to.assertNoErrors(); inner.onNext(3); inner.onComplete(); - ts.assertFailureAndMessage(TestException.class, "Forced failure", 2, 3, 2, 3); + to.assertFailureAndMessage(TestException.class, "Forced failure", 2, 3, 2, 3); } @Test @@ -218,7 +218,7 @@ public void mainErrorsImmediate() { PublishSubject main = PublishSubject.create(); final PublishSubject inner = PublishSubject.create(); - TestObserver ts = main.concatMapEager( + TestObserver to = main.concatMapEager( new Function>() { @Override public ObservableSource apply(Integer t) { @@ -231,7 +231,7 @@ public ObservableSource apply(Integer t) { inner.onNext(2); - ts.assertValue(2); + to.assertValue(2); main.onError(new TestException("Forced failure")); @@ -240,7 +240,7 @@ public ObservableSource apply(Integer t) { inner.onNext(3); inner.onComplete(); - ts.assertFailureAndMessage(TestException.class, "Forced failure", 2); + to.assertFailureAndMessage(TestException.class, "Forced failure", 2); } @Test @@ -259,7 +259,7 @@ public ObservableSource apply(Integer v) { .assertComplete(); } - TestObserver ts; + TestObserver to; Function> toJust = new Function>() { @Override @@ -277,25 +277,25 @@ public Observable apply(Integer t) { @Before public void before() { - ts = new TestObserver(); + to = new TestObserver(); } @Test public void testSimple() { - Observable.range(1, 100).concatMapEager(toJust).subscribe(ts); + Observable.range(1, 100).concatMapEager(toJust).subscribe(to); - ts.assertNoErrors(); - ts.assertValueCount(100); - ts.assertComplete(); + to.assertNoErrors(); + to.assertValueCount(100); + to.assertComplete(); } @Test public void testSimple2() { - Observable.range(1, 100).concatMapEager(toRange).subscribe(ts); + Observable.range(1, 100).concatMapEager(toRange).subscribe(to); - ts.assertNoErrors(); - ts.assertValueCount(200); - ts.assertComplete(); + to.assertNoErrors(); + to.assertValueCount(200); + to.assertComplete(); } @SuppressWarnings("unchecked") @@ -309,13 +309,13 @@ public void accept(Integer t) { } }).hide(); - Observable.concatArrayEager(source, source).subscribe(ts); + Observable.concatArrayEager(source, source).subscribe(to); Assert.assertEquals(2, count.get()); - ts.assertValueCount(count.get()); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValueCount(count.get()); + to.assertNoErrors(); + to.assertComplete(); } @SuppressWarnings("unchecked") @@ -329,13 +329,13 @@ public void accept(Integer t) { } }).hide(); - Observable.concatArrayEager(source, source, source).subscribe(ts); + Observable.concatArrayEager(source, source, source).subscribe(to); Assert.assertEquals(3, count.get()); - ts.assertValueCount(count.get()); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValueCount(count.get()); + to.assertNoErrors(); + to.assertComplete(); } @SuppressWarnings("unchecked") @@ -349,13 +349,13 @@ public void accept(Integer t) { } }).hide(); - Observable.concatArrayEager(source, source, source, source).subscribe(ts); + Observable.concatArrayEager(source, source, source, source).subscribe(to); Assert.assertEquals(4, count.get()); - ts.assertValueCount(count.get()); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValueCount(count.get()); + to.assertNoErrors(); + to.assertComplete(); } @SuppressWarnings("unchecked") @@ -369,13 +369,13 @@ public void accept(Integer t) { } }).hide(); - Observable.concatArrayEager(source, source, source, source, source).subscribe(ts); + Observable.concatArrayEager(source, source, source, source, source).subscribe(to); Assert.assertEquals(5, count.get()); - ts.assertValueCount(count.get()); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValueCount(count.get()); + to.assertNoErrors(); + to.assertComplete(); } @SuppressWarnings("unchecked") @@ -389,13 +389,13 @@ public void accept(Integer t) { } }).hide(); - Observable.concatArrayEager(source, source, source, source, source, source).subscribe(ts); + Observable.concatArrayEager(source, source, source, source, source, source).subscribe(to); Assert.assertEquals(6, count.get()); - ts.assertValueCount(count.get()); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValueCount(count.get()); + to.assertNoErrors(); + to.assertComplete(); } @SuppressWarnings("unchecked") @@ -409,13 +409,13 @@ public void accept(Integer t) { } }).hide(); - Observable.concatArrayEager(source, source, source, source, source, source, source).subscribe(ts); + Observable.concatArrayEager(source, source, source, source, source, source, source).subscribe(to); Assert.assertEquals(7, count.get()); - ts.assertValueCount(count.get()); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValueCount(count.get()); + to.assertNoErrors(); + to.assertComplete(); } @SuppressWarnings("unchecked") @@ -429,13 +429,13 @@ public void accept(Integer t) { } }).hide(); - Observable.concatArrayEager(source, source, source, source, source, source, source, source).subscribe(ts); + Observable.concatArrayEager(source, source, source, source, source, source, source, source).subscribe(to); Assert.assertEquals(8, count.get()); - ts.assertValueCount(count.get()); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValueCount(count.get()); + to.assertNoErrors(); + to.assertComplete(); } @SuppressWarnings("unchecked") @@ -449,22 +449,22 @@ public void accept(Integer t) { } }).hide(); - Observable.concatArrayEager(source, source, source, source, source, source, source, source, source).subscribe(ts); + Observable.concatArrayEager(source, source, source, source, source, source, source, source, source).subscribe(to); Assert.assertEquals(9, count.get()); - ts.assertValueCount(count.get()); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValueCount(count.get()); + to.assertNoErrors(); + to.assertComplete(); } @Test public void testMainError() { - Observable.error(new TestException()).concatMapEager(toJust).subscribe(ts); + Observable.error(new TestException()).concatMapEager(toJust).subscribe(to); - ts.assertNoValues(); - ts.assertError(TestException.class); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertError(TestException.class); + to.assertNotComplete(); } @SuppressWarnings("unchecked") @@ -475,23 +475,23 @@ public void testInnerError() { PublishSubject ps = PublishSubject.create(); Observable.concatArrayEager(Observable.just(1), ps) - .subscribe(ts); + .subscribe(to); ps.onError(new TestException()); - ts.assertValue(1); - ts.assertError(TestException.class); - ts.assertNotComplete(); + to.assertValue(1); + to.assertError(TestException.class); + to.assertNotComplete(); } @SuppressWarnings("unchecked") @Test public void testInnerEmpty() { - Observable.concatArrayEager(Observable.empty(), Observable.empty()).subscribe(ts); + Observable.concatArrayEager(Observable.empty(), Observable.empty()).subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertComplete(); } @Test @@ -501,11 +501,11 @@ public void testMapperThrows() { public Observable apply(Integer t) { throw new TestException(); } - }).subscribe(ts); + }).subscribe(to); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(TestException.class); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(TestException.class); } @Test(expected = IllegalArgumentException.class) @@ -546,11 +546,11 @@ public void testAsynchronousRun() { public Observable apply(Integer t) { return Observable.range(1, 1000).subscribeOn(Schedulers.computation()); } - }).observeOn(Schedulers.newThread()).subscribe(ts); + }).observeOn(Schedulers.newThread()).subscribe(to); - ts.awaitTerminalEvent(5, TimeUnit.SECONDS); - ts.assertNoErrors(); - ts.assertValueCount(2000); + to.awaitTerminalEvent(5, TimeUnit.SECONDS); + to.assertNoErrors(); + to.assertValueCount(2000); } @Test @@ -573,13 +573,13 @@ public void accept(Integer t) { } } }) - .subscribe(ts); + .subscribe(to); subject.onNext(1); - ts.assertNoErrors(); - ts.assertNotComplete(); - ts.assertValues(1, 2); + to.assertNoErrors(); + to.assertNotComplete(); + to.assertValues(1, 2); } @Test @@ -587,7 +587,7 @@ public void accept(Integer t) { public void testPrefetchIsBounded() { final AtomicInteger count = new AtomicInteger(); - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); Observable.just(1).concatMapEager(new Function>() { @Override @@ -600,11 +600,11 @@ public void accept(Integer t) { } }).hide(); } - }).subscribe(ts); + }).subscribe(to); - ts.assertNoErrors(); - ts.assertNoValues(); - ts.assertNotComplete(); + to.assertNoErrors(); + to.assertNoValues(); + to.assertNotComplete(); Assert.assertEquals(Observable.bufferSize(), count.get()); } @@ -616,11 +616,11 @@ public void testInnerNull() { public Observable apply(Integer t) { return Observable.just(null); } - }).subscribe(ts); + }).subscribe(to); - ts.assertNoErrors(); - ts.assertComplete(); - ts.assertValue(null); + to.assertNoErrors(); + to.assertComplete(); + to.assertValue(null); } @@ -663,13 +663,13 @@ public void many() throws Exception { Method m = Observable.class.getMethod("concatEager", clazz); - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ((Observable)m.invoke(null, (Object[])obs)).subscribe(ts); + ((Observable)m.invoke(null, (Object[])obs)).subscribe(to); - ts.assertValues(expected); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValues(expected); + to.assertNoErrors(); + to.assertComplete(); } } @@ -677,37 +677,37 @@ public void many() throws Exception { @Test public void capacityHint() { Observable source = Observable.just(1); - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - Observable.concatEager(Arrays.asList(source, source, source), 1, 1).subscribe(ts); + Observable.concatEager(Arrays.asList(source, source, source), 1, 1).subscribe(to); - ts.assertValues(1, 1, 1); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValues(1, 1, 1); + to.assertNoErrors(); + to.assertComplete(); } @Test public void Observable() { Observable source = Observable.just(1); - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - Observable.concatEager(Observable.just(source, source, source)).subscribe(ts); + Observable.concatEager(Observable.just(source, source, source)).subscribe(to); - ts.assertValues(1, 1, 1); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValues(1, 1, 1); + to.assertNoErrors(); + to.assertComplete(); } @Test public void ObservableCapacityHint() { Observable source = Observable.just(1); - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - Observable.concatEager(Observable.just(source, source, source), 1, 1).subscribe(ts); + Observable.concatEager(Observable.just(source, source, source), 1, 1).subscribe(to); - ts.assertValues(1, 1, 1); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValues(1, 1, 1); + to.assertNoErrors(); + to.assertComplete(); } @SuppressWarnings("unchecked") diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java index 2a158cb714..f1f95d2f68 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java @@ -393,17 +393,17 @@ public void testConcatUnsubscribe() { final TestObservable w2 = new TestObservable(callOnce, okToContinue, "four", "five", "six"); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); final Observable concat = Observable.concat(Observable.unsafeCreate(w1), Observable.unsafeCreate(w2)); try { // Subscribe - concat.subscribe(ts); + concat.subscribe(to); //Block main thread to allow Observable "w1" to complete and Observable "w2" to call onNext once. callOnce.await(); // Unsubcribe - ts.dispose(); + to.dispose(); //Unblock the Observable to continue. okToContinue.countDown(); w1.t.join(); @@ -435,19 +435,19 @@ public void testConcatUnsubscribeConcurrent() { final TestObservable w2 = new TestObservable(callOnce, okToContinue, "four", "five", "six"); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); @SuppressWarnings("unchecked") TestObservable> observableOfObservables = new TestObservable>(Observable.unsafeCreate(w1), Observable.unsafeCreate(w2)); Observable concatF = Observable.concat(Observable.unsafeCreate(observableOfObservables)); - concatF.subscribe(ts); + concatF.subscribe(to); try { //Block main thread to allow Observable "w1" to complete and Observable "w2" to call onNext exactly once. callOnce.await(); //"four" from w2 has been processed by onNext() - ts.dispose(); + to.dispose(); //"five" and "six" will NOT be processed by onNext() //Unblock the Observable to continue. okToContinue.countDown(); @@ -672,12 +672,12 @@ public void subscribe(Observer s) { }); - TestObserver ts = new TestObserver(); - Observable.concat(o, o).subscribe(ts); - ts.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); - ts.assertTerminated(); - ts.assertNoErrors(); - ts.assertValues("hello", "hello"); + TestObserver to = new TestObserver(); + Observable.concat(o, o).subscribe(to); + to.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); + to.assertTerminated(); + to.assertNoErrors(); + to.assertValues("hello", "hello"); } @Test(timeout = 30000) @@ -743,7 +743,7 @@ public void concatMapRangeAsyncLoopIssue2876() { if (i % 1000 == 0) { System.out.println("concatMapRangeAsyncLoop > " + i); } - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(0, 1000) .concatMap(new Function>() { @Override @@ -751,13 +751,13 @@ public Observable apply(Integer t) { return Observable.fromIterable(Arrays.asList(t)); } }) - .observeOn(Schedulers.computation()).subscribe(ts); + .observeOn(Schedulers.computation()).subscribe(to); - ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); - ts.assertTerminated(); - ts.assertNoErrors(); - assertEquals(1000, ts.valueCount()); - assertEquals((Integer)999, ts.values().get(999)); + to.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); + to.assertTerminated(); + to.assertNoErrors(); + assertEquals(1000, to.valueCount()); + assertEquals((Integer)999, to.values().get(999)); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java index c2ad3b5ae1..e6a17f1d5a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java @@ -28,75 +28,75 @@ public class ObservableConcatWithCompletableTest { @Test public void normal() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.range(1, 5) .concatWith(Completable.fromAction(new Action() { @Override public void run() throws Exception { - ts.onNext(100); + to.onNext(100); } })) - .subscribe(ts); + .subscribe(to); - ts.assertResult(1, 2, 3, 4, 5, 100); + to.assertResult(1, 2, 3, 4, 5, 100); } @Test public void mainError() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.error(new TestException()) .concatWith(Completable.fromAction(new Action() { @Override public void run() throws Exception { - ts.onNext(100); + to.onNext(100); } })) - .subscribe(ts); + .subscribe(to); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test public void otherError() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.range(1, 5) .concatWith(Completable.error(new TestException())) - .subscribe(ts); + .subscribe(to); - ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); + to.assertFailure(TestException.class, 1, 2, 3, 4, 5); } @Test public void takeMain() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.range(1, 5) .concatWith(Completable.fromAction(new Action() { @Override public void run() throws Exception { - ts.onNext(100); + to.onNext(100); } })) .take(3) - .subscribe(ts); + .subscribe(to); - ts.assertResult(1, 2, 3); + to.assertResult(1, 2, 3); } @Test public void cancelOther() { CompletableSubject other = CompletableSubject.create(); - TestObserver ts = Observable.empty() + TestObserver to = Observable.empty() .concatWith(other) .test(); assertTrue(other.hasObservers()); - ts.cancel(); + to.cancel(); assertFalse(other.hasObservers()); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java index 586d9315e4..3d323a979a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java @@ -28,87 +28,87 @@ public class ObservableConcatWithMaybeTest { @Test public void normalEmpty() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.range(1, 5) .concatWith(Maybe.fromAction(new Action() { @Override public void run() throws Exception { - ts.onNext(100); + to.onNext(100); } })) - .subscribe(ts); + .subscribe(to); - ts.assertResult(1, 2, 3, 4, 5, 100); + to.assertResult(1, 2, 3, 4, 5, 100); } @Test public void normalNonEmpty() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.range(1, 5) .concatWith(Maybe.just(100)) - .subscribe(ts); + .subscribe(to); - ts.assertResult(1, 2, 3, 4, 5, 100); + to.assertResult(1, 2, 3, 4, 5, 100); } @Test public void mainError() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.error(new TestException()) .concatWith(Maybe.fromAction(new Action() { @Override public void run() throws Exception { - ts.onNext(100); + to.onNext(100); } })) - .subscribe(ts); + .subscribe(to); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test public void otherError() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.range(1, 5) .concatWith(Maybe.error(new TestException())) - .subscribe(ts); + .subscribe(to); - ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); + to.assertFailure(TestException.class, 1, 2, 3, 4, 5); } @Test public void takeMain() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.range(1, 5) .concatWith(Maybe.fromAction(new Action() { @Override public void run() throws Exception { - ts.onNext(100); + to.onNext(100); } })) .take(3) - .subscribe(ts); + .subscribe(to); - ts.assertResult(1, 2, 3); + to.assertResult(1, 2, 3); } @Test public void cancelOther() { MaybeSubject other = MaybeSubject.create(); - TestObserver ts = Observable.empty() + TestObserver to = Observable.empty() .concatWith(other) .test(); assertTrue(other.hasObservers()); - ts.cancel(); + to.cancel(); assertFalse(other.hasObservers()); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java index 5fc06d83e3..3de6edfd0f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java @@ -27,60 +27,60 @@ public class ObservableConcatWithSingleTest { @Test public void normal() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.range(1, 5) .concatWith(Single.just(100)) - .subscribe(ts); + .subscribe(to); - ts.assertResult(1, 2, 3, 4, 5, 100); + to.assertResult(1, 2, 3, 4, 5, 100); } @Test public void mainError() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.error(new TestException()) .concatWith(Single.just(100)) - .subscribe(ts); + .subscribe(to); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test public void otherError() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.range(1, 5) .concatWith(Single.error(new TestException())) - .subscribe(ts); + .subscribe(to); - ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); + to.assertFailure(TestException.class, 1, 2, 3, 4, 5); } @Test public void takeMain() { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observable.range(1, 5) .concatWith(Single.just(100)) .take(3) - .subscribe(ts); + .subscribe(to); - ts.assertResult(1, 2, 3); + to.assertResult(1, 2, 3); } @Test public void cancelOther() { SingleSubject other = SingleSubject.create(); - TestObserver ts = Observable.empty() + TestObserver to = Observable.empty() .concatWith(other) .test(); assertTrue(other.hasObservers()); - ts.cancel(); + to.cancel(); assertFalse(other.hasObservers()); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDelaySubscriptionOtherTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDelaySubscriptionOtherTest.java index 566bf0ffb3..6c416421a7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDelaySubscriptionOtherTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDelaySubscriptionOtherTest.java @@ -31,7 +31,7 @@ public class ObservableDelaySubscriptionOtherTest { public void testNoPrematureSubscription() { PublishSubject other = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger subscribed = new AtomicInteger(); @@ -43,11 +43,11 @@ public void accept(Disposable d) { } }) .delaySubscription(other) - .subscribe(ts); + .subscribe(to); - ts.assertNotComplete(); - ts.assertNoErrors(); - ts.assertNoValues(); + to.assertNotComplete(); + to.assertNoErrors(); + to.assertNoValues(); Assert.assertEquals("Premature subscription", 0, subscribed.get()); @@ -55,16 +55,16 @@ public void accept(Disposable d) { Assert.assertEquals("No subscription", 1, subscribed.get()); - ts.assertValue(1); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(1); + to.assertNoErrors(); + to.assertComplete(); } @Test public void testNoMultipleSubscriptions() { PublishSubject other = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger subscribed = new AtomicInteger(); @@ -76,11 +76,11 @@ public void accept(Disposable d) { } }) .delaySubscription(other) - .subscribe(ts); + .subscribe(to); - ts.assertNotComplete(); - ts.assertNoErrors(); - ts.assertNoValues(); + to.assertNotComplete(); + to.assertNoErrors(); + to.assertNoValues(); Assert.assertEquals("Premature subscription", 0, subscribed.get()); @@ -89,16 +89,16 @@ public void accept(Disposable d) { Assert.assertEquals("No subscription", 1, subscribed.get()); - ts.assertValue(1); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(1); + to.assertNoErrors(); + to.assertComplete(); } @Test public void testCompleteTriggersSubscription() { PublishSubject other = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger subscribed = new AtomicInteger(); @@ -110,11 +110,11 @@ public void accept(Disposable d) { } }) .delaySubscription(other) - .subscribe(ts); + .subscribe(to); - ts.assertNotComplete(); - ts.assertNoErrors(); - ts.assertNoValues(); + to.assertNotComplete(); + to.assertNoErrors(); + to.assertNoValues(); Assert.assertEquals("Premature subscription", 0, subscribed.get()); @@ -122,16 +122,16 @@ public void accept(Disposable d) { Assert.assertEquals("No subscription", 1, subscribed.get()); - ts.assertValue(1); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(1); + to.assertNoErrors(); + to.assertComplete(); } @Test public void testNoPrematureSubscriptionToError() { PublishSubject other = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger subscribed = new AtomicInteger(); @@ -143,11 +143,11 @@ public void accept(Disposable d) { } }) .delaySubscription(other) - .subscribe(ts); + .subscribe(to); - ts.assertNotComplete(); - ts.assertNoErrors(); - ts.assertNoValues(); + to.assertNotComplete(); + to.assertNoErrors(); + to.assertNoValues(); Assert.assertEquals("Premature subscription", 0, subscribed.get()); @@ -155,16 +155,16 @@ public void accept(Disposable d) { Assert.assertEquals("No subscription", 1, subscribed.get()); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(TestException.class); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(TestException.class); } @Test public void testNoSubscriptionIfOtherErrors() { PublishSubject other = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger subscribed = new AtomicInteger(); @@ -176,11 +176,11 @@ public void accept(Disposable d) { } }) .delaySubscription(other) - .subscribe(ts); + .subscribe(to); - ts.assertNotComplete(); - ts.assertNoErrors(); - ts.assertNoValues(); + to.assertNotComplete(); + to.assertNoErrors(); + to.assertNoValues(); Assert.assertEquals("Premature subscription", 0, subscribed.get()); @@ -188,9 +188,9 @@ public void accept(Disposable d) { Assert.assertEquals("Premature subscription", 0, subscribed.get()); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(TestException.class); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(TestException.class); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDelayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDelayTest.java index 9073b4ee93..1088f2abc1 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDelayTest.java @@ -218,10 +218,10 @@ public void testDelaySubscriptionDisposeBeforeTime() { Observable result = Observable.just(1, 2, 3).delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); Observer o = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(o); + TestObserver to = new TestObserver(o); - result.subscribe(ts); - ts.dispose(); + result.subscribe(to); + to.dispose(); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); verify(o, never()).onNext(any()); @@ -640,7 +640,7 @@ public void accept(Notification t1) { @Test public void testBackpressureWithTimedDelay() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, Flowable.bufferSize() * 2) .delay(100, TimeUnit.MILLISECONDS) .observeOn(Schedulers.computation()) @@ -659,16 +659,16 @@ public Integer apply(Integer t) { return t; } - }).subscribe(ts); + }).subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(Flowable.bufferSize() * 2, ts.valueCount()); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(Flowable.bufferSize() * 2, to.valueCount()); } @Test public void testBackpressureWithSubscriptionTimedDelay() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, Flowable.bufferSize() * 2) .delaySubscription(100, TimeUnit.MILLISECONDS) .delay(100, TimeUnit.MILLISECONDS) @@ -688,16 +688,16 @@ public Integer apply(Integer t) { return t; } - }).subscribe(ts); + }).subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(Flowable.bufferSize() * 2, ts.valueCount()); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(Flowable.bufferSize() * 2, to.valueCount()); } @Test public void testBackpressureWithSelectorDelay() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, Flowable.bufferSize() * 2) .delay(new Function>() { @@ -723,16 +723,16 @@ public Integer apply(Integer t) { return t; } - }).subscribe(ts); + }).subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(Flowable.bufferSize() * 2, ts.valueCount()); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(Flowable.bufferSize() * 2, to.valueCount()); } @Test public void testBackpressureWithSelectorDelayAndSubscriptionDelay() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, Flowable.bufferSize() * 2) .delay(Observable.timer(500, TimeUnit.MILLISECONDS) , new Function>() { @@ -759,11 +759,11 @@ public Integer apply(Integer t) { return t; } - }).subscribe(ts); + }).subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(Flowable.bufferSize() * 2, ts.valueCount()); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(Flowable.bufferSize() * 2, to.valueCount()); } @Test @@ -772,9 +772,9 @@ public void testErrorRunsBeforeOnNext() { PublishSubject ps = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - ps.delay(1, TimeUnit.SECONDS, test).subscribe(ts); + ps.delay(1, TimeUnit.SECONDS, test).subscribe(to); ps.onNext(1); @@ -784,9 +784,9 @@ public void testErrorRunsBeforeOnNext() { test.advanceTimeBy(1, TimeUnit.SECONDS); - ts.assertNoValues(); - ts.assertError(TestException.class); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertError(TestException.class); + to.assertNotComplete(); } @Test @@ -795,19 +795,19 @@ public void testDelaySupplierSimple() { Observable source = Observable.range(1, 5); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.delaySubscription(ps).subscribe(ts); + source.delaySubscription(ps).subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertNotComplete(); ps.onNext(1); - ts.assertValues(1, 2, 3, 4, 5); - ts.assertComplete(); - ts.assertNoErrors(); + to.assertValues(1, 2, 3, 4, 5); + to.assertComplete(); + to.assertNoErrors(); } @Test @@ -816,20 +816,20 @@ public void testDelaySupplierCompletes() { Observable source = Observable.range(1, 5); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.delaySubscription(ps).subscribe(ts); + source.delaySubscription(ps).subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertNotComplete(); // FIXME should this complete the source instead of consuming it? ps.onComplete(); - ts.assertValues(1, 2, 3, 4, 5); - ts.assertComplete(); - ts.assertNoErrors(); + to.assertValues(1, 2, 3, 4, 5); + to.assertComplete(); + to.assertNoErrors(); } @Test @@ -838,19 +838,19 @@ public void testDelaySupplierErrors() { Observable source = Observable.range(1, 5); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.delaySubscription(ps).subscribe(ts); + source.delaySubscription(ps).subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertNotComplete(); ps.onError(new TestException()); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(TestException.class); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(TestException.class); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java index c72ae018cc..a5017c68c4 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java @@ -96,10 +96,10 @@ public void testCompletePassThru() { Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - dematerialize.subscribe(ts); + TestObserver to = new TestObserver(observer); + dematerialize.subscribe(to); - System.out.println(ts.errors()); + System.out.println(to.errors()); verify(observer, never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java index 8c1ff32467..8a9c9f6daa 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java @@ -35,13 +35,13 @@ public void just() throws Exception { WeakReference wr = new WeakReference(o); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.just(o).count().toObservable().onTerminateDetach().subscribe(ts); + Observable.just(o).count().toObservable().onTerminateDetach().subscribe(to); - ts.assertValue(1L); - ts.assertComplete(); - ts.assertNoErrors(); + to.assertValue(1L); + to.assertComplete(); + to.assertNoErrors(); o = null; @@ -54,35 +54,35 @@ public void just() throws Exception { @Test public void error() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.error(new TestException()).onTerminateDetach().subscribe(ts); + Observable.error(new TestException()).onTerminateDetach().subscribe(to); - ts.assertNoValues(); - ts.assertError(TestException.class); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertError(TestException.class); + to.assertNotComplete(); } @Test public void empty() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.empty().onTerminateDetach().subscribe(ts); + Observable.empty().onTerminateDetach().subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertComplete(); } @Test public void range() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.range(1, 1000).onTerminateDetach().subscribe(ts); + Observable.range(1, 1000).onTerminateDetach().subscribe(to); - ts.assertValueCount(1000); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValueCount(1000); + to.assertNoErrors(); + to.assertComplete(); } @@ -93,17 +93,17 @@ public void backpressured() throws Exception { // // WeakReference wr = new WeakReference(o); // -// TestObserver ts = new TestObserver(0L); +// TestObserver to = new TestObserver(0L); // // Observable.just(o).count().onTerminateDetach().subscribe(ts); // -// ts.assertNoValues(); +// to.assertNoValues(); // -// ts.request(1); +// to.request(1); // -// ts.assertValue(1L); -// ts.assertComplete(); -// ts.assertNoErrors(); +// to.assertValue(1L); +// to.assertComplete(); +// to.assertNoErrors(); // // o = null; // @@ -119,10 +119,10 @@ public void justUnsubscribed() throws Exception { WeakReference wr = new WeakReference(o); - TestObserver ts = Observable.just(o).count().toObservable().onTerminateDetach().test(); + TestObserver to = Observable.just(o).count().toObservable().onTerminateDetach().test(); o = null; - ts.cancel(); + to.cancel(); System.gc(); Thread.sleep(200); @@ -136,26 +136,26 @@ public void justUnsubscribed() throws Exception { public void deferredUpstreamProducer() { // final AtomicReference> subscriber = new AtomicReference>(); // -// TestObserver ts = new TestObserver(0); +// TestObserver to = new TestObserver(0); // // Observable.unsafeCreate(new ObservableSource() { // @Override // public void subscribe(Subscriber t) { // subscriber.set(t); // } -// }).onTerminateDetach().subscribe(ts); +// }).onTerminateDetach().subscribe(to); // -// ts.request(2); +// to.request(2); // // new ObservableRange(1, 3).subscribe(subscriber.get()); // -// ts.assertValues(1, 2); +// to.assertValues(1, 2); // -// ts.request(1); +// to.request(1); // -// ts.assertValues(1, 2, 3); -// ts.assertComplete(); -// ts.assertNoErrors(); +// to.assertValues(1, 2, 3); +// to.assertComplete(); +// to.assertNoErrors(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctTest.java index 299a5c3010..8114d64f9a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctTest.java @@ -30,7 +30,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.UnicastSubject; @@ -144,19 +144,19 @@ public void error() { @Test public void fusedSync() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); Observable.just(1, 1, 2, 1, 3, 2, 4, 5, 4) .distinct() .subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.SYNC) + ObserverFusion.assertFusion(to, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); } @Test public void fusedAsync() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); UnicastSubject us = UnicastSubject.create(); @@ -166,7 +166,7 @@ public void fusedAsync() { TestHelper.emit(us, 1, 1, 2, 1, 3, 2, 4, 5, 4); - ObserverFusion.assertFusion(to, QueueDisposable.ASYNC) + ObserverFusion.assertFusion(to, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java index c519e3d036..74bc2dfbfd 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java @@ -26,7 +26,7 @@ import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.*; @@ -142,7 +142,7 @@ public void testDistinctUntilChangedOfSourceWithExceptionsFromKeySelector() { public void customComparator() { Observable source = Observable.just("a", "b", "B", "A","a", "C"); - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); source.distinctUntilChanged(new BiPredicate() { @Override @@ -150,18 +150,18 @@ public boolean test(String a, String b) { return a.compareToIgnoreCase(b) == 0; } }) - .subscribe(ts); + .subscribe(to); - ts.assertValues("a", "b", "A", "C"); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValues("a", "b", "A", "C"); + to.assertNoErrors(); + to.assertComplete(); } @Test public void customComparatorThrows() { Observable source = Observable.just("a", "b", "B", "A","a", "C"); - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); source.distinctUntilChanged(new BiPredicate() { @Override @@ -169,16 +169,16 @@ public boolean test(String a, String b) { throw new TestException(); } }) - .subscribe(ts); + .subscribe(to); - ts.assertValue("a"); - ts.assertNotComplete(); - ts.assertError(TestException.class); + to.assertValue("a"); + to.assertNotComplete(); + to.assertError(TestException.class); } @Test public void fused() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); Observable.just(1, 2, 2, 3, 3, 4, 5) .distinctUntilChanged(new BiPredicate() { @@ -190,14 +190,14 @@ public boolean test(Integer a, Integer b) throws Exception { .subscribe(to); to.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.SYNC)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(1, 2, 3, 4, 5) ; } @Test public void fusedAsync() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); UnicastSubject up = UnicastSubject.create(); @@ -213,7 +213,7 @@ public boolean test(Integer a, Integer b) throws Exception { TestHelper.emit(up, 1, 2, 2, 3, 3, 4, 5); to.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.ASYNC)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2, 3, 4, 5) ; } @@ -257,9 +257,9 @@ class Mutable { public void mutableWithSelector() { Mutable m = new Mutable(); - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.distinctUntilChanged(new Function() { + TestObserver to = ps.distinctUntilChanged(new Function() { @Override public Object apply(Mutable m) throws Exception { return m.value; @@ -267,11 +267,11 @@ public Object apply(Mutable m) throws Exception { }) .test(); - pp.onNext(m); + ps.onNext(m); m.value = 1; - pp.onNext(m); - pp.onComplete(); + ps.onNext(m); + ps.onComplete(); - ts.assertResult(m, m); + to.assertResult(m, m); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoAfterNextTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoAfterNextTest.java index a6002a9117..a091306b9e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoAfterNextTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoAfterNextTest.java @@ -24,7 +24,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.Consumer; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.observers.*; import io.reactivex.subjects.UnicastSubject; @@ -39,7 +39,7 @@ public void accept(Integer e) throws Exception { } }; - final TestObserver ts = new TestObserver() { + final TestObserver to = new TestObserver() { @Override public void onNext(Integer t) { super.onNext(t); @@ -51,7 +51,7 @@ public void onNext(Integer t) { public void just() { Observable.just(1) .doAfterNext(afterNext) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1); assertEquals(Arrays.asList(1, -1), values); @@ -62,7 +62,7 @@ public void justHidden() { Observable.just(1) .hide() .doAfterNext(afterNext) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1); assertEquals(Arrays.asList(1, -1), values); @@ -72,7 +72,7 @@ public void justHidden() { public void range() { Observable.range(1, 5) .doAfterNext(afterNext) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(1, -1, 2, -2, 3, -3, 4, -4, 5, -5), values); @@ -82,7 +82,7 @@ public void range() { public void error() { Observable.error(new TestException()) .doAfterNext(afterNext) - .subscribeWith(ts) + .subscribeWith(to) .assertFailure(TestException.class); assertTrue(values.isEmpty()); @@ -92,7 +92,7 @@ public void error() { public void empty() { Observable.empty() .doAfterNext(afterNext) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(); assertTrue(values.isEmpty()); @@ -100,13 +100,13 @@ public void empty() { @Test public void syncFused() { - TestObserver ts0 = ObserverFusion.newTest(QueueSubscription.SYNC); + TestObserver to0 = ObserverFusion.newTest(QueueFuseable.SYNC); Observable.range(1, 5) .doAfterNext(afterNext) - .subscribe(ts0); + .subscribe(to0); - ObserverFusion.assertFusion(ts0, QueueSubscription.SYNC) + ObserverFusion.assertFusion(to0, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -114,13 +114,13 @@ public void syncFused() { @Test public void asyncFusedRejected() { - TestObserver ts0 = ObserverFusion.newTest(QueueSubscription.ASYNC); + TestObserver to0 = ObserverFusion.newTest(QueueFuseable.ASYNC); Observable.range(1, 5) .doAfterNext(afterNext) - .subscribe(ts0); + .subscribe(to0); - ObserverFusion.assertFusion(ts0, QueueSubscription.NONE) + ObserverFusion.assertFusion(to0, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -128,7 +128,7 @@ public void asyncFusedRejected() { @Test public void asyncFused() { - TestObserver ts0 = ObserverFusion.newTest(QueueSubscription.ASYNC); + TestObserver to0 = ObserverFusion.newTest(QueueFuseable.ASYNC); UnicastSubject up = UnicastSubject.create(); @@ -136,9 +136,9 @@ public void asyncFused() { up .doAfterNext(afterNext) - .subscribe(ts0); + .subscribe(to0); - ObserverFusion.assertFusion(ts0, QueueSubscription.ASYNC) + ObserverFusion.assertFusion(to0, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -154,7 +154,7 @@ public void justConditional() { Observable.just(1) .doAfterNext(afterNext) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1); assertEquals(Arrays.asList(1, -1), values); @@ -165,7 +165,7 @@ public void rangeConditional() { Observable.range(1, 5) .doAfterNext(afterNext) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(1, -1, 2, -2, 3, -3, 4, -4, 5, -5), values); @@ -176,7 +176,7 @@ public void errorConditional() { Observable.error(new TestException()) .doAfterNext(afterNext) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertFailure(TestException.class); assertTrue(values.isEmpty()); @@ -187,7 +187,7 @@ public void emptyConditional() { Observable.empty() .doAfterNext(afterNext) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(); assertTrue(values.isEmpty()); @@ -195,14 +195,14 @@ public void emptyConditional() { @Test public void syncFusedConditional() { - TestObserver ts0 = ObserverFusion.newTest(QueueSubscription.SYNC); + TestObserver to0 = ObserverFusion.newTest(QueueFuseable.SYNC); Observable.range(1, 5) .doAfterNext(afterNext) .filter(Functions.alwaysTrue()) - .subscribe(ts0); + .subscribe(to0); - ObserverFusion.assertFusion(ts0, QueueSubscription.SYNC) + ObserverFusion.assertFusion(to0, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -210,14 +210,14 @@ public void syncFusedConditional() { @Test public void asyncFusedRejectedConditional() { - TestObserver ts0 = ObserverFusion.newTest(QueueSubscription.ASYNC); + TestObserver to0 = ObserverFusion.newTest(QueueFuseable.ASYNC); Observable.range(1, 5) .doAfterNext(afterNext) .filter(Functions.alwaysTrue()) - .subscribe(ts0); + .subscribe(to0); - ObserverFusion.assertFusion(ts0, QueueSubscription.NONE) + ObserverFusion.assertFusion(to0, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); @@ -225,7 +225,7 @@ public void asyncFusedRejectedConditional() { @Test public void asyncFusedConditional() { - TestObserver ts0 = ObserverFusion.newTest(QueueSubscription.ASYNC); + TestObserver to0 = ObserverFusion.newTest(QueueFuseable.ASYNC); UnicastSubject up = UnicastSubject.create(); @@ -234,9 +234,9 @@ public void asyncFusedConditional() { up .doAfterNext(afterNext) .filter(Functions.alwaysTrue()) - .subscribe(ts0); + .subscribe(to0); - ObserverFusion.assertFusion(ts0, QueueSubscription.ASYNC) + ObserverFusion.assertFusion(to0, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java index 27ae321f4f..5cdb2bed8b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java @@ -26,7 +26,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.UnicastSubject; @@ -99,13 +99,13 @@ public Observable apply(Observable f) throws Exception { @Test public void syncFused() { - TestObserver ts = ObserverFusion.newTest(QueueDisposable.SYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC); Observable.range(1, 5) .doFinally(this) - .subscribe(ts); + .subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.SYNC) + ObserverFusion.assertFusion(to, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -113,13 +113,13 @@ public void syncFused() { @Test public void syncFusedBoundary() { - TestObserver ts = ObserverFusion.newTest(QueueDisposable.SYNC | QueueDisposable.BOUNDARY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC | QueueFuseable.BOUNDARY); Observable.range(1, 5) .doFinally(this) - .subscribe(ts); + .subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -127,16 +127,16 @@ public void syncFusedBoundary() { @Test public void asyncFused() { - TestObserver ts = ObserverFusion.newTest(QueueDisposable.ASYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ASYNC); UnicastSubject up = UnicastSubject.create(); TestHelper.emit(up, 1, 2, 3, 4, 5); up .doFinally(this) - .subscribe(ts); + .subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.ASYNC) + ObserverFusion.assertFusion(to, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -144,16 +144,16 @@ public void asyncFused() { @Test public void asyncFusedBoundary() { - TestObserver ts = ObserverFusion.newTest(QueueDisposable.ASYNC | QueueDisposable.BOUNDARY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ASYNC | QueueFuseable.BOUNDARY); UnicastSubject up = UnicastSubject.create(); TestHelper.emit(up, 1, 2, 3, 4, 5); up .doFinally(this) - .subscribe(ts); + .subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -207,14 +207,14 @@ public void normalTakeConditional() { @Test public void syncFusedConditional() { - TestObserver ts = ObserverFusion.newTest(QueueDisposable.SYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC); Observable.range(1, 5) .doFinally(this) .filter(Functions.alwaysTrue()) - .subscribe(ts); + .subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.SYNC) + ObserverFusion.assertFusion(to, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -222,13 +222,13 @@ public void syncFusedConditional() { @Test public void nonFused() { - TestObserver ts = ObserverFusion.newTest(QueueDisposable.SYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC); Observable.range(1, 5).hide() .doFinally(this) - .subscribe(ts); + .subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -236,14 +236,14 @@ public void nonFused() { @Test public void nonFusedConditional() { - TestObserver ts = ObserverFusion.newTest(QueueDisposable.SYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC); Observable.range(1, 5).hide() .doFinally(this) .filter(Functions.alwaysTrue()) - .subscribe(ts); + .subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -251,14 +251,14 @@ public void nonFusedConditional() { @Test public void syncFusedBoundaryConditional() { - TestObserver ts = ObserverFusion.newTest(QueueDisposable.SYNC | QueueDisposable.BOUNDARY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC | QueueFuseable.BOUNDARY); Observable.range(1, 5) .doFinally(this) .filter(Functions.alwaysTrue()) - .subscribe(ts); + .subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -266,7 +266,7 @@ public void syncFusedBoundaryConditional() { @Test public void asyncFusedConditional() { - TestObserver ts = ObserverFusion.newTest(QueueDisposable.ASYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ASYNC); UnicastSubject up = UnicastSubject.create(); TestHelper.emit(up, 1, 2, 3, 4, 5); @@ -274,9 +274,9 @@ public void asyncFusedConditional() { up .doFinally(this) .filter(Functions.alwaysTrue()) - .subscribe(ts); + .subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.ASYNC) + ObserverFusion.assertFusion(to, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -284,7 +284,7 @@ public void asyncFusedConditional() { @Test public void asyncFusedBoundaryConditional() { - TestObserver ts = ObserverFusion.newTest(QueueDisposable.ASYNC | QueueDisposable.BOUNDARY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ASYNC | QueueFuseable.BOUNDARY); UnicastSubject up = UnicastSubject.create(); TestHelper.emit(up, 1, 2, 3, 4, 5); @@ -292,9 +292,9 @@ public void asyncFusedBoundaryConditional() { up .doFinally(this) .filter(Functions.alwaysTrue()) - .subscribe(ts); + .subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); assertEquals(1, calls); @@ -359,7 +359,7 @@ public void onSubscribe(Disposable s) { @SuppressWarnings("unchecked") QueueDisposable qs = (QueueDisposable)s; - qs.requestFusion(QueueDisposable.ANY); + qs.requestFusion(QueueFuseable.ANY); assertFalse(qs.isEmpty()); @@ -406,7 +406,7 @@ public void onSubscribe(Disposable s) { @SuppressWarnings("unchecked") QueueDisposable qs = (QueueDisposable)s; - qs.requestFusion(QueueDisposable.ANY); + qs.requestFusion(QueueFuseable.ANY); assertFalse(qs.isEmpty()); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java index e1640677a7..20538da8ca 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java @@ -28,7 +28,7 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.UnicastSubject; @@ -201,7 +201,7 @@ public void accept(List booleans) { @Test public void onErrorThrows() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); Observable.error(new TestException()) .doOnError(new Consumer() { @@ -209,13 +209,13 @@ public void onErrorThrows() { public void accept(Throwable e) { throw new TestException(); } - }).subscribe(ts); + }).subscribe(to); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(CompositeException.class); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(CompositeException.class); - CompositeException ex = (CompositeException)ts.errors().get(0); + CompositeException ex = (CompositeException)to.errors().get(0); List exceptions = ex.getExceptions(); assertEquals(2, exceptions.size()); @@ -451,7 +451,7 @@ public void run() throws Exception { @Test public void onErrorOnErrorCrashConditional() { - TestObserver ts = Observable.error(new TestException("Outer")) + TestObserver to = Observable.error(new TestException("Outer")) .doOnError(new Consumer() { @Override public void accept(Throwable e) throws Exception { @@ -462,7 +462,7 @@ public void accept(Throwable e) throws Exception { .test() .assertFailure(CompositeException.class); - List errors = TestHelper.compositeList(ts.errors().get(0)); + List errors = TestHelper.compositeList(to.errors().get(0)); TestHelper.assertError(errors, 0, TestException.class, "Outer"); TestHelper.assertError(errors, 1, TestException.class, "Inner"); @@ -471,7 +471,7 @@ public void accept(Throwable e) throws Exception { @Test @Ignore("Fusion not supported yet") // TODO decide/implement fusion public void fused() { - TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); final int[] call = { 0, 0 }; @@ -488,10 +488,10 @@ public void run() throws Exception { call[1]++; } }) - .subscribe(ts); + .subscribe(to); - ts.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.SYNC)) + to.assertOf(ObserverFusion.assertFuseable()) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(1, 2, 3, 4, 5); assertEquals(5, call[0]); @@ -501,7 +501,7 @@ public void run() throws Exception { @Test @Ignore("Fusion not supported yet") // TODO decide/implement fusion public void fusedOnErrorCrash() { - TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); final int[] call = { 0 }; @@ -518,10 +518,10 @@ public void run() throws Exception { call[0]++; } }) - .subscribe(ts); + .subscribe(to); - ts.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.SYNC)) + to.assertOf(ObserverFusion.assertFuseable()) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.SYNC)) .assertFailure(TestException.class); assertEquals(0, call[0]); @@ -530,7 +530,7 @@ public void run() throws Exception { @Test @Ignore("Fusion not supported yet") // TODO decide/implement fusion public void fusedConditional() { - TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); final int[] call = { 0, 0 }; @@ -548,10 +548,10 @@ public void run() throws Exception { } }) .filter(Functions.alwaysTrue()) - .subscribe(ts); + .subscribe(to); - ts.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.SYNC)) + to.assertOf(ObserverFusion.assertFuseable()) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.SYNC)) .assertResult(1, 2, 3, 4, 5); assertEquals(5, call[0]); @@ -561,7 +561,7 @@ public void run() throws Exception { @Test @Ignore("Fusion not supported yet") // TODO decide/implement fusion public void fusedOnErrorCrashConditional() { - TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); final int[] call = { 0 }; @@ -579,10 +579,10 @@ public void run() throws Exception { } }) .filter(Functions.alwaysTrue()) - .subscribe(ts); + .subscribe(to); - ts.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.SYNC)) + to.assertOf(ObserverFusion.assertFuseable()) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.SYNC)) .assertFailure(TestException.class); assertEquals(0, call[0]); @@ -591,7 +591,7 @@ public void run() throws Exception { @Test @Ignore("Fusion not supported yet") // TODO decide/implement fusion public void fusedAsync() { - TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); final int[] call = { 0, 0 }; @@ -610,12 +610,12 @@ public void run() throws Exception { call[1]++; } }) - .subscribe(ts); + .subscribe(to); TestHelper.emit(up, 1, 2, 3, 4, 5); - ts.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.ASYNC)) + to.assertOf(ObserverFusion.assertFuseable()) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2, 3, 4, 5); assertEquals(5, call[0]); @@ -625,7 +625,7 @@ public void run() throws Exception { @Test @Ignore("Fusion not supported yet") // TODO decide/implement fusion public void fusedAsyncConditional() { - TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); final int[] call = { 0, 0 }; @@ -645,12 +645,12 @@ public void run() throws Exception { } }) .filter(Functions.alwaysTrue()) - .subscribe(ts); + .subscribe(to); TestHelper.emit(up, 1, 2, 3, 4, 5); - ts.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.ASYNC)) + to.assertOf(ObserverFusion.assertFuseable()) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2, 3, 4, 5); assertEquals(5, call[0]); @@ -660,7 +660,7 @@ public void run() throws Exception { @Test @Ignore("Fusion not supported yet") // TODO decide/implement fusion public void fusedAsyncConditional2() { - TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); final int[] call = { 0, 0 }; @@ -680,12 +680,12 @@ public void run() throws Exception { } }) .filter(Functions.alwaysTrue()) - .subscribe(ts); + .subscribe(to); TestHelper.emit(up, 1, 2, 3, 4, 5); - ts.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.NONE)) + to.assertOf(ObserverFusion.assertFuseable()) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.NONE)) .assertResult(1, 2, 3, 4, 5); assertEquals(5, call[0]); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFilterTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFilterTest.java index 0ddb43e8b6..e855c07820 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFilterTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFilterTest.java @@ -23,7 +23,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; import io.reactivex.subjects.UnicastSubject; @@ -94,7 +94,7 @@ public ObservableSource apply(Observable o) throws Exception { @Test public void fusedSync() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); Observable.range(1, 5) .filter(new Predicate() { @@ -105,13 +105,13 @@ public boolean test(Integer v) throws Exception { }) .subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.SYNC) + ObserverFusion.assertFusion(to, QueueFuseable.SYNC) .assertResult(2, 4); } @Test public void fusedAsync() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); UnicastSubject us = UnicastSubject.create(); @@ -126,13 +126,13 @@ public boolean test(Integer v) throws Exception { TestHelper.emit(us, 1, 2, 3, 4, 5); - ObserverFusion.assertFusion(to, QueueDisposable.ASYNC) + ObserverFusion.assertFusion(to, QueueFuseable.ASYNC) .assertResult(2, 4); } @Test public void fusedReject() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY | QueueDisposable.BOUNDARY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY | QueueFuseable.BOUNDARY); Observable.range(1, 5) .filter(new Predicate() { @@ -143,7 +143,7 @@ public boolean test(Integer v) throws Exception { }) .subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(2, 4); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java index 421c881c26..33ba15307e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java @@ -24,7 +24,7 @@ import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; @@ -169,7 +169,7 @@ public CompletableSource apply(Integer v) throws Exception { @Test public void fusedObservable() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); Observable.range(1, 10) .flatMapCompletable(new Function() { @@ -182,7 +182,7 @@ public CompletableSource apply(Integer v) throws Exception { to .assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.ASYNC)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(); } @@ -335,7 +335,7 @@ public CompletableSource apply(Integer v) throws Exception { @Test public void fused() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); Observable.range(1, 10) .flatMapCompletable(new Function() { @@ -349,7 +349,7 @@ public CompletableSource apply(Integer v) throws Exception { to .assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.ASYNC)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index 70daea3fd9..9e40bd1925 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -338,17 +338,17 @@ public Observable apply(Integer t1) { } }, m); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.subscribe(ts); + source.subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + to.awaitTerminalEvent(); + to.assertNoErrors(); Set expected = new HashSet(Arrays.asList( 10, 11, 20, 21, 30, 31, 40, 41, 50, 51, 60, 61, 70, 71, 80, 81, 90, 91, 100, 101 )); - Assert.assertEquals(expected.size(), ts.valueCount()); - Assert.assertTrue(expected.containsAll(ts.values())); + Assert.assertEquals(expected.size(), to.valueCount()); + Assert.assertTrue(expected.containsAll(to.values())); } @Test public void testFlatMapSelectorMaxConcurrent() { @@ -368,19 +368,19 @@ public Integer apply(Integer t1, Integer t2) { } }, m); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.subscribe(ts); + source.subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + to.awaitTerminalEvent(); + to.assertNoErrors(); Set expected = new HashSet(Arrays.asList( 1010, 1011, 2020, 2021, 3030, 3031, 4040, 4041, 5050, 5051, 6060, 6061, 7070, 7071, 8080, 8081, 9090, 9091, 10100, 10101 )); - Assert.assertEquals(expected.size(), ts.valueCount()); - System.out.println("--> testFlatMapSelectorMaxConcurrent: " + ts.values()); - Assert.assertTrue(expected.containsAll(ts.values())); + Assert.assertEquals(expected.size(), to.valueCount()); + System.out.println("--> testFlatMapSelectorMaxConcurrent: " + to.values()); + Assert.assertTrue(expected.containsAll(to.values())); } @Test @@ -414,14 +414,14 @@ public void testFlatMapTransformsMaxConcurrentNormal() { Observable source = Observable.fromIterable(Arrays.asList(10, 20, 30)); Observer o = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(o); + TestObserver to = new TestObserver(o); Function> just = just(onError); - source.flatMap(just(onNext), just, just0(onComplete), m).subscribe(ts); + source.flatMap(just(onNext), just, just0(onComplete), m).subscribe(to); - ts.awaitTerminalEvent(1, TimeUnit.SECONDS); - ts.assertNoErrors(); - ts.assertTerminated(); + to.awaitTerminalEvent(1, TimeUnit.SECONDS); + to.assertNoErrors(); + to.assertTerminated(); verify(o, times(3)).onNext(1); verify(o, times(3)).onNext(2); @@ -440,7 +440,7 @@ public void flatMapRangeAsyncLoop() { if (i % 10 == 0) { System.out.println("flatMapRangeAsyncLoop > " + i); } - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(0, 1000) .flatMap(new Function>() { @Override @@ -449,15 +449,15 @@ public Observable apply(Integer t) { } }) .observeOn(Schedulers.computation()) - .subscribe(ts); + .subscribe(to); - ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); - if (ts.completions() == 0) { - System.out.println(ts.valueCount()); + to.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); + if (to.completions() == 0) { + System.out.println(to.valueCount()); } - ts.assertTerminated(); - ts.assertNoErrors(); - List list = ts.values(); + to.assertTerminated(); + to.assertNoErrors(); + List list = to.values(); assertEquals(1000, list.size()); boolean f = false; for (int j = 0; j < list.size(); j++) { @@ -477,7 +477,7 @@ public void flatMapRangeMixedAsyncLoop() { if (i % 10 == 0) { System.out.println("flatMapRangeAsyncLoop > " + i); } - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(0, 1000) .flatMap(new Function>() { final Random rnd = new Random(); @@ -491,15 +491,15 @@ public Observable apply(Integer t) { } }) .observeOn(Schedulers.computation()) - .subscribe(ts); + .subscribe(to); - ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); - if (ts.completions() == 0) { - System.out.println(ts.valueCount()); + to.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); + if (to.completions() == 0) { + System.out.println(to.valueCount()); } - ts.assertTerminated(); - ts.assertNoErrors(); - List list = ts.values(); + to.assertTerminated(); + to.assertNoErrors(); + List list = to.values(); if (list.size() < 1000) { Set set = new HashSet(list); for (int j = 0; j < 1000; j++) { @@ -515,37 +515,37 @@ public Observable apply(Integer t) { @Test public void flatMapIntPassthruAsync() { for (int i = 0;i < 1000; i++) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, 1000).flatMap(new Function>() { @Override public Observable apply(Integer t) { return Observable.just(1).subscribeOn(Schedulers.computation()); } - }).subscribe(ts); + }).subscribe(to); - ts.awaitTerminalEvent(5, TimeUnit.SECONDS); - ts.assertNoErrors(); - ts.assertComplete(); - ts.assertValueCount(1000); + to.awaitTerminalEvent(5, TimeUnit.SECONDS); + to.assertNoErrors(); + to.assertComplete(); + to.assertValueCount(1000); } } @Test public void flatMapTwoNestedSync() { for (final int n : new int[] { 1, 1000, 1000000 }) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.just(1, 2).flatMap(new Function>() { @Override public Observable apply(Integer t) { return Observable.range(1, n); } - }).subscribe(ts); + }).subscribe(to); System.out.println("flatMapTwoNestedSync >> @ " + n); - ts.assertNoErrors(); - ts.assertComplete(); - ts.assertValueCount(n * 2); + to.assertNoErrors(); + to.assertComplete(); + to.assertValueCount(n * 2); } } @@ -762,7 +762,7 @@ public Integer apply(Integer w) throws Exception { @Test public void noCrossBoundaryFusion() { for (int i = 0; i < 500; i++) { - TestObserver ts = Observable.merge( + TestObserver to = Observable.merge( Observable.just(1).observeOn(Schedulers.single()).map(new Function() { @Override public Object apply(Integer v) throws Exception { @@ -780,7 +780,7 @@ public Object apply(Integer v) throws Exception { .awaitDone(5, TimeUnit.SECONDS) .assertValueCount(2); - List list = ts.values(); + List list = to.values(); assertTrue(list.toString(), list.contains("RxSi")); assertTrue(list.toString(), list.contains("RxCo")); @@ -793,20 +793,20 @@ public void cancelScalarDrainRace() { List errors = TestHelper.trackPluginErrors(); try { - final PublishSubject> pp = PublishSubject.create(); + final PublishSubject> ps = PublishSubject.create(); - final TestObserver ts = pp.flatMap(Functions.>identity()).test(); + final TestObserver to = ps.flatMap(Functions.>identity()).test(); Runnable r1 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; Runnable r2 = new Runnable() { @Override public void run() { - pp.onComplete(); + ps.onComplete(); } }; @@ -826,20 +826,20 @@ public void cancelDrainRace() { List errors = TestHelper.trackPluginErrors(); try { - final PublishSubject> pp = PublishSubject.create(); + final PublishSubject> ps = PublishSubject.create(); - final TestObserver ts = pp.flatMap(Functions.>identity()).test(); + final TestObserver to = ps.flatMap(Functions.>identity()).test(); final PublishSubject just = PublishSubject.create(); final PublishSubject just2 = PublishSubject.create(); - pp.onNext(just); - pp.onNext(just2); + ps.onNext(just); + ps.onNext(just2); Runnable r1 = new Runnable() { @Override public void run() { just2.onNext(1); - ts.cancel(); + to.cancel(); } }; Runnable r2 = new Runnable() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromIterableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromIterableTest.java index 5b121664c9..3b0a9d4970 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromIterableTest.java @@ -29,7 +29,7 @@ import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.util.CrashingIterable; import io.reactivex.observers.*; @@ -118,12 +118,12 @@ public void testObservableFromIterable() { public void testNoBackpressure() { Observable o = Observable.fromIterable(Arrays.asList(1, 2, 3, 4, 5)); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - o.subscribe(ts); + o.subscribe(to); - ts.assertValues(1, 2, 3, 4, 5); - ts.assertTerminated(); + to.assertValues(1, 2, 3, 4, 5); + to.assertTerminated(); } @Test @@ -131,13 +131,13 @@ public void testSubscribeMultipleTimes() { Observable o = Observable.fromIterable(Arrays.asList(1, 2, 3)); for (int i = 0; i < 10; i++) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - o.subscribe(ts); + o.subscribe(to); - ts.assertValues(1, 2, 3); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValues(1, 2, 3); + to.assertNoErrors(); + to.assertComplete(); } } @@ -302,12 +302,12 @@ public void remove() { @Test public void fusionRejected() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ASYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ASYNC); Observable.fromIterable(Arrays.asList(1, 2, 3)) .subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1, 2, 3); } @@ -320,7 +320,7 @@ public void onSubscribe(Disposable d) { @SuppressWarnings("unchecked") QueueDisposable qd = (QueueDisposable)d; - qd.requestFusion(QueueDisposable.ANY); + qd.requestFusion(QueueFuseable.ANY); try { assertEquals(1, qd.poll().intValue()); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromTest.java index f39ef54d84..586480cc5b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromTest.java @@ -77,12 +77,12 @@ public ObservableSource apply(Flowable f) throws Exception { @Test public void fusionRejected() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ASYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ASYNC); Observable.fromArray(1, 2, 3) .subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1, 2, 3); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java index 3ced845ea4..ae00fc2403 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java @@ -1026,7 +1026,7 @@ public Boolean apply(Integer n) { @Test public void testGroupByBackpressure() throws InterruptedException { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, 4000) .groupBy(IS_EVEN2) @@ -1052,9 +1052,9 @@ public String apply(Integer l) { }); } - }).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + }).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); } Function just(final R value) { @@ -1153,12 +1153,12 @@ public String apply(String v) { } }); - TestObserver ts = new TestObserver(); - m.subscribe(ts); - ts.awaitTerminalEvent(); - System.out.println("ts .get " + ts.values()); - ts.assertNoErrors(); - assertEquals(ts.values(), + TestObserver to = new TestObserver(); + m.subscribe(to); + to.awaitTerminalEvent(); + System.out.println("ts .get " + to.values()); + to.assertNoErrors(); + assertEquals(to.values(), Arrays.asList("foo-0", "foo-1", "bar-0", "foo-0", "baz-0", "qux-0", "bar-1", "bar-0", "foo-1", "baz-1", "baz-0", "foo-0")); } @@ -1169,11 +1169,11 @@ public void keySelectorThrows() { Observable m = source.groupBy(fail(0), dbl).flatMap(FLATTEN_INTEGER); - TestObserver ts = new TestObserver(); - m.subscribe(ts); - ts.awaitTerminalEvent(); - assertEquals(1, ts.errorCount()); - ts.assertNoValues(); + TestObserver to = new TestObserver(); + m.subscribe(to); + to.awaitTerminalEvent(); + assertEquals(1, to.errorCount()); + to.assertNoValues(); } @Test @@ -1181,11 +1181,11 @@ public void valueSelectorThrows() { Observable source = Observable.just(0, 1, 2, 3, 4, 5, 6); Observable m = source.groupBy(identity, fail(0)).flatMap(FLATTEN_INTEGER); - TestObserver ts = new TestObserver(); - m.subscribe(ts); - ts.awaitTerminalEvent(); - assertEquals(1, ts.errorCount()); - ts.assertNoValues(); + TestObserver to = new TestObserver(); + m.subscribe(to); + to.awaitTerminalEvent(); + assertEquals(1, to.errorCount()); + to.assertNoValues(); } @@ -1195,11 +1195,11 @@ public void innerEscapeCompleted() { Observable m = source.groupBy(identity, dbl).flatMap(FLATTEN_INTEGER); - TestObserver ts = new TestObserver(); - m.subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - System.out.println(ts.values()); + TestObserver to = new TestObserver(); + m.subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + System.out.println(to.values()); } /** @@ -1239,16 +1239,16 @@ public void testError2() { Observable m = source.groupBy(identity, dbl).flatMap(FLATTEN_INTEGER); - TestObserver ts = new TestObserver(); - m.subscribe(ts); - ts.awaitTerminalEvent(); - assertEquals(1, ts.errorCount()); - ts.assertValueCount(1); + TestObserver to = new TestObserver(); + m.subscribe(to); + to.awaitTerminalEvent(); + assertEquals(1, to.errorCount()); + to.assertValueCount(1); } @Test public void testgroupByBackpressure() throws InterruptedException { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, 4000).groupBy(IS_EVEN2).flatMap(new Function, Observable>() { @@ -1297,15 +1297,15 @@ public void accept(Notification t1) { System.out.println("NEXT: " + t1); } - }).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + }).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); } @Test public void testgroupByBackpressure2() throws InterruptedException { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, 4000).groupBy(IS_EVEN2).flatMap(new Function, Observable>() { @@ -1329,9 +1329,9 @@ public String apply(Integer l) { }); } - }).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + }).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); } static Function, Observable> FLATTEN_INTEGER = new Function, Observable>() { @@ -1382,7 +1382,7 @@ public void subscribe(Observer observer) { } } ); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); o.groupBy(new Function() { @@ -1390,9 +1390,9 @@ public void subscribe(Observer observer) { public Integer apply(Integer integer) { return null; } - }).subscribe(ts); + }).subscribe(to); - ts.dispose(); + to.dispose(); verify(s).dispose(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableIgnoreElementsTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableIgnoreElementsTest.java index 1a2e7c7782..7e75e12a8d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableIgnoreElementsTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableIgnoreElementsTest.java @@ -57,26 +57,26 @@ public void accept(Integer t) { @Test public void testCompletedOkObservable() { - TestObserver ts = new TestObserver(); - Observable.range(1, 10).ignoreElements().toObservable().subscribe(ts); - ts.assertNoErrors(); - ts.assertNoValues(); - ts.assertTerminated(); + TestObserver to = new TestObserver(); + Observable.range(1, 10).ignoreElements().toObservable().subscribe(to); + to.assertNoErrors(); + to.assertNoValues(); + to.assertTerminated(); // FIXME no longer testable // ts.assertUnsubscribed(); } @Test public void testErrorReceivedObservable() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); TestException ex = new TestException("boo"); - Observable.error(ex).ignoreElements().toObservable().subscribe(ts); - ts.assertNoValues(); - ts.assertTerminated(); + Observable.error(ex).ignoreElements().toObservable().subscribe(to); + to.assertNoValues(); + to.assertTerminated(); // FIXME no longer testable // ts.assertUnsubscribed(); - ts.assertError(TestException.class); - ts.assertErrorMessage("boo"); + to.assertError(TestException.class); + to.assertErrorMessage("boo"); } @Test @@ -124,26 +124,26 @@ public void accept(Integer t) { @Test public void testCompletedOk() { - TestObserver ts = new TestObserver(); - Observable.range(1, 10).ignoreElements().subscribe(ts); - ts.assertNoErrors(); - ts.assertNoValues(); - ts.assertTerminated(); + TestObserver to = new TestObserver(); + Observable.range(1, 10).ignoreElements().subscribe(to); + to.assertNoErrors(); + to.assertNoValues(); + to.assertTerminated(); // FIXME no longer testable // ts.assertUnsubscribed(); } @Test public void testErrorReceived() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); TestException ex = new TestException("boo"); - Observable.error(ex).ignoreElements().subscribe(ts); - ts.assertNoValues(); - ts.assertTerminated(); + Observable.error(ex).ignoreElements().subscribe(to); + to.assertNoValues(); + to.assertTerminated(); // FIXME no longer testable // ts.assertUnsubscribed(); - ts.assertError(TestException.class); - ts.assertErrorMessage("boo"); + to.assertError(TestException.class); + to.assertErrorMessage("boo"); } @Test @@ -164,17 +164,17 @@ public void run() { @Test public void cancel() { - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.ignoreElements().toObservable().test(); + TestObserver to = ps.ignoreElements().toObservable().test(); - assertTrue(pp.hasObservers()); + assertTrue(ps.hasObservers()); - ts.cancel(); + to.cancel(); - assertFalse(pp.hasObservers()); + assertFalse(ps.hasObservers()); - TestHelper.checkDisposed(pp.ignoreElements().toObservable()); + TestHelper.checkDisposed(ps.ignoreElements().toObservable()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableIntervalTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableIntervalTest.java index e834a2accb..17d370a56d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableIntervalTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableIntervalTest.java @@ -39,14 +39,14 @@ public void cancel() { @Test public void cancelledOnRun() { - TestObserver ts = new TestObserver(); - IntervalObserver is = new IntervalObserver(ts); - ts.onSubscribe(is); + TestObserver to = new TestObserver(); + IntervalObserver is = new IntervalObserver(to); + to.onSubscribe(is); is.dispose(); is.run(); - ts.assertEmpty(); + to.assertEmpty(); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMapNotificationTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMapNotificationTest.java index fae7c60afd..748078fd02 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMapNotificationTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMapNotificationTest.java @@ -28,7 +28,7 @@ public class ObservableMapNotificationTest { @Test public void testJust() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.just(1) .flatMap( new Function>() { @@ -49,11 +49,11 @@ public Observable call() { return Observable.never(); } } - ).subscribe(ts); + ).subscribe(to); - ts.assertNoErrors(); - ts.assertNotComplete(); - ts.assertValue(2); + to.assertNoErrors(); + to.assertNotComplete(); + to.assertValue(2); } @Test @@ -89,7 +89,7 @@ public ObservableSource apply(Observable o) throws Exception { @Test public void onErrorCrash() { - TestObserver ts = Observable.error(new TestException("Outer")) + TestObserver to = Observable.error(new TestException("Outer")) .flatMap(Functions.justFunction(Observable.just(1)), new Function>() { @Override @@ -101,7 +101,7 @@ public Observable apply(Throwable t) throws Exception { .test() .assertFailure(CompositeException.class); - TestHelper.assertError(ts, 0, TestException.class, "Outer"); - TestHelper.assertError(ts, 1, TestException.class, "Inner"); + TestHelper.assertError(to, 0, TestException.class, "Outer"); + TestHelper.assertError(to, 1, TestException.class, "Inner"); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMapTest.java index 662c1ed8bb..3d824be862 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMapTest.java @@ -13,7 +13,8 @@ package io.reactivex.internal.operators.observable; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; @@ -25,7 +26,7 @@ import io.reactivex.Observer; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.UnicastSubject; @@ -349,19 +350,19 @@ public ObservableSource apply(Observable o) throws Exception { @Test public void fusedSync() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); Observable.range(1, 5) .map(Functions.identity()) .subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.SYNC) + ObserverFusion.assertFusion(to, QueueFuseable.SYNC) .assertResult(1, 2, 3, 4, 5); } @Test public void fusedAsync() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); UnicastSubject us = UnicastSubject.create(); @@ -371,19 +372,19 @@ public void fusedAsync() { TestHelper.emit(us, 1, 2, 3, 4, 5); - ObserverFusion.assertFusion(to, QueueDisposable.ASYNC) + ObserverFusion.assertFusion(to, QueueFuseable.ASYNC) .assertResult(1, 2, 3, 4, 5); } @Test public void fusedReject() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY | QueueDisposable.BOUNDARY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY | QueueFuseable.BOUNDARY); Observable.range(1, 5) .map(Functions.identity()) .subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMaterializeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMaterializeTest.java index dfc7ba2fab..d163293c69 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMaterializeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMaterializeTest.java @@ -101,17 +101,17 @@ public void testMultipleSubscribes() throws InterruptedException, ExecutionExcep @Test public void testWithCompletionCausingError() { - TestObserver> ts = new TestObserver>(); + TestObserver> to = new TestObserver>(); final RuntimeException ex = new RuntimeException("boo"); Observable.empty().materialize().doOnNext(new Consumer() { @Override public void accept(Object t) { throw ex; } - }).subscribe(ts); - ts.assertError(ex); - ts.assertNoValues(); - ts.assertTerminated(); + }).subscribe(to); + to.assertError(ex); + to.assertNoValues(); + to.assertTerminated(); } private static class TestLocalObserver extends DefaultObserver> { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeDelayErrorTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeDelayErrorTest.java index 2ddcd54994..472a25300b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeDelayErrorTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeDelayErrorTest.java @@ -487,15 +487,15 @@ public void onComplete() { @Test public void testErrorInParentObservable() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.mergeDelayError( Observable.just(Observable.just(1), Observable.just(2)) .startWith(Observable. error(new RuntimeException())) - ).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertTerminated(); - ts.assertValues(1, 2); - assertEquals(1, ts.errorCount()); + ).subscribe(to); + to.awaitTerminalEvent(); + to.assertTerminated(); + to.assertValues(1, 2); + assertEquals(1, to.errorCount()); } @@ -516,12 +516,12 @@ public void subscribe(Observer> op) { Observer stringObserver = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(stringObserver); + TestObserver to = new TestObserver(stringObserver); Observable m = Observable.mergeDelayError(parentObservable); - m.subscribe(ts); + m.subscribe(to); System.out.println("testErrorInParentObservableDelayed | " + i); - ts.awaitTerminalEvent(2000, TimeUnit.MILLISECONDS); - ts.assertTerminated(); + to.awaitTerminalEvent(2000, TimeUnit.MILLISECONDS); + to.assertTerminated(); verify(stringObserver, times(2)).onNext("hello"); verify(stringObserver, times(1)).onError(any(NullPointerException.class)); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeMaxConcurrentTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeMaxConcurrentTest.java index 202fe7fdc8..582421d42b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeMaxConcurrentTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeMaxConcurrentTest.java @@ -156,7 +156,7 @@ public void testMergeALotOfSourcesOneByOneSynchronouslyTakeHalf() { @Test public void testSimple() { for (int i = 1; i < 100; i++) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); List> sourceList = new ArrayList>(i); List result = new ArrayList(i); for (int j = 1; j <= i; j++) { @@ -164,17 +164,17 @@ public void testSimple() { result.add(j); } - Observable.merge(sourceList, i).subscribe(ts); + Observable.merge(sourceList, i).subscribe(to); - ts.assertNoErrors(); - ts.assertTerminated(); - ts.assertValueSequence(result); + to.assertNoErrors(); + to.assertTerminated(); + to.assertValueSequence(result); } } @Test public void testSimpleOneLess() { for (int i = 2; i < 100; i++) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); List> sourceList = new ArrayList>(i); List result = new ArrayList(i); for (int j = 1; j <= i; j++) { @@ -182,11 +182,11 @@ public void testSimpleOneLess() { result.add(j); } - Observable.merge(sourceList, i - 1).subscribe(ts); + Observable.merge(sourceList, i - 1).subscribe(to); - ts.assertNoErrors(); - ts.assertTerminated(); - ts.assertValueSequence(result); + to.assertNoErrors(); + to.assertTerminated(); + to.assertValueSequence(result); } } @Test//(timeout = 20000) @@ -204,7 +204,7 @@ public void testSimpleAsyncLoop() { @Test(timeout = 30000) public void testSimpleAsync() { for (int i = 1; i < 50; i++) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); List> sourceList = new ArrayList>(i); Set expected = new HashSet(i); for (int j = 1; j <= i; j++) { @@ -212,11 +212,11 @@ public void testSimpleAsync() { expected.add(j); } - Observable.merge(sourceList, i).subscribe(ts); + Observable.merge(sourceList, i).subscribe(to); - ts.awaitTerminalEvent(1, TimeUnit.SECONDS); - ts.assertNoErrors(); - Set actual = new HashSet(ts.values()); + to.awaitTerminalEvent(1, TimeUnit.SECONDS); + to.assertNoErrors(); + Set actual = new HashSet(to.values()); assertEquals(expected, actual); } @@ -234,7 +234,7 @@ public void testSimpleOneLessAsync() { if (System.currentTimeMillis() - t > TimeUnit.SECONDS.toMillis(9)) { break; } - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); List> sourceList = new ArrayList>(i); Set expected = new HashSet(i); for (int j = 1; j <= i; j++) { @@ -242,11 +242,11 @@ public void testSimpleOneLessAsync() { expected.add(j); } - Observable.merge(sourceList, i - 1).subscribe(ts); + Observable.merge(sourceList, i - 1).subscribe(to); - ts.awaitTerminalEvent(1, TimeUnit.SECONDS); - ts.assertNoErrors(); - Set actual = new HashSet(ts.values()); + to.awaitTerminalEvent(1, TimeUnit.SECONDS); + to.assertNoErrors(); + Set actual = new HashSet(to.values()); assertEquals(expected, actual); } @@ -260,12 +260,12 @@ public void testTake() throws Exception { sourceList.add(Observable.range(0, 100000).subscribeOn(Schedulers.io())); sourceList.add(Observable.range(0, 100000).subscribeOn(Schedulers.io())); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.merge(sourceList, 2).take(5).subscribe(ts); + Observable.merge(sourceList, 2).take(5).subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - ts.assertValueCount(5); + to.awaitTerminalEvent(); + to.assertNoErrors(); + to.assertValueCount(5); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java index 85907bcf23..1b808a9234 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java @@ -189,11 +189,11 @@ public void testMergeArrayWithThreading() { final TestASynchronousObservable o2 = new TestASynchronousObservable(); Observable m = Observable.merge(Observable.unsafeCreate(o1), Observable.unsafeCreate(o2)); - TestObserver ts = new TestObserver(stringObserver); - m.subscribe(ts); + TestObserver to = new TestObserver(stringObserver); + m.subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + to.awaitTerminalEvent(); + to.assertNoErrors(); verify(stringObserver, never()).onError(any(Throwable.class)); verify(stringObserver, times(2)).onNext("hello"); @@ -339,7 +339,7 @@ public void testError2() { @Test @Ignore("Subscribe should not throw") public void testThrownErrorHandling() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable o1 = Observable.unsafeCreate(new ObservableSource() { @Override @@ -349,10 +349,10 @@ public void subscribe(Observer s) { }); - Observable.merge(o1, o1).subscribe(ts); - ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); - ts.assertTerminated(); - System.out.println("Error: " + ts.errors()); + Observable.merge(o1, o1).subscribe(to); + to.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); + to.assertTerminated(); + System.out.println("Error: " + to.errors()); } private static class TestSynchronousObservable implements ObservableSource { @@ -425,16 +425,16 @@ public void testUnsubscribeAsObservablesComplete() { AtomicBoolean os2 = new AtomicBoolean(false); Observable o2 = createObservableOf5IntervalsOf1SecondIncrementsWithSubscriptionHook(scheduler2, os2); - TestObserver ts = new TestObserver(); - Observable.merge(o1, o2).subscribe(ts); + TestObserver to = new TestObserver(); + Observable.merge(o1, o2).subscribe(to); // we haven't incremented time so nothing should be received yet - ts.assertNoValues(); + to.assertNoValues(); scheduler1.advanceTimeBy(3, TimeUnit.SECONDS); scheduler2.advanceTimeBy(2, TimeUnit.SECONDS); - ts.assertValues(0L, 1L, 2L, 0L, 1L); + to.assertValues(0L, 1L, 2L, 0L, 1L); // not unsubscribed yet assertFalse(os1.get()); assertFalse(os2.get()); @@ -442,18 +442,18 @@ public void testUnsubscribeAsObservablesComplete() { // advance to the end at which point it should complete scheduler1.advanceTimeBy(3, TimeUnit.SECONDS); - ts.assertValues(0L, 1L, 2L, 0L, 1L, 3L, 4L); + to.assertValues(0L, 1L, 2L, 0L, 1L, 3L, 4L); assertTrue(os1.get()); assertFalse(os2.get()); // both should be completed now scheduler2.advanceTimeBy(3, TimeUnit.SECONDS); - ts.assertValues(0L, 1L, 2L, 0L, 1L, 3L, 4L, 2L, 3L, 4L); + to.assertValues(0L, 1L, 2L, 0L, 1L, 3L, 4L, 2L, 3L, 4L); assertTrue(os1.get()); assertTrue(os2.get()); - ts.assertTerminated(); + to.assertTerminated(); } @Test @@ -467,27 +467,27 @@ public void testEarlyUnsubscribe() { AtomicBoolean os2 = new AtomicBoolean(false); Observable o2 = createObservableOf5IntervalsOf1SecondIncrementsWithSubscriptionHook(scheduler2, os2); - TestObserver ts = new TestObserver(); - Observable.merge(o1, o2).subscribe(ts); + TestObserver to = new TestObserver(); + Observable.merge(o1, o2).subscribe(to); // we haven't incremented time so nothing should be received yet - ts.assertNoValues(); + to.assertNoValues(); scheduler1.advanceTimeBy(3, TimeUnit.SECONDS); scheduler2.advanceTimeBy(2, TimeUnit.SECONDS); - ts.assertValues(0L, 1L, 2L, 0L, 1L); + to.assertValues(0L, 1L, 2L, 0L, 1L); // not unsubscribed yet assertFalse(os1.get()); assertFalse(os2.get()); // early unsubscribe - ts.dispose(); + to.dispose(); assertTrue(os1.get()); assertTrue(os2.get()); - ts.assertValues(0L, 1L, 2L, 0L, 1L); + to.assertValues(0L, 1L, 2L, 0L, 1L); // FIXME not happening anymore // ts.assertUnsubscribed(); } @@ -540,14 +540,14 @@ public void testConcurrency() { for (int i = 0; i < 10; i++) { Observable merge = Observable.merge(o, o, o); - TestObserver ts = new TestObserver(); - merge.subscribe(ts); - - ts.awaitTerminalEvent(3, TimeUnit.SECONDS); - ts.assertTerminated(); - ts.assertNoErrors(); - ts.assertComplete(); - List onNextEvents = ts.values(); + TestObserver to = new TestObserver(); + merge.subscribe(to); + + to.awaitTerminalEvent(3, TimeUnit.SECONDS); + to.assertTerminated(); + to.assertNoErrors(); + to.assertComplete(); + List onNextEvents = to.values(); assertEquals(30000, onNextEvents.size()); // System.out.println("onNext: " + onNextEvents.size() + " onComplete: " + ts.getOnCompletedEvents().size()); } @@ -593,12 +593,12 @@ public void run() { for (int i = 0; i < 10; i++) { Observable merge = Observable.merge(o, o, o); - TestObserver ts = new TestObserver(); - merge.subscribe(ts); + TestObserver to = new TestObserver(); + merge.subscribe(to); - ts.awaitTerminalEvent(); - ts.assertComplete(); - List onNextEvents = ts.values(); + to.awaitTerminalEvent(); + to.assertComplete(); + List onNextEvents = to.values(); assertEquals(300, onNextEvents.size()); // System.out.println("onNext: " + onNextEvents.size() + " onComplete: " + ts.getOnCompletedEvents().size()); } @@ -640,13 +640,13 @@ public void run() { for (int i = 0; i < 10; i++) { Observable merge = Observable.merge(o, o, o); - TestObserver ts = new TestObserver(); - merge.subscribe(ts); + TestObserver to = new TestObserver(); + merge.subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - ts.assertComplete(); - List onNextEvents = ts.values(); + to.awaitTerminalEvent(); + to.assertNoErrors(); + to.assertComplete(); + List onNextEvents = to.values(); assertEquals(30000, onNextEvents.size()); // System.out.println("onNext: " + onNextEvents.size() + " onComplete: " + ts.getOnCompletedEvents().size()); } @@ -825,18 +825,18 @@ public void onNext(Integer t) { @Ignore("Null values not permitted") public void mergeWithNullValues() { System.out.println("mergeWithNullValues"); - TestObserver ts = new TestObserver(); - Observable.merge(Observable.just(null, "one"), Observable.just("two", null)).subscribe(ts); - ts.assertTerminated(); - ts.assertNoErrors(); - ts.assertValues(null, "one", "two", null); + TestObserver to = new TestObserver(); + Observable.merge(Observable.just(null, "one"), Observable.just("two", null)).subscribe(to); + to.assertTerminated(); + to.assertNoErrors(); + to.assertValues(null, "one", "two", null); } @Test @Ignore("Null values are no longer permitted") public void mergeWithTerminalEventAfterUnsubscribe() { System.out.println("mergeWithTerminalEventAfterUnsubscribe"); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable bad = Observable.unsafeCreate(new ObservableSource() { @Override @@ -848,72 +848,72 @@ public void subscribe(Observer s) { } }); - Observable.merge(Observable.just(null, "one"), bad).subscribe(ts); - ts.assertNoErrors(); - ts.assertValues(null, "one", "two"); + Observable.merge(Observable.just(null, "one"), bad).subscribe(to); + to.assertNoErrors(); + to.assertValues(null, "one", "two"); } @Test @Ignore("Null values are not permitted") public void mergingNullObservable() { - TestObserver ts = new TestObserver(); - Observable.merge(Observable.just("one"), null).subscribe(ts); - ts.assertNoErrors(); - ts.assertValue("one"); + TestObserver to = new TestObserver(); + Observable.merge(Observable.just("one"), null).subscribe(to); + to.assertNoErrors(); + to.assertValue("one"); } @Test public void merge1AsyncStreamOf1() { - TestObserver ts = new TestObserver(); - mergeNAsyncStreamsOfN(1, 1).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(1, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNAsyncStreamsOfN(1, 1).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(1, to.values().size()); } @Test public void merge1AsyncStreamOf1000() { - TestObserver ts = new TestObserver(); - mergeNAsyncStreamsOfN(1, 1000).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(1000, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNAsyncStreamsOfN(1, 1000).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(1000, to.values().size()); } @Test public void merge10AsyncStreamOf1000() { - TestObserver ts = new TestObserver(); - mergeNAsyncStreamsOfN(10, 1000).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(10000, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNAsyncStreamsOfN(10, 1000).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(10000, to.values().size()); } @Test public void merge1000AsyncStreamOf1000() { - TestObserver ts = new TestObserver(); - mergeNAsyncStreamsOfN(1000, 1000).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(1000000, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNAsyncStreamsOfN(1000, 1000).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(1000000, to.values().size()); } @Test public void merge2000AsyncStreamOf100() { - TestObserver ts = new TestObserver(); - mergeNAsyncStreamsOfN(2000, 100).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(200000, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNAsyncStreamsOfN(2000, 100).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(200000, to.values().size()); } @Test public void merge100AsyncStreamOf1() { - TestObserver ts = new TestObserver(); - mergeNAsyncStreamsOfN(100, 1).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(100, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNAsyncStreamsOfN(100, 1).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(100, to.values().size()); } private Observable mergeNAsyncStreamsOfN(final int outerSize, final int innerSize) { @@ -931,47 +931,47 @@ public Observable apply(Integer i) { @Test public void merge1SyncStreamOf1() { - TestObserver ts = new TestObserver(); - mergeNSyncStreamsOfN(1, 1).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(1, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNSyncStreamsOfN(1, 1).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(1, to.values().size()); } @Test public void merge1SyncStreamOf1000000() { - TestObserver ts = new TestObserver(); - mergeNSyncStreamsOfN(1, 1000000).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(1000000, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNSyncStreamsOfN(1, 1000000).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(1000000, to.values().size()); } @Test public void merge1000SyncStreamOf1000() { - TestObserver ts = new TestObserver(); - mergeNSyncStreamsOfN(1000, 1000).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(1000000, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNSyncStreamsOfN(1000, 1000).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(1000000, to.values().size()); } @Test public void merge10000SyncStreamOf10() { - TestObserver ts = new TestObserver(); - mergeNSyncStreamsOfN(10000, 10).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(100000, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNSyncStreamsOfN(10000, 10).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(100000, to.values().size()); } @Test public void merge1000000SyncStreamOf1() { - TestObserver ts = new TestObserver(); - mergeNSyncStreamsOfN(1000000, 1).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(1000000, ts.values().size()); + TestObserver to = new TestObserver(); + mergeNSyncStreamsOfN(1000000, 1).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(1000000, to.values().size()); } private Observable mergeNSyncStreamsOfN(final int outerSize, final int innerSize) { @@ -1014,7 +1014,7 @@ public boolean hasNext() { @Test public void mergeManyAsyncSingle() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable> os = Observable.range(1, 10000) .map(new Function>() { @@ -1040,10 +1040,10 @@ public void subscribe(Observer s) { } }); - Observable.merge(os).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(10000, ts.values().size()); + Observable.merge(os).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(10000, to.values().size()); } Function> toScalar = new Function>() { @@ -1061,21 +1061,21 @@ public Observable apply(Integer t) { }; ; - void runMerge(Function> func, TestObserver ts) { + void runMerge(Function> func, TestObserver to) { List list = new ArrayList(); for (int i = 0; i < 1000; i++) { list.add(i); } Observable source = Observable.fromIterable(list); - source.flatMap(func).subscribe(ts); + source.flatMap(func).subscribe(to); - if (ts.values().size() != 1000) { - System.out.println(ts.values()); + if (to.values().size() != 1000) { + System.out.println(to.values()); } - ts.assertTerminated(); - ts.assertNoErrors(); - ts.assertValueSequence(list); + to.assertTerminated(); + to.assertNoErrors(); + to.assertValueSequence(list); } @Test @@ -1089,7 +1089,7 @@ public void testFastMergeHiddenScalar() { @Test public void testSlowMergeFullScalar() { for (final int req : new int[] { 16, 32, 64, 128, 256 }) { - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { int remaining = req; @Override @@ -1100,13 +1100,13 @@ public void onNext(Integer t) { } } }; - runMerge(toScalar, ts); + runMerge(toScalar, to); } } @Test public void testSlowMergeHiddenScalar() { for (final int req : new int[] { 16, 32, 64, 128, 256 }) { - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { int remaining = req; @Override public void onNext(Integer t) { @@ -1116,7 +1116,7 @@ public void onNext(Integer t) { } } }; - runMerge(toHiddenScalar, ts); + runMerge(toHiddenScalar, to); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java index 8b0dedc22b..0062e220ee 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java @@ -64,13 +64,13 @@ public void testOrdering() throws InterruptedException { Observer observer = TestHelper.mockObserver(); InOrder inOrder = inOrder(observer); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); - obs.observeOn(Schedulers.computation()).subscribe(ts); + obs.observeOn(Schedulers.computation()).subscribe(to); - ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); - if (ts.errors().size() > 0) { - for (Throwable t : ts.errors()) { + to.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); + if (to.errors().size() > 0) { + for (Throwable t : to.errors()) { t.printStackTrace(); } fail("failed with exception"); @@ -388,13 +388,13 @@ public void testAfterUnsubscribeCalledThenObserverOnNextNeverCalled() { final TestScheduler testScheduler = new TestScheduler(); final Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); Observable.just(1, 2, 3) .observeOn(testScheduler) - .subscribe(ts); + .subscribe(to); - ts.dispose(); + to.dispose(); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); final InOrder inOrder = inOrder(observer); @@ -429,23 +429,23 @@ public boolean hasNext() { } }); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); o .take(7) .observeOn(Schedulers.newThread()) - .subscribe(ts); + .subscribe(to); - ts.awaitTerminalEvent(); - ts.assertValues(0, 1, 2, 3, 4, 5, 6); + to.awaitTerminalEvent(); + to.assertValues(0, 1, 2, 3, 4, 5, 6); assertEquals(7, generated.get()); } @Test public void testAsyncChild() { - TestObserver ts = new TestObserver(); - Observable.range(0, 100000).observeOn(Schedulers.newThread()).observeOn(Schedulers.newThread()).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + TestObserver to = new TestObserver(); + Observable.range(0, 100000).observeOn(Schedulers.newThread()).observeOn(Schedulers.newThread()).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); } @Test @@ -566,33 +566,33 @@ public void inputAsyncFusedErrorDelayed() { @Test public void outputFused() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); Observable.range(1, 5).hide() .observeOn(Schedulers.single()) .subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.ASYNC) + ObserverFusion.assertFusion(to, QueueFuseable.ASYNC) .awaitDone(5, TimeUnit.SECONDS) .assertResult(1, 2, 3, 4, 5); } @Test public void outputFusedReject() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.SYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC); Observable.range(1, 5).hide() .observeOn(Schedulers.single()) .subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .awaitDone(5, TimeUnit.SECONDS) .assertResult(1, 2, 3, 4, 5); } @Test public void inputOutputAsyncFusedError() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); UnicastSubject us = UnicastSubject.create(); @@ -605,14 +605,14 @@ public void inputOutputAsyncFusedError() { .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); - ObserverFusion.assertFusion(to, QueueDisposable.ASYNC) + ObserverFusion.assertFusion(to, QueueFuseable.ASYNC) .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test public void inputOutputAsyncFusedErrorDelayed() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); UnicastSubject us = UnicastSubject.create(); @@ -625,7 +625,7 @@ public void inputOutputAsyncFusedErrorDelayed() { .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); - ObserverFusion.assertFusion(to, QueueDisposable.ASYNC) + ObserverFusion.assertFusion(to, QueueFuseable.ASYNC) .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @@ -643,7 +643,7 @@ public void outputFusedCancelReentrant() throws Exception { @Override public void onSubscribe(Disposable d) { this.d = d; - ((QueueDisposable)d).requestFusion(QueueDisposable.ANY); + ((QueueDisposable)d).requestFusion(QueueFuseable.ANY); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java index 0a94717712..ffb1e5c37b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java @@ -151,7 +151,7 @@ public Observable apply(Throwable t1) { @Test @Ignore("Failed operator may leave the child Observer in an inconsistent state which prevents further error delivery.") public void testOnErrorResumeReceivesErrorFromPreviousNonProtectedOperator() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.just(1).lift(new ObservableOperator() { @Override @@ -170,11 +170,11 @@ public Observable apply(Throwable t1) { } } - }).subscribe(ts); + }).subscribe(to); - ts.assertTerminated(); - System.out.println(ts.values()); - ts.assertValue("success"); + to.assertTerminated(); + System.out.println(to.values()); + to.assertValue("success"); } /** @@ -184,7 +184,7 @@ public Observable apply(Throwable t1) { @Test @Ignore("A crashing operator may leave the downstream in an inconsistent state and not suitable for event delivery") public void testOnErrorResumeReceivesErrorFromPreviousNonProtectedOperatorOnNext() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.just(1).lift(new ObservableOperator() { @Override @@ -225,11 +225,11 @@ public Observable apply(Throwable t1) { } } - }).subscribe(ts); + }).subscribe(to); - ts.assertTerminated(); - System.out.println(ts.values()); - ts.assertValue("success"); + to.assertTerminated(); + System.out.println(to.values()); + to.assertValue("success"); } @Test @@ -262,9 +262,9 @@ public Observable apply(Throwable t1) { @SuppressWarnings("unchecked") DefaultObserver observer = mock(DefaultObserver.class); - TestObserver ts = new TestObserver(observer); - o.subscribe(ts); - ts.awaitTerminalEvent(); + TestObserver to = new TestObserver(observer); + o.subscribe(to); + to.awaitTerminalEvent(); verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); @@ -314,7 +314,7 @@ public void run() { @Test public void testBackpressure() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(0, 100000) .onErrorResumeNext(new Function>() { @@ -342,9 +342,9 @@ public Integer apply(Integer t1) { } }) - .subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + .subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java index b4c490524c..c0c8edc358 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java @@ -135,10 +135,10 @@ public void subscribe(Observer t1) { @SuppressWarnings("unchecked") DefaultObserver observer = mock(DefaultObserver.class); - TestObserver ts = new TestObserver(observer); - observable.subscribe(ts); + TestObserver to = new TestObserver(observer); + observable.subscribe(to); - ts.awaitTerminalEvent(); + to.awaitTerminalEvent(); verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); @@ -190,7 +190,7 @@ public void run() { @Test public void testBackpressure() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(0, 100000) .onErrorResumeNext(Observable.just(1)) .observeOn(Schedulers.computation()) @@ -211,8 +211,8 @@ public Integer apply(Integer t1) { } }) - .subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + .subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturnTest.java index d03b184442..18d43e90d4 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturnTest.java @@ -130,9 +130,9 @@ public String apply(Throwable t1) { @SuppressWarnings("unchecked") DefaultObserver observer = mock(DefaultObserver.class); - TestObserver ts = new TestObserver(observer); - observable.subscribe(ts); - ts.awaitTerminalEvent(); + TestObserver to = new TestObserver(observer); + observable.subscribe(to); + to.awaitTerminalEvent(); verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); @@ -144,7 +144,7 @@ public String apply(Throwable t1) { @Test public void testBackpressure() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(0, 100000) .onErrorReturn(new Function() { @@ -172,9 +172,9 @@ public Integer apply(Integer t1) { } }) - .subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + .subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); } private static class TestObservable implements ObservableSource { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java index adab10b79d..173f506bce 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java @@ -186,7 +186,7 @@ public String apply(String s) { @Test public void testBackpressure() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(0, 100000) .onExceptionResumeNext(Observable.just(1)) .observeOn(Schedulers.computation()) @@ -207,9 +207,9 @@ public Integer apply(Integer t1) { } }) - .subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + .subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java index 90a78db347..e280f5cf9d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java @@ -125,12 +125,12 @@ public void run() { }); - TestObserver ts = new TestObserver(); - Observable.merge(fast, slow).subscribe(ts); + TestObserver to = new TestObserver(); + Observable.merge(fast, slow).subscribe(to); is.connect(); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(Flowable.bufferSize() * 4, ts.valueCount()); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(Flowable.bufferSize() * 4, to.valueCount()); } // use case from https://github.com/ReactiveX/RxJava/issues/1732 @@ -145,7 +145,7 @@ public void accept(Integer t1) { } }); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); xs.publish(new Function, Observable>() { @Override @@ -160,19 +160,19 @@ public boolean test(Integer i) { })); } - }).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - ts.assertValues(0, 1, 2, 3); + }).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + to.assertValues(0, 1, 2, 3); assertEquals(5, emitted.get()); - System.out.println(ts.values()); + System.out.println(to.values()); } // use case from https://github.com/ReactiveX/RxJava/issues/1732 @Test public void testTakeUntilWithPublishedStream() { Observable xs = Observable.range(0, Flowable.bufferSize() * 2); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); ConnectableObservable xsp = xs.publish(); xsp.takeUntil(xsp.skipWhile(new Predicate() { @@ -181,9 +181,9 @@ public boolean test(Integer i) { return i <= 3; } - })).subscribe(ts); + })).subscribe(to); xsp.connect(); - System.out.println(ts.values()); + System.out.println(to.values()); } @Test(timeout = 10000) @@ -208,9 +208,9 @@ public void run() { final AtomicBoolean child1Unsubscribed = new AtomicBoolean(); final AtomicBoolean child2Unsubscribed = new AtomicBoolean(); - final TestObserver ts2 = new TestObserver(); + final TestObserver to2 = new TestObserver(); - final TestObserver ts1 = new TestObserver() { + final TestObserver to1 = new TestObserver() { @Override public void onNext(Integer t) { if (valueCount() == 2) { @@ -219,7 +219,7 @@ public void onNext(Integer t) { public void run() { child2Unsubscribed.set(true); } - }).take(5).subscribe(ts2); + }).take(5).subscribe(to2); } super.onNext(t); } @@ -231,20 +231,20 @@ public void run() { child1Unsubscribed.set(true); } }).take(5) - .subscribe(ts1); + .subscribe(to1); - ts1.awaitTerminalEvent(); - ts2.awaitTerminalEvent(); + to1.awaitTerminalEvent(); + to2.awaitTerminalEvent(); - ts1.assertNoErrors(); - ts2.assertNoErrors(); + to1.assertNoErrors(); + to2.assertNoErrors(); assertTrue(sourceUnsubscribed.get()); assertTrue(child1Unsubscribed.get()); assertTrue(child2Unsubscribed.get()); - ts1.assertValues(1, 2, 3, 4, 5); - ts2.assertValues(4, 5, 6, 7, 8); + to1.assertValues(1, 2, 3, 4, 5); + to2.assertValues(4, 5, 6, 7, 8); assertEquals(8, sourceEmission.get()); } @@ -269,25 +269,25 @@ public void testConnectWithNoSubscriber() { public void testSubscribeAfterDisconnectThenConnect() { ConnectableObservable source = Observable.just(1).publish(); - TestObserver ts1 = new TestObserver(); + TestObserver to1 = new TestObserver(); - source.subscribe(ts1); + source.subscribe(to1); Disposable s = source.connect(); - ts1.assertValue(1); - ts1.assertNoErrors(); - ts1.assertTerminated(); + to1.assertValue(1); + to1.assertNoErrors(); + to1.assertTerminated(); - TestObserver ts2 = new TestObserver(); + TestObserver to2 = new TestObserver(); - source.subscribe(ts2); + source.subscribe(to2); Disposable s2 = source.connect(); - ts2.assertValue(1); - ts2.assertNoErrors(); - ts2.assertTerminated(); + to2.assertValue(1); + to2.assertNoErrors(); + to2.assertTerminated(); System.out.println(s); System.out.println(s2); @@ -297,19 +297,19 @@ public void testSubscribeAfterDisconnectThenConnect() { public void testNoSubscriberRetentionOnCompleted() { ObservablePublish source = (ObservablePublish)Observable.just(1).publish(); - TestObserver ts1 = new TestObserver(); + TestObserver to1 = new TestObserver(); - source.subscribe(ts1); + source.subscribe(to1); - ts1.assertNoValues(); - ts1.assertNoErrors(); - ts1.assertNotComplete(); + to1.assertNoValues(); + to1.assertNoErrors(); + to1.assertNotComplete(); source.connect(); - ts1.assertValue(1); - ts1.assertNoErrors(); - ts1.assertTerminated(); + to1.assertValue(1); + to1.assertNoErrors(); + to1.assertTerminated(); assertNull(source.current.get()); } @@ -378,20 +378,20 @@ public void testObserveOn() { Observable obs = co.observeOn(Schedulers.computation()); for (int i = 0; i < 1000; i++) { for (int j = 1; j < 6; j++) { - List> tss = new ArrayList>(); + List> tos = new ArrayList>(); for (int k = 1; k < j; k++) { - TestObserver ts = new TestObserver(); - tss.add(ts); - obs.subscribe(ts); + TestObserver to = new TestObserver(); + tos.add(to); + obs.subscribe(to); } Disposable s = co.connect(); - for (TestObserver ts : tss) { - ts.awaitTerminalEvent(2, TimeUnit.SECONDS); - ts.assertTerminated(); - ts.assertNoErrors(); - assertEquals(1000, ts.valueCount()); + for (TestObserver to : tos) { + to.awaitTerminalEvent(2, TimeUnit.SECONDS); + to.assertTerminated(); + to.assertNoErrors(); + assertEquals(1000, to.valueCount()); } s.dispose(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeLongTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeLongTest.java index e06da6205b..d09ec0d6ce 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeLongTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeLongTest.java @@ -24,7 +24,7 @@ import io.reactivex.*; import io.reactivex.functions.Consumer; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; public class ObservableRangeLongTest { @@ -99,12 +99,12 @@ public void testNoBackpressure() { Observable o = Observable.rangeLong(1, list.size()); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - o.subscribe(ts); + o.subscribe(to); - ts.assertValueSequence(list); - ts.assertTerminated(); + to.assertValueSequence(list); + to.assertTerminated(); } @Test @@ -136,12 +136,12 @@ public void onNext(Long t) { @Test(timeout = 1000) public void testNearMaxValueWithoutBackpressure() { - TestObserver ts = new TestObserver(); - Observable.rangeLong(Long.MAX_VALUE - 1L, 2L).subscribe(ts); + TestObserver to = new TestObserver(); + Observable.rangeLong(Long.MAX_VALUE - 1L, 2L).subscribe(to); - ts.assertComplete(); - ts.assertNoErrors(); - ts.assertValues(Long.MAX_VALUE - 1, Long.MAX_VALUE); + to.assertComplete(); + to.assertNoErrors(); + to.assertValues(Long.MAX_VALUE - 1, Long.MAX_VALUE); } @Test @@ -170,21 +170,21 @@ public void noOverflow() { @Test public void fused() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); Observable.rangeLong(1, 2).subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.SYNC) + ObserverFusion.assertFusion(to, QueueFuseable.SYNC) .assertResult(1L, 2L); } @Test public void fusedReject() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ASYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ASYNC); Observable.rangeLong(1, 2).subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1L, 2L); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeTest.java index 3fe8a047f0..cbdc0130ec 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.ArrayList; @@ -23,7 +24,7 @@ import io.reactivex.*; import io.reactivex.functions.Consumer; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.observers.*; public class ObservableRangeTest { @@ -99,12 +100,12 @@ public void testNoBackpressure() { Observable o = Observable.range(1, list.size()); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - o.subscribe(ts); + o.subscribe(to); - ts.assertValueSequence(list); - ts.assertTerminated(); + to.assertValueSequence(list); + to.assertTerminated(); } @Test @@ -136,12 +137,12 @@ public void onNext(Integer t) { @Test(timeout = 1000) public void testNearMaxValueWithoutBackpressure() { - TestObserver ts = new TestObserver(); - Observable.range(Integer.MAX_VALUE - 1, 2).subscribe(ts); + TestObserver to = new TestObserver(); + Observable.range(Integer.MAX_VALUE - 1, 2).subscribe(to); - ts.assertComplete(); - ts.assertNoErrors(); - ts.assertValues(Integer.MAX_VALUE - 1, Integer.MAX_VALUE); + to.assertComplete(); + to.assertNoErrors(); + to.assertValues(Integer.MAX_VALUE - 1, Integer.MAX_VALUE); } @Test @@ -156,12 +157,12 @@ public void negativeCount() { @Test public void requestWrongFusion() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ASYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ASYNC); Observable.range(1, 5) .subscribe(to); - ObserverFusion.assertFusion(to, QueueDisposable.NONE) + ObserverFusion.assertFusion(to, QueueFuseable.NONE) .assertResult(1, 2, 3, 4, 5); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index abd93aa73b..4df48c59ac 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -186,20 +186,20 @@ public void run() { .publish().refCount(); for (int i = 0; i < 10; i++) { - TestObserver ts1 = new TestObserver(); - TestObserver ts2 = new TestObserver(); - r.subscribe(ts1); - r.subscribe(ts2); + TestObserver to1 = new TestObserver(); + TestObserver to2 = new TestObserver(); + r.subscribe(to1); + r.subscribe(to2); try { Thread.sleep(50); } catch (InterruptedException e) { } - ts1.dispose(); - ts2.dispose(); - ts1.assertNoErrors(); - ts2.assertNoErrors(); - assertTrue(ts1.valueCount() > 0); - assertTrue(ts2.valueCount() > 0); + to1.dispose(); + to2.dispose(); + to1.assertNoErrors(); + to2.assertNoErrors(); + assertTrue(to1.valueCount() > 0); + assertTrue(to2.valueCount() > 0); } assertEquals(10, subscribeCount.get()); @@ -494,19 +494,19 @@ public Integer apply(Integer t1, Integer t2) { }) .publish().refCount(); - TestObserver ts1 = new TestObserver(); - TestObserver ts2 = new TestObserver(); + TestObserver to1 = new TestObserver(); + TestObserver to2 = new TestObserver(); - combined.subscribe(ts1); - combined.subscribe(ts2); + combined.subscribe(to1); + combined.subscribe(to2); - ts1.assertTerminated(); - ts1.assertNoErrors(); - ts1.assertValue(30); + to1.assertTerminated(); + to1.assertNoErrors(); + to1.assertValue(30); - ts2.assertTerminated(); - ts2.assertNoErrors(); - ts2.assertValue(30); + to2.assertTerminated(); + to2.assertNoErrors(); + to2.assertValue(30); } @Test(timeout = 10000) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java index 04fc4cddf8..3616ef729f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java @@ -162,20 +162,20 @@ public void testRepeatAndDistinctUnbounded() { .repeat(3) .distinct(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - src.subscribe(ts); + src.subscribe(to); - ts.assertNoErrors(); - ts.assertTerminated(); - ts.assertValues(1, 2, 3); + to.assertNoErrors(); + to.assertTerminated(); + to.assertValues(1, 2, 3); } /** Issue #2844: wrong target of request. */ @Test(timeout = 3000) public void testRepeatRetarget() { final List concatBase = new ArrayList(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.just(1, 2) .repeat(5) .concatMap(new Function>() { @@ -187,11 +187,11 @@ public Observable apply(Integer x) { .delay(200, TimeUnit.MILLISECONDS); } }) - .subscribe(ts); + .subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - ts.assertNoValues(); + to.awaitTerminalEvent(); + to.assertNoErrors(); + to.assertNoValues(); assertEquals(Arrays.asList(1, 2, 1, 2, 1, 2, 1, 2, 1, 2), concatBase); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java index 0d64c4308f..8c483fc40d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java @@ -872,13 +872,13 @@ public void testSizedTruncation() { public void testColdReplayNoBackpressure() { Observable source = Observable.range(0, 1000).replay().autoConnect(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.subscribe(ts); + source.subscribe(to); - ts.assertNoErrors(); - ts.assertTerminated(); - List onNextEvents = ts.values(); + to.assertNoErrors(); + to.assertTerminated(); + List onNextEvents = to.values(); assertEquals(1000, onNextEvents.size()); for (int i = 0; i < 1000; i++) { @@ -950,14 +950,14 @@ public void testUnsubscribeSource() throws Exception { @Test public void testTake() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable cached = Observable.range(1, 100).replay().autoConnect(); - cached.take(10).subscribe(ts); + cached.take(10).subscribe(to); - ts.assertNoErrors(); - ts.assertTerminated(); - ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + to.assertNoErrors(); + to.assertTerminated(); + to.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // FIXME no longer assertable // ts.assertUnsubscribed(); } @@ -966,24 +966,24 @@ public void testTake() { public void testAsync() { Observable source = Observable.range(1, 10000); for (int i = 0; i < 100; i++) { - TestObserver ts1 = new TestObserver(); + TestObserver to1 = new TestObserver(); Observable cached = source.replay().autoConnect(); - cached.observeOn(Schedulers.computation()).subscribe(ts1); + cached.observeOn(Schedulers.computation()).subscribe(to1); - ts1.awaitTerminalEvent(2, TimeUnit.SECONDS); - ts1.assertNoErrors(); - ts1.assertTerminated(); - assertEquals(10000, ts1.values().size()); + to1.awaitTerminalEvent(2, TimeUnit.SECONDS); + to1.assertNoErrors(); + to1.assertTerminated(); + assertEquals(10000, to1.values().size()); - TestObserver ts2 = new TestObserver(); - cached.observeOn(Schedulers.computation()).subscribe(ts2); + TestObserver to2 = new TestObserver(); + cached.observeOn(Schedulers.computation()).subscribe(to2); - ts2.awaitTerminalEvent(2, TimeUnit.SECONDS); - ts2.assertNoErrors(); - ts2.assertTerminated(); - assertEquals(10000, ts2.values().size()); + to2.awaitTerminalEvent(2, TimeUnit.SECONDS); + to2.assertNoErrors(); + to2.assertTerminated(); + assertEquals(10000, to2.values().size()); } } @Test @@ -997,9 +997,9 @@ public void testAsyncComeAndGo() { List> list = new ArrayList>(100); for (int i = 0; i < 100; i++) { - TestObserver ts = new TestObserver(); - list.add(ts); - output.skip(i * 10).take(10).subscribe(ts); + TestObserver to = new TestObserver(); + list.add(to); + output.skip(i * 10).take(10).subscribe(to); } List expected = new ArrayList(); @@ -1007,16 +1007,16 @@ public void testAsyncComeAndGo() { expected.add((long)(i - 10)); } int j = 0; - for (TestObserver ts : list) { - ts.awaitTerminalEvent(3, TimeUnit.SECONDS); - ts.assertNoErrors(); - ts.assertTerminated(); + for (TestObserver to : list) { + to.awaitTerminalEvent(3, TimeUnit.SECONDS); + to.assertNoErrors(); + to.assertTerminated(); for (int i = j * 10; i < j * 10 + 10; i++) { expected.set(i - j * 10, (long)i); } - ts.assertValueSequence(expected); + to.assertValueSequence(expected); j++; } @@ -1036,14 +1036,14 @@ public void subscribe(Observer t) { } }); - TestObserver ts = new TestObserver(); - firehose.replay().autoConnect().observeOn(Schedulers.computation()).takeLast(100).subscribe(ts); + TestObserver to = new TestObserver(); + firehose.replay().autoConnect().observeOn(Schedulers.computation()).takeLast(100).subscribe(to); - ts.awaitTerminalEvent(3, TimeUnit.SECONDS); - ts.assertNoErrors(); - ts.assertTerminated(); + to.awaitTerminalEvent(3, TimeUnit.SECONDS); + to.assertNoErrors(); + to.assertTerminated(); - assertEquals(100, ts.values().size()); + assertEquals(100, to.values().size()); } @Test @@ -1053,19 +1053,19 @@ public void testValuesAndThenError() { .replay().autoConnect(); - TestObserver ts = new TestObserver(); - source.subscribe(ts); + TestObserver to = new TestObserver(); + source.subscribe(to); - ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - ts.assertNotComplete(); - Assert.assertEquals(1, ts.errors().size()); + to.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + to.assertNotComplete(); + Assert.assertEquals(1, to.errors().size()); - TestObserver ts2 = new TestObserver(); - source.subscribe(ts2); + TestObserver to2 = new TestObserver(); + source.subscribe(to2); - ts2.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - ts2.assertNotComplete(); - Assert.assertEquals(1, ts2.errors().size()); + to2.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + to2.assertNotComplete(); + Assert.assertEquals(1, to2.errors().size()); } @Test @@ -1082,20 +1082,20 @@ public void accept(Integer t) { }) .replay().autoConnect(); - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { @Override public void onNext(Integer t) { throw new TestException(); } }; - source.subscribe(ts); + source.subscribe(to); Assert.assertEquals(100, count.get()); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(TestException.class); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(TestException.class); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java index 2d5e3d2aa8..a776cc97a7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java @@ -60,7 +60,7 @@ public void subscribe(Observer t1) { } }); - TestObserver ts = new TestObserver(consumer); + TestObserver to = new TestObserver(consumer); producer.retryWhen(new Function, Observable>() { @Override @@ -86,9 +86,9 @@ public Observable apply(Tuple t) { Observable.timer(t.count * 1L, TimeUnit.MILLISECONDS); }}).cast(Object.class); } - }).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + }).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); InOrder inOrder = inOrder(consumer); inOrder.verify(consumer, never()).onError(any(Throwable.class)); @@ -451,7 +451,7 @@ public void run() { public void testSourceObservableCallsUnsubscribe() throws InterruptedException { final AtomicInteger subsCount = new AtomicInteger(0); - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); ObservableSource onSubscribe = new ObservableSource() { @Override @@ -474,7 +474,7 @@ public void subscribe(Observer s) { } }; - Observable.unsafeCreate(onSubscribe).retry(3).subscribe(ts); + Observable.unsafeCreate(onSubscribe).retry(3).subscribe(to); assertEquals(4, subsCount.get()); // 1 + 3 retries } @@ -482,7 +482,7 @@ public void subscribe(Observer s) { public void testSourceObservableRetry1() throws InterruptedException { final AtomicInteger subsCount = new AtomicInteger(0); - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); ObservableSource onSubscribe = new ObservableSource() { @Override @@ -493,7 +493,7 @@ public void subscribe(Observer s) { } }; - Observable.unsafeCreate(onSubscribe).retry(1).subscribe(ts); + Observable.unsafeCreate(onSubscribe).retry(1).subscribe(to); assertEquals(2, subsCount.get()); } @@ -501,7 +501,7 @@ public void subscribe(Observer s) { public void testSourceObservableRetry0() throws InterruptedException { final AtomicInteger subsCount = new AtomicInteger(0); - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); ObservableSource onSubscribe = new ObservableSource() { @Override @@ -512,7 +512,7 @@ public void subscribe(Observer s) { } }; - Observable.unsafeCreate(onSubscribe).retry(0).subscribe(ts); + Observable.unsafeCreate(onSubscribe).retry(0).subscribe(to); assertEquals(1, subsCount.get()); } @@ -663,9 +663,9 @@ public void testRetryWithBackpressure() throws InterruptedException { for (int i = 0; i < 400; i++) { Observer observer = TestHelper.mockObserver(); Observable origin = Observable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); - TestObserver ts = new TestObserver(observer); - origin.retry().observeOn(Schedulers.computation()).subscribe(ts); - ts.awaitTerminalEvent(5, TimeUnit.SECONDS); + TestObserver to = new TestObserver(observer); + origin.retry().observeOn(Schedulers.computation()).subscribe(to); + to.awaitTerminalEvent(5, TimeUnit.SECONDS); InOrder inOrder = inOrder(observer); // should have no errors @@ -706,16 +706,16 @@ public void run() { final AtomicInteger nexts = new AtomicInteger(); try { Observable origin = Observable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); origin.retry() - .observeOn(Schedulers.computation()).subscribe(ts); - ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); - List onNextEvents = new ArrayList(ts.values()); + .observeOn(Schedulers.computation()).subscribe(to); + to.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); + List onNextEvents = new ArrayList(to.values()); if (onNextEvents.size() != NUM_RETRIES + 2) { - for (Throwable t : ts.errors()) { + for (Throwable t : to.errors()) { onNextEvents.add(t.toString()); } - for (long err = ts.completions(); err != 0; err--) { + for (long err = to.completions(); err != 0; err--) { onNextEvents.add("onComplete"); } data.put(j, onNextEvents); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java index 1763f74d9f..db87844952 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java @@ -277,7 +277,7 @@ public void testTimeoutWithRetry() { @Test public void testIssue2826() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final RuntimeException e = new RuntimeException("You shall not pass"); final AtomicInteger c = new AtomicInteger(); Observable.just(1).map(new Function() { @@ -286,11 +286,11 @@ public Integer apply(Integer t1) { c.incrementAndGet(); throw e; } - }).retry(retry5).subscribe(ts); + }).retry(retry5).subscribe(to); - ts.assertTerminated(); + to.assertTerminated(); assertEquals(6, c.get()); - assertEquals(Collections.singletonList(e), ts.errors()); + assertEquals(Collections.singletonList(e), to.errors()); } @Test public void testJustAndRetry() throws Exception { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java index 92569c5d92..3ad79160a0 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java @@ -323,17 +323,17 @@ public void emitLastTimedRunCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler scheduler = new TestScheduler(); - final PublishSubject pp = PublishSubject.create(); + final PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.sample(1, TimeUnit.SECONDS, scheduler, true) + TestObserver to = ps.sample(1, TimeUnit.SECONDS, scheduler, true) .test(); - pp.onNext(1); + ps.onNext(1); Runnable r1 = new Runnable() { @Override public void run() { - pp.onComplete(); + ps.onComplete(); } }; @@ -346,7 +346,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertResult(1); + to.assertResult(1); } } @@ -369,18 +369,18 @@ public void emitLastOtherEmpty() { @Test public void emitLastOtherRunCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishSubject pp = PublishSubject.create(); + final PublishSubject ps = PublishSubject.create(); final PublishSubject sampler = PublishSubject.create(); - TestObserver ts = pp.sample(sampler, true) + TestObserver to = ps.sample(sampler, true) .test(); - pp.onNext(1); + ps.onNext(1); Runnable r1 = new Runnable() { @Override public void run() { - pp.onComplete(); + ps.onComplete(); } }; @@ -393,24 +393,24 @@ public void run() { TestHelper.race(r1, r2); - ts.assertResult(1); + to.assertResult(1); } } @Test public void emitLastOtherCompleteCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishSubject pp = PublishSubject.create(); + final PublishSubject ps = PublishSubject.create(); final PublishSubject sampler = PublishSubject.create(); - TestObserver ts = pp.sample(sampler, true).test(); + TestObserver to = ps.sample(sampler, true).test(); - pp.onNext(1); + ps.onNext(1); Runnable r1 = new Runnable() { @Override public void run() { - pp.onComplete(); + ps.onComplete(); } }; @@ -423,7 +423,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertResult(1); + to.assertResult(1); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java index ba401f5124..cb4661943c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java @@ -73,85 +73,85 @@ public Integer call() throws Exception { @Test public void tryScalarXMap() { - TestObserver ts = new TestObserver(); - assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new CallablePublisher(), ts, new Function>() { + TestObserver to = new TestObserver(); + assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new CallablePublisher(), to, new Function>() { @Override public ObservableSource apply(Integer f) throws Exception { return Observable.just(1); } })); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test public void emptyXMap() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new EmptyCallablePublisher(), ts, new Function>() { + assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new EmptyCallablePublisher(), to, new Function>() { @Override public ObservableSource apply(Integer f) throws Exception { return Observable.just(1); } })); - ts.assertResult(); + to.assertResult(); } @Test public void mapperCrashes() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new OneCallablePublisher(), ts, new Function>() { + assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new OneCallablePublisher(), to, new Function>() { @Override public ObservableSource apply(Integer f) throws Exception { throw new TestException(); } })); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test public void mapperToJust() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new OneCallablePublisher(), ts, new Function>() { + assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new OneCallablePublisher(), to, new Function>() { @Override public ObservableSource apply(Integer f) throws Exception { return Observable.just(1); } })); - ts.assertResult(1); + to.assertResult(1); } @Test public void mapperToEmpty() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new OneCallablePublisher(), ts, new Function>() { + assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new OneCallablePublisher(), to, new Function>() { @Override public ObservableSource apply(Integer f) throws Exception { return Observable.empty(); } })); - ts.assertResult(); + to.assertResult(); } @Test public void mapperToCrashingCallable() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new OneCallablePublisher(), ts, new Function>() { + assertTrue(ObservableScalarXMap.tryScalarXMapSubscribe(new OneCallablePublisher(), to, new Function>() { @Override public ObservableSource apply(Integer f) throws Exception { return new CallablePublisher(); } })); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java index 8baf9b427e..8cd3aa75b6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java @@ -115,7 +115,7 @@ public Integer apply(Integer t1, Integer t2) { @Test public void shouldNotEmitUntilAfterSubscription() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, 100).scan(0, new BiFunction() { @Override @@ -131,9 +131,9 @@ public boolean test(Integer t1) { return t1 > 0; } - }).subscribe(ts); + }).subscribe(to); - assertEquals(100, ts.values().size()); + assertEquals(100, to.values().size()); } @Test @@ -219,18 +219,18 @@ public Integer apply(Integer t1, Integer t2) { public void testInitialValueEmittedNoProducer() { PublishSubject source = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); source.scan(0, new BiFunction() { @Override public Integer apply(Integer t1, Integer t2) { return t1 + t2; } - }).subscribe(ts); + }).subscribe(to); - ts.assertNoErrors(); - ts.assertNotComplete(); - ts.assertValue(0); + to.assertNoErrors(); + to.assertNotComplete(); + to.assertValue(0); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java index b88bd7855b..b89d70b8df 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java @@ -96,11 +96,11 @@ public void testSkipLastWithNull() { @Test public void testSkipLastWithBackpressure() { Observable o = Observable.range(0, Flowable.bufferSize() * 2).skipLast(Flowable.bufferSize() + 10); - TestObserver ts = new TestObserver(); - o.observeOn(Schedulers.computation()).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals((Flowable.bufferSize()) - 10, ts.valueCount()); + TestObserver to = new TestObserver(); + o.observeOn(Schedulers.computation()).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals((Flowable.bufferSize()) - 10, to.valueCount()); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java index 681475c22c..d787de26bf 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java @@ -137,12 +137,12 @@ public void testSkipError() { @Test public void testRequestOverflowDoesNotOccur() { - TestObserver ts = new TestObserver(); - Observable.range(1, 10).skip(5).subscribe(ts); - ts.assertTerminated(); - ts.assertComplete(); - ts.assertNoErrors(); - assertEquals(Arrays.asList(6,7,8,9,10), ts.values()); + TestObserver to = new TestObserver(); + Observable.range(1, 10).skip(5).subscribe(to); + to.assertTerminated(); + to.assertComplete(); + to.assertNoErrors(); + assertEquals(Arrays.asList(6,7,8,9,10), to.values()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSubscribeOnTest.java index 6418c5338f..03e5472bde 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSubscribeOnTest.java @@ -74,7 +74,7 @@ public void subscribe( @Test @Ignore("ObservableSource.subscribe can't throw") public void testThrownErrorHandling() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.unsafeCreate(new ObservableSource() { @Override @@ -82,14 +82,14 @@ public void subscribe(Observer s) { throw new RuntimeException("fail"); } - }).subscribeOn(Schedulers.computation()).subscribe(ts); - ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); - ts.assertTerminated(); + }).subscribeOn(Schedulers.computation()).subscribe(to); + to.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); + to.assertTerminated(); } @Test public void testOnError() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.unsafeCreate(new ObservableSource() { @Override @@ -98,9 +98,9 @@ public void subscribe(Observer s) { s.onError(new RuntimeException("fail")); } - }).subscribeOn(Schedulers.computation()).subscribe(ts); - ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); - ts.assertTerminated(); + }).subscribeOn(Schedulers.computation()).subscribe(to); + to.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); + to.assertTerminated(); } public static class SlowScheduler extends Scheduler { @@ -162,7 +162,7 @@ public Disposable schedule(@NonNull final Runnable action, final long delayTime, @Test(timeout = 5000) public void testUnsubscribeInfiniteStream() throws InterruptedException { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger count = new AtomicInteger(); Observable.unsafeCreate(new ObservableSource() { @@ -176,12 +176,12 @@ public void subscribe(Observer sub) { } } - }).subscribeOn(Schedulers.newThread()).take(10).subscribe(ts); + }).subscribeOn(Schedulers.newThread()).take(10).subscribe(to); - ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); - ts.dispose(); + to.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); + to.dispose(); Thread.sleep(200); // give time for the loop to continue - ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + to.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); assertEquals(10, count.get()); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java index 034890b1bd..680eb17753 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java @@ -461,7 +461,7 @@ public String apply(Long i) { .share() ; - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { @Override public void onNext(String t) { super.onNext(t); @@ -471,16 +471,16 @@ public void onNext(String t) { } } }; - src.subscribe(ts); + src.subscribe(to); - ts.awaitTerminalEvent(10, TimeUnit.SECONDS); + to.awaitTerminalEvent(10, TimeUnit.SECONDS); - System.out.println("> testIssue2654: " + ts.valueCount()); + System.out.println("> testIssue2654: " + to.valueCount()); - ts.assertTerminated(); - ts.assertNoErrors(); + to.assertTerminated(); + to.assertNoErrors(); - Assert.assertEquals(250, ts.valueCount()); + Assert.assertEquals(250, to.valueCount()); } @@ -488,10 +488,10 @@ public void onNext(String t) { public void delayErrors() { PublishSubject> source = PublishSubject.create(); - TestObserver ts = source.switchMapDelayError(Functions.>identity()) + TestObserver to = source.switchMapDelayError(Functions.>identity()) .test(); - ts.assertNoValues() + to.assertNoValues() .assertNoErrors() .assertNotComplete(); @@ -507,11 +507,11 @@ public void delayErrors() { source.onError(new TestException("Forced failure 3")); - ts.assertValues(1, 2, 3, 4, 5) + to.assertValues(1, 2, 3, 4, 5) .assertNotComplete() .assertError(CompositeException.class); - List errors = ExceptionHelper.flatten(ts.errors().get(0)); + List errors = ExceptionHelper.flatten(to.errors().get(0)); TestHelper.assertError(errors, 0, TestException.class, "Forced failure 1"); TestHelper.assertError(errors, 1, TestException.class, "Forced failure 2"); @@ -522,40 +522,40 @@ public void delayErrors() { public void switchOnNextDelayError() { PublishSubject> ps = PublishSubject.create(); - TestObserver ts = Observable.switchOnNextDelayError(ps).test(); + TestObserver to = Observable.switchOnNextDelayError(ps).test(); ps.onNext(Observable.just(1)); ps.onNext(Observable.range(2, 4)); ps.onComplete(); - ts.assertResult(1, 2, 3, 4, 5); + to.assertResult(1, 2, 3, 4, 5); } @Test public void switchOnNextDelayErrorWithError() { PublishSubject> ps = PublishSubject.create(); - TestObserver ts = Observable.switchOnNextDelayError(ps).test(); + TestObserver to = Observable.switchOnNextDelayError(ps).test(); ps.onNext(Observable.just(1)); ps.onNext(Observable.error(new TestException())); ps.onNext(Observable.range(2, 4)); ps.onComplete(); - ts.assertFailure(TestException.class, 1, 2, 3, 4, 5); + to.assertFailure(TestException.class, 1, 2, 3, 4, 5); } @Test public void switchOnNextDelayErrorBufferSize() { PublishSubject> ps = PublishSubject.create(); - TestObserver ts = Observable.switchOnNextDelayError(ps, 2).test(); + TestObserver to = Observable.switchOnNextDelayError(ps, 2).test(); ps.onNext(Observable.just(1)); ps.onNext(Observable.range(2, 4)); ps.onComplete(); - ts.assertResult(1, 2, 3, 4, 5); + to.assertResult(1, 2, 3, 4, 5); } @Test @@ -610,17 +610,17 @@ public ObservableSource apply(Object v) throws Exception { @Test public void switchMapInnerCancelled() { - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver ts = Observable.just(1) - .switchMap(Functions.justFunction(pp)) + TestObserver to = Observable.just(1) + .switchMap(Functions.justFunction(ps)) .test(); - assertTrue(pp.hasObservers()); + assertTrue(ps.hasObservers()); - ts.cancel(); + to.cancel(); - assertFalse(pp.hasObservers()); + assertFalse(ps.hasObservers()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java index e2c91fb6a4..27327bffcf 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java @@ -103,23 +103,23 @@ public void testTakeLastWithNegativeCount() { @Test public void testBackpressure1() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, 100000).takeLast(1) .observeOn(Schedulers.newThread()) - .map(newSlowProcessor()).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - ts.assertValue(100000); + .map(newSlowProcessor()).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + to.assertValue(100000); } @Test public void testBackpressure2() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, 100000).takeLast(Flowable.bufferSize() * 4) - .observeOn(Schedulers.newThread()).map(newSlowProcessor()).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(Flowable.bufferSize() * 4, ts.valueCount()); + .observeOn(Schedulers.newThread()).map(newSlowProcessor()).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(Flowable.bufferSize() * 4, to.valueCount()); } private Function newSlowProcessor() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java index c094ad0c06..f966cd8647 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java @@ -281,12 +281,12 @@ public void subscribe(Observer op) { @Test(timeout = 2000) public void testTakeObserveOn() { Observer o = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(o); + TestObserver to = new TestObserver(o); INFINITE_OBSERVABLE - .observeOn(Schedulers.newThread()).take(1).subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + .observeOn(Schedulers.newThread()).take(1).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); verify(o).onNext(1L); verify(o, never()).onNext(2L); @@ -323,38 +323,38 @@ public void accept(Integer t1) { public void takeFinalValueThrows() { Observable source = Observable.just(1).take(1); - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { @Override public void onNext(Integer t) { throw new TestException(); } }; - source.safeSubscribe(ts); + source.safeSubscribe(to); - ts.assertNoValues(); - ts.assertError(TestException.class); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertError(TestException.class); + to.assertNotComplete(); } @Test public void testReentrantTake() { final PublishSubject source = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); source.take(1).doOnNext(new Consumer() { @Override public void accept(Integer v) { source.onNext(2); } - }).subscribe(ts); + }).subscribe(to); source.onNext(1); - ts.assertValue(1); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(1); + to.assertNoErrors(); + to.assertComplete(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java index 6e3614525b..722da7890a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java @@ -136,7 +136,7 @@ public boolean test(Integer v) { @Test public void testErrorIncludesLastValueAsCause() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final TestException e = new TestException("Forced failure"); Predicate predicate = (new Predicate() { @Override @@ -144,11 +144,11 @@ public boolean test(String t) { throw e; } }); - Observable.just("abc").takeUntil(predicate).subscribe(ts); + Observable.just("abc").takeUntil(predicate).subscribe(to); - ts.assertTerminated(); - ts.assertNotComplete(); - ts.assertError(TestException.class); + to.assertTerminated(); + to.assertNotComplete(); + to.assertError(TestException.class); // FIXME last cause value is not saved // assertTrue(ts.errors().get(0).getCause().getMessage().contains("abc")); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java index 9c6fcba337..7a2f139da9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java @@ -188,21 +188,21 @@ public void testUntilFires() { PublishSubject source = PublishSubject.create(); PublishSubject until = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.takeUntil(until).subscribe(ts); + source.takeUntil(until).subscribe(to); assertTrue(source.hasObservers()); assertTrue(until.hasObservers()); source.onNext(1); - ts.assertValue(1); + to.assertValue(1); until.onNext(1); - ts.assertValue(1); - ts.assertNoErrors(); - ts.assertTerminated(); + to.assertValue(1); + to.assertNoErrors(); + to.assertTerminated(); assertFalse("Source still has observers", source.hasObservers()); assertFalse("Until still has observers", until.hasObservers()); @@ -214,9 +214,9 @@ public void testMainCompletes() { PublishSubject source = PublishSubject.create(); PublishSubject until = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.takeUntil(until).subscribe(ts); + source.takeUntil(until).subscribe(to); assertTrue(source.hasObservers()); assertTrue(until.hasObservers()); @@ -224,9 +224,9 @@ public void testMainCompletes() { source.onNext(1); source.onComplete(); - ts.assertValue(1); - ts.assertNoErrors(); - ts.assertTerminated(); + to.assertValue(1); + to.assertNoErrors(); + to.assertTerminated(); assertFalse("Source still has observers", source.hasObservers()); assertFalse("Until still has observers", until.hasObservers()); @@ -238,18 +238,18 @@ public void testDownstreamUnsubscribes() { PublishSubject source = PublishSubject.create(); PublishSubject until = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.takeUntil(until).take(1).subscribe(ts); + source.takeUntil(until).take(1).subscribe(to); assertTrue(source.hasObservers()); assertTrue(until.hasObservers()); source.onNext(1); - ts.assertValue(1); - ts.assertNoErrors(); - ts.assertTerminated(); + to.assertValue(1); + to.assertNoErrors(); + to.assertTerminated(); assertFalse("Source still has observers", source.hasObservers()); assertFalse("Until still has observers", until.hasObservers()); @@ -266,8 +266,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>() { @Override - public Observable apply(Observable c) throws Exception { - return c.takeUntil(Observable.never()); + public Observable apply(Observable o) throws Exception { + return o.takeUntil(Observable.never()); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeWhileTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeWhileTest.java index 545cb4e65e..4b615de665 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeWhileTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeWhileTest.java @@ -221,12 +221,12 @@ public boolean test(Integer t1) { return t1 < 2; } }); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - source.subscribe(ts); + source.subscribe(to); - ts.assertNoErrors(); - ts.assertValue(1); + to.assertNoErrors(); + to.assertValue(1); // 2.0.2 - not anymore // Assert.assertTrue("Not cancelled!", ts.isCancelled()); @@ -234,17 +234,17 @@ public boolean test(Integer t1) { @Test public void testErrorCauseIncludesLastValue() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.just("abc").takeWhile(new Predicate() { @Override public boolean test(String t1) { throw new TestException(); } - }).subscribe(ts); + }).subscribe(to); - ts.assertTerminated(); - ts.assertNoValues(); - ts.assertError(TestException.class); + to.assertTerminated(); + to.assertNoValues(); + to.assertError(TestException.class); // FIXME last cause value not recorded // assertTrue(ts.getOnErrorEvents().get(0).getCause().getMessage().contains("abc")); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java index 3c244964c9..07e7c4c39b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java @@ -50,24 +50,24 @@ public void setUp() { @Test public void shouldNotTimeoutIfOnNextWithinTimeout() { Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); - withTimeout.subscribe(ts); + withTimeout.subscribe(to); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); verify(observer).onNext("One"); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); verify(observer, never()).onError(any(Throwable.class)); - ts.dispose(); + to.dispose(); } @Test public void shouldNotTimeoutIfSecondOnNextWithinTimeout() { Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); - withTimeout.subscribe(ts); + withTimeout.subscribe(to); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); @@ -76,57 +76,57 @@ public void shouldNotTimeoutIfSecondOnNextWithinTimeout() { verify(observer).onNext("Two"); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); verify(observer, never()).onError(any(Throwable.class)); - ts.dispose(); + to.dispose(); } @Test public void shouldTimeoutIfOnNextNotWithinTimeout() { Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); - withTimeout.subscribe(ts); + withTimeout.subscribe(to); testScheduler.advanceTimeBy(TIMEOUT + 1, TimeUnit.SECONDS); verify(observer).onError(any(TimeoutException.class)); - ts.dispose(); + to.dispose(); } @Test public void shouldTimeoutIfSecondOnNextNotWithinTimeout() { Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); withTimeout.subscribe(observer); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); verify(observer).onNext("One"); testScheduler.advanceTimeBy(TIMEOUT + 1, TimeUnit.SECONDS); verify(observer).onError(any(TimeoutException.class)); - ts.dispose(); + to.dispose(); } @Test public void shouldCompleteIfUnderlyingComletes() { Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); withTimeout.subscribe(observer); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onComplete(); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); verify(observer).onComplete(); verify(observer, never()).onError(any(Throwable.class)); - ts.dispose(); + to.dispose(); } @Test public void shouldErrorIfUnderlyingErrors() { Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); withTimeout.subscribe(observer); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onError(new UnsupportedOperationException()); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); verify(observer).onError(any(UnsupportedOperationException.class)); - ts.dispose(); + to.dispose(); } @Test @@ -135,8 +135,8 @@ public void shouldSwitchToOtherIfOnNextNotWithinTimeout() { Observable source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - source.subscribe(ts); + TestObserver to = new TestObserver(observer); + source.subscribe(to); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); @@ -149,7 +149,7 @@ public void shouldSwitchToOtherIfOnNextNotWithinTimeout() { inOrder.verify(observer, times(1)).onNext("c"); inOrder.verify(observer, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - ts.dispose(); + to.dispose(); } @Test @@ -158,8 +158,8 @@ public void shouldSwitchToOtherIfOnErrorNotWithinTimeout() { Observable source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - source.subscribe(ts); + TestObserver to = new TestObserver(observer); + source.subscribe(to); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); @@ -172,7 +172,7 @@ public void shouldSwitchToOtherIfOnErrorNotWithinTimeout() { inOrder.verify(observer, times(1)).onNext("c"); inOrder.verify(observer, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - ts.dispose(); + to.dispose(); } @Test @@ -181,8 +181,8 @@ public void shouldSwitchToOtherIfOnCompletedNotWithinTimeout() { Observable source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - source.subscribe(ts); + TestObserver to = new TestObserver(observer); + source.subscribe(to); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); @@ -195,7 +195,7 @@ public void shouldSwitchToOtherIfOnCompletedNotWithinTimeout() { inOrder.verify(observer, times(1)).onNext("c"); inOrder.verify(observer, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - ts.dispose(); + to.dispose(); } @Test @@ -204,8 +204,8 @@ public void shouldSwitchToOtherAndCanBeUnsubscribedIfOnNextNotWithinTimeout() { Observable source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - source.subscribe(ts); + TestObserver to = new TestObserver(observer); + source.subscribe(to); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); @@ -214,7 +214,7 @@ public void shouldSwitchToOtherAndCanBeUnsubscribedIfOnNextNotWithinTimeout() { other.onNext("a"); other.onNext("b"); - ts.dispose(); + to.dispose(); // The following messages should not be delivered. other.onNext("c"); @@ -235,7 +235,7 @@ public void shouldTimeoutIfSynchronizedObservableEmitFirstOnNextNotWithinTimeout final CountDownLatch timeoutSetuped = new CountDownLatch(1); final Observer observer = TestHelper.mockObserver(); - final TestObserver ts = new TestObserver(observer); + final TestObserver to = new TestObserver(observer); new Thread(new Runnable() { @@ -257,7 +257,7 @@ public void subscribe(Observer observer) { } }).timeout(1, TimeUnit.SECONDS, testScheduler) - .subscribe(ts); + .subscribe(to); } }).start(); @@ -287,8 +287,8 @@ public void subscribe(Observer observer) { Observable observableWithTimeout = never.timeout(1000, TimeUnit.MILLISECONDS, testScheduler); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - observableWithTimeout.subscribe(ts); + TestObserver to = new TestObserver(observer); + observableWithTimeout.subscribe(to); testScheduler.advanceTimeBy(2000, TimeUnit.MILLISECONDS); @@ -318,8 +318,8 @@ public void subscribe(Observer observer) { testScheduler); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - observableWithTimeout.subscribe(ts); + TestObserver to = new TestObserver(observer); + observableWithTimeout.subscribe(to); testScheduler.advanceTimeBy(2000, TimeUnit.MILLISECONDS); @@ -349,8 +349,8 @@ public void subscribe(Observer observer) { testScheduler); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - observableWithTimeout.subscribe(ts); + TestObserver to = new TestObserver(observer); + observableWithTimeout.subscribe(to); testScheduler.advanceTimeBy(2000, TimeUnit.MILLISECONDS); @@ -524,14 +524,14 @@ public void onNextOnTimeoutRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler sch = new TestScheduler(); - final PublishSubject pp = PublishSubject.create(); + final PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.timeout(1, TimeUnit.SECONDS, sch).test(); + TestObserver to = ps.timeout(1, TimeUnit.SECONDS, sch).test(); Runnable r1 = new Runnable() { @Override public void run() { - pp.onNext(1); + ps.onNext(1); } }; @@ -544,14 +544,14 @@ public void run() { TestHelper.race(r1, r2); - if (ts.valueCount() != 0) { - if (ts.errorCount() != 0) { - ts.assertFailure(TimeoutException.class, 1); + if (to.valueCount() != 0) { + if (to.errorCount() != 0) { + to.assertFailure(TimeoutException.class, 1); } else { - ts.assertValuesOnly(1); + to.assertValuesOnly(1); } } else { - ts.assertFailure(TimeoutException.class); + to.assertFailure(TimeoutException.class); } } } @@ -561,14 +561,14 @@ public void onNextOnTimeoutRaceFallback() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler sch = new TestScheduler(); - final PublishSubject pp = PublishSubject.create(); + final PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.timeout(1, TimeUnit.SECONDS, sch, Observable.just(2)).test(); + TestObserver to = ps.timeout(1, TimeUnit.SECONDS, sch, Observable.just(2)).test(); Runnable r1 = new Runnable() { @Override public void run() { - pp.onNext(1); + ps.onNext(1); } }; @@ -581,16 +581,16 @@ public void run() { TestHelper.race(r1, r2); - if (ts.isTerminated()) { - int c = ts.valueCount(); + if (to.isTerminated()) { + int c = to.valueCount(); if (c == 1) { - int v = ts.values().get(0); + int v = to.values().get(0); assertTrue("" + v, v == 1 || v == 2); } else { - ts.assertResult(1, 2); + to.assertResult(1, 2); } } else { - ts.assertValuesOnly(1); + to.assertValuesOnly(1); } } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java index 276971e5c9..921cd50383 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java @@ -328,14 +328,14 @@ public Void answer(InvocationOnMock invocation) throws Throwable { }).when(o).onComplete(); - final TestObserver ts = new TestObserver(o); + final TestObserver to = new TestObserver(o); new Thread(new Runnable() { @Override public void run() { PublishSubject source = PublishSubject.create(); - source.timeout(timeoutFunc, Observable.just(3)).subscribe(ts); + source.timeout(timeoutFunc, Observable.just(3)).subscribe(to); source.onNext(1); // start timeout try { if (!enteredTimeoutOne.await(30, TimeUnit.SECONDS)) { @@ -568,7 +568,7 @@ protected void subscribeActual( } }; - TestObserver ts = ps.timeout(Functions.justFunction(pp2)).test(); + TestObserver to = ps.timeout(Functions.justFunction(pp2)).test(); ps.onNext(0); @@ -590,7 +590,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertValueAt(0, 0); + to.assertValueAt(0, 0); if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); @@ -623,7 +623,7 @@ protected void subscribeActual( } }; - TestObserver ts = ps.timeout(Functions.justFunction(pp2), Observable.never()).test(); + TestObserver to = ps.timeout(Functions.justFunction(pp2), Observable.never()).test(); ps.onNext(0); @@ -645,7 +645,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertValueAt(0, 0); + to.assertValueAt(0, 0); if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); @@ -678,7 +678,7 @@ protected void subscribeActual( } }; - TestObserver ts = ps.timeout(Functions.justFunction(pp2)).test(); + TestObserver to = ps.timeout(Functions.justFunction(pp2)).test(); ps.onNext(0); @@ -700,7 +700,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertValueAt(0, 0); + to.assertValueAt(0, 0); if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); @@ -733,7 +733,7 @@ protected void subscribeActual( } }; - TestObserver ts = ps.timeout(Functions.justFunction(pp2)).test(); + TestObserver to = ps.timeout(Functions.justFunction(pp2)).test(); ps.onNext(0); @@ -753,7 +753,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertValueAt(0, 0); + to.assertValueAt(0, 0); if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); @@ -786,7 +786,7 @@ protected void subscribeActual( } }; - TestObserver ts = ps.timeout(Functions.justFunction(pp2), Observable.never()).test(); + TestObserver to = ps.timeout(Functions.justFunction(pp2), Observable.never()).test(); ps.onNext(0); @@ -806,7 +806,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertValueAt(0, 0); + to.assertValueAt(0, 0); if (!errors.isEmpty()) { TestHelper.assertUndeliverable(errors, 0, TestException.class); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java index 6101e11977..416a5e10e0 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java @@ -63,169 +63,169 @@ public void testTimerOnce() { @Test public void testTimerPeriodically() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.interval(100, 100, TimeUnit.MILLISECONDS, scheduler).subscribe(ts); + Observable.interval(100, 100, TimeUnit.MILLISECONDS, scheduler).subscribe(to); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - ts.assertValue(0L); + to.assertValue(0L); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - ts.assertValues(0L, 1L); + to.assertValues(0L, 1L); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - ts.assertValues(0L, 1L, 2L); + to.assertValues(0L, 1L, 2L); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - ts.assertValues(0L, 1L, 2L, 3L); + to.assertValues(0L, 1L, 2L, 3L); - ts.dispose(); + to.dispose(); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - ts.assertValues(0L, 1L, 2L, 3L); + to.assertValues(0L, 1L, 2L, 3L); - ts.assertNotComplete(); - ts.assertNoErrors(); + to.assertNotComplete(); + to.assertNoErrors(); } @Test public void testInterval() { Observable w = Observable.interval(1, TimeUnit.SECONDS, scheduler); - TestObserver ts = new TestObserver(); - w.subscribe(ts); + TestObserver to = new TestObserver(); + w.subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertNotComplete(); scheduler.advanceTimeTo(2, TimeUnit.SECONDS); - ts.assertValues(0L, 1L); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertValues(0L, 1L); + to.assertNoErrors(); + to.assertNotComplete(); - ts.dispose(); + to.dispose(); scheduler.advanceTimeTo(4, TimeUnit.SECONDS); - ts.assertValues(0L, 1L); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertValues(0L, 1L); + to.assertNoErrors(); + to.assertNotComplete(); } @Test public void testWithMultipleSubscribersStartingAtSameTime() { Observable w = Observable.interval(1, TimeUnit.SECONDS, scheduler); - TestObserver ts1 = new TestObserver(); - TestObserver ts2 = new TestObserver(); + TestObserver to1 = new TestObserver(); + TestObserver to2 = new TestObserver(); - w.subscribe(ts1); - w.subscribe(ts2); + w.subscribe(to1); + w.subscribe(to2); - ts1.assertNoValues(); - ts2.assertNoValues(); + to1.assertNoValues(); + to2.assertNoValues(); scheduler.advanceTimeTo(2, TimeUnit.SECONDS); - ts1.assertValues(0L, 1L); - ts1.assertNoErrors(); - ts1.assertNotComplete(); + to1.assertValues(0L, 1L); + to1.assertNoErrors(); + to1.assertNotComplete(); - ts2.assertValues(0L, 1L); - ts2.assertNoErrors(); - ts2.assertNotComplete(); + to2.assertValues(0L, 1L); + to2.assertNoErrors(); + to2.assertNotComplete(); - ts1.dispose(); - ts2.dispose(); + to1.dispose(); + to2.dispose(); scheduler.advanceTimeTo(4, TimeUnit.SECONDS); - ts1.assertValues(0L, 1L); - ts1.assertNoErrors(); - ts1.assertNotComplete(); + to1.assertValues(0L, 1L); + to1.assertNoErrors(); + to1.assertNotComplete(); - ts2.assertValues(0L, 1L); - ts2.assertNoErrors(); - ts2.assertNotComplete(); + to2.assertValues(0L, 1L); + to2.assertNoErrors(); + to2.assertNotComplete(); } @Test public void testWithMultipleStaggeredSubscribers() { Observable w = Observable.interval(1, TimeUnit.SECONDS, scheduler); - TestObserver ts1 = new TestObserver(); + TestObserver to1 = new TestObserver(); - w.subscribe(ts1); + w.subscribe(to1); - ts1.assertNoErrors(); + to1.assertNoErrors(); scheduler.advanceTimeTo(2, TimeUnit.SECONDS); - TestObserver ts2 = new TestObserver(); + TestObserver to2 = new TestObserver(); - w.subscribe(ts2); + w.subscribe(to2); - ts1.assertValues(0L, 1L); - ts1.assertNoErrors(); - ts1.assertNotComplete(); + to1.assertValues(0L, 1L); + to1.assertNoErrors(); + to1.assertNotComplete(); - ts2.assertNoValues(); + to2.assertNoValues(); scheduler.advanceTimeTo(4, TimeUnit.SECONDS); - ts1.assertValues(0L, 1L, 2L, 3L); + to1.assertValues(0L, 1L, 2L, 3L); - ts2.assertValues(0L, 1L); + to2.assertValues(0L, 1L); - ts1.dispose(); - ts2.dispose(); + to1.dispose(); + to2.dispose(); - ts1.assertValues(0L, 1L, 2L, 3L); - ts1.assertNoErrors(); - ts1.assertNotComplete(); + to1.assertValues(0L, 1L, 2L, 3L); + to1.assertNoErrors(); + to1.assertNotComplete(); - ts2.assertValues(0L, 1L); - ts2.assertNoErrors(); - ts2.assertNotComplete(); + to2.assertValues(0L, 1L); + to2.assertNoErrors(); + to2.assertNotComplete(); } @Test public void testWithMultipleStaggeredSubscribersAndPublish() { ConnectableObservable w = Observable.interval(1, TimeUnit.SECONDS, scheduler).publish(); - TestObserver ts1 = new TestObserver(); + TestObserver to1 = new TestObserver(); - w.subscribe(ts1); + w.subscribe(to1); w.connect(); - ts1.assertNoValues(); + to1.assertNoValues(); scheduler.advanceTimeTo(2, TimeUnit.SECONDS); - TestObserver ts2 = new TestObserver(); - w.subscribe(ts2); + TestObserver to2 = new TestObserver(); + w.subscribe(to2); - ts1.assertValues(0L, 1L); - ts1.assertNoErrors(); - ts1.assertNotComplete(); + to1.assertValues(0L, 1L); + to1.assertNoErrors(); + to1.assertNotComplete(); - ts2.assertNoValues(); + to2.assertNoValues(); scheduler.advanceTimeTo(4, TimeUnit.SECONDS); - ts1.assertValues(0L, 1L, 2L, 3L); + to1.assertValues(0L, 1L, 2L, 3L); - ts2.assertValues(2L, 3L); + to2.assertValues(2L, 3L); - ts1.dispose(); - ts2.dispose(); + to1.dispose(); + to2.dispose(); - ts1.assertValues(0L, 1L, 2L, 3L); - ts1.assertNoErrors(); - ts1.assertNotComplete(); + to1.assertValues(0L, 1L, 2L, 3L); + to1.assertNoErrors(); + to1.assertNotComplete(); - ts2.assertValues(2L, 3L); - ts2.assertNoErrors(); - ts2.assertNotComplete(); + to2.assertValues(2L, 3L); + to2.assertNoErrors(); + to2.assertNotComplete(); } @Test public void testOnceObserverThrows() { @@ -315,7 +315,7 @@ public void timerInterruptible() throws Exception { try { for (Scheduler s : new Scheduler[] { Schedulers.single(), Schedulers.computation(), Schedulers.newThread(), Schedulers.io(), Schedulers.from(exec) }) { final AtomicBoolean interrupted = new AtomicBoolean(); - TestObserver ts = Observable.timer(1, TimeUnit.MILLISECONDS, s) + TestObserver to = Observable.timer(1, TimeUnit.MILLISECONDS, s) .map(new Function() { @Override public Long apply(Long v) throws Exception { @@ -331,7 +331,7 @@ public Long apply(Long v) throws Exception { Thread.sleep(500); - ts.cancel(); + to.cancel(); Thread.sleep(500); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableToFutureTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableToFutureTest.java index 5de707f461..4cd7e26076 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableToFutureTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableToFutureTest.java @@ -35,11 +35,11 @@ public void testSuccess() throws Exception { Observer o = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(o); + TestObserver to = new TestObserver(o); - Observable.fromFuture(future).subscribe(ts); + Observable.fromFuture(future).subscribe(to); - ts.dispose(); + to.dispose(); verify(o, times(1)).onNext(value); verify(o, times(1)).onComplete(); @@ -57,9 +57,9 @@ public void testSuccessOperatesOnSuppliedScheduler() throws Exception { Observer o = TestHelper.mockObserver(); TestScheduler scheduler = new TestScheduler(); - TestObserver ts = new TestObserver(o); + TestObserver to = new TestObserver(o); - Observable.fromFuture(future, scheduler).subscribe(ts); + Observable.fromFuture(future, scheduler).subscribe(to); verify(o, never()).onNext(value); @@ -77,11 +77,11 @@ public void testFailure() throws Exception { Observer o = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(o); + TestObserver to = new TestObserver(o); - Observable.fromFuture(future).subscribe(ts); + Observable.fromFuture(future).subscribe(to); - ts.dispose(); + to.dispose(); verify(o, never()).onNext(null); verify(o, never()).onComplete(); @@ -98,13 +98,13 @@ public void testCancelledBeforeSubscribe() throws Exception { Observer o = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(o); - ts.dispose(); + TestObserver to = new TestObserver(o); + to.dispose(); - Observable.fromFuture(future).subscribe(ts); + Observable.fromFuture(future).subscribe(to); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertNoErrors(); + to.assertNotComplete(); } @Test @@ -144,17 +144,17 @@ public Object get(long timeout, TimeUnit unit) throws InterruptedException, Exec Observer o = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(o); + TestObserver to = new TestObserver(o); Observable futureObservable = Observable.fromFuture(future); - futureObservable.subscribeOn(Schedulers.computation()).subscribe(ts); + futureObservable.subscribeOn(Schedulers.computation()).subscribe(to); Thread.sleep(100); - ts.dispose(); + to.dispose(); - ts.assertNoErrors(); - ts.assertNoValues(); - ts.assertNotComplete(); + to.assertNoErrors(); + to.assertNoValues(); + to.assertNotComplete(); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java index 6c084f01d6..000b116615 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java @@ -253,7 +253,7 @@ public void onComplete() { @Test public void testWindowNoDuplication() { final PublishSubject source = PublishSubject.create(); - final TestObserver tsw = new TestObserver() { + final TestObserver tow = new TestObserver() { boolean once; @Override public void onNext(Integer t) { @@ -264,10 +264,10 @@ public void onNext(Integer t) { super.onNext(t); } }; - TestObserver> ts = new TestObserver>() { + TestObserver> to = new TestObserver>() { @Override public void onNext(Observable t) { - t.subscribe(tsw); + t.subscribe(tow); super.onNext(t); } }; @@ -276,13 +276,13 @@ public void onNext(Observable t) { public Observable call() { return Observable.never(); } - }).subscribe(ts); + }).subscribe(to); source.onNext(1); source.onComplete(); - ts.assertValueCount(1); - tsw.assertValues(1, 2); + to.assertValueCount(1); + tow.assertValues(1, 2); } @Test @@ -295,12 +295,12 @@ public Observable call() { } }; - TestObserver> ts = new TestObserver>(); - source.window(boundary).subscribe(ts); + TestObserver> to = new TestObserver>(); + source.window(boundary).subscribe(to); // 2.0.2 - not anymore // assertTrue("Not cancelled!", ts.isCancelled()); - ts.assertComplete(); + to.assertComplete(); } @Test @@ -314,8 +314,8 @@ public Observable call() { } }; - TestObserver> ts = new TestObserver>(); - source.window(boundaryFunc).subscribe(ts); + TestObserver> to = new TestObserver>(); + source.window(boundaryFunc).subscribe(to); assertTrue(source.hasObservers()); assertTrue(boundary.hasObservers()); @@ -325,9 +325,9 @@ public Observable call() { assertFalse(source.hasObservers()); assertFalse(boundary.hasObservers()); - ts.assertComplete(); - ts.assertNoErrors(); - ts.assertValueCount(1); + to.assertComplete(); + to.assertNoErrors(); + to.assertValueCount(1); } @Test public void testMainUnsubscribedOnBoundaryCompletion() { @@ -340,8 +340,8 @@ public Observable call() { } }; - TestObserver> ts = new TestObserver>(); - source.window(boundaryFunc).subscribe(ts); + TestObserver> to = new TestObserver>(); + source.window(boundaryFunc).subscribe(to); assertTrue(source.hasObservers()); assertTrue(boundary.hasObservers()); @@ -352,9 +352,9 @@ public Observable call() { assertFalse(source.hasObservers()); assertFalse(boundary.hasObservers()); - ts.assertComplete(); - ts.assertNoErrors(); - ts.assertValueCount(1); + to.assertComplete(); + to.assertNoErrors(); + to.assertValueCount(1); } @Test @@ -368,25 +368,25 @@ public Observable call() { } }; - TestObserver> ts = new TestObserver>(); - source.window(boundaryFunc).subscribe(ts); + TestObserver> to = new TestObserver>(); + source.window(boundaryFunc).subscribe(to); assertTrue(source.hasObservers()); assertTrue(boundary.hasObservers()); - ts.dispose(); + to.dispose(); assertTrue(source.hasObservers()); assertFalse(boundary.hasObservers()); - ts.values().get(0).test(true); + to.values().get(0).test(true); assertFalse(source.hasObservers()); - ts.assertNotComplete(); - ts.assertNoErrors(); - ts.assertValueCount(1); + to.assertNotComplete(); + to.assertNoErrors(); + to.assertValueCount(1); } @Test @@ -402,8 +402,8 @@ public Observable call() { } }; - TestObserver> ts = new TestObserver>(); - source.window(boundaryFunc).subscribe(ts); + TestObserver> to = new TestObserver>(); + source.window(boundaryFunc).subscribe(to); source.onNext(1); boundary.onNext(1); @@ -420,9 +420,9 @@ public Observable call() { source.onNext(4); source.onComplete(); - ts.assertNoErrors(); - ts.assertValueCount(4); - ts.assertComplete(); + to.assertNoErrors(); + to.assertValueCount(4); + to.assertComplete(); assertFalse(source.hasObservers()); assertFalse(boundary.hasObservers()); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java index 5be74817a8..a3f2fedc41 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java @@ -105,7 +105,7 @@ public void testSkipAndCountWindowsWithGaps() { @Test public void testWindowUnsubscribeNonOverlapping() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger count = new AtomicInteger(); Observable.merge(Observable.range(1, 10000).doOnNext(new Consumer() { @@ -114,17 +114,17 @@ public void accept(Integer t1) { count.incrementAndGet(); } - }).window(5).take(2)).subscribe(ts); - ts.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); - ts.assertTerminated(); - ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + }).window(5).take(2)).subscribe(to); + to.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); + to.assertTerminated(); + to.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // System.out.println(ts.getOnNextEvents()); assertEquals(10, count.get()); } @Test public void testWindowUnsubscribeNonOverlappingAsyncSource() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger count = new AtomicInteger(); Observable.merge(Observable.range(1, 100000) .doOnNext(new Consumer() { @@ -145,17 +145,17 @@ public void accept(Integer t1) { .observeOn(Schedulers.computation()) .window(5) .take(2)) - .subscribe(ts); - ts.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); - ts.assertTerminated(); - ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + .subscribe(to); + to.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); + to.assertTerminated(); + to.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // make sure we don't emit all values ... the unsubscribe should propagate assertTrue(count.get() < 100000); } @Test public void testWindowUnsubscribeOverlapping() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger count = new AtomicInteger(); Observable.merge(Observable.range(1, 10000).doOnNext(new Consumer() { @@ -164,17 +164,17 @@ public void accept(Integer t1) { count.incrementAndGet(); } - }).window(5, 4).take(2)).subscribe(ts); - ts.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); - ts.assertTerminated(); + }).window(5, 4).take(2)).subscribe(to); + to.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); + to.assertTerminated(); // System.out.println(ts.getOnNextEvents()); - ts.assertValues(1, 2, 3, 4, 5, 5, 6, 7, 8, 9); + to.assertValues(1, 2, 3, 4, 5, 5, 6, 7, 8, 9); assertEquals(9, count.get()); } @Test public void testWindowUnsubscribeOverlappingAsyncSource() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger count = new AtomicInteger(); Observable.merge(Observable.range(1, 100000) .doOnNext(new Consumer() { @@ -188,10 +188,10 @@ public void accept(Integer t1) { .observeOn(Schedulers.computation()) .window(5, 4) .take(2), 128) - .subscribe(ts); - ts.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); - ts.assertTerminated(); - ts.assertValues(1, 2, 3, 4, 5, 5, 6, 7, 8, 9); + .subscribe(to); + to.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); + to.assertTerminated(); + to.assertValues(1, 2, 3, 4, 5, 5, 6, 7, 8, 9); // make sure we don't emit all values ... the unsubscribe should propagate // assertTrue(count.get() < 100000); // disabled: a small hiccup in the consumption may allow the source to run to completion } @@ -231,7 +231,7 @@ public void subscribe(Observer s) { @Test public void testTakeFlatMapCompletes() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final int indicator = 999999999; @@ -243,11 +243,11 @@ public void testTakeFlatMapCompletes() { public Observable apply(Observable w) { return w.startWith(indicator); } - }).subscribe(ts); + }).subscribe(to); - ts.awaitTerminalEvent(2, TimeUnit.SECONDS); - ts.assertComplete(); - ts.assertValueCount(22); + to.awaitTerminalEvent(2, TimeUnit.SECONDS); + to.assertComplete(); + to.assertValueCount(22); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java index 35a8bb3b60..41f3163f98 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java @@ -202,14 +202,14 @@ public void testNoUnsubscribeAndNoLeak() { PublishSubject open = PublishSubject.create(); final PublishSubject close = PublishSubject.create(); - TestObserver> ts = new TestObserver>(); + TestObserver> to = new TestObserver>(); source.window(open, new Function>() { @Override public Observable apply(Integer t) { return close; } - }).subscribe(ts); + }).subscribe(to); open.onNext(1); source.onNext(1); @@ -223,9 +223,9 @@ public Observable apply(Integer t) { source.onComplete(); - ts.assertComplete(); - ts.assertNoErrors(); - ts.assertValueCount(1); + to.assertComplete(); + to.assertNoErrors(); + to.assertValueCount(1); // 2.0.2 - not anymore // assertTrue("Not cancelled!", ts.isCancelled()); @@ -240,21 +240,21 @@ public void testUnsubscribeAll() { PublishSubject open = PublishSubject.create(); final PublishSubject close = PublishSubject.create(); - TestObserver> ts = new TestObserver>(); + TestObserver> to = new TestObserver>(); source.window(open, new Function>() { @Override public Observable apply(Integer t) { return close; } - }).subscribe(ts); + }).subscribe(to); open.onNext(1); assertTrue(open.hasObservers()); assertTrue(close.hasObservers()); - ts.dispose(); + to.dispose(); // FIXME subject has subscribers because of the open window assertTrue(open.hasObservers()); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java index d481991a24..bfccb343da 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java @@ -181,7 +181,7 @@ public void testExactWindowSize() { @Test public void testTakeFlatMapCompletes() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); final AtomicInteger wip = new AtomicInteger(); @@ -215,11 +215,11 @@ public void accept(Integer pv) { System.out.println(pv); } }) - .subscribe(ts); + .subscribe(to); - ts.awaitTerminalEvent(5, TimeUnit.SECONDS); - ts.assertComplete(); - Assert.assertTrue(ts.valueCount() != 0); + to.awaitTerminalEvent(5, TimeUnit.SECONDS); + to.assertComplete(); + Assert.assertTrue(to.valueCount() != 0); } @Test @@ -306,107 +306,107 @@ public void timeskipJustSkip() { public void timeskipSkipping() { TestScheduler scheduler = new TestScheduler(); - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.window(1, 2, TimeUnit.SECONDS, scheduler) + TestObserver to = ps.window(1, 2, TimeUnit.SECONDS, scheduler) .flatMap(Functions.>identity()) .test(); - pp.onNext(1); - pp.onNext(2); + ps.onNext(1); + ps.onNext(2); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - pp.onNext(3); - pp.onNext(4); + ps.onNext(3); + ps.onNext(4); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - pp.onNext(5); - pp.onNext(6); + ps.onNext(5); + ps.onNext(6); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - pp.onNext(7); - pp.onComplete(); + ps.onNext(7); + ps.onComplete(); - ts.assertResult(1, 2, 5, 6); + to.assertResult(1, 2, 5, 6); } @Test public void timeskipOverlapping() { TestScheduler scheduler = new TestScheduler(); - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.window(2, 1, TimeUnit.SECONDS, scheduler) + TestObserver to = ps.window(2, 1, TimeUnit.SECONDS, scheduler) .flatMap(Functions.>identity()) .test(); - pp.onNext(1); - pp.onNext(2); + ps.onNext(1); + ps.onNext(2); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - pp.onNext(3); - pp.onNext(4); + ps.onNext(3); + ps.onNext(4); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - pp.onNext(5); - pp.onNext(6); + ps.onNext(5); + ps.onNext(6); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - pp.onNext(7); - pp.onComplete(); + ps.onNext(7); + ps.onComplete(); - ts.assertResult(1, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7); + to.assertResult(1, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7); } @Test public void exactOnError() { TestScheduler scheduler = new TestScheduler(); - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.window(1, 1, TimeUnit.SECONDS, scheduler) + TestObserver to = ps.window(1, 1, TimeUnit.SECONDS, scheduler) .flatMap(Functions.>identity()) .test(); - pp.onError(new TestException()); + ps.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test public void overlappingOnError() { TestScheduler scheduler = new TestScheduler(); - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.window(2, 1, TimeUnit.SECONDS, scheduler) + TestObserver to = ps.window(2, 1, TimeUnit.SECONDS, scheduler) .flatMap(Functions.>identity()) .test(); - pp.onError(new TestException()); + ps.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test public void skipOnError() { TestScheduler scheduler = new TestScheduler(); - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.window(1, 2, TimeUnit.SECONDS, scheduler) + TestObserver to = ps.window(1, 2, TimeUnit.SECONDS, scheduler) .flatMap(Functions.>identity()) .test(); - pp.onError(new TestException()); + ps.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -591,17 +591,17 @@ public void sizeTimeTimeout() { TestScheduler scheduler = new TestScheduler(); Subject ps = PublishSubject.create(); - TestObserver> ts = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 100) + TestObserver> to = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 100) .test() .assertValueCount(1); scheduler.advanceTimeBy(5, TimeUnit.MILLISECONDS); - ts.assertValueCount(2) + to.assertValueCount(2) .assertNoErrors() .assertNotComplete(); - ts.values().get(0).test().assertResult(); + to.values().get(0).test().assertResult(); } @Test @@ -609,12 +609,12 @@ public void periodicWindowCompletion() { TestScheduler scheduler = new TestScheduler(); Subject ps = PublishSubject.create(); - TestObserver> ts = ps.window(5, TimeUnit.MILLISECONDS, scheduler, Long.MAX_VALUE, false) + TestObserver> to = ps.window(5, TimeUnit.MILLISECONDS, scheduler, Long.MAX_VALUE, false) .test(); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - ts.assertValueCount(21) + to.assertValueCount(21) .assertNoErrors() .assertNotComplete(); } @@ -624,12 +624,12 @@ public void periodicWindowCompletionRestartTimer() { TestScheduler scheduler = new TestScheduler(); Subject ps = PublishSubject.create(); - TestObserver> ts = ps.window(5, TimeUnit.MILLISECONDS, scheduler, Long.MAX_VALUE, true) + TestObserver> to = ps.window(5, TimeUnit.MILLISECONDS, scheduler, Long.MAX_VALUE, true) .test(); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - ts.assertValueCount(21) + to.assertValueCount(21) .assertNoErrors() .assertNotComplete(); } @@ -639,12 +639,12 @@ public void periodicWindowCompletionBounded() { TestScheduler scheduler = new TestScheduler(); Subject ps = PublishSubject.create(); - TestObserver> ts = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 5, false) + TestObserver> to = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 5, false) .test(); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - ts.assertValueCount(21) + to.assertValueCount(21) .assertNoErrors() .assertNotComplete(); } @@ -654,12 +654,12 @@ public void periodicWindowCompletionRestartTimerBounded() { TestScheduler scheduler = new TestScheduler(); Subject ps = PublishSubject.create(); - TestObserver> ts = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 5, true) + TestObserver> to = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 5, true) .test(); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - ts.assertValueCount(21) + to.assertValueCount(21) .assertNoErrors() .assertNotComplete(); } @@ -669,7 +669,7 @@ public void periodicWindowCompletionRestartTimerBoundedSomeData() { TestScheduler scheduler = new TestScheduler(); Subject ps = PublishSubject.create(); - TestObserver> ts = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 2, true) + TestObserver> to = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 2, true) .test(); ps.onNext(1); @@ -677,7 +677,7 @@ public void periodicWindowCompletionRestartTimerBoundedSomeData() { scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - ts.assertValueCount(22) + to.assertValueCount(22) .assertNoErrors() .assertNotComplete(); } @@ -687,7 +687,7 @@ public void countRestartsOnTimeTick() { TestScheduler scheduler = new TestScheduler(); Subject ps = PublishSubject.create(); - TestObserver> ts = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 5, true) + TestObserver> to = ps.window(5, TimeUnit.MILLISECONDS, scheduler, 5, true) .test(); // window #1 @@ -702,7 +702,7 @@ public void countRestartsOnTimeTick() { ps.onNext(5); ps.onNext(6); - ts.assertValueCount(2) + to.assertValueCount(2) .assertNoErrors() .assertNotComplete(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java index 4cba999e51..9b1ea3e54e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java @@ -89,9 +89,9 @@ public void testEmptySource() { Observable result = source.withLatestFrom(other, COMBINER); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - result.subscribe(ts); + result.subscribe(to); assertTrue(source.hasObservers()); assertTrue(other.hasObservers()); @@ -100,9 +100,9 @@ public void testEmptySource() { source.onComplete(); - ts.assertNoErrors(); - ts.assertTerminated(); - ts.assertNoValues(); + to.assertNoErrors(); + to.assertTerminated(); + to.assertNoValues(); assertFalse(source.hasObservers()); assertFalse(other.hasObservers()); @@ -115,9 +115,9 @@ public void testEmptyOther() { Observable result = source.withLatestFrom(other, COMBINER); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - result.subscribe(ts); + result.subscribe(to); assertTrue(source.hasObservers()); assertTrue(other.hasObservers()); @@ -126,9 +126,9 @@ public void testEmptyOther() { source.onComplete(); - ts.assertNoErrors(); - ts.assertTerminated(); - ts.assertNoValues(); + to.assertNoErrors(); + to.assertTerminated(); + to.assertNoValues(); assertFalse(source.hasObservers()); assertFalse(other.hasObservers()); @@ -142,9 +142,9 @@ public void testUnsubscription() { Observable result = source.withLatestFrom(other, COMBINER); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - result.subscribe(ts); + result.subscribe(to); assertTrue(source.hasObservers()); assertTrue(other.hasObservers()); @@ -152,11 +152,11 @@ public void testUnsubscription() { other.onNext(1); source.onNext(1); - ts.dispose(); + to.dispose(); - ts.assertValue((1 << 8) + 1); - ts.assertNoErrors(); - ts.assertNotComplete(); + to.assertValue((1 << 8) + 1); + to.assertNoErrors(); + to.assertNotComplete(); assertFalse(source.hasObservers()); assertFalse(other.hasObservers()); @@ -169,9 +169,9 @@ public void testSourceThrows() { Observable result = source.withLatestFrom(other, COMBINER); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - result.subscribe(ts); + result.subscribe(to); assertTrue(source.hasObservers()); assertTrue(other.hasObservers()); @@ -181,10 +181,10 @@ public void testSourceThrows() { source.onError(new TestException()); - ts.assertTerminated(); - ts.assertValue((1 << 8) + 1); - ts.assertError(TestException.class); - ts.assertNotComplete(); + to.assertTerminated(); + to.assertValue((1 << 8) + 1); + to.assertError(TestException.class); + to.assertNotComplete(); assertFalse(source.hasObservers()); assertFalse(other.hasObservers()); @@ -196,9 +196,9 @@ public void testOtherThrows() { Observable result = source.withLatestFrom(other, COMBINER); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - result.subscribe(ts); + result.subscribe(to); assertTrue(source.hasObservers()); assertTrue(other.hasObservers()); @@ -208,10 +208,10 @@ public void testOtherThrows() { other.onError(new TestException()); - ts.assertTerminated(); - ts.assertValue((1 << 8) + 1); - ts.assertNotComplete(); - ts.assertError(TestException.class); + to.assertTerminated(); + to.assertValue((1 << 8) + 1); + to.assertNotComplete(); + to.assertError(TestException.class); assertFalse(source.hasObservers()); assertFalse(other.hasObservers()); @@ -224,9 +224,9 @@ public void testFunctionThrows() { Observable result = source.withLatestFrom(other, COMBINER_ERROR); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - result.subscribe(ts); + result.subscribe(to); assertTrue(source.hasObservers()); assertTrue(other.hasObservers()); @@ -234,10 +234,10 @@ public void testFunctionThrows() { other.onNext(1); source.onNext(1); - ts.assertTerminated(); - ts.assertNotComplete(); - ts.assertNoValues(); - ts.assertError(TestException.class); + to.assertTerminated(); + to.assertNotComplete(); + to.assertNoValues(); + to.assertError(TestException.class); assertFalse(source.hasObservers()); assertFalse(other.hasObservers()); @@ -250,9 +250,9 @@ public void testNoDownstreamUnsubscribe() { Observable result = source.withLatestFrom(other, COMBINER); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - result.subscribe(ts); + result.subscribe(to); source.onComplete(); @@ -275,40 +275,40 @@ public void manySources() { PublishSubject ps3 = PublishSubject.create(); PublishSubject main = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); main.withLatestFrom(new Observable[] { ps1, ps2, ps3 }, toArray) - .subscribe(ts); + .subscribe(to); main.onNext("1"); - ts.assertNoValues(); + to.assertNoValues(); ps1.onNext("a"); - ts.assertNoValues(); + to.assertNoValues(); ps2.onNext("A"); - ts.assertNoValues(); + to.assertNoValues(); ps3.onNext("="); - ts.assertNoValues(); + to.assertNoValues(); main.onNext("2"); - ts.assertValues("[2, a, A, =]"); + to.assertValues("[2, a, A, =]"); ps2.onNext("B"); - ts.assertValues("[2, a, A, =]"); + to.assertValues("[2, a, A, =]"); ps3.onComplete(); - ts.assertValues("[2, a, A, =]"); + to.assertValues("[2, a, A, =]"); ps1.onNext("b"); main.onNext("3"); - ts.assertValues("[2, a, A, =]", "[3, b, B, =]"); + to.assertValues("[2, a, A, =]", "[3, b, B, =]"); main.onComplete(); - ts.assertValues("[2, a, A, =]", "[3, b, B, =]"); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValues("[2, a, A, =]", "[3, b, B, =]"); + to.assertNoErrors(); + to.assertComplete(); assertFalse("ps1 has subscribers?", ps1.hasObservers()); assertFalse("ps2 has subscribers?", ps2.hasObservers()); @@ -322,40 +322,40 @@ public void manySourcesIterable() { PublishSubject ps3 = PublishSubject.create(); PublishSubject main = PublishSubject.create(); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); main.withLatestFrom(Arrays.>asList(ps1, ps2, ps3), toArray) - .subscribe(ts); + .subscribe(to); main.onNext("1"); - ts.assertNoValues(); + to.assertNoValues(); ps1.onNext("a"); - ts.assertNoValues(); + to.assertNoValues(); ps2.onNext("A"); - ts.assertNoValues(); + to.assertNoValues(); ps3.onNext("="); - ts.assertNoValues(); + to.assertNoValues(); main.onNext("2"); - ts.assertValues("[2, a, A, =]"); + to.assertValues("[2, a, A, =]"); ps2.onNext("B"); - ts.assertValues("[2, a, A, =]"); + to.assertValues("[2, a, A, =]"); ps3.onComplete(); - ts.assertValues("[2, a, A, =]"); + to.assertValues("[2, a, A, =]"); ps1.onNext("b"); main.onNext("3"); - ts.assertValues("[2, a, A, =]", "[3, b, B, =]"); + to.assertValues("[2, a, A, =]", "[3, b, B, =]"); main.onComplete(); - ts.assertValues("[2, a, A, =]", "[3, b, B, =]"); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValues("[2, a, A, =]", "[3, b, B, =]"); + to.assertNoErrors(); + to.assertComplete(); assertFalse("ps1 has subscribers?", ps1.hasObservers()); assertFalse("ps2 has subscribers?", ps2.hasObservers()); @@ -376,20 +376,20 @@ public void manySourcesIterableSweep() { expected.add(String.valueOf(val)); } - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); PublishSubject main = PublishSubject.create(); - main.withLatestFrom(sources, toArray).subscribe(ts); + main.withLatestFrom(sources, toArray).subscribe(to); - ts.assertNoValues(); + to.assertNoValues(); main.onNext(val); main.onComplete(); - ts.assertValue(expected.toString()); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(expected.toString()); + to.assertNoErrors(); + to.assertComplete(); } } } @@ -400,18 +400,18 @@ public void backpressureNoSignal() { // PublishSubject ps1 = PublishSubject.create(); // PublishSubject ps2 = PublishSubject.create(); // -// TestObserver ts = new TestObserver(); +// TestObserver to = new TestObserver(); // // Observable.range(1, 10).withLatestFrom(new Observable[] { ps1, ps2 }, toArray) -// .subscribe(ts); +// .subscribe(to); // -// ts.assertNoValues(); +// to.assertNoValues(); // -// ts.request(1); +// to.request(1); // -// ts.assertNoValues(); -// ts.assertNoErrors(); -// ts.assertComplete(); +// to.assertNoValues(); +// to.assertNoErrors(); +// to.assertComplete(); // // assertFalse("ps1 has subscribers?", ps1.hasSubscribers()); // assertFalse("ps2 has subscribers?", ps2.hasSubscribers()); @@ -423,29 +423,29 @@ public void backpressureWithSignal() { // PublishSubject ps1 = PublishSubject.create(); // PublishSubject ps2 = PublishSubject.create(); // -// TestObserver ts = new TestObserver(); +// TestObserver to = new TestObserver(); // // Observable.range(1, 3).withLatestFrom(new Observable[] { ps1, ps2 }, toArray) // .subscribe(ts); // -// ts.assertNoValues(); +// to.assertNoValues(); // // ps1.onNext("1"); // ps2.onNext("1"); // -// ts.request(1); +// to.request(1); // -// ts.assertValue("[1, 1, 1]"); +// to.assertValue("[1, 1, 1]"); // -// ts.request(1); +// to.request(1); // -// ts.assertValues("[1, 1, 1]", "[2, 1, 1]"); +// to.assertValues("[1, 1, 1]", "[2, 1, 1]"); // -// ts.request(1); +// to.request(1); // -// ts.assertValues("[1, 1, 1]", "[2, 1, 1]", "[3, 1, 1]"); -// ts.assertNoErrors(); -// ts.assertComplete(); +// to.assertValues("[1, 1, 1]", "[2, 1, 1]", "[3, 1, 1]"); +// to.assertNoErrors(); +// to.assertComplete(); // // assertFalse("ps1 has subscribers?", ps1.hasSubscribers()); // assertFalse("ps2 has subscribers?", ps2.hasSubscribers()); @@ -453,48 +453,48 @@ public void backpressureWithSignal() { @Test public void withEmpty() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, 3).withLatestFrom( new Observable[] { Observable.just(1), Observable.empty() }, toArray) - .subscribe(ts); + .subscribe(to); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertNoValues(); + to.assertNoErrors(); + to.assertComplete(); } @Test public void withError() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.range(1, 3).withLatestFrom( new Observable[] { Observable.just(1), Observable.error(new TestException()) }, toArray) - .subscribe(ts); + .subscribe(to); - ts.assertNoValues(); - ts.assertError(TestException.class); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertError(TestException.class); + to.assertNotComplete(); } @Test public void withMainError() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.error(new TestException()).withLatestFrom( new Observable[] { Observable.just(1), Observable.just(1) }, toArray) - .subscribe(ts); + .subscribe(to); - ts.assertNoValues(); - ts.assertError(TestException.class); - ts.assertNotComplete(); + to.assertNoValues(); + to.assertError(TestException.class); + to.assertNotComplete(); } @Test public void with2Others() { Observable just = Observable.just(1); - TestObserver> ts = new TestObserver>(); + TestObserver> to = new TestObserver>(); just.withLatestFrom(just, just, new Function3>() { @Override @@ -502,18 +502,18 @@ public List apply(Integer a, Integer b, Integer c) { return Arrays.asList(a, b, c); } }) - .subscribe(ts); + .subscribe(to); - ts.assertValue(Arrays.asList(1, 1, 1)); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(Arrays.asList(1, 1, 1)); + to.assertNoErrors(); + to.assertComplete(); } @Test public void with3Others() { Observable just = Observable.just(1); - TestObserver> ts = new TestObserver>(); + TestObserver> to = new TestObserver>(); just.withLatestFrom(just, just, just, new Function4>() { @Override @@ -521,18 +521,18 @@ public List apply(Integer a, Integer b, Integer c, Integer d) { return Arrays.asList(a, b, c, d); } }) - .subscribe(ts); + .subscribe(to); - ts.assertValue(Arrays.asList(1, 1, 1, 1)); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(Arrays.asList(1, 1, 1, 1)); + to.assertNoErrors(); + to.assertComplete(); } @Test public void with4Others() { Observable just = Observable.just(1); - TestObserver> ts = new TestObserver>(); + TestObserver> to = new TestObserver>(); just.withLatestFrom(just, just, just, just, new Function5>() { @Override @@ -540,11 +540,11 @@ public List apply(Integer a, Integer b, Integer c, Integer d, Integer e return Arrays.asList(a, b, c, d, e); } }) - .subscribe(ts); + .subscribe(to); - ts.assertValue(Arrays.asList(1, 1, 1, 1, 1)); - ts.assertNoErrors(); - ts.assertComplete(); + to.assertValue(Arrays.asList(1, 1, 1, 1, 1)); + to.assertNoErrors(); + to.assertComplete(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java index 475cceeca7..ac68979af9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java @@ -349,9 +349,9 @@ public void testAggregatorUnsubscribe() { PublishSubject r2 = PublishSubject.create(); /* define an Observer to receive aggregated events */ Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); + TestObserver to = new TestObserver(observer); - Observable.zip(r1, r2, zipr2).subscribe(ts); + Observable.zip(r1, r2, zipr2).subscribe(to); /* simulate the Observables pushing data into the aggregator */ r1.onNext("hello"); @@ -361,7 +361,7 @@ public void testAggregatorUnsubscribe() { verify(observer, never()).onComplete(); verify(observer, times(1)).onNext("helloworld"); - ts.dispose(); + to.dispose(); r1.onNext("hello"); r2.onNext("again"); @@ -794,16 +794,16 @@ public String apply(Integer a, Integer b) { } }).take(5); - TestObserver ts = new TestObserver(); - os.subscribe(ts); + TestObserver to = new TestObserver(); + os.subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); + to.awaitTerminalEvent(); + to.assertNoErrors(); - assertEquals(5, ts.valueCount()); - assertEquals("1-1", ts.values().get(0)); - assertEquals("2-2", ts.values().get(1)); - assertEquals("5-5", ts.values().get(4)); + assertEquals(5, to.valueCount()); + assertEquals("1-1", to.values().get(0)); + assertEquals("2-2", to.values().get(1)); + assertEquals("5-5", to.values().get(4)); } @Test @@ -969,10 +969,10 @@ public Object apply(final Object[] args) { } }); - TestObserver ts = new TestObserver(); - o.subscribe(ts); - ts.awaitTerminalEvent(200, TimeUnit.MILLISECONDS); - ts.assertNoValues(); + TestObserver to = new TestObserver(); + o.subscribe(to); + to.awaitTerminalEvent(200, TimeUnit.MILLISECONDS); + to.assertNoValues(); } /** @@ -1003,7 +1003,7 @@ public void testDownstreamBackpressureRequestsWithFiniteSyncObservables() { Observable o1 = createInfiniteObservable(generatedA).take(Observable.bufferSize() * 2); Observable o2 = createInfiniteObservable(generatedB).take(Observable.bufferSize() * 2); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.zip(o1, o2, new BiFunction() { @Override @@ -1011,11 +1011,11 @@ public String apply(Integer t1, Integer t2) { return t1 + "-" + t2; } - }).observeOn(Schedulers.computation()).take(Observable.bufferSize() * 2).subscribe(ts); + }).observeOn(Schedulers.computation()).take(Observable.bufferSize() * 2).subscribe(to); - ts.awaitTerminalEvent(); - ts.assertNoErrors(); - assertEquals(Observable.bufferSize() * 2, ts.valueCount()); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(Observable.bufferSize() * 2, to.valueCount()); System.out.println("Generated => A: " + generatedA.get() + " B: " + generatedB.get()); assertTrue(generatedA.get() < (Observable.bufferSize() * 3)); assertTrue(generatedB.get() < (Observable.bufferSize() * 3)); @@ -1363,7 +1363,7 @@ public Object apply(Integer a, Integer b) throws Exception { @Test public void noCrossBoundaryFusion() { for (int i = 0; i < 500; i++) { - TestObserver> ts = Observable.zip( + TestObserver> to = Observable.zip( Observable.just(1).observeOn(Schedulers.single()).map(new Function() { @Override public Object apply(Integer v) throws Exception { @@ -1387,7 +1387,7 @@ public List apply(Object t1, Object t2) throws Exception { .awaitDone(5, TimeUnit.SECONDS) .assertValueCount(1); - List list = ts.values().get(0); + List list = to.values().get(0); assertTrue(list.toString(), list.contains("RxSi")); assertTrue(list.toString(), list.contains("RxCo")); @@ -1399,7 +1399,7 @@ public void eagerDispose() { final PublishSubject ps1 = PublishSubject.create(); final PublishSubject ps2 = PublishSubject.create(); - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { @Override public void onNext(Integer t) { super.onNext(t); @@ -1421,10 +1421,10 @@ public Integer apply(Integer t1, Integer t2) throws Exception { return t1 + t2; } }) - .subscribe(ts); + .subscribe(to); ps1.onNext(1); ps2.onNext(2); - ts.assertResult(3); + to.assertResult(3); } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java index e07b27129c..1bc00dedd6 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java @@ -32,7 +32,7 @@ public void ambWithFirstFires() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = pp1.single(-99).ambWith(pp2.single(-99)).test(); + TestObserver to = pp1.single(-99).ambWith(pp2.single(-99)).test(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -43,7 +43,7 @@ public void ambWithFirstFires() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(1); + to.assertResult(1); } @@ -52,7 +52,7 @@ public void ambWithSecondFires() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = pp1.single(-99).ambWith(pp2.single(-99)).test(); + TestObserver to = pp1.single(-99).ambWith(pp2.single(-99)).test(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -63,7 +63,7 @@ public void ambWithSecondFires() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(2); + to.assertResult(2); } @SuppressWarnings("unchecked") @@ -73,7 +73,7 @@ public void ambIterableWithFirstFires() { PublishProcessor pp2 = PublishProcessor.create(); List> singles = Arrays.asList(pp1.single(-99), pp2.single(-99)); - TestObserver ts = Single.amb(singles).test(); + TestObserver to = Single.amb(singles).test(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -84,7 +84,7 @@ public void ambIterableWithFirstFires() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(1); + to.assertResult(1); } @@ -95,7 +95,7 @@ public void ambIterableWithSecondFires() { PublishProcessor pp2 = PublishProcessor.create(); List> singles = Arrays.asList(pp1.single(-99), pp2.single(-99)); - TestObserver ts = Single.amb(singles).test(); + TestObserver to = Single.amb(singles).test(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -106,7 +106,7 @@ public void ambIterableWithSecondFires() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(2); + to.assertResult(2); } @SuppressWarnings("unchecked") diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleCacheTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleCacheTest.java index cd56bb5fe9..ce348eebeb 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleCacheTest.java @@ -28,12 +28,12 @@ public void cancelImmediately() { Single cached = pp.single(-99).cache(); - TestObserver ts = cached.test(true); + TestObserver to = cached.test(true); pp.onNext(1); pp.onComplete(); - ts.assertEmpty(); + to.assertEmpty(); cached.test().assertResult(1); } @@ -45,12 +45,12 @@ public void addRemoveRace() { final Single cached = pp.single(-99).cache(); - final TestObserver ts1 = cached.test(); + final TestObserver to1 = cached.test(); Runnable r1 = new Runnable() { @Override public void run() { - ts1.cancel(); + to1.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleDoAfterSuccessTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleDoAfterSuccessTest.java index 7dbe7729c6..d0e3376307 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleDoAfterSuccessTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleDoAfterSuccessTest.java @@ -38,7 +38,7 @@ public void accept(Integer e) throws Exception { } }; - final TestObserver ts = new TestObserver() { + final TestObserver to = new TestObserver() { @Override public void onNext(Integer t) { super.onNext(t); @@ -50,7 +50,7 @@ public void onNext(Integer t) { public void just() { Single.just(1) .doAfterSuccess(afterSuccess) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1); assertEquals(Arrays.asList(1, -1), values); @@ -60,7 +60,7 @@ public void just() { public void error() { Single.error(new TestException()) .doAfterSuccess(afterSuccess) - .subscribeWith(ts) + .subscribeWith(to) .assertFailure(TestException.class); assertTrue(values.isEmpty()); @@ -76,7 +76,7 @@ public void justConditional() { Single.just(1) .doAfterSuccess(afterSuccess) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1); assertEquals(Arrays.asList(1, -1), values); @@ -87,7 +87,7 @@ public void errorConditional() { Single.error(new TestException()) .doAfterSuccess(afterSuccess) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertFailure(TestException.class); assertTrue(values.isEmpty()); diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleDoAfterTerminateTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleDoAfterTerminateTest.java index b1a55dc588..b7566cce30 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleDoAfterTerminateTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleDoAfterTerminateTest.java @@ -40,13 +40,13 @@ public void run() throws Exception { } }; - private final TestObserver ts = new TestObserver(); + private final TestObserver to = new TestObserver(); @Test public void just() { Single.just(1) .doAfterTerminate(afterTerminate) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1); assertAfterTerminateCalledOnce(); @@ -56,7 +56,7 @@ public void just() { public void error() { Single.error(new TestException()) .doAfterTerminate(afterTerminate) - .subscribeWith(ts) + .subscribeWith(to) .assertFailure(TestException.class); assertAfterTerminateCalledOnce(); @@ -72,7 +72,7 @@ public void justConditional() { Single.just(1) .doAfterTerminate(afterTerminate) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertResult(1); assertAfterTerminateCalledOnce(); @@ -83,7 +83,7 @@ public void errorConditional() { Single.error(new TestException()) .doAfterTerminate(afterTerminate) .filter(Functions.alwaysTrue()) - .subscribeWith(ts) + .subscribeWith(to) .assertFailure(TestException.class); assertAfterTerminateCalledOnce(); diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java index 749e326ce6..086f72f838 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java @@ -19,7 +19,7 @@ import java.util.concurrent.TimeUnit; import org.junit.Test; -import org.reactivestreams.*; +import org.reactivestreams.Subscription; import io.reactivex.*; import io.reactivex.exceptions.TestException; @@ -108,7 +108,7 @@ public Iterable apply(Integer v) throws Exception { @Test public void fused() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Single.just(1).flattenAsFlowable(new Function>() { @Override @@ -116,17 +116,17 @@ public Iterable apply(Integer v) throws Exception { return Arrays.asList(v, v + 1); } }) - .subscribe(to); + .subscribe(ts); - to.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueDisposable.ASYNC)) + ts.assertOf(SubscriberFusion.assertFuseable()) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2); ; } @Test public void fusedNoSync() { - TestSubscriber to = SubscriberFusion.newTest(QueueDisposable.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); Single.just(1).flattenAsFlowable(new Function>() { @Override @@ -134,10 +134,10 @@ public Iterable apply(Integer v) throws Exception { return Arrays.asList(v, v + 1); } }) - .subscribe(to); + .subscribe(ts); - to.assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueDisposable.NONE)) + ts.assertOf(SubscriberFusion.assertFuseable()) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.NONE)) .assertResult(1, 2); ; } @@ -292,7 +292,7 @@ public Iterable apply(Object v) throws Exception { public void onSubscribe(Subscription d) { qd = (QueueSubscription)d; - assertEquals(QueueSubscription.ASYNC, qd.requestFusion(QueueSubscription.ANY)); + assertEquals(QueueFuseable.ASYNC, qd.requestFusion(QueueFuseable.ANY)); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservableTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservableTest.java index f1079e4669..8ae89d62d0 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservableTest.java @@ -25,7 +25,7 @@ import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.util.CrashingIterable; import io.reactivex.observers.*; import io.reactivex.schedulers.Schedulers; @@ -86,7 +86,7 @@ public Iterable apply(Integer v) throws Exception { @Test public void fused() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); Single.just(1).flattenAsObservable(new Function>() { @Override @@ -97,14 +97,14 @@ public Iterable apply(Integer v) throws Exception { .subscribe(to); to.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.ASYNC)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2); ; } @Test public void fusedNoSync() { - TestObserver to = ObserverFusion.newTest(QueueDisposable.SYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC); Single.just(1).flattenAsObservable(new Function>() { @Override @@ -115,7 +115,7 @@ public Iterable apply(Integer v) throws Exception { .subscribe(to); to.assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.NONE)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.NONE)) .assertResult(1, 2); ; } @@ -295,7 +295,7 @@ public Iterable apply(Object v) throws Exception { public void onSubscribe(Disposable d) { qd = (QueueDisposable)d; - assertEquals(QueueDisposable.ASYNC, qd.requestFusion(QueueDisposable.ANY)); + assertEquals(QueueFuseable.ASYNC, qd.requestFusion(QueueFuseable.ANY)); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFromPublisherTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFromPublisherTest.java index c6cc2f46d5..b7231738a6 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFromPublisherTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFromPublisherTest.java @@ -61,13 +61,13 @@ public void error() { public void dispose() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = Single.fromPublisher(pp).test(); + TestObserver to = Single.fromPublisher(pp).test(); assertTrue(pp.hasSubscribers()); pp.onNext(1); - ts.cancel(); + to.cancel(); assertFalse(pp.hasSubscribers()); } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleSubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleSubscribeOnTest.java index ff669d0203..6f8b247056 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleSubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleSubscribeOnTest.java @@ -35,13 +35,13 @@ public void normal() { try { TestScheduler scheduler = new TestScheduler(); - TestObserver ts = Single.just(1) + TestObserver to = Single.just(1) .subscribeOn(scheduler) .test(); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - ts.assertResult(1); + to.assertResult(1); assertTrue(list.toString(), list.isEmpty()); } finally { diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java index c9d7ab4467..07dd073f35 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java @@ -33,13 +33,13 @@ public void mainSuccessPublisher() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp) + TestObserver to = source.single(-99).takeUntil(pp) .test(); source.onNext(1); source.onComplete(); - ts.assertResult(1); + to.assertResult(1); } @Test @@ -47,13 +47,13 @@ public void mainSuccessSingle() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp.single(-99)) + TestObserver to = source.single(-99).takeUntil(pp.single(-99)) .test(); source.onNext(1); source.onComplete(); - ts.assertResult(1); + to.assertResult(1); } @@ -62,13 +62,13 @@ public void mainSuccessCompletable() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp.ignoreElements()) + TestObserver to = source.single(-99).takeUntil(pp.ignoreElements()) .test(); source.onNext(1); source.onComplete(); - ts.assertResult(1); + to.assertResult(1); } @Test @@ -76,12 +76,12 @@ public void mainErrorPublisher() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp) + TestObserver to = source.single(-99).takeUntil(pp) .test(); source.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -89,12 +89,12 @@ public void mainErrorSingle() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp.single(-99)) + TestObserver to = source.single(-99).takeUntil(pp.single(-99)) .test(); source.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -102,12 +102,12 @@ public void mainErrorCompletable() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp.ignoreElements()) + TestObserver to = source.single(-99).takeUntil(pp.ignoreElements()) .test(); source.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -115,12 +115,12 @@ public void otherOnNextPublisher() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp) + TestObserver to = source.single(-99).takeUntil(pp) .test(); pp.onNext(1); - ts.assertFailure(CancellationException.class); + to.assertFailure(CancellationException.class); } @Test @@ -128,13 +128,13 @@ public void otherOnNextSingle() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp.single(-99)) + TestObserver to = source.single(-99).takeUntil(pp.single(-99)) .test(); pp.onNext(1); pp.onComplete(); - ts.assertFailure(CancellationException.class); + to.assertFailure(CancellationException.class); } @Test @@ -142,13 +142,13 @@ public void otherOnNextCompletable() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp.ignoreElements()) + TestObserver to = source.single(-99).takeUntil(pp.ignoreElements()) .test(); pp.onNext(1); pp.onComplete(); - ts.assertFailure(CancellationException.class); + to.assertFailure(CancellationException.class); } @Test @@ -156,12 +156,12 @@ public void otherOnCompletePublisher() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp) + TestObserver to = source.single(-99).takeUntil(pp) .test(); pp.onComplete(); - ts.assertFailure(CancellationException.class); + to.assertFailure(CancellationException.class); } @Test @@ -169,12 +169,12 @@ public void otherOnCompleteCompletable() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp.ignoreElements()) + TestObserver to = source.single(-99).takeUntil(pp.ignoreElements()) .test(); pp.onComplete(); - ts.assertFailure(CancellationException.class); + to.assertFailure(CancellationException.class); } @Test @@ -182,12 +182,12 @@ public void otherErrorPublisher() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp) + TestObserver to = source.single(-99).takeUntil(pp) .test(); pp.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -195,12 +195,12 @@ public void otherErrorSingle() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp.single(-99)) + TestObserver to = source.single(-99).takeUntil(pp.single(-99)) .test(); pp.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -208,12 +208,12 @@ public void otherErrorCompletable() { PublishProcessor pp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); - TestObserver ts = source.single(-99).takeUntil(pp.ignoreElements()) + TestObserver to = source.single(-99).takeUntil(pp.ignoreElements()) .test(); pp.onError(new TestException()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test @@ -227,24 +227,24 @@ public void onErrorRace() { List errors = TestHelper.trackPluginErrors(); try { - final PublishProcessor ps1 = PublishProcessor.create(); - final PublishProcessor ps2 = PublishProcessor.create(); + final PublishProcessor pp1 = PublishProcessor.create(); + final PublishProcessor pp2 = PublishProcessor.create(); - TestObserver to = ps1.singleOrError().takeUntil(ps2).test(); + TestObserver to = pp1.singleOrError().takeUntil(pp2).test(); final TestException ex = new TestException(); Runnable r1 = new Runnable() { @Override public void run() { - ps1.onError(ex); + pp1.onError(ex); } }; Runnable r2 = new Runnable() { @Override public void run() { - ps2.onError(ex); + pp2.onError(ex); } }; diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleTimerTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleTimerTest.java index 93719ed764..55932efb37 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleTimerTest.java @@ -38,7 +38,7 @@ public void timerInterruptible() throws Exception { try { for (Scheduler s : new Scheduler[] { Schedulers.single(), Schedulers.computation(), Schedulers.newThread(), Schedulers.io(), Schedulers.from(exec) }) { final AtomicBoolean interrupted = new AtomicBoolean(); - TestObserver ts = Single.timer(1, TimeUnit.MILLISECONDS, s) + TestObserver to = Single.timer(1, TimeUnit.MILLISECONDS, s) .map(new Function() { @Override public Long apply(Long v) throws Exception { @@ -54,7 +54,7 @@ public Long apply(Long v) throws Exception { Thread.sleep(500); - ts.cancel(); + to.cancel(); Thread.sleep(500); diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleUsingTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleUsingTest.java index c0d3229e59..f49c35144d 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleUsingTest.java @@ -101,11 +101,11 @@ public void errorNonEager() { @Test public void eagerMapperThrowsDisposerThrows() { - TestObserver ts = Single.using(Functions.justCallable(Disposables.empty()), mapperThrows, disposerThrows) + TestObserver to = Single.using(Functions.justCallable(Disposables.empty()), mapperThrows, disposerThrows) .test() .assertFailure(CompositeException.class); - List ce = TestHelper.compositeList(ts.errors().get(0)); + List ce = TestHelper.compositeList(to.errors().get(0)); TestHelper.assertError(ce, 0, TestException.class, "Mapper"); TestHelper.assertError(ce, 1, TestException.class, "Disposer"); } @@ -182,7 +182,7 @@ public void disposerThrowsNonEager() { @Test public void errorAndDisposerThrowsEager() { - TestObserver ts = Single.using(Functions.justCallable(Disposables.empty()), + TestObserver to = Single.using(Functions.justCallable(Disposables.empty()), new Function>() { @Override public SingleSource apply(Disposable v) throws Exception { @@ -192,7 +192,7 @@ public SingleSource apply(Disposable v) throws Exception { .test() .assertFailure(CompositeException.class); - List ce = TestHelper.compositeList(ts.errors().get(0)); + List ce = TestHelper.compositeList(to.errors().get(0)); TestHelper.assertError(ce, 0, TestException.class, "Mapper-run"); TestHelper.assertError(ce, 1, TestException.class, "Disposer"); } @@ -224,7 +224,7 @@ public void successDisposeRace() { Disposable d = Disposables.empty(); - final TestObserver ts = Single.using(Functions.justCallable(d), new Function>() { + final TestObserver to = Single.using(Functions.justCallable(d), new Function>() { @Override public SingleSource apply(Disposable v) throws Exception { return pp.single(-99); @@ -243,7 +243,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; @@ -299,7 +299,7 @@ public void errorDisposeRace() { Disposable d = Disposables.empty(); - final TestObserver ts = Single.using(Functions.justCallable(d), new Function>() { + final TestObserver to = Single.using(Functions.justCallable(d), new Function>() { @Override public SingleSource apply(Disposable v) throws Exception { return pp.single(-99); @@ -318,7 +318,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; diff --git a/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java index 59a7f22fc4..c6ec1c24ee 100644 --- a/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java @@ -106,13 +106,13 @@ public void error() { @Test public void unsubscribeComposes() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); TestSubscriber ts = TestSubscriber.create(0L); TestingDeferredScalarSubscriber ds = new TestingDeferredScalarSubscriber(ts); - ps.subscribe(ds); + pp.subscribe(ds); - assertTrue("No subscribers?", ps.hasSubscribers()); + assertTrue("No subscribers?", pp.hasSubscribers()); ts.cancel(); @@ -125,7 +125,7 @@ public void unsubscribeComposes() { ts.assertNoErrors(); ts.assertNotComplete(); - assertFalse("Subscribers?", ps.hasSubscribers()); + assertFalse("Subscribers?", pp.hasSubscribers()); assertTrue("Deferred not unsubscribed?", ds.isCancelled()); } diff --git a/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java index f07d7bdc30..b6eef24c5e 100644 --- a/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java @@ -290,11 +290,11 @@ public void accept(Subscription s) throws Exception { @Test public void onNextThrowsCancelsUpstream() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); final List errors = new ArrayList(); - ps.subscribe(new Consumer() { + pp.subscribe(new Consumer() { @Override public void accept(Integer v) throws Exception { throw new TestException(); @@ -306,12 +306,12 @@ public void accept(Throwable e) throws Exception { } }); - assertTrue("No observers?!", ps.hasSubscribers()); + assertTrue("No observers?!", pp.hasSubscribers()); assertTrue("Has errors already?!", errors.isEmpty()); - ps.onNext(1); + pp.onNext(1); - assertFalse("Has observers?!", ps.hasSubscribers()); + assertFalse("Has observers?!", pp.hasSubscribers()); assertFalse("No errors?!", errors.isEmpty()); assertTrue(errors.toString(), errors.get(0) instanceof TestException); @@ -319,11 +319,11 @@ public void accept(Throwable e) throws Exception { @Test public void onSubscribeThrowsCancelsUpstream() { - PublishProcessor ps = PublishProcessor.create(); + PublishProcessor pp = PublishProcessor.create(); final List errors = new ArrayList(); - ps.subscribe(new Consumer() { + pp.subscribe(new Consumer() { @Override public void accept(Integer v) throws Exception { } @@ -343,7 +343,7 @@ public void accept(Subscription s) throws Exception { } }); - assertFalse("Has observers?!", ps.hasSubscribers()); + assertFalse("Has observers?!", pp.hasSubscribers()); assertFalse("No errors?!", errors.isEmpty()); assertTrue(errors.toString(), errors.get(0) instanceof TestException); diff --git a/src/test/java/io/reactivex/internal/subscriptions/DeferredScalarSubscriptionTest.java b/src/test/java/io/reactivex/internal/subscriptions/DeferredScalarSubscriptionTest.java index 6ad325a9d4..430e3c71c5 100644 --- a/src/test/java/io/reactivex/internal/subscriptions/DeferredScalarSubscriptionTest.java +++ b/src/test/java/io/reactivex/internal/subscriptions/DeferredScalarSubscriptionTest.java @@ -18,7 +18,7 @@ import org.junit.Test; import io.reactivex.TestHelper; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.subscribers.TestSubscriber; public class DeferredScalarSubscriptionTest { @@ -27,7 +27,7 @@ public class DeferredScalarSubscriptionTest { public void queueSubscriptionSyncRejected() { DeferredScalarSubscription ds = new DeferredScalarSubscription(new TestSubscriber()); - assertEquals(QueueSubscription.NONE, ds.requestFusion(QueueSubscription.SYNC)); + assertEquals(QueueFuseable.NONE, ds.requestFusion(QueueFuseable.SYNC)); } @Test diff --git a/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java b/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java index a0262cd328..38e099db23 100644 --- a/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java +++ b/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java @@ -207,28 +207,28 @@ public void onNextOnCompleteRace() { final AtomicInteger wip = new AtomicInteger(); final AtomicThrowable error = new AtomicThrowable(); - final TestObserver ts = new TestObserver(); - ts.onSubscribe(Disposables.empty()); + final TestObserver to = new TestObserver(); + to.onSubscribe(Disposables.empty()); Runnable r1 = new Runnable() { @Override public void run() { - HalfSerializer.onNext(ts, 1, wip, error); + HalfSerializer.onNext(to, 1, wip, error); } }; Runnable r2 = new Runnable() { @Override public void run() { - HalfSerializer.onComplete(ts, wip, error); + HalfSerializer.onComplete(to, wip, error); } }; TestHelper.race(r1, r2); - ts.assertComplete().assertNoErrors(); + to.assertComplete().assertNoErrors(); - assertTrue(ts.valueCount() <= 1); + assertTrue(to.valueCount() <= 1); } } @@ -239,32 +239,32 @@ public void onErrorOnCompleteRace() { final AtomicInteger wip = new AtomicInteger(); final AtomicThrowable error = new AtomicThrowable(); - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); final TestException ex = new TestException(); Runnable r1 = new Runnable() { @Override public void run() { - HalfSerializer.onError(ts, ex, wip, error); + HalfSerializer.onError(to, ex, wip, error); } }; Runnable r2 = new Runnable() { @Override public void run() { - HalfSerializer.onComplete(ts, wip, error); + HalfSerializer.onComplete(to, wip, error); } }; TestHelper.race(r1, r2); - if (ts.completions() != 0) { - ts.assertResult(); + if (to.completions() != 0) { + to.assertResult(); } else { - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } } } diff --git a/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java b/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java index dded845762..14375b506a 100644 --- a/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java +++ b/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java @@ -598,8 +598,8 @@ public boolean accept(Subscriber a, Integer v) { @Test public void observerCheckTerminatedDelayErrorEmpty() { - TestObserver ts = new TestObserver(); - ts.onSubscribe(Disposables.empty()); + TestObserver to = new TestObserver(); + to.onSubscribe(Disposables.empty()); ObservableQueueDrain qd = new ObservableQueueDrain() { @Override @@ -634,15 +634,15 @@ public void accept(Observer a, Integer v) { SpscArrayQueue q = new SpscArrayQueue(32); - QueueDrainHelper.checkTerminated(true, true, ts, true, q, null, qd); + QueueDrainHelper.checkTerminated(true, true, to, true, q, null, qd); - ts.assertResult(); + to.assertResult(); } @Test public void observerCheckTerminatedDelayErrorEmptyResource() { - TestObserver ts = new TestObserver(); - ts.onSubscribe(Disposables.empty()); + TestObserver to = new TestObserver(); + to.onSubscribe(Disposables.empty()); ObservableQueueDrain qd = new ObservableQueueDrain() { @Override @@ -679,17 +679,17 @@ public void accept(Observer a, Integer v) { Disposable d = Disposables.empty(); - QueueDrainHelper.checkTerminated(true, true, ts, true, q, d, qd); + QueueDrainHelper.checkTerminated(true, true, to, true, q, d, qd); - ts.assertResult(); + to.assertResult(); assertTrue(d.isDisposed()); } @Test public void observerCheckTerminatedDelayErrorNonEmpty() { - TestObserver ts = new TestObserver(); - ts.onSubscribe(Disposables.empty()); + TestObserver to = new TestObserver(); + to.onSubscribe(Disposables.empty()); ObservableQueueDrain qd = new ObservableQueueDrain() { @Override @@ -724,15 +724,15 @@ public void accept(Observer a, Integer v) { SpscArrayQueue q = new SpscArrayQueue(32); - QueueDrainHelper.checkTerminated(true, false, ts, true, q, null, qd); + QueueDrainHelper.checkTerminated(true, false, to, true, q, null, qd); - ts.assertEmpty(); + to.assertEmpty(); } @Test public void observerCheckTerminatedDelayErrorEmptyError() { - TestObserver ts = new TestObserver(); - ts.onSubscribe(Disposables.empty()); + TestObserver to = new TestObserver(); + to.onSubscribe(Disposables.empty()); ObservableQueueDrain qd = new ObservableQueueDrain() { @Override @@ -767,15 +767,15 @@ public void accept(Observer a, Integer v) { SpscArrayQueue q = new SpscArrayQueue(32); - QueueDrainHelper.checkTerminated(true, true, ts, true, q, null, qd); + QueueDrainHelper.checkTerminated(true, true, to, true, q, null, qd); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test public void observerCheckTerminatedNonDelayErrorError() { - TestObserver ts = new TestObserver(); - ts.onSubscribe(Disposables.empty()); + TestObserver to = new TestObserver(); + to.onSubscribe(Disposables.empty()); ObservableQueueDrain qd = new ObservableQueueDrain() { @Override @@ -810,14 +810,14 @@ public void accept(Observer a, Integer v) { SpscArrayQueue q = new SpscArrayQueue(32); - QueueDrainHelper.checkTerminated(true, false, ts, false, q, null, qd); + QueueDrainHelper.checkTerminated(true, false, to, false, q, null, qd); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test public void observerCheckTerminatedNonDelayErrorErrorResource() { - TestObserver ts = new TestObserver(); - ts.onSubscribe(Disposables.empty()); + TestObserver to = new TestObserver(); + to.onSubscribe(Disposables.empty()); ObservableQueueDrain qd = new ObservableQueueDrain() { @Override @@ -854,9 +854,9 @@ public void accept(Observer a, Integer v) { Disposable d = Disposables.empty(); - QueueDrainHelper.checkTerminated(true, false, ts, false, q, d, qd); + QueueDrainHelper.checkTerminated(true, false, to, false, q, d, qd); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); assertTrue(d.isDisposed()); } diff --git a/src/test/java/io/reactivex/maybe/MaybeTest.java b/src/test/java/io/reactivex/maybe/MaybeTest.java index 14705243ea..18fe1fea4c 100644 --- a/src/test/java/io/reactivex/maybe/MaybeTest.java +++ b/src/test/java/io/reactivex/maybe/MaybeTest.java @@ -30,7 +30,7 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.internal.operators.flowable.FlowableZipTest.ArgsToString; import io.reactivex.internal.operators.maybe.*; import io.reactivex.observers.TestObserver; @@ -89,11 +89,11 @@ public void fromFlowableMany() { public void fromFlowableDisposeComposesThrough() { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = pp.singleElement().test(); + TestObserver to = pp.singleElement().test(); assertTrue(pp.hasSubscribers()); - ts.cancel(); + to.cancel(); assertFalse(pp.hasSubscribers()); } @@ -144,24 +144,24 @@ public void fromObservableMany() { @Test public void fromObservableDisposeComposesThrough() { - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.singleElement().test(false); + TestObserver to = ps.singleElement().test(false); - assertTrue(pp.hasObservers()); + assertTrue(ps.hasObservers()); - ts.cancel(); + to.cancel(); - assertFalse(pp.hasObservers()); + assertFalse(ps.hasObservers()); } @Test public void fromObservableDisposeComposesThroughImmediatelyCancelled() { - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - pp.singleElement().test(true); + ps.singleElement().test(true); - assertFalse(pp.hasObservers()); + assertFalse(ps.hasObservers()); } @Test @@ -542,9 +542,9 @@ public boolean test(Integer v) throws Exception { @Test public void cast() { - TestObserver ts = Maybe.just(1).cast(Number.class).test(); + TestObserver to = Maybe.just(1).cast(Number.class).test(); // don'n inline this due to the generic type - ts.assertResult((Number)1); + to.assertResult((Number)1); } @Test(expected = NullPointerException.class) @@ -870,7 +870,7 @@ public void doOnDisposeThrows() { try { PublishProcessor pp = PublishProcessor.create(); - TestObserver ts = pp.singleElement().doOnDispose(new Action() { + TestObserver to = pp.singleElement().doOnDispose(new Action() { @Override public void run() throws Exception { throw new TestException(); @@ -880,11 +880,11 @@ public void run() throws Exception { assertTrue(pp.hasSubscribers()); - ts.cancel(); + to.cancel(); assertFalse(pp.hasSubscribers()); - ts.assertSubscribed() + to.assertSubscribed() .assertNoValues() .assertNoErrors() .assertNotComplete(); @@ -1623,10 +1623,10 @@ public void ambArray1SignalsSuccess() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) + TestObserver to = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1637,7 +1637,7 @@ public void ambArray1SignalsSuccess() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(1); + to.assertResult(1); } @SuppressWarnings("unchecked") @@ -1646,10 +1646,10 @@ public void ambArray2SignalsSuccess() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) + TestObserver to = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1660,7 +1660,7 @@ public void ambArray2SignalsSuccess() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(2); + to.assertResult(2); } @SuppressWarnings("unchecked") @@ -1669,10 +1669,10 @@ public void ambArray1SignalsError() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) + TestObserver to = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1682,7 +1682,7 @@ public void ambArray1SignalsError() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @SuppressWarnings("unchecked") @@ -1691,10 +1691,10 @@ public void ambArray2SignalsError() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) + TestObserver to = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1704,7 +1704,7 @@ public void ambArray2SignalsError() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @SuppressWarnings("unchecked") @@ -1713,10 +1713,10 @@ public void ambArray1SignalsComplete() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) + TestObserver to = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1726,7 +1726,7 @@ public void ambArray1SignalsComplete() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(); + to.assertResult(); } @SuppressWarnings("unchecked") @@ -1735,10 +1735,10 @@ public void ambArray2SignalsComplete() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) + TestObserver to = Maybe.ambArray(pp1.singleElement(), pp2.singleElement()) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1748,7 +1748,7 @@ public void ambArray2SignalsComplete() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(); + to.assertResult(); } @SuppressWarnings("unchecked") @@ -1757,10 +1757,10 @@ public void ambIterable1SignalsSuccess() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) + TestObserver to = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1771,7 +1771,7 @@ public void ambIterable1SignalsSuccess() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(1); + to.assertResult(1); } @SuppressWarnings("unchecked") @@ -1780,10 +1780,10 @@ public void ambIterable2SignalsSuccess() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) + TestObserver to = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1794,7 +1794,7 @@ public void ambIterable2SignalsSuccess() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(2); + to.assertResult(2); } @SuppressWarnings("unchecked") @@ -1803,10 +1803,10 @@ public void ambIterable2SignalsSuccessWithOverlap() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) + TestObserver to = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1818,7 +1818,7 @@ public void ambIterable2SignalsSuccessWithOverlap() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(2); + to.assertResult(2); } @SuppressWarnings("unchecked") @@ -1827,10 +1827,10 @@ public void ambIterable1SignalsError() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) + TestObserver to = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1840,7 +1840,7 @@ public void ambIterable1SignalsError() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @SuppressWarnings("unchecked") @@ -1849,10 +1849,10 @@ public void ambIterable2SignalsError() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) + TestObserver to = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1862,7 +1862,7 @@ public void ambIterable2SignalsError() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @SuppressWarnings("unchecked") @@ -1871,10 +1871,10 @@ public void ambIterable2SignalsErrorWithOverlap() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) + TestObserver to = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1885,7 +1885,7 @@ public void ambIterable2SignalsErrorWithOverlap() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertFailureAndMessage(TestException.class, "2"); + to.assertFailureAndMessage(TestException.class, "2"); } @SuppressWarnings("unchecked") @@ -1894,10 +1894,10 @@ public void ambIterable1SignalsComplete() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) + TestObserver to = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1907,7 +1907,7 @@ public void ambIterable1SignalsComplete() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(); + to.assertResult(); } @SuppressWarnings("unchecked") @@ -1916,10 +1916,10 @@ public void ambIterable2SignalsComplete() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) + TestObserver to = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement())) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -1929,7 +1929,7 @@ public void ambIterable2SignalsComplete() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(); + to.assertResult(); } @Test(expected = NullPointerException.class) @@ -2076,13 +2076,13 @@ public void mergeArrayBackpressuredMixed3() { @SuppressWarnings("unchecked") @Test public void mergeArrayFused() { - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Maybe.mergeArray(Maybe.just(1), Maybe.just(2), Maybe.just(3)).subscribe(ts); ts.assertSubscribed() .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1, 2, 3); } @@ -2093,13 +2093,13 @@ public void mergeArrayFusedRace() { final PublishProcessor pp1 = PublishProcessor.create(); final PublishProcessor pp2 = PublishProcessor.create(); - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Maybe.mergeArray(pp1.singleElement(), pp2.singleElement()).subscribe(ts); ts.assertSubscribed() .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) ; TestHelper.race(new Runnable() { @@ -2210,14 +2210,14 @@ public void mergeALotFused() { Maybe[] sources = new Maybe[Flowable.bufferSize() * 2]; Arrays.fill(sources, Maybe.just(1)); - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); Maybe.mergeArray(sources).subscribe(ts); ts .assertSubscribed() .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertValueCount(sources.length) .assertNoErrors() .assertComplete(); @@ -2420,7 +2420,7 @@ public void accept(Integer v, Throwable e) throws Exception { @Test public void doOnEventErrorThrows() { - TestObserver ts = Maybe.error(new TestException("Outer")) + TestObserver to = Maybe.error(new TestException("Outer")) .doOnEvent(new BiConsumer() { @Override public void accept(Integer v, Throwable e) throws Exception { @@ -2430,7 +2430,7 @@ public void accept(Integer v, Throwable e) throws Exception { .test() .assertFailure(CompositeException.class); - List list = TestHelper.compositeList(ts.errors().get(0)); + List list = TestHelper.compositeList(to.errors().get(0)); TestHelper.assertError(list, 0, TestException.class, "Outer"); TestHelper.assertError(list, 1, TestException.class, "Inner"); assertEquals(2, list.size()); @@ -2989,10 +2989,10 @@ public void ambWith1SignalsSuccess() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = pp1.singleElement().ambWith(pp2.singleElement()) + TestObserver to = pp1.singleElement().ambWith(pp2.singleElement()) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -3003,7 +3003,7 @@ public void ambWith1SignalsSuccess() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(1); + to.assertResult(1); } @Test @@ -3011,10 +3011,10 @@ public void ambWith2SignalsSuccess() { PublishProcessor pp1 = PublishProcessor.create(); PublishProcessor pp2 = PublishProcessor.create(); - TestObserver ts = pp1.singleElement().ambWith(pp2.singleElement()) + TestObserver to = pp1.singleElement().ambWith(pp2.singleElement()) .test(); - ts.assertEmpty(); + to.assertEmpty(); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); @@ -3025,7 +3025,7 @@ public void ambWith2SignalsSuccess() { assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); - ts.assertResult(2); + to.assertResult(2); } @Test diff --git a/src/test/java/io/reactivex/observable/ObservableCovarianceTest.java b/src/test/java/io/reactivex/observable/ObservableCovarianceTest.java index 5861cbfd57..5b2206001d 100644 --- a/src/test/java/io/reactivex/observable/ObservableCovarianceTest.java +++ b/src/test/java/io/reactivex/observable/ObservableCovarianceTest.java @@ -66,7 +66,7 @@ public int compare(Media t1, Media t2) { @Test public void testGroupByCompose() { Observable movies = Observable.just(new HorrorMovie(), new ActionMovie(), new Movie()); - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); movies .groupBy(new Function() { @Override @@ -105,11 +105,11 @@ public String apply(Movie v) { }); } }) - .subscribe(ts); - ts.assertTerminated(); - ts.assertNoErrors(); + .subscribe(to); + to.assertTerminated(); + to.assertNoErrors(); // System.out.println(ts.getOnNextEvents()); - assertEquals(6, ts.valueCount()); + assertEquals(6, to.valueCount()); } @SuppressWarnings("unused") diff --git a/src/test/java/io/reactivex/observable/ObservableFuseableTest.java b/src/test/java/io/reactivex/observable/ObservableFuseableTest.java index ba65019910..070810461c 100644 --- a/src/test/java/io/reactivex/observable/ObservableFuseableTest.java +++ b/src/test/java/io/reactivex/observable/ObservableFuseableTest.java @@ -17,7 +17,7 @@ import org.junit.Test; import io.reactivex.Observable; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.observers.ObserverFusion; public class ObservableFuseableTest { @@ -26,8 +26,8 @@ public class ObservableFuseableTest { public void syncRange() { Observable.range(1, 10) - .to(ObserverFusion.test(QueueSubscription.ANY, false)) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.SYNC)) + .to(ObserverFusion.test(QueueFuseable.ANY, false)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.SYNC)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); @@ -37,8 +37,8 @@ public void syncRange() { public void syncArray() { Observable.fromArray(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) - .to(ObserverFusion.test(QueueSubscription.ANY, false)) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.SYNC)) + .to(ObserverFusion.test(QueueFuseable.ANY, false)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.SYNC)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); @@ -48,8 +48,8 @@ public void syncArray() { public void syncIterable() { Observable.fromIterable(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) - .to(ObserverFusion.test(QueueSubscription.ANY, false)) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.SYNC)) + .to(ObserverFusion.test(QueueFuseable.ANY, false)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.SYNC)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); @@ -59,9 +59,9 @@ public void syncIterable() { public void syncRangeHidden() { Observable.range(1, 10).hide() - .to(ObserverFusion.test(QueueSubscription.ANY, false)) + .to(ObserverFusion.test(QueueFuseable.ANY, false)) .assertOf(ObserverFusion.assertNotFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.NONE)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); @@ -71,9 +71,9 @@ public void syncRangeHidden() { public void syncArrayHidden() { Observable.fromArray(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) .hide() - .to(ObserverFusion.test(QueueSubscription.ANY, false)) + .to(ObserverFusion.test(QueueFuseable.ANY, false)) .assertOf(ObserverFusion.assertNotFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.NONE)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); @@ -83,9 +83,9 @@ public void syncArrayHidden() { public void syncIterableHidden() { Observable.fromIterable(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) .hide() - .to(ObserverFusion.test(QueueSubscription.ANY, false)) + .to(ObserverFusion.test(QueueFuseable.ANY, false)) .assertOf(ObserverFusion.assertNotFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.NONE)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.NONE)) .assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .assertNoErrors() .assertComplete(); diff --git a/src/test/java/io/reactivex/observable/ObservableNullTests.java b/src/test/java/io/reactivex/observable/ObservableNullTests.java index bc97de83d7..105a429b1f 100644 --- a/src/test/java/io/reactivex/observable/ObservableNullTests.java +++ b/src/test/java/io/reactivex/observable/ObservableNullTests.java @@ -368,11 +368,11 @@ public void fromFutureReturnsNull() { FutureTask f = new FutureTask(Functions.EMPTY_RUNNABLE, null); f.run(); - TestObserver ts = new TestObserver(); - Observable.fromFuture(f).subscribe(ts); - ts.assertNoValues(); - ts.assertNotComplete(); - ts.assertError(NullPointerException.class); + TestObserver to = new TestObserver(); + Observable.fromFuture(f).subscribe(to); + to.assertNoValues(); + to.assertNotComplete(); + to.assertError(NullPointerException.class); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java b/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java index a6761dc9e4..5e927ad46b 100644 --- a/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java +++ b/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java @@ -174,10 +174,10 @@ public void methodTestCancelled() { @Test public void safeSubscriberAlreadySafe() { - TestObserver ts = new TestObserver(); - Observable.just(1).safeSubscribe(new SafeObserver(ts)); + TestObserver to = new TestObserver(); + Observable.just(1).safeSubscribe(new SafeObserver(to)); - ts.assertResult(1); + to.assertResult(1); } diff --git a/src/test/java/io/reactivex/observable/ObservableTest.java b/src/test/java/io/reactivex/observable/ObservableTest.java index fc79edaa9c..9b549670a8 100644 --- a/src/test/java/io/reactivex/observable/ObservableTest.java +++ b/src/test/java/io/reactivex/observable/ObservableTest.java @@ -1026,23 +1026,23 @@ public void testRangeWithScheduler() { @Test public void testMergeWith() { - TestObserver ts = new TestObserver(); - Observable.just(1).mergeWith(Observable.just(2)).subscribe(ts); - ts.assertValues(1, 2); + TestObserver to = new TestObserver(); + Observable.just(1).mergeWith(Observable.just(2)).subscribe(to); + to.assertValues(1, 2); } @Test public void testConcatWith() { - TestObserver ts = new TestObserver(); - Observable.just(1).concatWith(Observable.just(2)).subscribe(ts); - ts.assertValues(1, 2); + TestObserver to = new TestObserver(); + Observable.just(1).concatWith(Observable.just(2)).subscribe(to); + to.assertValues(1, 2); } @Test public void testAmbWith() { - TestObserver ts = new TestObserver(); - Observable.just(1).ambWith(Observable.just(2)).subscribe(ts); - ts.assertValue(1); + TestObserver to = new TestObserver(); + Observable.just(1).ambWith(Observable.just(2)).subscribe(to); + to.assertValue(1); } @Test @@ -1072,7 +1072,7 @@ public void accept(List booleans) { @Test public void testCompose() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Observable.just(1, 2, 3).compose(new ObservableTransformer() { @Override public Observable apply(Observable t1) { @@ -1084,10 +1084,10 @@ public String apply(Integer v) { }); } }) - .subscribe(ts); - ts.assertTerminated(); - ts.assertNoErrors(); - ts.assertValues("1", "2", "3"); + .subscribe(to); + to.assertTerminated(); + to.assertNoErrors(); + to.assertValues("1", "2", "3"); } @Test diff --git a/src/test/java/io/reactivex/observers/ObserverFusion.java b/src/test/java/io/reactivex/observers/ObserverFusion.java index a70c577ca3..22b3466b19 100644 --- a/src/test/java/io/reactivex/observers/ObserverFusion.java +++ b/src/test/java/io/reactivex/observers/ObserverFusion.java @@ -32,7 +32,7 @@ public enum ObserverFusion { * Use this as follows: *
                      * source
                -     * .to(ObserverFusion.test(QueueDisposable.ANY, false))
                +     * .to(ObserverFusion.test(QueueFuseable.ANY, false))
                      * .assertResult(0);
                      * 
                * @param the value type @@ -52,7 +52,7 @@ public static Function, TestObserver> test( * Use this as follows: *
                      * source
                -     * .to(ObserverFusion.test(0, QueueDisposable.ANY, false))
                +     * .to(ObserverFusion.test(0, QueueFuseable.ANY, false))
                      * .assertOf(ObserverFusion.assertFuseable());
                      * 
                * @param the value type @@ -71,8 +71,8 @@ static final class AssertFusionConsumer implements Consumer> } @Override - public void accept(TestObserver ts) throws Exception { - ts.assertFusionMode(mode); + public void accept(TestObserver to) throws Exception { + to.assertFusionMode(mode); } } @@ -87,21 +87,21 @@ static final class TestFunctionCallback implements Function, Te @Override public TestObserver apply(Observable t) throws Exception { - TestObserver ts = new TestObserver(); - ts.setInitialFusionMode(mode); + TestObserver to = new TestObserver(); + to.setInitialFusionMode(mode); if (cancelled) { - ts.cancel(); + to.cancel(); } - t.subscribe(ts); - return ts; + t.subscribe(to); + return to; } } enum AssertFuseable implements Consumer> { INSTANCE; @Override - public void accept(TestObserver ts) throws Exception { - ts.assertFuseable(); + public void accept(TestObserver to) throws Exception { + to.assertFuseable(); } } @@ -112,7 +112,7 @@ public void accept(TestObserver ts) throws Exception { * Use this as follows: *
                      * source
                -     * .to(ObserverFusion.test(0, QueueDisposable.ANY, false))
                +     * .to(ObserverFusion.test(0, QueueFuseable.ANY, false))
                      * .assertOf(ObserverFusion.assertNotFuseable());
                      * 
                * @param the value type @@ -126,8 +126,8 @@ public static Consumer> assertNotFuseable() { enum AssertNotFuseable implements Consumer> { INSTANCE; @Override - public void accept(TestObserver ts) throws Exception { - ts.assertNotFuseable(); + public void accept(TestObserver to) throws Exception { + to.assertNotFuseable(); } } @@ -139,11 +139,11 @@ public void accept(TestObserver ts) throws Exception { * Use this as follows: *
                      * source
                -     * .to(ObserverFusion.test(0, QueueDisposable.ANY, false))
                -     * .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.SYNC));
                +     * .to(ObserverFusion.test(0, QueueFuseable.ANY, false))
                +     * .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.SYNC));
                      * 
                * @param the value type - * @param mode the expected established fusion mode, see {@link QueueDisposable} constants. + * @param mode the expected established fusion mode, see {@link QueueFuseable} constants. * @return the new Consumer instance */ public static Consumer> assertFusionMode(final int mode) { @@ -154,25 +154,25 @@ public static Consumer> assertFusionMode(final int mode) { /** * Constructs a TestObserver with the given required fusion mode. * @param the value type - * @param mode the requested fusion mode, see {@link QueueSubscription} constants + * @param mode the requested fusion mode, see {@link QueueFuseable} constants * @return the new TestSubscriber */ public static TestObserver newTest(int mode) { - TestObserver ts = new TestObserver(); - ts.setInitialFusionMode(mode); - return ts; + TestObserver to = new TestObserver(); + to.setInitialFusionMode(mode); + return to; } /** - * Assert that the TestSubscriber received a fuseabe QueueSubscription and + * Assert that the TestSubscriber received a fuseabe QueueFuseable.and * is in the given fusion mode. * @param the value type - * @param ts the TestSubscriber instance + * @param to the TestSubscriber instance * @param mode the expected mode * @return the TestSubscriber */ - public static TestObserver assertFusion(TestObserver ts, int mode) { - return ts.assertOf(ObserverFusion.assertFuseable()) + public static TestObserver assertFusion(TestObserver to, int mode) { + return to.assertOf(ObserverFusion.assertFuseable()) .assertOf(ObserverFusion.assertFusionMode(mode)); } } diff --git a/src/test/java/io/reactivex/observers/SafeObserverTest.java b/src/test/java/io/reactivex/observers/SafeObserverTest.java index cf92a7139c..ee6eb83f43 100644 --- a/src/test/java/io/reactivex/observers/SafeObserverTest.java +++ b/src/test/java/io/reactivex/observers/SafeObserverTest.java @@ -490,15 +490,15 @@ public void onComplete() { @Test public void dispose() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - SafeObserver so = new SafeObserver(ts); + SafeObserver so = new SafeObserver(to); Disposable d = Disposables.empty(); so.onSubscribe(d); - ts.dispose(); + to.dispose(); assertTrue(d.isDisposed()); @@ -507,9 +507,9 @@ public void dispose() { @Test public void onNextAfterComplete() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - SafeObserver so = new SafeObserver(ts); + SafeObserver so = new SafeObserver(to); Disposable d = Disposables.empty(); @@ -523,14 +523,14 @@ public void onNextAfterComplete() { so.onComplete(); - ts.assertResult(); + to.assertResult(); } @Test public void onNextNull() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - SafeObserver so = new SafeObserver(ts); + SafeObserver so = new SafeObserver(to); Disposable d = Disposables.empty(); @@ -538,50 +538,50 @@ public void onNextNull() { so.onNext(null); - ts.assertFailure(NullPointerException.class); + to.assertFailure(NullPointerException.class); } @Test public void onNextWithoutOnSubscribe() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - SafeObserver so = new SafeObserver(ts); + SafeObserver so = new SafeObserver(to); so.onNext(1); - ts.assertFailureAndMessage(NullPointerException.class, "Subscription not set!"); + to.assertFailureAndMessage(NullPointerException.class, "Subscription not set!"); } @Test public void onErrorWithoutOnSubscribe() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - SafeObserver so = new SafeObserver(ts); + SafeObserver so = new SafeObserver(to); so.onError(new TestException()); - ts.assertFailure(CompositeException.class); + to.assertFailure(CompositeException.class); - TestHelper.assertError(ts, 0, TestException.class); - TestHelper.assertError(ts, 1, NullPointerException.class, "Subscription not set!"); + TestHelper.assertError(to, 0, TestException.class); + TestHelper.assertError(to, 1, NullPointerException.class, "Subscription not set!"); } @Test public void onCompleteWithoutOnSubscribe() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - SafeObserver so = new SafeObserver(ts); + SafeObserver so = new SafeObserver(to); so.onComplete(); - ts.assertFailureAndMessage(NullPointerException.class, "Subscription not set!"); + to.assertFailureAndMessage(NullPointerException.class, "Subscription not set!"); } @Test public void onNextNormal() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - SafeObserver so = new SafeObserver(ts); + SafeObserver so = new SafeObserver(to); Disposable d = Disposables.empty(); @@ -590,7 +590,7 @@ public void onNextNormal() { so.onNext(1); so.onComplete(); - ts.assertResult(1); + to.assertResult(1); } static final class CrashDummy implements Observer, Disposable { diff --git a/src/test/java/io/reactivex/observers/SerializedObserverTest.java b/src/test/java/io/reactivex/observers/SerializedObserverTest.java index ee50af3730..720964c1c0 100644 --- a/src/test/java/io/reactivex/observers/SerializedObserverTest.java +++ b/src/test/java/io/reactivex/observers/SerializedObserverTest.java @@ -957,7 +957,7 @@ public void onNext(Integer t) { public void testErrorReentry() { final AtomicReference> serial = new AtomicReference>(); - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { @Override public void onNext(Integer v) { serial.get().onError(new TestException()); @@ -965,20 +965,20 @@ public void onNext(Integer v) { super.onNext(v); } }; - SerializedObserver sobs = new SerializedObserver(ts); + SerializedObserver sobs = new SerializedObserver(to); sobs.onSubscribe(Disposables.empty()); serial.set(sobs); sobs.onNext(1); - ts.assertValue(1); - ts.assertError(TestException.class); + to.assertValue(1); + to.assertError(TestException.class); } @Test public void testCompleteReentry() { final AtomicReference> serial = new AtomicReference>(); - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { @Override public void onNext(Integer v) { serial.get().onComplete(); @@ -986,22 +986,22 @@ public void onNext(Integer v) { super.onNext(v); } }; - SerializedObserver sobs = new SerializedObserver(ts); + SerializedObserver sobs = new SerializedObserver(to); sobs.onSubscribe(Disposables.empty()); serial.set(sobs); sobs.onNext(1); - ts.assertValue(1); - ts.assertComplete(); - ts.assertNoErrors(); + to.assertValue(1); + to.assertComplete(); + to.assertNoErrors(); } @Test public void dispose() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - SerializedObserver so = new SerializedObserver(ts); + SerializedObserver so = new SerializedObserver(to); Disposable d = Disposables.empty(); @@ -1009,7 +1009,7 @@ public void dispose() { assertFalse(so.isDisposed()); - ts.cancel(); + to.cancel(); assertTrue(so.isDisposed()); @@ -1019,9 +1019,9 @@ public void dispose() { @Test public void onCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - final SerializedObserver so = new SerializedObserver(ts); + final SerializedObserver so = new SerializedObserver(to); Disposable d = Disposables.empty(); @@ -1036,7 +1036,7 @@ public void run() { TestHelper.race(r, r); - ts.awaitDone(5, TimeUnit.SECONDS) + to.awaitDone(5, TimeUnit.SECONDS) .assertResult(); } @@ -1045,9 +1045,9 @@ public void run() { @Test public void onNextOnCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - final SerializedObserver so = new SerializedObserver(ts); + final SerializedObserver so = new SerializedObserver(to); Disposable d = Disposables.empty(); @@ -1069,11 +1069,11 @@ public void run() { TestHelper.race(r1, r2); - ts.awaitDone(5, TimeUnit.SECONDS) + to.awaitDone(5, TimeUnit.SECONDS) .assertNoErrors() .assertComplete(); - assertTrue(ts.valueCount() <= 1); + assertTrue(to.valueCount() <= 1); } } @@ -1081,9 +1081,9 @@ public void run() { @Test public void onNextOnErrorRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - final SerializedObserver so = new SerializedObserver(ts); + final SerializedObserver so = new SerializedObserver(to); Disposable d = Disposables.empty(); @@ -1107,11 +1107,11 @@ public void run() { TestHelper.race(r1, r2); - ts.awaitDone(5, TimeUnit.SECONDS) + to.awaitDone(5, TimeUnit.SECONDS) .assertError(ex) .assertNotComplete(); - assertTrue(ts.valueCount() <= 1); + assertTrue(to.valueCount() <= 1); } } @@ -1119,9 +1119,9 @@ public void run() { @Test public void onNextOnErrorRaceDelayError() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - final SerializedObserver so = new SerializedObserver(ts, true); + final SerializedObserver so = new SerializedObserver(to, true); Disposable d = Disposables.empty(); @@ -1145,11 +1145,11 @@ public void run() { TestHelper.race(r1, r2); - ts.awaitDone(5, TimeUnit.SECONDS) + to.awaitDone(5, TimeUnit.SECONDS) .assertError(ex) .assertNotComplete(); - assertTrue(ts.valueCount() <= 1); + assertTrue(to.valueCount() <= 1); } } @@ -1160,9 +1160,9 @@ public void startOnce() { List error = TestHelper.trackPluginErrors(); try { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - final SerializedObserver so = new SerializedObserver(ts); + final SerializedObserver so = new SerializedObserver(to); so.onSubscribe(Disposables.empty()); @@ -1184,9 +1184,9 @@ public void onCompleteOnErrorRace() { List errors = TestHelper.trackPluginErrors(); try { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - final SerializedObserver so = new SerializedObserver(ts); + final SerializedObserver so = new SerializedObserver(to); Disposable d = Disposables.empty(); @@ -1210,12 +1210,12 @@ public void run() { TestHelper.race(r1, r2); - ts.awaitDone(5, TimeUnit.SECONDS); + to.awaitDone(5, TimeUnit.SECONDS); - if (ts.completions() != 0) { - ts.assertResult(); + if (to.completions() != 0) { + to.assertResult(); } else { - ts.assertFailure(TestException.class).assertError(ex); + to.assertFailure(TestException.class).assertError(ex); } for (Throwable e : errors) { @@ -1231,9 +1231,9 @@ public void run() { @Test public void nullOnNext() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - final SerializedObserver so = new SerializedObserver(ts); + final SerializedObserver so = new SerializedObserver(to); Disposable d = Disposables.empty(); @@ -1241,6 +1241,6 @@ public void nullOnNext() { so.onNext(null); - ts.assertFailureAndMessage(NullPointerException.class, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); + to.assertFailureAndMessage(NullPointerException.class, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); } } diff --git a/src/test/java/io/reactivex/observers/TestObserverTest.java b/src/test/java/io/reactivex/observers/TestObserverTest.java index d2896519a8..cca65c0b72 100644 --- a/src/test/java/io/reactivex/observers/TestObserverTest.java +++ b/src/test/java/io/reactivex/observers/TestObserverTest.java @@ -32,7 +32,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueDisposable; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.operators.observable.ObservableScalarXMap.ScalarDisposable; import io.reactivex.internal.subscriptions.EmptySubscription; import io.reactivex.processors.PublishProcessor; @@ -197,46 +197,46 @@ public void testErrorSwallowed() { @Test public void testGetEvents() { - TestSubscriber to = new TestSubscriber(); - to.onSubscribe(EmptySubscription.INSTANCE); - to.onNext(1); - to.onNext(2); + TestSubscriber ts = new TestSubscriber(); + ts.onSubscribe(EmptySubscription.INSTANCE); + ts.onNext(1); + ts.onNext(2); assertEquals(Arrays.asList(Arrays.asList(1, 2), Collections.emptyList(), - Collections.emptyList()), to.getEvents()); + Collections.emptyList()), ts.getEvents()); - to.onComplete(); + ts.onComplete(); assertEquals(Arrays.asList(Arrays.asList(1, 2), Collections.emptyList(), - Collections.singletonList(Notification.createOnComplete())), to.getEvents()); + Collections.singletonList(Notification.createOnComplete())), ts.getEvents()); TestException ex = new TestException(); - TestSubscriber to2 = new TestSubscriber(); - to2.onSubscribe(EmptySubscription.INSTANCE); - to2.onNext(1); - to2.onNext(2); + TestSubscriber ts2 = new TestSubscriber(); + ts2.onSubscribe(EmptySubscription.INSTANCE); + ts2.onNext(1); + ts2.onNext(2); assertEquals(Arrays.asList(Arrays.asList(1, 2), Collections.emptyList(), - Collections.emptyList()), to2.getEvents()); + Collections.emptyList()), ts2.getEvents()); - to2.onError(ex); + ts2.onError(ex); assertEquals(Arrays.asList( Arrays.asList(1, 2), Collections.singletonList(ex), Collections.emptyList()), - to2.getEvents()); + ts2.getEvents()); } @Test public void testNullExpected() { - TestSubscriber to = new TestSubscriber(); - to.onNext(1); + TestSubscriber ts = new TestSubscriber(); + ts.onNext(1); try { - to.assertValue((Integer) null); + ts.assertValue((Integer) null); } catch (AssertionError ex) { // this is expected return; @@ -246,11 +246,11 @@ public void testNullExpected() { @Test public void testNullActual() { - TestSubscriber to = new TestSubscriber(); - to.onNext(null); + TestSubscriber ts = new TestSubscriber(); + ts.onNext(null); try { - to.assertValue(1); + ts.assertValue(1); } catch (AssertionError ex) { // this is expected return; @@ -260,12 +260,12 @@ public void testNullActual() { @Test public void testTerminalErrorOnce() { - TestSubscriber to = new TestSubscriber(); - to.onError(new TestException()); - to.onError(new TestException()); + TestSubscriber ts = new TestSubscriber(); + ts.onError(new TestException()); + ts.onError(new TestException()); try { - to.assertTerminated(); + ts.assertTerminated(); } catch (AssertionError ex) { // this is expected return; @@ -274,12 +274,12 @@ public void testTerminalErrorOnce() { } @Test public void testTerminalCompletedOnce() { - TestSubscriber to = new TestSubscriber(); - to.onComplete(); - to.onComplete(); + TestSubscriber ts = new TestSubscriber(); + ts.onComplete(); + ts.onComplete(); try { - to.assertTerminated(); + ts.assertTerminated(); } catch (AssertionError ex) { // this is expected return; @@ -289,12 +289,12 @@ public void testTerminalCompletedOnce() { @Test public void testTerminalOneKind() { - TestSubscriber to = new TestSubscriber(); - to.onError(new TestException()); - to.onComplete(); + TestSubscriber ts = new TestSubscriber(); + ts.onError(new TestException()); + ts.onComplete(); try { - to.assertTerminated(); + ts.assertTerminated(); } catch (AssertionError ex) { // this is expected return; @@ -304,68 +304,68 @@ public void testTerminalOneKind() { @Test public void createDelegate() { - TestObserver ts1 = TestObserver.create(); + TestObserver to1 = TestObserver.create(); - TestObserver ts = TestObserver.create(ts1); + TestObserver to = TestObserver.create(to1); - ts.assertNotSubscribed(); + to.assertNotSubscribed(); - assertFalse(ts.hasSubscription()); + assertFalse(to.hasSubscription()); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); try { - ts.assertNotSubscribed(); + to.assertNotSubscribed(); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } - assertTrue(ts.hasSubscription()); + assertTrue(to.hasSubscription()); - assertFalse(ts.isDisposed()); + assertFalse(to.isDisposed()); - ts.onNext(1); - ts.onError(new TestException()); - ts.onComplete(); + to.onNext(1); + to.onError(new TestException()); + to.onComplete(); - ts1.assertValue(1).assertError(TestException.class).assertComplete(); + to1.assertValue(1).assertError(TestException.class).assertComplete(); - ts.dispose(); + to.dispose(); - assertTrue(ts.isDisposed()); + assertTrue(to.isDisposed()); - assertTrue(ts.isTerminated()); + assertTrue(to.isTerminated()); - assertSame(Thread.currentThread(), ts.lastThread()); + assertSame(Thread.currentThread(), to.lastThread()); try { - ts.assertNoValues(); + to.assertNoValues(); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } try { - ts.assertValueCount(0); + to.assertValueCount(0); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } - ts.assertValueSequence(Collections.singletonList(1)); + to.assertValueSequence(Collections.singletonList(1)); try { - ts.assertValueSequence(Collections.singletonList(2)); + to.assertValueSequence(Collections.singletonList(2)); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } - ts.assertValueSet(Collections.singleton(1)); + to.assertValueSet(Collections.singleton(1)); try { - ts.assertValueSet(Collections.singleton(2)); + to.assertValueSet(Collections.singleton(2)); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected @@ -375,115 +375,115 @@ public void createDelegate() { @Test public void assertError() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); try { - ts.assertError(TestException.class); + to.assertError(TestException.class); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } try { - ts.assertError(new TestException()); + to.assertError(new TestException()); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } try { - ts.assertError(Functions.alwaysTrue()); + to.assertError(Functions.alwaysTrue()); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } try { - ts.assertErrorMessage(""); + to.assertErrorMessage(""); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } try { - ts.assertSubscribed(); + to.assertSubscribed(); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } try { - ts.assertTerminated(); + to.assertTerminated(); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - ts.assertSubscribed(); + to.assertSubscribed(); - ts.assertNoErrors(); + to.assertNoErrors(); TestException ex = new TestException("Forced failure"); - ts.onError(ex); + to.onError(ex); - ts.assertError(ex); + to.assertError(ex); - ts.assertError(TestException.class); + to.assertError(TestException.class); - ts.assertError(Functions.alwaysTrue()); + to.assertError(Functions.alwaysTrue()); - ts.assertError(new Predicate() { + to.assertError(new Predicate() { @Override public boolean test(Throwable t) throws Exception { return t.getMessage() != null && t.getMessage().contains("Forced"); } }); - ts.assertErrorMessage("Forced failure"); + to.assertErrorMessage("Forced failure"); try { - ts.assertErrorMessage(""); + to.assertErrorMessage(""); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } try { - ts.assertError(new RuntimeException()); + to.assertError(new RuntimeException()); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } try { - ts.assertError(IOException.class); + to.assertError(IOException.class); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } try { - ts.assertError(Functions.alwaysFalse()); + to.assertError(Functions.alwaysFalse()); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } try { - ts.assertNoErrors(); + to.assertNoErrors(); throw new RuntimeException("Should have thrown"); } catch (AssertionError exc) { // expected } - ts.assertTerminated(); + to.assertTerminated(); - ts.assertValueCount(0); + to.assertValueCount(0); - ts.assertNoValues(); + to.assertNoValues(); } @@ -502,67 +502,67 @@ public void valueAndClass() { @Test public void assertFailure() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - ts.onError(new TestException("Forced failure")); + to.onError(new TestException("Forced failure")); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); - ts.assertFailure(Functions.alwaysTrue()); + to.assertFailure(Functions.alwaysTrue()); - ts.assertFailureAndMessage(TestException.class, "Forced failure"); + to.assertFailureAndMessage(TestException.class, "Forced failure"); - ts.onNext(1); + to.onNext(1); - ts.assertFailure(TestException.class, 1); + to.assertFailure(TestException.class, 1); - ts.assertFailure(Functions.alwaysTrue(), 1); + to.assertFailure(Functions.alwaysTrue(), 1); - ts.assertFailureAndMessage(TestException.class, "Forced failure", 1); + to.assertFailureAndMessage(TestException.class, "Forced failure", 1); } @Test public void assertFuseable() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - ts.assertNotFuseable(); + to.assertNotFuseable(); try { - ts.assertFuseable(); + to.assertFuseable(); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } try { - ts.assertFusionMode(QueueDisposable.SYNC); + to.assertFusionMode(QueueFuseable.SYNC); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } - ts = TestObserver.create(); - ts.setInitialFusionMode(QueueDisposable.ANY); + to = TestObserver.create(); + to.setInitialFusionMode(QueueFuseable.ANY); - ts.onSubscribe(new ScalarDisposable(ts, 1)); + to.onSubscribe(new ScalarDisposable(to, 1)); - ts.assertFuseable(); + to.assertFuseable(); - ts.assertFusionMode(QueueDisposable.SYNC); + to.assertFusionMode(QueueFuseable.SYNC); try { - ts.assertFusionMode(QueueDisposable.NONE); + to.assertFusionMode(QueueFuseable.NONE); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } try { - ts.assertNotFuseable(); + to.assertNotFuseable(); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected @@ -572,14 +572,14 @@ public void assertFuseable() { @Test public void assertTerminated() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.assertNotTerminated(); + to.assertNotTerminated(); - ts.onError(null); + to.onError(null); try { - ts.assertNotTerminated(); + to.assertNotTerminated(); throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { // expected @@ -588,9 +588,9 @@ public void assertTerminated() { @Test public void assertOf() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.assertOf(new Consumer>() { + to.assertOf(new Consumer>() { @Override public void accept(TestObserver f) throws Exception { f.assertNotSubscribed(); @@ -598,7 +598,7 @@ public void accept(TestObserver f) throws Exception { }); try { - ts.assertOf(new Consumer>() { + to.assertOf(new Consumer>() { @Override public void accept(TestObserver f) throws Exception { f.assertSubscribed(); @@ -610,7 +610,7 @@ public void accept(TestObserver f) throws Exception { } try { - ts.assertOf(new Consumer>() { + to.assertOf(new Consumer>() { @Override public void accept(TestObserver f) throws Exception { throw new IllegalArgumentException(); @@ -624,34 +624,34 @@ public void accept(TestObserver f) throws Exception { @Test public void assertResult() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - ts.onComplete(); + to.onComplete(); - ts.assertResult(); + to.assertResult(); try { - ts.assertResult(1); + to.assertResult(1); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } - ts.onNext(1); + to.onNext(1); - ts.assertResult(1); + to.assertResult(1); try { - ts.assertResult(2); + to.assertResult(2); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } try { - ts.assertResult(); + to.assertResult(); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected @@ -661,139 +661,139 @@ public void assertResult() { @Test(timeout = 5000) public void await() throws Exception { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - assertFalse(ts.await(100, TimeUnit.MILLISECONDS)); + assertFalse(to.await(100, TimeUnit.MILLISECONDS)); - ts.awaitDone(100, TimeUnit.MILLISECONDS); + to.awaitDone(100, TimeUnit.MILLISECONDS); - assertTrue(ts.isDisposed()); + assertTrue(to.isDisposed()); - assertFalse(ts.awaitTerminalEvent(100, TimeUnit.MILLISECONDS)); + assertFalse(to.awaitTerminalEvent(100, TimeUnit.MILLISECONDS)); - assertEquals(0, ts.completions()); - assertEquals(0, ts.errorCount()); + assertEquals(0, to.completions()); + assertEquals(0, to.errorCount()); - ts.onComplete(); + to.onComplete(); - assertTrue(ts.await(100, TimeUnit.MILLISECONDS)); + assertTrue(to.await(100, TimeUnit.MILLISECONDS)); - ts.await(); + to.await(); - ts.awaitDone(5, TimeUnit.SECONDS); + to.awaitDone(5, TimeUnit.SECONDS); - assertEquals(1, ts.completions()); - assertEquals(0, ts.errorCount()); + assertEquals(1, to.completions()); + assertEquals(0, to.errorCount()); - assertTrue(ts.awaitTerminalEvent()); + assertTrue(to.awaitTerminalEvent()); - final TestObserver ts1 = TestObserver.create(); + final TestObserver to1 = TestObserver.create(); - ts1.onSubscribe(Disposables.empty()); + to1.onSubscribe(Disposables.empty()); Schedulers.single().scheduleDirect(new Runnable() { @Override public void run() { - ts1.onComplete(); + to1.onComplete(); } }, 200, TimeUnit.MILLISECONDS); - ts1.await(); + to1.await(); - ts1.assertValueSet(Collections.emptySet()); + to1.assertValueSet(Collections.emptySet()); } @Test public void errors() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - assertEquals(0, ts.errors().size()); + assertEquals(0, to.errors().size()); - ts.onError(new TestException()); + to.onError(new TestException()); - assertEquals(1, ts.errors().size()); + assertEquals(1, to.errors().size()); - TestHelper.assertError(ts.errors(), 0, TestException.class); + TestHelper.assertError(to.errors(), 0, TestException.class); } @SuppressWarnings("unchecked") @Test public void onNext() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - assertEquals(0, ts.valueCount()); + assertEquals(0, to.valueCount()); - assertEquals(Collections.emptyList(), ts.values()); + assertEquals(Collections.emptyList(), to.values()); - ts.onNext(1); + to.onNext(1); - assertEquals(Collections.singletonList(1), ts.values()); + assertEquals(Collections.singletonList(1), to.values()); - ts.cancel(); + to.cancel(); - assertTrue(ts.isCancelled()); - assertTrue(ts.isDisposed()); + assertTrue(to.isCancelled()); + assertTrue(to.isDisposed()); - ts.assertValue(1); + to.assertValue(1); - assertEquals(Arrays.asList(Collections.singletonList(1), Collections.emptyList(), Collections.emptyList()), ts.getEvents()); + assertEquals(Arrays.asList(Collections.singletonList(1), Collections.emptyList(), Collections.emptyList()), to.getEvents()); - ts.onComplete(); + to.onComplete(); - assertEquals(Arrays.asList(Collections.singletonList(1), Collections.emptyList(), Collections.singletonList(Notification.createOnComplete())), ts.getEvents()); + assertEquals(Arrays.asList(Collections.singletonList(1), Collections.emptyList(), Collections.singletonList(Notification.createOnComplete())), to.getEvents()); } @Test public void fusionModeToString() { - assertEquals("NONE", TestObserver.fusionModeToString(QueueDisposable.NONE)); - assertEquals("SYNC", TestObserver.fusionModeToString(QueueDisposable.SYNC)); - assertEquals("ASYNC", TestObserver.fusionModeToString(QueueDisposable.ASYNC)); + assertEquals("NONE", TestObserver.fusionModeToString(QueueFuseable.NONE)); + assertEquals("SYNC", TestObserver.fusionModeToString(QueueFuseable.SYNC)); + assertEquals("ASYNC", TestObserver.fusionModeToString(QueueFuseable.ASYNC)); assertEquals("Unknown(100)", TestObserver.fusionModeToString(100)); } @Test public void multipleTerminals() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - ts.assertNotComplete(); + to.assertNotComplete(); - ts.onComplete(); + to.onComplete(); try { - ts.assertNotComplete(); + to.assertNotComplete(); throw new RuntimeException("Should have thrown"); } catch (Throwable ex) { // expected } - ts.assertTerminated(); + to.assertTerminated(); - ts.onComplete(); + to.onComplete(); try { - ts.assertComplete(); + to.assertComplete(); throw new RuntimeException("Should have thrown"); } catch (Throwable ex) { // expected } try { - ts.assertTerminated(); + to.assertTerminated(); throw new RuntimeException("Should have thrown"); } catch (Throwable ex) { // expected } try { - ts.assertNotComplete(); + to.assertNotComplete(); throw new RuntimeException("Should have thrown"); } catch (Throwable ex) { // expected @@ -802,32 +802,32 @@ public void multipleTerminals() { @Test public void assertValue() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); try { - ts.assertValue(1); + to.assertValue(1); throw new RuntimeException("Should have thrown"); } catch (Throwable ex) { // expected } - ts.onNext(1); + to.onNext(1); - ts.assertValue(1); + to.assertValue(1); try { - ts.assertValue(2); + to.assertValue(2); throw new RuntimeException("Should have thrown"); } catch (Throwable ex) { // expected } - ts.onNext(2); + to.onNext(2); try { - ts.assertValue(1); + to.assertValue(1); throw new RuntimeException("Should have thrown"); } catch (Throwable ex) { // expected @@ -836,77 +836,77 @@ public void assertValue() { @Test public void onNextMisbehave() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onNext(1); + to.onNext(1); - ts.assertError(IllegalStateException.class); + to.assertError(IllegalStateException.class); - ts = TestObserver.create(); + to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - ts.onNext(null); + to.onNext(null); - ts.assertFailure(NullPointerException.class, (Integer)null); + to.assertFailure(NullPointerException.class, (Integer)null); } @Test public void awaitTerminalEventInterrupt() { - final TestObserver ts = TestObserver.create(); + final TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); Thread.currentThread().interrupt(); - ts.awaitTerminalEvent(); + to.awaitTerminalEvent(); assertTrue(Thread.interrupted()); Thread.currentThread().interrupt(); - ts.awaitTerminalEvent(5, TimeUnit.SECONDS); + to.awaitTerminalEvent(5, TimeUnit.SECONDS); assertTrue(Thread.interrupted()); } @Test public void assertTerminated2() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - assertFalse(ts.isTerminated()); + assertFalse(to.isTerminated()); - ts.onError(new TestException()); - ts.onError(new IOException()); + to.onError(new TestException()); + to.onError(new IOException()); - assertTrue(ts.isTerminated()); + assertTrue(to.isTerminated()); try { - ts.assertTerminated(); + to.assertTerminated(); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } try { - ts.assertError(TestException.class); + to.assertError(TestException.class); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } - ts = TestObserver.create(); + to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - ts.onError(new TestException()); - ts.onComplete(); + to.onError(new TestException()); + to.onComplete(); try { - ts.assertTerminated(); + to.assertTerminated(); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected @@ -915,30 +915,30 @@ public void assertTerminated2() { @Test public void onSubscribe() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(null); + to.onSubscribe(null); - ts.assertError(NullPointerException.class); + to.assertError(NullPointerException.class); - ts = TestObserver.create(); + to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); Disposable d1 = Disposables.empty(); - ts.onSubscribe(d1); + to.onSubscribe(d1); assertTrue(d1.isDisposed()); - ts.assertError(IllegalStateException.class); + to.assertError(IllegalStateException.class); - ts = TestObserver.create(); - ts.dispose(); + to = TestObserver.create(); + to.dispose(); d1 = Disposables.empty(); - ts.onSubscribe(d1); + to.onSubscribe(d1); assertTrue(d1.isDisposed()); @@ -946,31 +946,31 @@ public void onSubscribe() { @Test public void assertValueSequence() { - TestObserver ts = TestObserver.create(); + TestObserver to = TestObserver.create(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - ts.onNext(1); - ts.onNext(2); + to.onNext(1); + to.onNext(2); try { - ts.assertValueSequence(Collections.emptyList()); + to.assertValueSequence(Collections.emptyList()); throw new RuntimeException("Should have thrown"); } catch (AssertionError expected) { assertTrue(expected.getMessage(), expected.getMessage().startsWith("More values received than expected (0)")); } try { - ts.assertValueSequence(Collections.singletonList(1)); + to.assertValueSequence(Collections.singletonList(1)); throw new RuntimeException("Should have thrown"); } catch (AssertionError expected) { assertTrue(expected.getMessage(), expected.getMessage().startsWith("More values received than expected (1)")); } - ts.assertValueSequence(Arrays.asList(1, 2)); + to.assertValueSequence(Arrays.asList(1, 2)); try { - ts.assertValueSequence(Arrays.asList(1, 2, 3)); + to.assertValueSequence(Arrays.asList(1, 2, 3)); throw new RuntimeException("Should have thrown"); } catch (AssertionError expected) { assertTrue(expected.getMessage(), expected.getMessage().startsWith("Fewer values received than expected (2)")); @@ -979,23 +979,23 @@ public void assertValueSequence() { @Test public void assertEmpty() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); try { - ts.assertEmpty(); + to.assertEmpty(); throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { // expected } - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); - ts.assertEmpty(); + to.assertEmpty(); - ts.onNext(1); + to.onNext(1); try { - ts.assertEmpty(); + to.assertEmpty(); throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { // expected @@ -1004,12 +1004,12 @@ public void assertEmpty() { @Test public void awaitDoneTimed() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); Thread.currentThread().interrupt(); try { - ts.awaitDone(5, TimeUnit.SECONDS); + to.awaitDone(5, TimeUnit.SECONDS); } catch (RuntimeException ex) { assertTrue(ex.toString(), ex.getCause() instanceof InterruptedException); } @@ -1017,14 +1017,14 @@ public void awaitDoneTimed() { @Test public void assertNotSubscribed() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - ts.assertNotSubscribed(); + to.assertNotSubscribed(); - ts.errors().add(new TestException()); + to.errors().add(new TestException()); try { - ts.assertNotSubscribed(); + to.assertNotSubscribed(); throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { // expected @@ -1033,32 +1033,32 @@ public void assertNotSubscribed() { @Test public void assertErrorMultiple() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); TestException e = new TestException(); - ts.errors().add(e); - ts.errors().add(new TestException()); + to.errors().add(e); + to.errors().add(new TestException()); try { - ts.assertError(TestException.class); + to.assertError(TestException.class); throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { // expected } try { - ts.assertError(e); + to.assertError(e); throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { // expected } try { - ts.assertError(Functions.alwaysTrue()); + to.assertError(Functions.alwaysTrue()); throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { // expected } try { - ts.assertErrorMessage(""); + to.assertErrorMessage(""); throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { // expected @@ -1067,10 +1067,10 @@ public void assertErrorMultiple() { @Test public void testErrorInPredicate() { - TestObserver ts = new TestObserver(); - ts.onError(new RuntimeException()); + TestObserver to = new TestObserver(); + to.onError(new RuntimeException()); try { - ts.assertError(new Predicate() { + to.assertError(new Predicate() { @Override public boolean test(Throwable throwable) throws Exception { throw new TestException(); @@ -1085,25 +1085,25 @@ public boolean test(Throwable throwable) throws Exception { @Test public void assertComplete() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); try { - ts.assertComplete(); + to.assertComplete(); throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { // expected } - ts.onComplete(); + to.onComplete(); - ts.assertComplete(); + to.assertComplete(); - ts.onComplete(); + to.onComplete(); try { - ts.assertComplete(); + to.assertComplete(); throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { // expected @@ -1112,16 +1112,16 @@ public void assertComplete() { @Test public void completeWithoutOnSubscribe() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - ts.onComplete(); + to.onComplete(); - ts.assertError(IllegalStateException.class); + to.assertError(IllegalStateException.class); } @Test public void completeDelegateThrows() { - TestObserver ts = new TestObserver(new Observer() { + TestObserver to = new TestObserver(new Observer() { @Override public void onSubscribe(Disposable d) { @@ -1145,19 +1145,19 @@ public void onComplete() { }); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); try { - ts.onComplete(); + to.onComplete(); throw new RuntimeException("Should have thrown!"); } catch (TestException ex) { - assertTrue(ts.isTerminated()); + assertTrue(to.isTerminated()); } } @Test public void errorDelegateThrows() { - TestObserver ts = new TestObserver(new Observer() { + TestObserver to = new TestObserver(new Observer() { @Override public void onSubscribe(Disposable d) { @@ -1181,38 +1181,38 @@ public void onComplete() { }); - ts.onSubscribe(Disposables.empty()); + to.onSubscribe(Disposables.empty()); try { - ts.onError(new IOException()); + to.onError(new IOException()); throw new RuntimeException("Should have thrown!"); } catch (TestException ex) { - assertTrue(ts.isTerminated()); + assertTrue(to.isTerminated()); } } @Test public void syncQueueThrows() { - TestObserver ts = new TestObserver(); - ts.setInitialFusionMode(QueueDisposable.SYNC); + TestObserver to = new TestObserver(); + to.setInitialFusionMode(QueueFuseable.SYNC); Observable.range(1, 5) .map(new Function() { @Override public Object apply(Integer v) throws Exception { throw new TestException(); } }) - .subscribe(ts); + .subscribe(to); - ts.assertSubscribed() + to.assertSubscribed() .assertFuseable() - .assertFusionMode(QueueDisposable.SYNC) + .assertFusionMode(QueueFuseable.SYNC) .assertFailure(TestException.class); } @Test public void asyncQueueThrows() { - TestObserver ts = new TestObserver(); - ts.setInitialFusionMode(QueueDisposable.ANY); + TestObserver to = new TestObserver(); + to.setInitialFusionMode(QueueFuseable.ANY); UnicastSubject up = UnicastSubject.create(); @@ -1221,13 +1221,13 @@ public void asyncQueueThrows() { @Override public Object apply(Integer v) throws Exception { throw new TestException(); } }) - .subscribe(ts); + .subscribe(to); up.onNext(1); - ts.assertSubscribed() + to.assertSubscribed() .assertFuseable() - .assertFusionMode(QueueDisposable.ASYNC) + .assertFusionMode(QueueFuseable.ASYNC) .assertFailure(TestException.class); } @@ -1249,32 +1249,32 @@ public void errorMeansDisposed() { @Test public void asyncFusion() { - TestObserver ts = new TestObserver(); - ts.setInitialFusionMode(QueueDisposable.ANY); + TestObserver to = new TestObserver(); + to.setInitialFusionMode(QueueFuseable.ANY); UnicastSubject up = UnicastSubject.create(); up - .subscribe(ts); + .subscribe(to); up.onNext(1); up.onComplete(); - ts.assertSubscribed() + to.assertSubscribed() .assertFuseable() - .assertFusionMode(QueueDisposable.ASYNC) + .assertFusionMode(QueueFuseable.ASYNC) .assertResult(1); } @Test public void assertValuePredicateEmpty() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.empty().subscribe(ts); + Observable.empty().subscribe(to); thrown.expect(AssertionError.class); thrown.expectMessage("No values"); - ts.assertValue(new Predicate() { + to.assertValue(new Predicate() { @Override public boolean test(final Object o) throws Exception { return false; } @@ -1283,11 +1283,11 @@ public void assertValuePredicateEmpty() { @Test public void assertValuePredicateMatch() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.just(1).subscribe(ts); + Observable.just(1).subscribe(to); - ts.assertValue(new Predicate() { + to.assertValue(new Predicate() { @Override public boolean test(final Integer o) throws Exception { return o == 1; } @@ -1296,13 +1296,13 @@ public void assertValuePredicateMatch() { @Test public void assertValuePredicateNoMatch() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.just(1).subscribe(ts); + Observable.just(1).subscribe(to); thrown.expect(AssertionError.class); thrown.expectMessage("Value not present"); - ts.assertValue(new Predicate() { + to.assertValue(new Predicate() { @Override public boolean test(final Integer o) throws Exception { return o != 1; } @@ -1311,13 +1311,13 @@ public void assertValuePredicateNoMatch() { @Test public void assertValuePredicateMatchButMore() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.just(1, 2).subscribe(ts); + Observable.just(1, 2).subscribe(to); thrown.expect(AssertionError.class); thrown.expectMessage("Value present but other values as well"); - ts.assertValue(new Predicate() { + to.assertValue(new Predicate() { @Override public boolean test(final Integer o) throws Exception { return o == 1; } @@ -1326,13 +1326,13 @@ public void assertValuePredicateMatchButMore() { @Test public void assertValueAtPredicateEmpty() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.empty().subscribe(ts); + Observable.empty().subscribe(to); thrown.expect(AssertionError.class); thrown.expectMessage("No values"); - ts.assertValueAt(0, new Predicate() { + to.assertValueAt(0, new Predicate() { @Override public boolean test(final Object o) throws Exception { return false; } @@ -1341,11 +1341,11 @@ public void assertValueAtPredicateEmpty() { @Test public void assertValueAtPredicateMatch() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.just(1, 2).subscribe(ts); + Observable.just(1, 2).subscribe(to); - ts.assertValueAt(1, new Predicate() { + to.assertValueAt(1, new Predicate() { @Override public boolean test(final Integer o) throws Exception { return o == 2; } @@ -1354,13 +1354,13 @@ public void assertValueAtPredicateMatch() { @Test public void assertValueAtPredicateNoMatch() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.just(1, 2, 3).subscribe(ts); + Observable.just(1, 2, 3).subscribe(to); thrown.expect(AssertionError.class); thrown.expectMessage("Value not present"); - ts.assertValueAt(2, new Predicate() { + to.assertValueAt(2, new Predicate() { @Override public boolean test(final Integer o) throws Exception { return o != 3; } @@ -1369,13 +1369,13 @@ public void assertValueAtPredicateNoMatch() { @Test public void assertValueAtInvalidIndex() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.just(1, 2).subscribe(ts); + Observable.just(1, 2).subscribe(to); thrown.expect(AssertionError.class); thrown.expectMessage("Invalid index: 2 (latch = 0, values = 2, errors = 0, completions = 1)"); - ts.assertValueAt(2, new Predicate() { + to.assertValueAt(2, new Predicate() { @Override public boolean test(final Integer o) throws Exception { return o == 1; } @@ -1384,44 +1384,44 @@ public void assertValueAtInvalidIndex() { @Test public void assertValueAtIndexEmpty() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.empty().subscribe(ts); + Observable.empty().subscribe(to); thrown.expect(AssertionError.class); thrown.expectMessage("No values"); - ts.assertValueAt(0, "a"); + to.assertValueAt(0, "a"); } @Test public void assertValueAtIndexMatch() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.just("a", "b").subscribe(ts); + Observable.just("a", "b").subscribe(to); - ts.assertValueAt(1, "b"); + to.assertValueAt(1, "b"); } @Test public void assertValueAtIndexNoMatch() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.just("a", "b", "c").subscribe(ts); + Observable.just("a", "b", "c").subscribe(to); thrown.expect(AssertionError.class); thrown.expectMessage("Expected: b (class: String), Actual: c (class: String) (latch = 0, values = 3, errors = 0, completions = 1)"); - ts.assertValueAt(2, "b"); + to.assertValueAt(2, "b"); } @Test public void assertValueAtIndexInvalidIndex() { - TestObserver ts = new TestObserver(); + TestObserver to = new TestObserver(); - Observable.just("a", "b").subscribe(ts); + Observable.just("a", "b").subscribe(to); thrown.expect(AssertionError.class); thrown.expectMessage("Invalid index: 2 (latch = 0, values = 2, errors = 0, completions = 1)"); - ts.assertValueAt(2, "c"); + to.assertValueAt(2, "c"); } @Test diff --git a/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java b/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java index 69ccfc3db6..baa37e3fee 100644 --- a/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java +++ b/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java @@ -25,7 +25,7 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.subscribers.BasicFuseableSubscriber; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.processors.UnicastProcessor; @@ -93,11 +93,11 @@ public void onNext(T t) { public int requestFusion(int mode) { QueueSubscription fs = qs; if (fs != null) { - int m = fs.requestFusion(mode & ~QueueSubscription.BOUNDARY); + int m = fs.requestFusion(mode & ~QueueFuseable.BOUNDARY); this.sourceMode = m; return m; } - return QueueSubscription.NONE; + return QueueFuseable.NONE; } @Override diff --git a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java index 488b58ac88..71251e7c9c 100644 --- a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java +++ b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java @@ -27,7 +27,7 @@ import io.reactivex.TestHelper; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Consumer; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.subscribers.*; @@ -391,13 +391,13 @@ public void testCurrentStateMethodsError() { public void fusionLive() { AsyncProcessor ap = new AsyncProcessor(); - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); ap.subscribe(ts); ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)); + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)); ts.assertNoValues().assertNoErrors().assertNotComplete(); @@ -416,13 +416,13 @@ public void fusionOfflie() { ap.onNext(1); ap.onComplete(); - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); ap.subscribe(ts); ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1); } diff --git a/src/test/java/io/reactivex/processors/PublishProcessorTest.java b/src/test/java/io/reactivex/processors/PublishProcessorTest.java index ae0248a8c5..9989f6b392 100644 --- a/src/test/java/io/reactivex/processors/PublishProcessorTest.java +++ b/src/test/java/io/reactivex/processors/PublishProcessorTest.java @@ -260,14 +260,14 @@ public void accept(String v) { */ @Test public void testReSubscribe() { - final PublishProcessor ps = PublishProcessor.create(); + final PublishProcessor pp = PublishProcessor.create(); Subscriber o1 = TestHelper.mockSubscriber(); TestSubscriber ts = new TestSubscriber(o1); - ps.subscribe(ts); + pp.subscribe(ts); // emit - ps.onNext(1); + pp.onNext(1); // validate we got it InOrder inOrder1 = inOrder(o1); @@ -278,14 +278,14 @@ public void testReSubscribe() { ts.dispose(); // emit again but nothing will be there to receive it - ps.onNext(2); + pp.onNext(2); Subscriber o2 = TestHelper.mockSubscriber(); TestSubscriber ts2 = new TestSubscriber(o2); - ps.subscribe(ts2); + pp.subscribe(ts2); // emit - ps.onNext(3); + pp.onNext(3); // validate we got it InOrder inOrder2 = inOrder(o2); diff --git a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java index 63e0c840d4..c822d61a00 100644 --- a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java @@ -39,13 +39,13 @@ protected FlowableProcessor create() { public void fusionLive() { UnicastProcessor ap = UnicastProcessor.create(); - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); ap.subscribe(ts); ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)); + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)); ts.assertNoValues().assertNoErrors().assertNotComplete(); @@ -64,13 +64,13 @@ public void fusionOfflie() { ap.onNext(1); ap.onComplete(); - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); ap.subscribe(ts); ts .assertOf(SubscriberFusion.assertFuseable()) - .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1); } @@ -95,7 +95,7 @@ public void failFastFusionOffline() { ap.onNext(1); ap.onError(new RuntimeException()); - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); ap.subscribe(ts); ts @@ -263,11 +263,11 @@ public void onErrorStatePeeking() { public void rejectSyncFusion() { UnicastProcessor p = UnicastProcessor.create(); - TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.SYNC); + TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.SYNC); p.subscribe(ts); - SubscriberFusion.assertFusion(ts, QueueSubscription.NONE); + SubscriberFusion.assertFusion(ts, QueueFuseable.NONE); } @Test @@ -297,7 +297,7 @@ public void fusedDrainCancel() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final UnicastProcessor p = UnicastProcessor.create(); - final TestSubscriber ts = SubscriberFusion.newTest(QueueSubscription.ANY); + final TestSubscriber ts = SubscriberFusion.newTest(QueueFuseable.ANY); p.subscribe(ts); @@ -360,11 +360,11 @@ public void hasObservers() { assertFalse(us.hasSubscribers()); - TestSubscriber to = us.test(); + TestSubscriber ts = us.test(); assertTrue(us.hasSubscribers()); - to.cancel(); + ts.cancel(); assertFalse(us.hasSubscribers()); } @@ -374,12 +374,12 @@ public void drainFusedFailFast() { UnicastProcessor us = UnicastProcessor.create(false); - TestSubscriber to = us.to(SubscriberFusion.test(1, QueueDisposable.ANY, false)); + TestSubscriber ts = us.to(SubscriberFusion.test(1, QueueFuseable.ANY, false)); us.done = true; - us.drainFused(to); + us.drainFused(ts); - to.assertResult(); + ts.assertResult(); } @Test @@ -387,22 +387,22 @@ public void drainFusedFailFastEmpty() { UnicastProcessor us = UnicastProcessor.create(false); - TestSubscriber to = us.to(SubscriberFusion.test(1, QueueDisposable.ANY, false)); + TestSubscriber ts = us.to(SubscriberFusion.test(1, QueueFuseable.ANY, false)); - us.drainFused(to); + us.drainFused(ts); - to.assertEmpty(); + ts.assertEmpty(); } @Test public void checkTerminatedFailFastEmpty() { UnicastProcessor us = UnicastProcessor.create(false); - TestSubscriber to = us.to(SubscriberFusion.test(1, QueueDisposable.ANY, false)); + TestSubscriber ts = us.to(SubscriberFusion.test(1, QueueFuseable.ANY, false)); - us.checkTerminated(true, true, false, to, us.queue); + us.checkTerminated(true, true, false, ts, us.queue); - to.assertEmpty(); + ts.assertEmpty(); } @Test diff --git a/src/test/java/io/reactivex/single/SingleCacheTest.java b/src/test/java/io/reactivex/single/SingleCacheTest.java index acdf75679a..ddfa964ac0 100644 --- a/src/test/java/io/reactivex/single/SingleCacheTest.java +++ b/src/test/java/io/reactivex/single/SingleCacheTest.java @@ -55,15 +55,15 @@ public void delayed() { PublishSubject ps = PublishSubject.create(); Single cache = ps.single(-99).cache(); - TestObserver ts1 = cache.test(); + TestObserver to1 = cache.test(); - TestObserver ts2 = cache.test(); + TestObserver to2 = cache.test(); ps.onNext(1); ps.onComplete(); - ts1.assertResult(1); - ts2.assertResult(1); + to1.assertResult(1); + to2.assertResult(1); } @Test @@ -71,17 +71,17 @@ public void delayedDisposed() { PublishSubject ps = PublishSubject.create(); Single cache = ps.single(-99).cache(); - TestObserver ts1 = cache.test(); + TestObserver to1 = cache.test(); - TestObserver ts2 = cache.test(); + TestObserver to2 = cache.test(); - ts1.cancel(); + to1.cancel(); ps.onNext(1); ps.onComplete(); - ts1.assertNoValues().assertNoErrors().assertNotComplete(); - ts2.assertResult(1); + to1.assertNoValues().assertNoErrors().assertNotComplete(); + to2.assertResult(1); } @Test diff --git a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java index b1fbf0efe9..9376962b95 100644 --- a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java @@ -27,7 +27,7 @@ import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Consumer; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.observers.*; public class AsyncSubjectTest extends SubjectTest { @@ -151,13 +151,13 @@ public void testUnsubscribeBeforeCompleted() { AsyncSubject subject = AsyncSubject.create(); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - subject.subscribe(ts); + TestObserver to = new TestObserver(observer); + subject.subscribe(to); subject.onNext("one"); subject.onNext("two"); - ts.dispose(); + to.dispose(); verify(observer, Mockito.never()).onNext(anyString()); verify(observer, Mockito.never()).onError(any(Throwable.class)); @@ -282,8 +282,8 @@ public void run() { // AsyncSubject ps = AsyncSubject.create(); // // ps.subscribe(); -// TestObserver ts = new TestObserver(); -// ps.subscribe(ts); +// TestObserver to = new TestObserver(); +// ps.subscribe(to); // // try { // ps.onError(new RuntimeException("an exception")); @@ -292,7 +292,7 @@ public void run() { // // ignore // } // // even though the onError above throws we should still receive it on the other subscriber -// assertEquals(1, ts.getOnErrorEvents().size()); +// assertEquals(1, to.getOnErrorEvents().size()); // } @@ -306,8 +306,8 @@ public void run() { // // ps.subscribe(); // ps.subscribe(); -// TestObserver ts = new TestObserver(); -// ps.subscribe(ts); +// TestObserver to = new TestObserver(); +// ps.subscribe(to); // ps.subscribe(); // ps.subscribe(); // ps.subscribe(); @@ -320,7 +320,7 @@ public void run() { // assertEquals(5, e.getExceptions().size()); // } // // even though the onError above throws we should still receive it on the other subscriber -// assertEquals(1, ts.getOnErrorEvents().size()); +// assertEquals(1, to.getOnErrorEvents().size()); // } @Test @@ -391,23 +391,23 @@ public void testCurrentStateMethodsError() { public void fusionLive() { AsyncSubject ap = new AsyncSubject(); - TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); - ap.subscribe(ts); + ap.subscribe(to); - ts + to .assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.ASYNC)); + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)); - ts.assertNoValues().assertNoErrors().assertNotComplete(); + to.assertNoValues().assertNoErrors().assertNotComplete(); ap.onNext(1); - ts.assertNoValues().assertNoErrors().assertNotComplete(); + to.assertNoValues().assertNoErrors().assertNotComplete(); ap.onComplete(); - ts.assertResult(1); + to.assertResult(1); } @Test @@ -416,13 +416,13 @@ public void fusionOfflie() { ap.onNext(1); ap.onComplete(); - TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); - ap.subscribe(ts); + ap.subscribe(to); - ts + to .assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueSubscription.ASYNC)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1); } @@ -464,20 +464,20 @@ public void cancelRace() { AsyncSubject p = AsyncSubject.create(); for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final TestObserver ts1 = p.test(); - final TestObserver ts2 = p.test(); + final TestObserver to1 = p.test(); + final TestObserver to2 = p.test(); Runnable r1 = new Runnable() { @Override public void run() { - ts1.cancel(); + to1.cancel(); } }; Runnable r2 = new Runnable() { @Override public void run() { - ts2.cancel(); + to2.cancel(); } }; @@ -491,12 +491,12 @@ public void onErrorCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AsyncSubject p = AsyncSubject.create(); - final TestObserver ts1 = p.test(); + final TestObserver to1 = p.test(); Runnable r1 = new Runnable() { @Override public void run() { - ts1.cancel(); + to1.cancel(); } }; @@ -511,10 +511,10 @@ public void run() { TestHelper.race(r1, r2); - if (ts1.errorCount() != 0) { - ts1.assertFailure(TestException.class); + if (to1.errorCount() != 0) { + to1.assertFailure(TestException.class); } else { - ts1.assertEmpty(); + to1.assertEmpty(); } } } @@ -523,66 +523,66 @@ public void run() { public void onNextCrossCancel() { AsyncSubject p = AsyncSubject.create(); - final TestObserver ts2 = new TestObserver(); - TestObserver ts1 = new TestObserver() { + final TestObserver to2 = new TestObserver(); + TestObserver to1 = new TestObserver() { @Override public void onNext(Object t) { - ts2.cancel(); + to2.cancel(); super.onNext(t); } }; - p.subscribe(ts1); - p.subscribe(ts2); + p.subscribe(to1); + p.subscribe(to2); p.onNext(1); p.onComplete(); - ts1.assertResult(1); - ts2.assertEmpty(); + to1.assertResult(1); + to2.assertEmpty(); } @Test public void onErrorCrossCancel() { AsyncSubject p = AsyncSubject.create(); - final TestObserver ts2 = new TestObserver(); - TestObserver ts1 = new TestObserver() { + final TestObserver to2 = new TestObserver(); + TestObserver to1 = new TestObserver() { @Override public void onError(Throwable t) { - ts2.cancel(); + to2.cancel(); super.onError(t); } }; - p.subscribe(ts1); - p.subscribe(ts2); + p.subscribe(to1); + p.subscribe(to2); p.onError(new TestException()); - ts1.assertFailure(TestException.class); - ts2.assertEmpty(); + to1.assertFailure(TestException.class); + to2.assertEmpty(); } @Test public void onCompleteCrossCancel() { AsyncSubject p = AsyncSubject.create(); - final TestObserver ts2 = new TestObserver(); - TestObserver ts1 = new TestObserver() { + final TestObserver to2 = new TestObserver(); + TestObserver to1 = new TestObserver() { @Override public void onComplete() { - ts2.cancel(); + to2.cancel(); super.onComplete(); } }; - p.subscribe(ts1); - p.subscribe(ts2); + p.subscribe(to1); + p.subscribe(to2); p.onComplete(); - ts1.assertResult(); - ts2.assertEmpty(); + to1.assertResult(); + to2.assertEmpty(); } } diff --git a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java index 1d57599d16..f8044d5a11 100644 --- a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java @@ -135,9 +135,9 @@ public void testCompletedStopsEmittingData() { Observer observerB = TestHelper.mockObserver(); Observer observerC = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observerA); + TestObserver to = new TestObserver(observerA); - channel.subscribe(ts); + channel.subscribe(to); channel.subscribe(observerB); InOrder inOrderA = inOrder(observerA); @@ -152,7 +152,7 @@ public void testCompletedStopsEmittingData() { inOrderA.verify(observerA).onNext(42); inOrderB.verify(observerB).onNext(42); - ts.dispose(); + to.dispose(); inOrderA.verifyNoMoreInteractions(); channel.onNext(4711); @@ -367,8 +367,8 @@ public void testTakeOneSubscriber() { // BehaviorSubject ps = BehaviorSubject.create(); // // ps.subscribe(); -// TestObserver ts = new TestObserver(); -// ps.subscribe(ts); +// TestObserver to = new TestObserver(); +// ps.subscribe(to); // // try { // ps.onError(new RuntimeException("an exception")); @@ -377,7 +377,7 @@ public void testTakeOneSubscriber() { // // ignore // } // // even though the onError above throws we should still receive it on the other subscriber -// assertEquals(1, ts.getOnErrorEvents().size()); +// assertEquals(1, to.getOnErrorEvents().size()); // } // FIXME RS subscribers are not allowed to throw @@ -390,8 +390,8 @@ public void testTakeOneSubscriber() { // // ps.subscribe(); // ps.subscribe(); -// TestObserver ts = new TestObserver(); -// ps.subscribe(ts); +// TestObserver to = new TestObserver(); +// ps.subscribe(to); // ps.subscribe(); // ps.subscribe(); // ps.subscribe(); @@ -404,7 +404,7 @@ public void testTakeOneSubscriber() { // assertEquals(5, e.getExceptions().size()); // } // // even though the onError above throws we should still receive it on the other subscriber -// assertEquals(1, ts.getOnErrorEvents().size()); +// assertEquals(1, to.getOnErrorEvents().size()); // } @Test public void testEmissionSubscriptionRace() throws Exception { @@ -619,14 +619,14 @@ public void onErrorAfterComplete() { public void cancelOnArrival2() { BehaviorSubject p = BehaviorSubject.create(); - TestObserver ts = p.test(); + TestObserver to = p.test(); p.test(true).assertEmpty(); p.onNext(1); p.onComplete(); - ts.assertResult(1); + to.assertResult(1); } @Test @@ -634,7 +634,7 @@ public void addRemoveRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorSubject p = BehaviorSubject.create(); - final TestObserver ts = p.test(); + final TestObserver to = p.test(); Runnable r1 = new Runnable() { @Override @@ -646,7 +646,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; @@ -660,12 +660,12 @@ public void subscribeOnNextRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorSubject p = BehaviorSubject.createDefault((Object)1); - final TestObserver[] ts = { null }; + final TestObserver[] to = { null }; Runnable r1 = new Runnable() { @Override public void run() { - ts[0] = p.test(); + to[0] = p.test(); } }; @@ -678,10 +678,10 @@ public void run() { TestHelper.race(r1, r2); - if (ts[0].valueCount() == 1) { - ts[0].assertValue(2).assertNoErrors().assertNotComplete(); + if (to[0].valueCount() == 1) { + to[0].assertValue(2).assertNoErrors().assertNotComplete(); } else { - ts[0].assertValues(1, 2).assertNoErrors().assertNotComplete(); + to[0].assertValues(1, 2).assertNoErrors().assertNotComplete(); } } } @@ -722,12 +722,12 @@ public void completeSubscribeRace() throws Exception { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorSubject p = BehaviorSubject.create(); - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Runnable r1 = new Runnable() { @Override public void run() { - p.subscribe(ts); + p.subscribe(to); } }; @@ -740,7 +740,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertResult(); + to.assertResult(); } } @@ -749,14 +749,14 @@ public void errorSubscribeRace() throws Exception { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final BehaviorSubject p = BehaviorSubject.create(); - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); final TestException ex = new TestException(); Runnable r1 = new Runnable() { @Override public void run() { - p.subscribe(ts); + p.subscribe(to); } }; @@ -769,7 +769,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } } diff --git a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java index bfe9f7c02b..3d93324d94 100644 --- a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java @@ -67,9 +67,9 @@ public void testCompletedStopsEmittingData() { Observer observerB = TestHelper.mockObserver(); Observer observerC = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observerA); + TestObserver to = new TestObserver(observerA); - channel.subscribe(ts); + channel.subscribe(to); channel.subscribe(observerB); InOrder inOrderA = inOrder(observerA); @@ -81,7 +81,7 @@ public void testCompletedStopsEmittingData() { inOrderA.verify(observerA).onNext(42); inOrderB.verify(observerB).onNext(42); - ts.dispose(); + to.dispose(); inOrderA.verifyNoMoreInteractions(); channel.onNext(4711); @@ -176,13 +176,13 @@ public void testUnsubscribeFirstSubscriber() { PublishSubject subject = PublishSubject.create(); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - subject.subscribe(ts); + TestObserver to = new TestObserver(observer); + subject.subscribe(to); subject.onNext("one"); subject.onNext("two"); - ts.dispose(); + to.dispose(); assertObservedUntilTwo(observer); Observer anotherSubscriber = TestHelper.mockObserver(); @@ -262,8 +262,8 @@ public void testReSubscribe() { final PublishSubject ps = PublishSubject.create(); Observer o1 = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(o1); - ps.subscribe(ts); + TestObserver to = new TestObserver(o1); + ps.subscribe(to); // emit ps.onNext(1); @@ -274,14 +274,14 @@ public void testReSubscribe() { inOrder1.verifyNoMoreInteractions(); // unsubscribe - ts.dispose(); + to.dispose(); // emit again but nothing will be there to receive it ps.onNext(2); Observer o2 = TestHelper.mockObserver(); - TestObserver ts2 = new TestObserver(o2); - ps.subscribe(ts2); + TestObserver to2 = new TestObserver(o2); + ps.subscribe(to2); // emit ps.onNext(3); @@ -291,7 +291,7 @@ public void testReSubscribe() { inOrder2.verify(o2, times(1)).onNext(3); inOrder2.verifyNoMoreInteractions(); - ts2.dispose(); + to2.dispose(); } private final Throwable testException = new Throwable(); @@ -345,8 +345,8 @@ public void onComplete() { // PublishSubject ps = PublishSubject.create(); // // ps.subscribe(); -// TestObserver ts = new TestObserver(); -// ps.subscribe(ts); +// TestObserver to = new TestObserver(); +// ps.subscribe(to); // // try { // ps.onError(new RuntimeException("an exception")); @@ -355,7 +355,7 @@ public void onComplete() { // // ignore // } // // even though the onError above throws we should still receive it on the other subscriber -// assertEquals(1, ts.getOnErrorEvents().size()); +// assertEquals(1, to.getOnErrorEvents().size()); // } // FIXME RS subscribers are not allowed to throw @@ -368,8 +368,8 @@ public void onComplete() { // // ps.subscribe(); // ps.subscribe(); -// TestObserver ts = new TestObserver(); -// ps.subscribe(ts); +// TestObserver to = new TestObserver(); +// ps.subscribe(to); // ps.subscribe(); // ps.subscribe(); // ps.subscribe(); @@ -382,7 +382,7 @@ public void onComplete() { // assertEquals(5, e.getExceptions().size()); // } // // even though the onError above throws we should still receive it on the other subscriber -// assertEquals(1, ts.getOnErrorEvents().size()); +// assertEquals(1, to.getOnErrorEvents().size()); // } @Test public void testCurrentStateMethodsNormal() { @@ -442,83 +442,83 @@ public void requestValidation() { @Test public void crossCancel() { - final TestObserver ts1 = new TestObserver(); - TestObserver ts2 = new TestObserver() { + final TestObserver to1 = new TestObserver(); + TestObserver to2 = new TestObserver() { @Override public void onNext(Integer t) { super.onNext(t); - ts1.cancel(); + to1.cancel(); } }; - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - pp.subscribe(ts2); - pp.subscribe(ts1); + ps.subscribe(to2); + ps.subscribe(to1); - pp.onNext(1); + ps.onNext(1); - ts2.assertValue(1); + to2.assertValue(1); - ts1.assertNoValues(); + to1.assertNoValues(); } @Test public void crossCancelOnError() { - final TestObserver ts1 = new TestObserver(); - TestObserver ts2 = new TestObserver() { + final TestObserver to1 = new TestObserver(); + TestObserver to2 = new TestObserver() { @Override public void onError(Throwable t) { super.onError(t); - ts1.cancel(); + to1.cancel(); } }; - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - pp.subscribe(ts2); - pp.subscribe(ts1); + ps.subscribe(to2); + ps.subscribe(to1); - pp.onError(new TestException()); + ps.onError(new TestException()); - ts2.assertError(TestException.class); + to2.assertError(TestException.class); - ts1.assertNoErrors(); + to1.assertNoErrors(); } @Test public void crossCancelOnComplete() { - final TestObserver ts1 = new TestObserver(); - TestObserver ts2 = new TestObserver() { + final TestObserver to1 = new TestObserver(); + TestObserver to2 = new TestObserver() { @Override public void onComplete() { super.onComplete(); - ts1.cancel(); + to1.cancel(); } }; - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - pp.subscribe(ts2); - pp.subscribe(ts1); + ps.subscribe(to2); + ps.subscribe(to1); - pp.onComplete(); + ps.onComplete(); - ts2.assertComplete(); + to2.assertComplete(); - ts1.assertNotComplete(); + to1.assertNotComplete(); } @Test @Ignore("Observable doesn't do backpressure") public void backpressureOverflow() { -// PublishSubject pp = PublishSubject.create(); +// PublishSubject ps = PublishSubject.create(); // -// TestObserver ts = pp.test(0L); +// TestObserver to = ps.test(0L); // -// pp.onNext(1); +// ps.onNext(1); // -// ts.assertNoValues() +// to.assertNoValues() // .assertNotComplete() // .assertError(MissingBackpressureException.class) // ; @@ -526,11 +526,11 @@ public void backpressureOverflow() { @Test public void onSubscribeCancelsImmediately() { - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.test(); + TestObserver to = ps.test(); - pp.subscribe(new Observer() { + ps.subscribe(new Observer() { @Override public void onSubscribe(Disposable s) { @@ -555,29 +555,29 @@ public void onComplete() { }); - ts.cancel(); + to.cancel(); - assertFalse(pp.hasObservers()); + assertFalse(ps.hasObservers()); } @Test public void terminateRace() throws Exception { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishSubject pp = PublishSubject.create(); + final PublishSubject ps = PublishSubject.create(); - TestObserver ts = pp.test(); + TestObserver to = ps.test(); Runnable task = new Runnable() { @Override public void run() { - pp.onComplete(); + ps.onComplete(); } }; TestHelper.race(task, task); - ts + to .awaitDone(5, TimeUnit.SECONDS) .assertResult(); } @@ -587,20 +587,20 @@ public void run() { public void addRemoveRance() throws Exception { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishSubject pp = PublishSubject.create(); + final PublishSubject ps = PublishSubject.create(); - final TestObserver ts = pp.test(); + final TestObserver to = ps.test(); Runnable r1 = new Runnable() { @Override public void run() { - pp.subscribe(); + ps.subscribe(); } }; Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; @@ -612,18 +612,18 @@ public void run() { public void addTerminateRance() throws Exception { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishSubject pp = PublishSubject.create(); + final PublishSubject ps = PublishSubject.create(); Runnable r1 = new Runnable() { @Override public void run() { - pp.subscribe(); + ps.subscribe(); } }; Runnable r2 = new Runnable() { @Override public void run() { - pp.onComplete(); + ps.onComplete(); } }; @@ -635,56 +635,56 @@ public void run() { public void addCompleteRance() throws Exception { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishSubject pp = PublishSubject.create(); + final PublishSubject ps = PublishSubject.create(); - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Runnable r1 = new Runnable() { @Override public void run() { - pp.subscribe(ts); + ps.subscribe(to); } }; Runnable r2 = new Runnable() { @Override public void run() { - pp.onComplete(); + ps.onComplete(); } }; TestHelper.race(r1, r2); - ts.awaitDone(5, TimeUnit.SECONDS) + to.awaitDone(5, TimeUnit.SECONDS) .assertResult(); } } @Test public void subscribeToAfterComplete() { - PublishSubject pp = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); - pp.onComplete(); + ps.onComplete(); - PublishSubject pp2 = PublishSubject.create(); + PublishSubject ps2 = PublishSubject.create(); - pp2.subscribe(pp); + ps2.subscribe(ps); - assertFalse(pp2.hasObservers()); + assertFalse(ps2.hasObservers()); } @Test public void subscribedTo() { - PublishSubject pp = PublishSubject.create(); - PublishSubject pp2 = PublishSubject.create(); + PublishSubject ps = PublishSubject.create(); + PublishSubject ps2 = PublishSubject.create(); - pp.subscribe(pp2); + ps.subscribe(ps2); - TestObserver ts = pp2.test(); + TestObserver to = ps2.test(); - pp.onNext(1); - pp.onNext(2); - pp.onComplete(); + ps.onNext(1); + ps.onNext(2); + ps.onComplete(); - ts.assertResult(1, 2); + to.assertResult(1, 2); } } diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java index e93b4860da..4a03449597 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java @@ -294,11 +294,11 @@ public void run() { public void testRaceForTerminalState() { final List expected = Arrays.asList(1); for (int i = 0; i < 100000; i++) { - TestObserver ts = new TestObserver(); - Observable.just(1).subscribeOn(Schedulers.computation()).cache().subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertValueSequence(expected); - ts.assertTerminated(); + TestObserver to = new TestObserver(); + Observable.just(1).subscribeOn(Schedulers.computation()).cache().subscribe(to); + to.awaitTerminalEvent(); + to.assertValueSequence(expected); + to.assertTerminated(); } } diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java index 7275df7cd0..adf238118f 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java @@ -294,11 +294,11 @@ public void run() { public void testRaceForTerminalState() { final List expected = Arrays.asList(1); for (int i = 0; i < 100000; i++) { - TestObserver ts = new TestObserver(); - Observable.just(1).subscribeOn(Schedulers.computation()).cache().subscribe(ts); - ts.awaitTerminalEvent(); - ts.assertValueSequence(expected); - ts.assertTerminated(); + TestObserver to = new TestObserver(); + Observable.just(1).subscribeOn(Schedulers.computation()).cache().subscribe(to); + to.awaitTerminalEvent(); + to.assertValueSequence(expected); + to.assertTerminated(); } } diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java index ccb5047cff..870b53e2d9 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java @@ -72,9 +72,9 @@ public void testCompletedStopsEmittingData() { Observer observerB = TestHelper.mockObserver(); Observer observerC = TestHelper.mockObserver(); Observer observerD = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observerA); + TestObserver to = new TestObserver(observerA); - channel.subscribe(ts); + channel.subscribe(to); channel.subscribe(observerB); InOrder inOrderA = inOrder(observerA); @@ -88,7 +88,7 @@ public void testCompletedStopsEmittingData() { inOrderA.verify(observerA).onNext(42); inOrderB.verify(observerB).onNext(42); - ts.dispose(); + to.dispose(); // a should receive no more inOrderA.verifyNoMoreInteractions(); @@ -223,13 +223,13 @@ public void testUnsubscribeFirstSubscriber() { ReplaySubject subject = ReplaySubject.create(); Observer observer = TestHelper.mockObserver(); - TestObserver ts = new TestObserver(observer); - subject.subscribe(ts); + TestObserver to = new TestObserver(observer); + subject.subscribe(to); subject.onNext("one"); subject.onNext("two"); - ts.dispose(); + to.dispose(); assertObservedUntilTwo(observer); Observer anotherSubscriber = TestHelper.mockObserver(); @@ -541,8 +541,8 @@ public void testReplayTimestampedDirectly() { // ReplaySubject ps = ReplaySubject.create(); // // ps.subscribe(); -// TestObserver ts = new TestObserver(); -// ps.subscribe(ts); +// TestObserver to = new TestObserver(); +// ps.subscribe(to); // // try { // ps.onError(new RuntimeException("an exception")); @@ -551,7 +551,7 @@ public void testReplayTimestampedDirectly() { // // ignore // } // // even though the onError above throws we should still receive it on the other subscriber -// assertEquals(1, ts.errors().size()); +// assertEquals(1, to.errors().size()); // } // FIXME RS subscribers can't throw @@ -564,8 +564,8 @@ public void testReplayTimestampedDirectly() { // // ps.subscribe(); // ps.subscribe(); -// TestObserver ts = new TestObserver(); -// ps.subscribe(ts); +// TestObserver to = new TestObserver(); +// ps.subscribe(to); // ps.subscribe(); // ps.subscribe(); // ps.subscribe(); @@ -578,7 +578,7 @@ public void testReplayTimestampedDirectly() { // assertEquals(5, e.getExceptions().size()); // } // // even though the onError above throws we should still receive it on the other subscriber -// assertEquals(1, ts.getOnErrorEvents().size()); +// assertEquals(1, to.getOnErrorEvents().size()); // } @Test @@ -780,8 +780,8 @@ public void testSizeAndHasAnyValueSizeBounded() { @Test public void testSizeAndHasAnyValueTimeBounded() { - TestScheduler ts = new TestScheduler(); - ReplaySubject rs = ReplaySubject.createWithTime(1, TimeUnit.SECONDS, ts); + TestScheduler to = new TestScheduler(); + ReplaySubject rs = ReplaySubject.createWithTime(1, TimeUnit.SECONDS, to); assertEquals(0, rs.size()); assertFalse(rs.hasValue()); @@ -790,7 +790,7 @@ public void testSizeAndHasAnyValueTimeBounded() { rs.onNext(i); assertEquals(1, rs.size()); assertTrue(rs.hasValue()); - ts.advanceTimeBy(2, TimeUnit.SECONDS); + to.advanceTimeBy(2, TimeUnit.SECONDS); assertEquals(0, rs.size()); assertFalse(rs.hasValue()); } @@ -864,11 +864,11 @@ public void hasSubscribers() { assertFalse(rp.hasObservers()); - TestObserver ts = rp.test(); + TestObserver to = rp.test(); assertTrue(rp.hasObservers()); - ts.cancel(); + to.cancel(); assertFalse(rp.hasObservers()); } @@ -972,21 +972,21 @@ public void capacityHint() { @Test public void subscribeCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); final ReplaySubject rp = ReplaySubject.create(); Runnable r1 = new Runnable() { @Override public void run() { - rp.subscribe(ts); + rp.subscribe(to); } }; Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; @@ -1028,11 +1028,11 @@ public void cancelUpfront() { rp.test(); rp.test(); - TestObserver ts = rp.test(true); + TestObserver to = rp.test(true); assertEquals(2, rp.observerCount()); - ts.assertEmpty(); + to.assertEmpty(); } @Test @@ -1040,20 +1040,20 @@ public void cancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final ReplaySubject rp = ReplaySubject.create(); - final TestObserver ts1 = rp.test(); - final TestObserver ts2 = rp.test(); + final TestObserver to1 = rp.test(); + final TestObserver to2 = rp.test(); Runnable r1 = new Runnable() { @Override public void run() { - ts1.cancel(); + to1.cancel(); } }; Runnable r2 = new Runnable() { @Override public void run() { - ts2.cancel(); + to2.cancel(); } }; @@ -1140,7 +1140,7 @@ public void reentrantDrain() { final ReplaySubject rp = ReplaySubject.createWithTimeAndSize(1, TimeUnit.SECONDS, scheduler, 2); - TestObserver ts = new TestObserver() { + TestObserver to = new TestObserver() { @Override public void onNext(Integer t) { if (t == 1) { @@ -1150,12 +1150,12 @@ public void onNext(Integer t) { } }; - rp.subscribe(ts); + rp.subscribe(to); rp.onNext(1); rp.onComplete(); - ts.assertResult(1, 2); + to.assertResult(1, 2); } @Test diff --git a/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java b/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java index b3d22d83c5..e1042c8680 100644 --- a/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java @@ -23,22 +23,20 @@ import io.reactivex.TestHelper; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; -import io.reactivex.internal.subscriptions.BooleanSubscription; -import io.reactivex.observers.TestObserver; +import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.subscribers.*; public class SerializedSubjectTest { @Test public void testBasic() { SerializedSubject subject = new SerializedSubject(PublishSubject. create()); - TestObserver ts = new TestObserver(); - subject.subscribe(ts); + TestObserver to = new TestObserver(); + subject.subscribe(to); subject.onNext("hello"); subject.onComplete(); - ts.awaitTerminalEvent(); - ts.assertValue("hello"); + to.awaitTerminalEvent(); + to.assertValue("hello"); } @Test @@ -407,11 +405,11 @@ public void testDontWrapSerializedSubjectAgain() { public void normal() { Subject s = PublishSubject.create().toSerialized(); - TestObserver ts = s.test(); + TestObserver to = s.test(); Observable.range(1, 10).subscribe(s); - ts.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + to.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); assertFalse(s.hasObservers()); @@ -437,7 +435,7 @@ public void onNextOnNextRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); - TestObserver ts = s.test(); + TestObserver to = s.test(); Runnable r1 = new Runnable() { @Override @@ -455,7 +453,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertSubscribed().assertNoErrors().assertNotComplete() + to.assertSubscribed().assertNoErrors().assertNotComplete() .assertValueSet(Arrays.asList(1, 2)); } } @@ -465,7 +463,7 @@ public void onNextOnErrorRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); - TestObserver ts = s.test(); + TestObserver to = s.test(); final TestException ex = new TestException(); @@ -485,10 +483,10 @@ public void run() { TestHelper.race(r1, r2); - ts.assertError(ex).assertNotComplete(); + to.assertError(ex).assertNotComplete(); - if (ts.valueCount() != 0) { - ts.assertValue(1); + if (to.valueCount() != 0) { + to.assertValue(1); } } } @@ -498,7 +496,7 @@ public void onNextOnCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); - TestObserver ts = s.test(); + TestObserver to = s.test(); Runnable r1 = new Runnable() { @Override @@ -516,10 +514,10 @@ public void run() { TestHelper.race(r1, r2); - ts.assertComplete().assertNoErrors(); + to.assertComplete().assertNoErrors(); - if (ts.valueCount() != 0) { - ts.assertValue(1); + if (to.valueCount() != 0) { + to.assertValue(1); } } } @@ -529,7 +527,7 @@ public void onNextOnSubscribeRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); - TestObserver ts = s.test(); + TestObserver to = s.test(); final Disposable bs = Disposables.empty(); @@ -549,7 +547,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertValue(1).assertNotComplete().assertNoErrors(); + to.assertValue(1).assertNotComplete().assertNoErrors(); } } @@ -558,7 +556,7 @@ public void onCompleteOnSubscribeRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); - TestObserver ts = s.test(); + TestObserver to = s.test(); final Disposable bs = Disposables.empty(); @@ -578,7 +576,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertResult(); + to.assertResult(); } } @@ -587,7 +585,7 @@ public void onCompleteOnCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); - TestObserver ts = s.test(); + TestObserver to = s.test(); Runnable r1 = new Runnable() { @Override @@ -605,7 +603,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertResult(); + to.assertResult(); } } @@ -614,7 +612,7 @@ public void onErrorOnErrorRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); - TestObserver ts = s.test(); + TestObserver to = s.test(); final TestException ex = new TestException(); @@ -636,7 +634,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { @@ -650,7 +648,7 @@ public void onSubscribeOnSubscribeRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final Subject s = PublishSubject.create().toSerialized(); - TestObserver ts = s.test(); + TestObserver to = s.test(); final Disposable bs1 = Disposables.empty(); final Disposable bs2 = Disposables.empty(); @@ -671,21 +669,7 @@ public void run() { TestHelper.race(r1, r2); - ts.assertEmpty(); + to.assertEmpty(); } } - - @Test - public void nullOnNext() { - - TestSubscriber ts = new TestSubscriber(); - - final SerializedSubscriber so = new SerializedSubscriber(ts); - - so.onSubscribe(new BooleanSubscription()); - - so.onNext(null); - - ts.assertFailureAndMessage(NullPointerException.class, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - } } diff --git a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java index c05855dcf5..41a1d3e759 100644 --- a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java @@ -39,23 +39,23 @@ protected Subject create() { public void fusionLive() { UnicastSubject ap = UnicastSubject.create(); - TestObserver ts = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); - ap.subscribe(ts); + ap.subscribe(to); - ts + to .assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.ASYNC)); + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)); - ts.assertNoValues().assertNoErrors().assertNotComplete(); + to.assertNoValues().assertNoErrors().assertNotComplete(); ap.onNext(1); - ts.assertValue(1).assertNoErrors().assertNotComplete(); + to.assertValue(1).assertNoErrors().assertNotComplete(); ap.onComplete(); - ts.assertResult(1); + to.assertResult(1); } @Test @@ -64,13 +64,13 @@ public void fusionOfflie() { ap.onNext(1); ap.onComplete(); - TestObserver ts = ObserverFusion.newTest(QueueDisposable.ANY); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); - ap.subscribe(ts); + ap.subscribe(to); - ts + to .assertOf(ObserverFusion.assertFuseable()) - .assertOf(ObserverFusion.assertFusionMode(QueueDisposable.ASYNC)) + .assertOf(ObserverFusion.assertFusionMode(QueueFuseable.ASYNC)) .assertResult(1); } @@ -79,10 +79,10 @@ public void failFast() { UnicastSubject ap = UnicastSubject.create(false); ap.onNext(1); ap.onError(new RuntimeException()); - TestObserver ts = TestObserver.create(); - ap.subscribe(ts); + TestObserver to = TestObserver.create(); + ap.subscribe(to); - ts + to .assertValueCount(0) .assertError(RuntimeException.class); } @@ -93,10 +93,10 @@ public void threeArgsFactoryFailFast() { UnicastSubject ap = UnicastSubject.create(16, noop, false); ap.onNext(1); ap.onError(new RuntimeException()); - TestObserver ts = TestObserver.create(); - ap.subscribe(ts); + TestObserver to = TestObserver.create(); + ap.subscribe(to); - ts + to .assertValueCount(0) .assertError(RuntimeException.class); } @@ -107,10 +107,10 @@ public void threeArgsFactoryDelayError() { UnicastSubject ap = UnicastSubject.create(16, noop, true); ap.onNext(1); ap.onError(new RuntimeException()); - TestObserver ts = TestObserver.create(); - ap.subscribe(ts); + TestObserver to = TestObserver.create(); + ap.subscribe(to); - ts + to .assertValueCount(1) .assertError(RuntimeException.class); } @@ -120,10 +120,10 @@ public void fusionOfflineFailFast() { UnicastSubject ap = UnicastSubject.create(false); ap.onNext(1); ap.onError(new RuntimeException()); - TestObserver ts = ObserverFusion.newTest(QueueDisposable.ANY); - ap.subscribe(ts); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); + ap.subscribe(to); - ts + to .assertValueCount(0) .assertError(RuntimeException.class); } @@ -135,10 +135,10 @@ public void fusionOfflineFailFastMultipleEvents() { ap.onNext(2); ap.onNext(3); ap.onComplete(); - TestObserver ts = ObserverFusion.newTest(QueueDisposable.ANY); - ap.subscribe(ts); + TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); + ap.subscribe(to); - ts + to .assertValueCount(3) .assertComplete(); } @@ -150,10 +150,10 @@ public void failFastMultipleEvents() { ap.onNext(2); ap.onNext(3); ap.onComplete(); - TestObserver ts = TestObserver.create(); - ap.subscribe(ts); + TestObserver to = TestObserver.create(); + ap.subscribe(to); - ts + to .assertValueCount(3) .assertComplete(); } @@ -231,12 +231,12 @@ public void run() { } }); - final TestObserver ts = up.test(); + final TestObserver to = up.test(); Runnable r1 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; @@ -299,11 +299,11 @@ public void onErrorStatePeeking() { public void rejectSyncFusion() { UnicastSubject p = UnicastSubject.create(); - TestObserver ts = ObserverFusion.newTest(QueueDisposable.SYNC); + TestObserver to = ObserverFusion.newTest(QueueFuseable.SYNC); - p.subscribe(ts); + p.subscribe(to); - ObserverFusion.assertFusion(ts, QueueDisposable.NONE); + ObserverFusion.assertFusion(to, QueueFuseable.NONE); } @Test @@ -317,7 +317,7 @@ public void cancelOnArrival() { public void multiSubscriber() { UnicastSubject p = UnicastSubject.create(); - TestObserver ts = p.test(); + TestObserver to = p.test(); p.test() .assertFailure(IllegalStateException.class); @@ -325,7 +325,7 @@ public void multiSubscriber() { p.onNext(1); p.onComplete(); - ts.assertResult(1); + to.assertResult(1); } @Test @@ -333,9 +333,9 @@ public void fusedDrainCancel() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final UnicastSubject p = UnicastSubject.create(); - final TestObserver ts = ObserverFusion.newTest(QueueSubscription.ANY); + final TestObserver to = ObserverFusion.newTest(QueueFuseable.ANY); - p.subscribe(ts); + p.subscribe(to); Runnable r1 = new Runnable() { @Override @@ -347,7 +347,7 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - ts.cancel(); + to.cancel(); } }; @@ -389,30 +389,30 @@ public void subscribeRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final UnicastSubject us = UnicastSubject.create(); - final TestObserver ts1 = new TestObserver(); - final TestObserver ts2 = new TestObserver(); + final TestObserver to1 = new TestObserver(); + final TestObserver to2 = new TestObserver(); Runnable r1 = new Runnable() { @Override public void run() { - us.subscribe(ts1); + us.subscribe(to1); } }; Runnable r2 = new Runnable() { @Override public void run() { - us.subscribe(ts2); + us.subscribe(to2); } }; TestHelper.race(r1, r2); - if (ts1.errorCount() == 0) { - ts2.assertFailure(IllegalStateException.class); + if (to1.errorCount() == 0) { + to2.assertFailure(IllegalStateException.class); } else - if (ts2.errorCount() == 0) { - ts1.assertFailure(IllegalStateException.class); + if (to2.errorCount() == 0) { + to1.assertFailure(IllegalStateException.class); } else { fail("Neither TestObserver failed"); } @@ -439,7 +439,7 @@ public void drainFusedFailFast() { UnicastSubject us = UnicastSubject.create(false); - TestObserver to = us.to(ObserverFusion.test(QueueDisposable.ANY, false)); + TestObserver to = us.to(ObserverFusion.test(QueueFuseable.ANY, false)); us.done = true; us.drainFused(to); @@ -452,7 +452,7 @@ public void drainFusedFailFastEmpty() { UnicastSubject us = UnicastSubject.create(false); - TestObserver to = us.to(ObserverFusion.test(QueueDisposable.ANY, false)); + TestObserver to = us.to(ObserverFusion.test(QueueFuseable.ANY, false)); us.drainFused(to); diff --git a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java index e70777edc5..6f2e6fc7e6 100644 --- a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java @@ -14,6 +14,7 @@ package io.reactivex.subscribers; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; @@ -25,7 +26,7 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; -import io.reactivex.internal.subscriptions.*; +import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; @@ -266,7 +267,7 @@ public void testNotificationDelay() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch running = new CountDownLatch(2); - TestSubscriber to = new TestSubscriber(new DefaultSubscriber() { + TestSubscriber ts = new TestSubscriber(new DefaultSubscriber() { @Override public void onComplete() { @@ -289,7 +290,7 @@ public void onNext(String t) { } }); - Subscriber o = serializedSubscriber(to); + Subscriber o = serializedSubscriber(ts); Future f1 = tp1.submit(new OnNextThread(o, 1, onNextCount, running)); Future f2 = tp2.submit(new OnNextThread(o, 1, onNextCount, running)); @@ -298,7 +299,7 @@ public void onNext(String t) { firstOnNext.await(); - Thread t1 = to.lastThread(); + Thread t1 = ts.lastThread(); System.out.println("first onNext on thread: " + t1); latch.countDown(); @@ -306,16 +307,16 @@ public void onNext(String t) { waitOnThreads(f1, f2); // not completed yet - assertEquals(2, to.valueCount()); + assertEquals(2, ts.valueCount()); - Thread t2 = to.lastThread(); + Thread t2 = ts.lastThread(); System.out.println("second onNext on thread: " + t2); assertSame(t1, t2); - System.out.println(to.values()); + System.out.println(ts.values()); o.onComplete(); - System.out.println(to.values()); + System.out.println(ts.values()); } } finally { tp1.shutdown(); @@ -347,7 +348,7 @@ public void onNext(String t) { @Test public void testThreadStarvation() throws InterruptedException { - TestSubscriber to = new TestSubscriber(new DefaultSubscriber() { + TestSubscriber ts = new TestSubscriber(new DefaultSubscriber() { @Override public void onComplete() { @@ -369,7 +370,7 @@ public void onNext(String t) { } }); - final Subscriber o = serializedSubscriber(to); + final Subscriber o = serializedSubscriber(ts); AtomicInteger p1 = new AtomicInteger(); AtomicInteger p2 = new AtomicInteger(); @@ -839,7 +840,7 @@ protected void captureMaxThreads() { @Ignore("Null values not permitted") public void testSerializeNull() { final AtomicReference> serial = new AtomicReference>(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { if (t != null && t == 0) { @@ -849,25 +850,25 @@ public void onNext(Integer t) { } }; - SerializedSubscriber sobs = new SerializedSubscriber(to); + SerializedSubscriber sobs = new SerializedSubscriber(ts); serial.set(sobs); sobs.onNext(0); - to.assertValues(0, null); + ts.assertValues(0, null); } @Test @Ignore("Subscribers can't throw") public void testSerializeAllowsOnError() { - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { throw new TestException(); } }; - SerializedSubscriber sobs = new SerializedSubscriber(to); + SerializedSubscriber sobs = new SerializedSubscriber(ts); try { sobs.onNext(0); @@ -875,14 +876,14 @@ public void onNext(Integer t) { sobs.onError(ex); } - to.assertError(TestException.class); + ts.assertError(TestException.class); } @Test @Ignore("Null values no longer permitted") public void testSerializeReentrantNullAndComplete() { final AtomicReference> serial = new AtomicReference>(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { serial.get().onComplete(); @@ -890,7 +891,7 @@ public void onNext(Integer t) { } }; - SerializedSubscriber sobs = new SerializedSubscriber(to); + SerializedSubscriber sobs = new SerializedSubscriber(ts); serial.set(sobs); try { @@ -899,15 +900,15 @@ public void onNext(Integer t) { sobs.onError(ex); } - to.assertError(TestException.class); - to.assertNotComplete(); + ts.assertError(TestException.class); + ts.assertNotComplete(); } @Test @Ignore("Subscribers can't throw") public void testSerializeReentrantNullAndError() { final AtomicReference> serial = new AtomicReference>(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { serial.get().onError(new RuntimeException()); @@ -915,7 +916,7 @@ public void onNext(Integer t) { } }; - SerializedSubscriber sobs = new SerializedSubscriber(to); + SerializedSubscriber sobs = new SerializedSubscriber(ts); serial.set(sobs); try { @@ -924,15 +925,15 @@ public void onNext(Integer t) { sobs.onError(ex); } - to.assertError(TestException.class); - to.assertNotComplete(); + ts.assertError(TestException.class); + ts.assertNotComplete(); } @Test @Ignore("Null values no longer permitted") public void testSerializeDrainPhaseThrows() { final AtomicReference> serial = new AtomicReference>(); - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts = new TestSubscriber() { @Override public void onNext(Integer t) { if (t != null && t == 0) { @@ -945,13 +946,13 @@ public void onNext(Integer t) { } }; - SerializedSubscriber sobs = new SerializedSubscriber(to); + SerializedSubscriber sobs = new SerializedSubscriber(ts); serial.set(sobs); sobs.onNext(0); - to.assertError(TestException.class); - to.assertNotComplete(); + ts.assertError(TestException.class); + ts.assertNotComplete(); } @Test @@ -1214,4 +1215,18 @@ public void run() { } } + + @Test + public void nullOnNext() { + + TestSubscriber ts = new TestSubscriber(); + + final SerializedSubscriber so = new SerializedSubscriber(ts); + + so.onSubscribe(new BooleanSubscription()); + + so.onNext(null); + + ts.assertFailureAndMessage(NullPointerException.class, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); + } } diff --git a/src/test/java/io/reactivex/subscribers/SubscriberFusion.java b/src/test/java/io/reactivex/subscribers/SubscriberFusion.java index 43e15e350b..02e1f3a9a5 100644 --- a/src/test/java/io/reactivex/subscribers/SubscriberFusion.java +++ b/src/test/java/io/reactivex/subscribers/SubscriberFusion.java @@ -32,12 +32,12 @@ public enum SubscriberFusion { * Use this as follows: *
                      * source
                -     * .to(SubscriberFusion.test(0, QueueSubscription.ANY, false))
                +     * .to(SubscriberFusion.test(0, QueueFuseable.ANY, false))
                      * .assertResult(0);
                      * 
                * @param the value type * @param initialRequest the initial request amount, non-negative - * @param mode the fusion mode to request, see {@link QueueSubscription} constants. + * @param mode the fusion mode to request, see {@link QueueFuseable} constants. * @param cancelled should the TestSubscriber cancelled before the subscription even happens? * @return the new Function instance */ @@ -52,7 +52,7 @@ public static Function, TestSubscriber> test( * Use this as follows: *
                      * source
                -     * .to(ObserverFusion.test(0, QueueDisposable.ANY, false))
                +     * .to(ObserverFusion.test(0, QueueFuseable.ANY, false))
                      * .assertOf(ObserverFusion.assertFuseable());
                      * 
                * @param the value type @@ -114,7 +114,7 @@ public void accept(TestSubscriber ts) throws Exception { * Use this as follows: *
                      * source
                -     * .to(ObserverFusion.test(0, QueueDisposable.ANY, false))
                +     * .to(ObserverFusion.test(0, QueueFuseable.ANY, false))
                      * .assertOf(ObserverFusion.assertNotFuseable());
                      * 
                * @param the value type @@ -135,17 +135,17 @@ public void accept(TestSubscriber ts) throws Exception { /** * Returns a Consumer that asserts on its TestSubscriber parameter that - * the upstream is Fuseable (sent a QueueSubscription subclass in onSubscribe) + * the upstream is Fuseable (sent a QueueFuseable.subclass in onSubscribe) * and the established the given fusion mode. *

                * Use this as follows: *

                      * source
                -     * .to(SubscriberFusion.test(0, QueueSubscription.ANY, false))
                -     * .assertOf(SubscriberFusion.assertFusionMode(QueueSubscription.SYNC));
                +     * .to(SubscriberFusion.test(0, QueueFuseable.ANY, false))
                +     * .assertOf(SubscriberFusion.assertFusionMode(QueueFuseable.SYNC));
                      * 
                * @param the value type - * @param mode the expected established fusion mode, see {@link QueueSubscription} constants. + * @param mode the expected established fusion mode, see {@link QueueFuseable} constants. * @return the new Consumer instance */ public static Consumer> assertFusionMode(final int mode) { @@ -156,7 +156,7 @@ public static Consumer> assertFusionMode(final int mode) { * Constructs a TestSubscriber with the given initial request and required fusion mode. * @param the value type * @param initialRequest the initial request, non-negative - * @param mode the requested fusion mode, see {@link QueueSubscription} constants + * @param mode the requested fusion mode, see {@link QueueFuseable} constants * @return the new TestSubscriber */ public static TestSubscriber newTest(long initialRequest, int mode) { @@ -168,7 +168,7 @@ public static TestSubscriber newTest(long initialRequest, int mode) { /** * Constructs a TestSubscriber with the given required fusion mode. * @param the value type - * @param mode the requested fusion mode, see {@link QueueSubscription} constants + * @param mode the requested fusion mode, see {@link QueueFuseable} constants * @return the new TestSubscriber */ public static TestSubscriber newTest(int mode) { @@ -178,7 +178,7 @@ public static TestSubscriber newTest(int mode) { } /** - * Assert that the TestSubscriber received a fuseabe QueueSubscription and + * Assert that the TestSubscriber received a fuseabe QueueFuseable.and * is in the given fusion mode. * @param the value type * @param ts the TestSubscriber instance diff --git a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java index 39a384168d..ba04b04762 100644 --- a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java @@ -31,7 +31,7 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueSubscription; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.internal.subscriptions.*; import io.reactivex.observers.BaseTestConsumer; import io.reactivex.observers.BaseTestConsumer.TestWaitStrategy; @@ -243,13 +243,13 @@ public void testNullDelegate3() { @Test public void testDelegate1() { - TestSubscriber to = new TestSubscriber(); - to.onSubscribe(EmptySubscription.INSTANCE); + TestSubscriber ts0 = new TestSubscriber(); + ts0.onSubscribe(EmptySubscription.INSTANCE); - TestSubscriber ts = new TestSubscriber(to); + TestSubscriber ts = new TestSubscriber(ts0); ts.onComplete(); - to.assertTerminated(); + ts0.assertTerminated(); } @Test @@ -710,13 +710,13 @@ public void testValueCount() { @Test(timeout = 1000) public void testOnCompletedCrashCountsDownLatch() { - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts0 = new TestSubscriber() { @Override public void onComplete() { throw new TestException(); } }; - TestSubscriber ts = new TestSubscriber(to); + TestSubscriber ts = new TestSubscriber(ts0); try { ts.onComplete(); @@ -729,13 +729,13 @@ public void onComplete() { @Test(timeout = 1000) public void testOnErrorCrashCountsDownLatch() { - TestSubscriber to = new TestSubscriber() { + TestSubscriber ts0 = new TestSubscriber() { @Override public void onError(Throwable e) { throw new TestException(); } }; - TestSubscriber ts = new TestSubscriber(to); + TestSubscriber ts = new TestSubscriber(ts0); try { ts.onError(new RuntimeException()); @@ -984,22 +984,22 @@ public void assertFuseable() { } try { - ts.assertFusionMode(QueueSubscription.SYNC); + ts.assertFusionMode(QueueFuseable.SYNC); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected } ts = TestSubscriber.create(); - ts.setInitialFusionMode(QueueSubscription.ANY); + ts.setInitialFusionMode(QueueFuseable.ANY); ts.onSubscribe(new ScalarSubscription(ts, 1)); ts.assertFuseable(); - ts.assertFusionMode(QueueSubscription.SYNC); + ts.assertFusionMode(QueueFuseable.SYNC); try { - ts.assertFusionMode(QueueSubscription.NONE); + ts.assertFusionMode(QueueFuseable.NONE); throw new RuntimeException("Should have thrown"); } catch (AssertionError ex) { // expected @@ -1195,9 +1195,9 @@ public void onNext() { @Test public void fusionModeToString() { - assertEquals("NONE", TestSubscriber.fusionModeToString(QueueSubscription.NONE)); - assertEquals("SYNC", TestSubscriber.fusionModeToString(QueueSubscription.SYNC)); - assertEquals("ASYNC", TestSubscriber.fusionModeToString(QueueSubscription.ASYNC)); + assertEquals("NONE", TestSubscriber.fusionModeToString(QueueFuseable.NONE)); + assertEquals("SYNC", TestSubscriber.fusionModeToString(QueueFuseable.SYNC)); + assertEquals("ASYNC", TestSubscriber.fusionModeToString(QueueFuseable.ASYNC)); assertEquals("Unknown(100)", TestSubscriber.fusionModeToString(100)); } @@ -1615,7 +1615,7 @@ public void onComplete() { @Test public void syncQueueThrows() { TestSubscriber ts = new TestSubscriber(); - ts.setInitialFusionMode(QueueSubscription.SYNC); + ts.setInitialFusionMode(QueueFuseable.SYNC); Flowable.range(1, 5) .map(new Function() { @@ -1626,14 +1626,14 @@ public void syncQueueThrows() { ts.assertSubscribed() .assertFuseable() - .assertFusionMode(QueueSubscription.SYNC) + .assertFusionMode(QueueFuseable.SYNC) .assertFailure(TestException.class); } @Test public void asyncQueueThrows() { TestSubscriber ts = new TestSubscriber(); - ts.setInitialFusionMode(QueueSubscription.ANY); + ts.setInitialFusionMode(QueueFuseable.ANY); UnicastProcessor up = UnicastProcessor.create(); @@ -1648,7 +1648,7 @@ public void asyncQueueThrows() { ts.assertSubscribed() .assertFuseable() - .assertFusionMode(QueueSubscription.ASYNC) + .assertFusionMode(QueueFuseable.ASYNC) .assertFailure(TestException.class); } From 90bca55c39fcc515013f2737e2f6fb6cbd2e660b Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 13 Mar 2018 21:55:04 +0100 Subject: [PATCH 135/417] 2.x: Improve coverage, fix operator logic 03/12 (#5910) --- .../exceptions/CompositeException.java | 2 +- .../internal/functions/ObjectHelper.java | 2 +- .../FlowableBufferBoundarySupplier.java | 26 +- .../flowable/FlowableBufferTimed.java | 15 +- .../flowable/FlowableDebounceTimed.java | 37 +-- .../observable/ObservableBuffer.java | 10 +- .../ObservableBufferBoundarySupplier.java | 26 +- .../observable/ObservableDebounceTimed.java | 36 +-- .../operators/single/SingleTakeUntil.java | 7 +- .../internal/util/MergerBiFunction.java | 3 +- .../exceptions/CompositeExceptionTest.java | 16 ++ .../internal/functions/ObjectHelperTest.java | 7 + .../flowable/FlowableBufferTest.java | 202 +++++++++++++++ .../flowable/FlowableDebounceTest.java | 58 +++++ .../operators/flowable/FlowableUsingTest.java | 42 +++ .../maybe/MaybeFlatMapBiSelectorTest.java | 22 ++ .../observable/ObservableBufferTest.java | 242 ++++++++++++++++++ .../observable/ObservableDebounceTest.java | 54 ++++ .../observable/ObservableUsingTest.java | 41 +++ .../operators/single/SingleFlatMapTest.java | 17 ++ .../operators/single/SingleTakeUntilTest.java | 17 ++ .../internal/util/MergerBiFunctionTest.java | 88 +++++++ .../processors/ReplayProcessorTest.java | 5 + .../subscribers/TestSubscriberTest.java | 6 + 24 files changed, 895 insertions(+), 86 deletions(-) create mode 100644 src/test/java/io/reactivex/internal/util/MergerBiFunctionTest.java diff --git a/src/main/java/io/reactivex/exceptions/CompositeException.java b/src/main/java/io/reactivex/exceptions/CompositeException.java index 0b18f8ce3f..748b964cf7 100644 --- a/src/main/java/io/reactivex/exceptions/CompositeException.java +++ b/src/main/java/io/reactivex/exceptions/CompositeException.java @@ -278,7 +278,7 @@ public int size() { * @param e the {@link Throwable} {@code e}. * @return The root cause of {@code e}. If {@code e.getCause()} returns {@code null} or {@code e}, just return {@code e} itself. */ - private Throwable getRootCause(Throwable e) { + /*private */Throwable getRootCause(Throwable e) { Throwable root = e.getCause(); if (root == null || cause == root) { return e; diff --git a/src/main/java/io/reactivex/internal/functions/ObjectHelper.java b/src/main/java/io/reactivex/internal/functions/ObjectHelper.java index b9ce56560e..f574f7f477 100644 --- a/src/main/java/io/reactivex/internal/functions/ObjectHelper.java +++ b/src/main/java/io/reactivex/internal/functions/ObjectHelper.java @@ -71,7 +71,7 @@ public static int compare(int v1, int v2) { } /** - * Compares two integer values similar to Long.compare. + * Compares two long values similar to Long.compare. * @param v1 the first value * @param v2 the second value * @return the comparison result diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundarySupplier.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundarySupplier.java index af98d86cfe..a4cdcb8ced 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundarySupplier.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundarySupplier.java @@ -196,24 +196,20 @@ void next() { BufferBoundarySubscriber bs = new BufferBoundarySubscriber(this); - Disposable o = other.get(); - - if (!other.compareAndSet(o, bs)) { - return; - } - - U b; - synchronized (this) { - b = buffer; - if (b == null) { - return; + if (DisposableHelper.replace(other, bs)) { + U b; + synchronized (this) { + b = buffer; + if (b == null) { + return; + } + buffer = next; } - buffer = next; - } - boundary.subscribe(bs); + boundary.subscribe(bs); - fastPathEmitMax(b, false, this); + fastPathEmitMax(b, false, this); + } } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java index 2597a6d140..8c220a506a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java @@ -177,8 +177,8 @@ public void request(long n) { @Override public void cancel() { + cancelled = true; s.cancel(); - DisposableHelper.dispose(timer); } @@ -199,14 +199,10 @@ public void run() { synchronized (this) { current = buffer; - if (current != null) { - buffer = next; + if (current == null) { + return; } - } - - if (current == null) { - DisposableHelper.dispose(timer); - return; + buffer = next; } fastPathEmitMax(current, false, this); @@ -324,9 +320,10 @@ public void request(long n) { @Override public void cancel() { - clear(); + cancelled = true; s.cancel(); w.dispose(); + clear(); } void clear() { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java index 3f667dcb09..aea5af63e7 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java @@ -58,7 +58,7 @@ static final class DebounceTimedSubscriber extends AtomicLong Subscription s; - final SequentialDisposable timer = new SequentialDisposable(); + Disposable timer; volatile long index; @@ -88,17 +88,15 @@ public void onNext(T t) { long idx = index + 1; index = idx; - Disposable d = timer.get(); + Disposable d = timer; if (d != null) { d.dispose(); } DebounceEmitter de = new DebounceEmitter(t, idx, this); - if (timer.replace(de)) { - d = worker.schedule(de, timeout, unit); - - de.setResource(d); - } + timer = de; + d = worker.schedule(de, timeout, unit); + de.setResource(d); } @Override @@ -108,6 +106,10 @@ public void onError(Throwable t) { return; } done = true; + Disposable d = timer; + if (d != null) { + d.dispose(); + } actual.onError(t); worker.dispose(); } @@ -119,17 +121,18 @@ public void onComplete() { } done = true; - Disposable d = timer.get(); - if (!DisposableHelper.isDisposed(d)) { - @SuppressWarnings("unchecked") - DebounceEmitter de = (DebounceEmitter)d; - if (de != null) { - de.emit(); - } - DisposableHelper.dispose(timer); - actual.onComplete(); - worker.dispose(); + Disposable d = timer; + if (d != null) { + d.dispose(); + } + @SuppressWarnings("unchecked") + DebounceEmitter de = (DebounceEmitter)d; + if (de != null) { + de.emit(); } + + actual.onComplete(); + worker.dispose(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java index a75c0ce07d..9471c0b24a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java @@ -127,11 +127,13 @@ public void onError(Throwable t) { @Override public void onComplete() { U b = buffer; - buffer = null; - if (b != null && !b.isEmpty()) { - actual.onNext(b); + if (b != null) { + buffer = null; + if (!b.isEmpty()) { + actual.onNext(b); + } + actual.onComplete(); } - actual.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundarySupplier.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundarySupplier.java index ce97d264fc..15f0dd0a1c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundarySupplier.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundarySupplier.java @@ -190,24 +190,20 @@ void next() { BufferBoundaryObserver bs = new BufferBoundaryObserver(this); - Disposable o = other.get(); - - if (!other.compareAndSet(o, bs)) { - return; - } - - U b; - synchronized (this) { - b = buffer; - if (b == null) { - return; + if (DisposableHelper.replace(other, bs)) { + U b; + synchronized (this) { + b = buffer; + if (b == null) { + return; + } + buffer = next; } - buffer = next; - } - boundary.subscribe(bs); + boundary.subscribe(bs); - fastPathEmit(b, false, this); + fastPathEmit(b, false, this); + } } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java index 7cdd59e3bb..dcc56288a7 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java @@ -51,7 +51,7 @@ static final class DebounceTimedObserver Disposable s; - final AtomicReference timer = new AtomicReference(); + Disposable timer; volatile long index; @@ -80,18 +80,15 @@ public void onNext(T t) { long idx = index + 1; index = idx; - Disposable d = timer.get(); + Disposable d = timer; if (d != null) { d.dispose(); } DebounceEmitter de = new DebounceEmitter(t, idx, this); - if (timer.compareAndSet(d, de)) { - d = worker.schedule(de, timeout, unit); - - de.setResource(d); - } - + timer = de; + d = worker.schedule(de, timeout, unit); + de.setResource(d); } @Override @@ -100,6 +97,10 @@ public void onError(Throwable t) { RxJavaPlugins.onError(t); return; } + Disposable d = timer; + if (d != null) { + d.dispose(); + } done = true; actual.onError(t); worker.dispose(); @@ -112,16 +113,17 @@ public void onComplete() { } done = true; - Disposable d = timer.get(); - if (d != DisposableHelper.DISPOSED) { - @SuppressWarnings("unchecked") - DebounceEmitter de = (DebounceEmitter)d; - if (de != null) { - de.run(); - } - actual.onComplete(); - worker.dispose(); + Disposable d = timer; + if (d != null) { + d.dispose(); } + @SuppressWarnings("unchecked") + DebounceEmitter de = (DebounceEmitter)d; + if (de != null) { + de.run(); + } + actual.onComplete(); + worker.dispose(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java b/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java index 6d1183e80c..4eaa6f7620 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java @@ -85,12 +85,9 @@ public void onSubscribe(Disposable d) { public void onSuccess(T value) { other.dispose(); - Disposable a = get(); + Disposable a = getAndSet(DisposableHelper.DISPOSED); if (a != DisposableHelper.DISPOSED) { - a = getAndSet(DisposableHelper.DISPOSED); - if (a != DisposableHelper.DISPOSED) { - actual.onSuccess(value); - } + actual.onSuccess(value); } } diff --git a/src/main/java/io/reactivex/internal/util/MergerBiFunction.java b/src/main/java/io/reactivex/internal/util/MergerBiFunction.java index e3ad1d1c60..ba13a4b7a6 100644 --- a/src/main/java/io/reactivex/internal/util/MergerBiFunction.java +++ b/src/main/java/io/reactivex/internal/util/MergerBiFunction.java @@ -58,8 +58,7 @@ public List apply(List a, List b) throws Exception { while (at.hasNext()) { both.add(at.next()); } - } else - if (s2 != null) { + } else { both.add(s2); while (bt.hasNext()) { both.add(bt.next()); diff --git a/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java b/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java index ec969189a1..4b9f96ba8a 100644 --- a/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java +++ b/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java @@ -349,6 +349,22 @@ public void badException() { assertSame(e, new CompositeException(e).getCause().getCause()); assertSame(e, new CompositeException(new RuntimeException(e)).getCause().getCause().getCause()); } + + @Test + public void rootCauseEval() { + final TestException ex0 = new TestException(); + Throwable throwable = new Throwable() { + + private static final long serialVersionUID = 3597694032723032281L; + + @Override + public synchronized Throwable getCause() { + return ex0; + } + }; + CompositeException ex = new CompositeException(throwable); + assertSame(ex, ex.getRootCause(ex)); + } } final class BadException extends Throwable { diff --git a/src/test/java/io/reactivex/internal/functions/ObjectHelperTest.java b/src/test/java/io/reactivex/internal/functions/ObjectHelperTest.java index aefbfea49c..ce5a2b340d 100644 --- a/src/test/java/io/reactivex/internal/functions/ObjectHelperTest.java +++ b/src/test/java/io/reactivex/internal/functions/ObjectHelperTest.java @@ -58,4 +58,11 @@ public void compare() { assertEquals(0, ObjectHelper.compare(0, 0)); assertEquals(1, ObjectHelper.compare(2, 0)); } + + @Test + public void compareLong() { + assertEquals(-1, ObjectHelper.compare(0L, 2L)); + assertEquals(0, ObjectHelper.compare(0L, 0L)); + assertEquals(1, ObjectHelper.compare(2L, 0L)); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index 3a32a81c38..c8c75031bc 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -30,7 +30,10 @@ import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.*; import io.reactivex.functions.*; +import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.flowable.FlowableBufferBoundarySupplier.BufferBoundarySupplierSubscriber; +import io.reactivex.internal.operators.flowable.FlowableBufferTimed.*; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.*; @@ -2557,4 +2560,203 @@ protected void subscribeActual(Subscriber s) { RxJavaPlugins.reset(); } } + + @Test + public void bufferBoundarySupplierDisposed() { + TestSubscriber> ts = new TestSubscriber>(); + BufferBoundarySupplierSubscriber, Integer> sub = + new BufferBoundarySupplierSubscriber, Integer>( + ts, Functions.justCallable((List)new ArrayList()), + Functions.justCallable(Flowable.never()) + ); + + BooleanSubscription bs = new BooleanSubscription(); + + sub.onSubscribe(bs); + + assertFalse(sub.isDisposed()); + + sub.dispose(); + + assertTrue(sub.isDisposed()); + + sub.next(); + + assertSame(DisposableHelper.DISPOSED, sub.other.get()); + + sub.cancel(); + sub.cancel(); + + assertTrue(bs.isCancelled()); + } + + @Test + public void bufferBoundarySupplierBufferAlreadyCleared() { + TestSubscriber> ts = new TestSubscriber>(); + BufferBoundarySupplierSubscriber, Integer> sub = + new BufferBoundarySupplierSubscriber, Integer>( + ts, Functions.justCallable((List)new ArrayList()), + Functions.justCallable(Flowable.never()) + ); + + BooleanSubscription bs = new BooleanSubscription(); + + sub.onSubscribe(bs); + + sub.buffer = null; + + sub.next(); + + sub.onNext(1); + + sub.onComplete(); + } + + @Test + public void timedDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>>() { + @Override + public Publisher> apply(Flowable f) + throws Exception { + return f.buffer(1, TimeUnit.SECONDS); + } + }); + } + + @Test + public void timedCancelledUpfront() { + TestScheduler sch = new TestScheduler(); + + TestSubscriber> ts = Flowable.never() + .buffer(1, TimeUnit.MILLISECONDS, sch) + .test(1L, true); + + sch.advanceTimeBy(1, TimeUnit.MILLISECONDS); + + ts.assertEmpty(); + } + + @Test + public void timedInternalState() { + TestScheduler sch = new TestScheduler(); + + TestSubscriber> ts = new TestSubscriber>(); + + BufferExactUnboundedSubscriber> sub = new BufferExactUnboundedSubscriber>( + ts, Functions.justCallable((List)new ArrayList()), 1, TimeUnit.SECONDS, sch); + + sub.onSubscribe(new BooleanSubscription()); + + assertFalse(sub.isDisposed()); + + sub.onError(new TestException()); + sub.onNext(1); + sub.onComplete(); + + sub.run(); + + sub.dispose(); + + assertTrue(sub.isDisposed()); + + sub.buffer = new ArrayList(); + sub.enter(); + sub.onComplete(); + } + + @Test + public void timedSkipDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>>() { + @Override + public Publisher> apply(Flowable f) + throws Exception { + return f.buffer(2, 1, TimeUnit.SECONDS); + } + }); + } + + @Test + public void timedSizedDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>>() { + @Override + public Publisher> apply(Flowable f) + throws Exception { + return f.buffer(2, TimeUnit.SECONDS, 10); + } + }); + } + + @Test + public void timedSkipInternalState() { + TestScheduler sch = new TestScheduler(); + + TestSubscriber> ts = new TestSubscriber>(); + + BufferSkipBoundedSubscriber> sub = new BufferSkipBoundedSubscriber>( + ts, Functions.justCallable((List)new ArrayList()), 1, 1, TimeUnit.SECONDS, sch.createWorker()); + + sub.onSubscribe(new BooleanSubscription()); + + sub.enter(); + sub.onComplete(); + + sub.cancel(); + + sub.run(); + } + + @Test + public void timedSkipCancelWhenSecondBuffer() { + TestScheduler sch = new TestScheduler(); + + final TestSubscriber> ts = new TestSubscriber>(); + + BufferSkipBoundedSubscriber> sub = new BufferSkipBoundedSubscriber>( + ts, new Callable>() { + int calls; + @Override + public List call() throws Exception { + if (++calls == 2) { + ts.cancel(); + } + return new ArrayList(); + } + }, 1, 1, TimeUnit.SECONDS, sch.createWorker()); + + sub.onSubscribe(new BooleanSubscription()); + + sub.run(); + + assertTrue(ts.isCancelled()); + } + + @Test + public void timedSizeBufferAlreadyCleared() { + TestScheduler sch = new TestScheduler(); + + TestSubscriber> ts = new TestSubscriber>(); + + BufferExactBoundedSubscriber> sub = + new BufferExactBoundedSubscriber>( + ts, Functions.justCallable((List)new ArrayList()), + 1, TimeUnit.SECONDS, 1, false, sch.createWorker()) + ; + + BooleanSubscription bs = new BooleanSubscription(); + + sub.onSubscribe(bs); + + sub.producerIndex++; + + sub.run(); + + assertFalse(sub.isDisposed()); + + sub.enter(); + sub.onComplete(); + + assertTrue(sub.isDisposed()); + + sub.run(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java index fbd14694f0..c152929e1a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java @@ -30,6 +30,7 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.flowable.FlowableDebounceTimed.*; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.*; @@ -487,4 +488,61 @@ protected void subscribeActual(Subscriber subscriber) { public void badRequestReported() { TestHelper.assertBadRequestReported(Flowable.never().debounce(Functions.justFunction(Flowable.never()))); } + + @Test + public void timedDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) + throws Exception { + return f.debounce(1, TimeUnit.SECONDS); + } + }); + } + + @Test + public void timedDisposedIgnoredBySource() { + final TestSubscriber ts = new TestSubscriber(); + + new Flowable() { + @Override + protected void subscribeActual( + org.reactivestreams.Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + ts.cancel(); + s.onNext(1); + s.onComplete(); + } + } + .debounce(1, TimeUnit.SECONDS) + .subscribe(ts); + } + + @Test + public void timedBadRequest() { + TestHelper.assertBadRequestReported(Flowable.never().debounce(1, TimeUnit.SECONDS)); + } + + @Test + public void timedLateEmit() { + TestSubscriber ts = new TestSubscriber(); + DebounceTimedSubscriber sub = new DebounceTimedSubscriber( + ts, 1, TimeUnit.SECONDS, new TestScheduler().createWorker()); + + sub.onSubscribe(new BooleanSubscription()); + + DebounceEmitter de = new DebounceEmitter(1, 50, sub); + de.emit(); + de.emit(); + + ts.assertEmpty(); + } + + @Test + public void timedError() { + Flowable.error(new TestException()) + .debounce(1, TimeUnit.SECONDS) + .test() + .assertFailure(TestException.class); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java index 4638086065..e836796924 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java @@ -29,6 +29,7 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subscribers.TestSubscriber; @@ -637,4 +638,45 @@ public void sourceSupplierReturnsNull() { .assertFailureAndMessage(NullPointerException.class, "The sourceSupplier returned a null Publisher") ; } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Flowable>() { + @Override + public Flowable apply(Flowable o) + throws Exception { + return Flowable.using(Functions.justCallable(1), Functions.justFunction(o), Functions.emptyConsumer()); + } + }); + } + + @Test + public void eagerDisposedOnComplete() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.using(Functions.justCallable(1), Functions.justFunction(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ts.cancel(); + observer.onComplete(); + } + }), Functions.emptyConsumer(), true) + .subscribe(ts); + } + + @Test + public void eagerDisposedOnError() { + final TestSubscriber ts = new TestSubscriber(); + + Flowable.using(Functions.justCallable(1), Functions.justFunction(new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + ts.cancel(); + observer.onError(new TestException()); + } + }), Functions.emptyConsumer(), true) + .subscribe(ts); + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapBiSelectorTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapBiSelectorTest.java index a618ddc94a..f817bfa839 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapBiSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapBiSelectorTest.java @@ -20,6 +20,7 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; +import io.reactivex.observers.TestObserver; import io.reactivex.processors.PublishProcessor; public class MaybeFlatMapBiSelectorTest { @@ -210,4 +211,25 @@ public Object apply(Integer a, Integer b) throws Exception { .test() .assertFailure(NullPointerException.class); } + + @Test + public void mapperCancels() { + final TestObserver to = new TestObserver(); + + Maybe.just(1) + .flatMap(new Function>() { + @Override + public MaybeSource apply(Integer v) throws Exception { + to.cancel(); + return Maybe.just(2); + } + }, new BiFunction() { + @Override + public Integer apply(Integer a, Integer b) throws Exception { + throw new IllegalStateException(); + } + }) + .subscribeWith(to) + .assertEmpty(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 1e7407c121..3a02b31423 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -31,7 +31,11 @@ import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.*; +import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.observable.ObservableBuffer.BufferExactObserver; +import io.reactivex.internal.operators.observable.ObservableBufferBoundarySupplier.BufferBoundarySupplierObserver; +import io.reactivex.internal.operators.observable.ObservableBufferTimed.*; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; @@ -1884,4 +1888,242 @@ protected void subscribeActual(Observer s) { RxJavaPlugins.reset(); } } + + @Test + public void bufferBoundarySupplierDisposed() { + TestObserver> to = new TestObserver>(); + BufferBoundarySupplierObserver, Integer> sub = + new BufferBoundarySupplierObserver, Integer>( + to, Functions.justCallable((List)new ArrayList()), + Functions.justCallable(Observable.never()) + ); + + Disposable bs = Disposables.empty(); + + sub.onSubscribe(bs); + + assertFalse(sub.isDisposed()); + + sub.dispose(); + + assertTrue(sub.isDisposed()); + + sub.next(); + + assertSame(DisposableHelper.DISPOSED, sub.other.get()); + + sub.dispose(); + sub.dispose(); + + assertTrue(bs.isDisposed()); + } + + @Test + public void bufferBoundarySupplierBufferAlreadyCleared() { + TestObserver> to = new TestObserver>(); + BufferBoundarySupplierObserver, Integer> sub = + new BufferBoundarySupplierObserver, Integer>( + to, Functions.justCallable((List)new ArrayList()), + Functions.justCallable(Observable.never()) + ); + + Disposable bs = Disposables.empty(); + + sub.onSubscribe(bs); + + sub.buffer = null; + + sub.next(); + + sub.onNext(1); + + sub.onComplete(); + } + + @Test + public void timedDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>>() { + @Override + public Observable> apply(Observable f) + throws Exception { + return f.buffer(1, TimeUnit.SECONDS); + } + }); + } + + @Test + public void timedCancelledUpfront() { + TestScheduler sch = new TestScheduler(); + + TestObserver> to = Observable.never() + .buffer(1, TimeUnit.MILLISECONDS, sch) + .test(true); + + sch.advanceTimeBy(1, TimeUnit.MILLISECONDS); + + to.assertEmpty(); + } + + @Test + public void timedInternalState() { + TestScheduler sch = new TestScheduler(); + + TestObserver> to = new TestObserver>(); + + BufferExactUnboundedObserver> sub = new BufferExactUnboundedObserver>( + to, Functions.justCallable((List)new ArrayList()), 1, TimeUnit.SECONDS, sch); + + sub.onSubscribe(Disposables.empty()); + + assertFalse(sub.isDisposed()); + + sub.onError(new TestException()); + sub.onNext(1); + sub.onComplete(); + + sub.run(); + + sub.dispose(); + + assertTrue(sub.isDisposed()); + + sub.buffer = new ArrayList(); + sub.enter(); + sub.onComplete(); + } + + @Test + public void timedSkipDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>>() { + @Override + public Observable> apply(Observable f) + throws Exception { + return f.buffer(2, 1, TimeUnit.SECONDS); + } + }); + } + + @Test + public void timedSizedDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>>() { + @Override + public Observable> apply(Observable f) + throws Exception { + return f.buffer(2, TimeUnit.SECONDS, 10); + } + }); + } + + @Test + public void timedSkipInternalState() { + TestScheduler sch = new TestScheduler(); + + TestObserver> to = new TestObserver>(); + + BufferSkipBoundedObserver> sub = new BufferSkipBoundedObserver>( + to, Functions.justCallable((List)new ArrayList()), 1, 1, TimeUnit.SECONDS, sch.createWorker()); + + sub.onSubscribe(Disposables.empty()); + + sub.enter(); + sub.onComplete(); + + sub.dispose(); + + sub.run(); + } + + @Test + public void timedSkipCancelWhenSecondBuffer() { + TestScheduler sch = new TestScheduler(); + + final TestObserver> to = new TestObserver>(); + + BufferSkipBoundedObserver> sub = new BufferSkipBoundedObserver>( + to, new Callable>() { + int calls; + @Override + public List call() throws Exception { + if (++calls == 2) { + to.cancel(); + } + return new ArrayList(); + } + }, 1, 1, TimeUnit.SECONDS, sch.createWorker()); + + sub.onSubscribe(Disposables.empty()); + + sub.run(); + + assertTrue(to.isCancelled()); + } + + @Test + public void timedSizeBufferAlreadyCleared() { + TestScheduler sch = new TestScheduler(); + + TestObserver> to = new TestObserver>(); + + BufferExactBoundedObserver> sub = + new BufferExactBoundedObserver>( + to, Functions.justCallable((List)new ArrayList()), + 1, TimeUnit.SECONDS, 1, false, sch.createWorker()) + ; + + Disposable bs = Disposables.empty(); + + sub.onSubscribe(bs); + + sub.producerIndex++; + + sub.run(); + + assertFalse(sub.isDisposed()); + + sub.enter(); + sub.onComplete(); + + sub.dispose(); + + assertTrue(sub.isDisposed()); + + sub.run(); + + sub.onNext(1); + } + + @Test + public void bufferExactDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, ObservableSource>>() { + @Override + public ObservableSource> apply(Observable o) + throws Exception { + return o.buffer(1); + } + }); + } + + @Test + public void bufferExactState() { + TestObserver> to = new TestObserver>(); + + BufferExactObserver> sub = new BufferExactObserver>( + to, 1, Functions.justCallable((List)new ArrayList()) + ); + + sub.onComplete(); + sub.onNext(1); + sub.onComplete(); + } + + @Test + public void bufferSkipDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, ObservableSource>>() { + @Override + public ObservableSource> apply(Observable o) + throws Exception { + return o.buffer(1, 2); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java index 95cd9a1163..26ce6caa9c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java @@ -24,12 +24,14 @@ import org.junit.*; import org.mockito.InOrder; +import org.reactivestreams.Publisher; import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.observable.ObservableDebounceTimed.*; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.TestScheduler; @@ -450,4 +452,56 @@ protected void subscribeActual(Observer observer) { to .assertResult(2); } + + @Test + public void timedDoubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) + throws Exception { + return f.debounce(1, TimeUnit.SECONDS); + } + }); + } + + @Test + public void timedDisposedIgnoredBySource() { + final TestObserver to = new TestObserver(); + + new Observable() { + @Override + protected void subscribeActual( + Observer s) { + s.onSubscribe(Disposables.empty()); + to.cancel(); + s.onNext(1); + s.onComplete(); + } + } + .debounce(1, TimeUnit.SECONDS) + .subscribe(to); + } + + @Test + public void timedLateEmit() { + TestObserver to = new TestObserver(); + DebounceTimedObserver sub = new DebounceTimedObserver( + to, 1, TimeUnit.SECONDS, new TestScheduler().createWorker()); + + sub.onSubscribe(Disposables.empty()); + + DebounceEmitter de = new DebounceEmitter(1, 50, sub); + de.run(); + de.run(); + + to.assertEmpty(); + } + + @Test + public void timedError() { + Observable.error(new TestException()) + .debounce(1, TimeUnit.SECONDS) + .test() + .assertFailure(TestException.class); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java index 2bf61565d9..4276e3bc95 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java @@ -567,4 +567,45 @@ public void sourceSupplierReturnsNull() { .assertFailureAndMessage(NullPointerException.class, "The sourceSupplier returned a null ObservableSource") ; } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, ObservableSource>() { + @Override + public ObservableSource apply(Observable o) + throws Exception { + return Observable.using(Functions.justCallable(1), Functions.justFunction(o), Functions.emptyConsumer()); + } + }); + } + + @Test + public void eagerDisposedOnComplete() { + final TestObserver to = new TestObserver(); + + Observable.using(Functions.justCallable(1), Functions.justFunction(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + to.cancel(); + observer.onComplete(); + } + }), Functions.emptyConsumer(), true) + .subscribe(to); + } + + @Test + public void eagerDisposedOnError() { + final TestObserver to = new TestObserver(); + + Observable.using(Functions.justCallable(1), Functions.justFunction(new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + to.cancel(); + observer.onError(new TestException()); + } + }), Functions.emptyConsumer(), true) + .subscribe(to); + } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java index 4dfb835102..c2b1ecea91 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java @@ -223,4 +223,21 @@ public SingleSource apply(Integer v) throws Exception { .test() .assertFailure(TestException.class); } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeSingle(new Function, SingleSource>() { + @Override + public SingleSource apply(Single s) + throws Exception { + return s.flatMap(new Function>() { + @Override + public SingleSource apply(Object v) + throws Exception { + return Single.just(v); + } + }); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java index 07dd073f35..42633a9fcc 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java @@ -19,9 +19,11 @@ import java.util.concurrent.CancellationException; import org.junit.Test; +import org.reactivestreams.Subscriber; import io.reactivex.*; import io.reactivex.exceptions.TestException; +import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; @@ -274,4 +276,19 @@ public void otherSignalsAndCompletes() { RxJavaPlugins.reset(); } } + + @Test + public void flowableCancelDelayed() { + Single.never() + .takeUntil(new Flowable() { + @Override + protected void subscribeActual(Subscriber s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onNext(2); + } + }) + .test() + .assertFailure(CancellationException.class); + } } diff --git a/src/test/java/io/reactivex/internal/util/MergerBiFunctionTest.java b/src/test/java/io/reactivex/internal/util/MergerBiFunctionTest.java new file mode 100644 index 0000000000..db84d4cf1a --- /dev/null +++ b/src/test/java/io/reactivex/internal/util/MergerBiFunctionTest.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.util; + +import static org.junit.Assert.assertEquals; + +import java.util.*; + +import org.junit.Test; + +public class MergerBiFunctionTest { + + @Test + public void firstEmpty() throws Exception { + MergerBiFunction merger = new MergerBiFunction(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o1.compareTo(o2); + } + }); + List list = merger.apply(Collections.emptyList(), Arrays.asList(3, 5)); + + assertEquals(Arrays.asList(3, 5), list); + } + + @Test + public void bothEmpty() throws Exception { + MergerBiFunction merger = new MergerBiFunction(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o1.compareTo(o2); + } + }); + List list = merger.apply(Collections.emptyList(), Collections.emptyList()); + + assertEquals(Collections.emptyList(), list); + } + + @Test + public void secondEmpty() throws Exception { + MergerBiFunction merger = new MergerBiFunction(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o1.compareTo(o2); + } + }); + List list = merger.apply(Arrays.asList(2, 4), Collections.emptyList()); + + assertEquals(Arrays.asList(2, 4), list); + } + + @Test + public void sameSize() throws Exception { + MergerBiFunction merger = new MergerBiFunction(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o1.compareTo(o2); + } + }); + List list = merger.apply(Arrays.asList(2, 4), Arrays.asList(3, 5)); + + assertEquals(Arrays.asList(2, 3, 4, 5), list); + } + + @Test + public void sameSizeReverse() throws Exception { + MergerBiFunction merger = new MergerBiFunction(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o1.compareTo(o2); + } + }); + List list = merger.apply(Arrays.asList(3, 5), Arrays.asList(2, 4)); + + assertEquals(Arrays.asList(2, 3, 4, 5), list); + } +} diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index a80d1d0b83..20e6b9a8df 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -1678,4 +1678,9 @@ public void noHeadRetentionTime() { assertSame(o, buf.head); } + + @Test + public void invalidRequest() { + TestHelper.assertBadRequestReported(ReplayProcessor.create()); + } } diff --git a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java index ba04b04762..5e4082c399 100644 --- a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java @@ -2059,4 +2059,10 @@ public void assertValuesOnlyThrowsWhenErrored() { // expected } } + + @Test(timeout = 1000) + public void awaitCount0() { + TestSubscriber ts = TestSubscriber.create(); + ts.awaitCount(0, TestWaitStrategy.SLEEP_1MS, 0); + } } From 4bc516c066487818f7796b1e5cd57a3b582c832c Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 14 Mar 2018 23:36:21 +0100 Subject: [PATCH 136/417] 2.x: Benchmark X-Map-Z operators (#5914) --- .../java/io/reactivex/FlattenRangePerf.java | 69 +++ ... FlowableFlatMapCompletableAsyncPerf.java} | 2 +- src/jmh/java/io/reactivex/MemoryPerf.java | 517 ++++++++++++++++++ .../FlowableConcatMapCompletablePerf.java | 88 +++ .../FlowableConcatMapMaybeEmptyPerf.java | 88 +++ .../xmapz/FlowableConcatMapMaybePerf.java | 88 +++ .../xmapz/FlowableConcatMapSinglePerf.java | 88 +++ .../xmapz/FlowableFlatMapCompletablePerf.java | 88 +++ .../xmapz/FlowableFlatMapMaybeEmptyPerf.java | 88 +++ .../xmapz/FlowableFlatMapMaybePerf.java | 88 +++ .../xmapz/FlowableFlatMapSinglePerf.java | 88 +++ .../FlowableSwitchMapCompletablePerf.java | 88 +++ .../FlowableSwitchMapMaybeEmptyPerf.java | 88 +++ .../xmapz/FlowableSwitchMapMaybePerf.java | 88 +++ .../xmapz/FlowableSwitchMapSinglePerf.java | 88 +++ .../ObservableConcatMapCompletablePerf.java | 87 +++ .../ObservableConcatMapMaybeEmptyPerf.java | 87 +++ .../xmapz/ObservableConcatMapMaybePerf.java | 87 +++ .../xmapz/ObservableConcatMapSinglePerf.java | 87 +++ .../ObservableFlatMapCompletablePerf.java | 87 +++ .../ObservableFlatMapMaybeEmptyPerf.java | 87 +++ .../xmapz/ObservableFlatMapMaybePerf.java | 87 +++ .../xmapz/ObservableFlatMapSinglePerf.java | 87 +++ .../ObservableSwitchMapCompletablePerf.java | 87 +++ .../ObservableSwitchMapMaybeEmptyPerf.java | 87 +++ .../xmapz/ObservableSwitchMapMaybePerf.java | 87 +++ .../xmapz/ObservableSwitchMapSinglePerf.java | 87 +++ 27 files changed, 2687 insertions(+), 1 deletion(-) create mode 100644 src/jmh/java/io/reactivex/FlattenRangePerf.java rename src/jmh/java/io/reactivex/{FlowableFlatMapCompletablePerf.java => FlowableFlatMapCompletableAsyncPerf.java} (97%) create mode 100644 src/jmh/java/io/reactivex/MemoryPerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableConcatMapCompletablePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableConcatMapMaybeEmptyPerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableConcatMapMaybePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableConcatMapSinglePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableFlatMapCompletablePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableFlatMapMaybeEmptyPerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableFlatMapMaybePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableFlatMapSinglePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapCompletablePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapMaybeEmptyPerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapMaybePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapSinglePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableConcatMapCompletablePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableConcatMapMaybeEmptyPerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableConcatMapMaybePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableConcatMapSinglePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableFlatMapCompletablePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableFlatMapMaybeEmptyPerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableFlatMapMaybePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableFlatMapSinglePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapCompletablePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapMaybeEmptyPerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapMaybePerf.java create mode 100644 src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapSinglePerf.java diff --git a/src/jmh/java/io/reactivex/FlattenRangePerf.java b/src/jmh/java/io/reactivex/FlattenRangePerf.java new file mode 100644 index 0000000000..1d2fe51546 --- /dev/null +++ b/src/jmh/java/io/reactivex/FlattenRangePerf.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlattenRangePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int times; + + Flowable flowable; + + Observable observable; + + @Setup + public void setup() { + Integer[] array = new Integer[times]; + Arrays.fill(array, 777); + + final Iterable list = Arrays.asList(1, 2); + + flowable = Flowable.fromArray(array).flatMapIterable(new Function>() { + @Override + public Iterable apply(Integer v) throws Exception { + return list; + } + }); + + observable = Observable.fromArray(array).flatMapIterable(new Function>() { + @Override + public Iterable apply(Integer v) throws Exception { + return list; + } + }); + } + + @Benchmark + public void flowable(Blackhole bh) { + flowable.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void observable(Blackhole bh) { + observable.subscribe(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/FlowableFlatMapCompletablePerf.java b/src/jmh/java/io/reactivex/FlowableFlatMapCompletableAsyncPerf.java similarity index 97% rename from src/jmh/java/io/reactivex/FlowableFlatMapCompletablePerf.java rename to src/jmh/java/io/reactivex/FlowableFlatMapCompletableAsyncPerf.java index ec846d35eb..6dd4dcd263 100644 --- a/src/jmh/java/io/reactivex/FlowableFlatMapCompletablePerf.java +++ b/src/jmh/java/io/reactivex/FlowableFlatMapCompletableAsyncPerf.java @@ -29,7 +29,7 @@ @OutputTimeUnit(TimeUnit.SECONDS) @Fork(value = 1) @State(Scope.Thread) -public class FlowableFlatMapCompletablePerf implements Action { +public class FlowableFlatMapCompletableAsyncPerf implements Action { @Param({"1", "10", "100", "1000", "10000", "100000", "1000000"}) int items; diff --git a/src/jmh/java/io/reactivex/MemoryPerf.java b/src/jmh/java/io/reactivex/MemoryPerf.java new file mode 100644 index 0000000000..ba92a89b78 --- /dev/null +++ b/src/jmh/java/io/reactivex/MemoryPerf.java @@ -0,0 +1,517 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import java.lang.management.ManagementFactory; +import java.util.concurrent.Callable; + +import org.reactivestreams.Subscription; + +import io.reactivex.disposables.Disposable; +import io.reactivex.functions.*; + +/** + * Measure various prepared flows about their memory usage and print the result + * in a JMH compatible format; run {@link #main(String[])}. + */ +public final class MemoryPerf { + + private MemoryPerf() { } + + static long memoryUse() { + return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + } + + static final class MyRx2Subscriber implements FlowableSubscriber { + + org.reactivestreams.Subscription s; + + @Override + public void onSubscribe(Subscription s) { + this.s = s; + } + + @Override + public void onComplete() { + + } + + @Override + public void onError(Throwable e) { + + } + + @Override + public void onNext(Object t) { + + } + } + + static final class MyRx2Observer implements io.reactivex.Observer, io.reactivex.SingleObserver, + io.reactivex.MaybeObserver, io.reactivex.CompletableObserver { + + Disposable s; + + @Override + public void onSubscribe(Disposable s) { + this.s = s; + } + + @Override + public void onComplete() { + + } + + @Override + public void onError(Throwable e) { + + } + + @Override + public void onNext(Object t) { + + } + + @Override + public void onSuccess(Object value) { + + } + } + static void checkMemory(Callable item, String name, String typeLib) throws Exception { + checkMemory(item, name, typeLib, 1000000); + } + + static void checkMemory(Callable item, String name, String typeLib, int n) throws Exception { + // make sure classes are initialized + item.call(); + + Object[] array = new Object[n]; + + Thread.sleep(100); + System.gc(); + Thread.sleep(100); + + long before = memoryUse(); + + for (int i = 0; i < n; i++) { + array[i] = item.call(); + } + + Thread.sleep(100); + System.gc(); + Thread.sleep(100); + + long after = memoryUse(); + + double use = Math.max(0.0, (after - before) / 1024.0 / 1024.0); + + System.out.print(name); + System.out.print(" "); + System.out.print(typeLib); + System.out.print(" thrpt "); + System.out.print(n); + System.out.printf(" %.3f 0.000 MB%n", use); + + if (array.hashCode() == 1) { + System.out.print(""); + } + + array = null; + item = null; + + Thread.sleep(100); + System.gc(); + Thread.sleep(100); + } + + public static void main(String[] args) throws Exception { + + System.out.println("Benchmark (lib-type) Mode Cnt Score Error Units"); + + // --------------------------------------------------------------------------------------------------------------------- + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.just(1); + } + }, "just", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.range(1, 10); + } + }, "range", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.empty(); + } + }, "empty", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.fromCallable(new Callable() { + @Override + public Object call() throws Exception { + return 1; + } + }); + } + }, "fromCallable", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return new MyRx2Observer(); + } + }, "consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return new io.reactivex.observers.TestObserver(); + } + }, "test-consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.just(1).subscribeWith(new MyRx2Observer()); + } + }, "just+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.range(1, 10).subscribeWith(new MyRx2Observer()); + } + }, "range+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.range(1, 10).map(new Function() { + @Override + public Object apply(Integer v) throws Exception { + return v; + } + }).subscribeWith(new MyRx2Observer()); + } + }, "range+map+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.range(1, 10).map(new Function() { + @Override + public Object apply(Integer v) throws Exception { + return v; + } + }).filter(new Predicate() { + @Override + public boolean test(Object v) throws Exception { + return true; + } + }).subscribeWith(new MyRx2Observer()); + } + }, "range+map+filter+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.range(1, 10).subscribeOn(io.reactivex.schedulers.Schedulers.computation()).subscribeWith(new MyRx2Observer()); + } + }, "range+subscribeOn+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.range(1, 10).observeOn(io.reactivex.schedulers.Schedulers.computation()).subscribeWith(new MyRx2Observer()); + } + }, "range+observeOn+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Observable.range(1, 10).subscribeOn(io.reactivex.schedulers.Schedulers.computation()).observeOn(io.reactivex.schedulers.Schedulers.computation()).subscribeWith(new MyRx2Observer()); + } + }, "range+subscribeOn+observeOn+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.subjects.AsyncSubject.create(); + } + }, "Async", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.subjects.PublishSubject.create(); + } + }, "Publish", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.subjects.ReplaySubject.create(); + } + }, "Replay", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.subjects.BehaviorSubject.create(); + } + }, "Behavior", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.subjects.UnicastSubject.create(); + } + }, "Unicast", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.subjects.AsyncSubject.create().subscribeWith(new MyRx2Observer()); + } + }, "Async+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.subjects.PublishSubject.create().subscribeWith(new MyRx2Observer()); + } + }, "Publish+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.subjects.ReplaySubject.create().subscribeWith(new MyRx2Observer()); + } + }, "Replay+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.subjects.BehaviorSubject.create().subscribeWith(new MyRx2Observer()); + } + }, "Behavior+consumer", "Rx2Observable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.subjects.UnicastSubject.create().subscribeWith(new MyRx2Observer()); + } + }, "Unicast+consumer", "Rx2Observable"); + + // --------------------------------------------------------------------------------------------------------------------- + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.just(1); + } + }, "just", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.range(1, 10); + } + }, "range", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.empty(); + } + }, "empty", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.empty(); + } + }, "empty", "Rx2Flowable", 10000000); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.fromCallable(new Callable() { + @Override + public Object call() throws Exception { + return 1; + } + }); + } + }, "fromCallable", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return new MyRx2Subscriber(); + } + }, "consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return new io.reactivex.observers.TestObserver(); + } + }, "test-consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.just(1).subscribeWith(new MyRx2Subscriber()); + } + }, "just+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.range(1, 10).subscribeWith(new MyRx2Subscriber()); + } + }, "range+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.range(1, 10).map(new Function() { + @Override + public Object apply(Integer v) throws Exception { + return v; + } + }).subscribeWith(new MyRx2Subscriber()); + } + }, "range+map+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.range(1, 10).map(new Function() { + @Override + public Object apply(Integer v) throws Exception { + return v; + } + }).filter(new Predicate() { + @Override + public boolean test(Object v) throws Exception { + return true; + } + }).subscribeWith(new MyRx2Subscriber()); + } + }, "range+map+filter+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.range(1, 10).subscribeOn(io.reactivex.schedulers.Schedulers.computation()).subscribeWith(new MyRx2Subscriber()); + } + }, "range+subscribeOn+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.range(1, 10).observeOn(io.reactivex.schedulers.Schedulers.computation()).subscribeWith(new MyRx2Subscriber()); + } + }, "range+observeOn+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.Flowable.range(1, 10).subscribeOn(io.reactivex.schedulers.Schedulers.computation()).observeOn(io.reactivex.schedulers.Schedulers.computation()).subscribeWith(new MyRx2Subscriber()); + } + }, "range+subscribeOn+observeOn+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.processors.AsyncProcessor.create(); + } + }, "Async", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.processors.PublishProcessor.create(); + } + }, "Publish", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.processors.ReplayProcessor.create(); + } + }, "Replay", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.processors.BehaviorProcessor.create(); + } + }, "Behavior", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.processors.UnicastProcessor.create(); + } + }, "Unicast", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.processors.AsyncProcessor.create().subscribeWith(new MyRx2Subscriber()); + } + }, "Async+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.processors.PublishProcessor.create().subscribeWith(new MyRx2Subscriber()); + } + }, "Publish+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.processors.ReplayProcessor.create().subscribeWith(new MyRx2Subscriber()); + } + }, "Replay+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.processors.BehaviorProcessor.create().subscribeWith(new MyRx2Subscriber()); + } + }, "Behavior+consumer", "Rx2Flowable"); + + checkMemory(new Callable() { + @Override + public Object call() throws Exception { + return io.reactivex.processors.UnicastProcessor.create().subscribeWith(new MyRx2Subscriber()); + } + }, "Unicast+consumer", "Rx2Flowable"); + + // --------------------------------------------------------------------------------------------------------------------- + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapCompletablePerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapCompletablePerf.java new file mode 100644 index 0000000000..ab23c7e252 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapCompletablePerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableConcatMapCompletablePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Completable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.concatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.empty(); + } + }); + + flowableConvert = source.concatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Completable.complete().toFlowable(); + } + }); + + flowableDedicated = source.concatMapCompletable(new Function() { + @Override + public Completable apply(Integer v) + throws Exception { + return Completable.complete(); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapMaybeEmptyPerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapMaybeEmptyPerf.java new file mode 100644 index 0000000000..b439425bd0 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapMaybeEmptyPerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableConcatMapMaybeEmptyPerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable concatMapToFlowableEmpty; + + Flowable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.concatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.empty(); + } + }); + + concatMapToFlowableEmpty = source.concatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Maybe.empty().toFlowable(); + } + }); + + flowableDedicated = source.concatMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.empty(); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return concatMapToFlowableEmpty.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapMaybePerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapMaybePerf.java new file mode 100644 index 0000000000..7f891292d2 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapMaybePerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableConcatMapMaybePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Flowable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.concatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.just(v); + } + }); + + flowableConvert = source.concatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Maybe.just(v).toFlowable(); + } + }); + + flowableDedicated = source.concatMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapSinglePerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapSinglePerf.java new file mode 100644 index 0000000000..69f0b314fe --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableConcatMapSinglePerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableConcatMapSinglePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Flowable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.concatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.just(v); + } + }); + + flowableConvert = source.concatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Single.just(v).toFlowable(); + } + }); + + flowableDedicated = source.concatMapSingle(new Function>() { + @Override + public Single apply(Integer v) + throws Exception { + return Single.just(v); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapCompletablePerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapCompletablePerf.java new file mode 100644 index 0000000000..4b9f37664a --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapCompletablePerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableFlatMapCompletablePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Completable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.flatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.empty(); + } + }); + + flowableConvert = source.flatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Completable.complete().toFlowable(); + } + }); + + flowableDedicated = source.flatMapCompletable(new Function() { + @Override + public Completable apply(Integer v) + throws Exception { + return Completable.complete(); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapMaybeEmptyPerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapMaybeEmptyPerf.java new file mode 100644 index 0000000000..bf2ad4396e --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapMaybeEmptyPerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableFlatMapMaybeEmptyPerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Flowable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.flatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.empty(); + } + }); + + flowableConvert = source.flatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Maybe.empty().toFlowable(); + } + }); + + flowableDedicated = source.flatMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.empty(); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapMaybePerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapMaybePerf.java new file mode 100644 index 0000000000..37c970d6cc --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapMaybePerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableFlatMapMaybePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Flowable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.flatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.just(v); + } + }); + + flowableConvert = source.flatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Maybe.just(v).toFlowable(); + } + }); + + flowableDedicated = source.flatMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapSinglePerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapSinglePerf.java new file mode 100644 index 0000000000..e4405932f8 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableFlatMapSinglePerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableFlatMapSinglePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Flowable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.flatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.just(v); + } + }); + + flowableConvert = source.flatMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Single.just(v).toFlowable(); + } + }); + + flowableDedicated = source.flatMapSingle(new Function>() { + @Override + public Single apply(Integer v) + throws Exception { + return Single.just(v); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapCompletablePerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapCompletablePerf.java new file mode 100644 index 0000000000..d0c3041101 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapCompletablePerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableSwitchMapCompletablePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Completable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.switchMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.empty(); + } + }); + + flowableConvert = source.switchMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Completable.complete().toFlowable(); + } + }); + + flowableDedicated = source.switchMapCompletable(new Function() { + @Override + public Completable apply(Integer v) + throws Exception { + return Completable.complete(); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapMaybeEmptyPerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapMaybeEmptyPerf.java new file mode 100644 index 0000000000..217d7bdeba --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapMaybeEmptyPerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableSwitchMapMaybeEmptyPerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Flowable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.switchMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.empty(); + } + }); + + flowableConvert = source.switchMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Maybe.empty().toFlowable(); + } + }); + + flowableDedicated = source.switchMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.empty(); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapMaybePerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapMaybePerf.java new file mode 100644 index 0000000000..f00690b313 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapMaybePerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableSwitchMapMaybePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Flowable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.switchMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.just(v); + } + }); + + flowableConvert = source.switchMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Maybe.just(v).toFlowable(); + } + }); + + flowableDedicated = source.switchMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapSinglePerf.java b/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapSinglePerf.java new file mode 100644 index 0000000000..ad5b3209f0 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/FlowableSwitchMapSinglePerf.java @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class FlowableSwitchMapSinglePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Flowable flowableConvert; + + Flowable flowableDedicated; + + Flowable flowablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Flowable source = Flowable.fromArray(sourceArray); + + flowablePlain = source.switchMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.just(v); + } + }); + + flowableConvert = source.switchMap(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Single.just(v).toFlowable(); + } + }); + + flowableDedicated = source.switchMapSingle(new Function>() { + @Override + public Single apply(Integer v) + throws Exception { + return Single.just(v); + } + }); + } + + @Benchmark + public Object flowablePlain(Blackhole bh) { + return flowablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableConvert(Blackhole bh) { + return flowableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object flowableDedicated(Blackhole bh) { + return flowableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapCompletablePerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapCompletablePerf.java new file mode 100644 index 0000000000..18382f6d55 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapCompletablePerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableConcatMapCompletablePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable observableConvert; + + Completable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.concatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.empty(); + } + }); + + observableConvert = source.concatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Completable.complete().toObservable(); + } + }); + + observableDedicated = source.concatMapCompletable(new Function() { + @Override + public Completable apply(Integer v) + throws Exception { + return Completable.complete(); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapMaybeEmptyPerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapMaybeEmptyPerf.java new file mode 100644 index 0000000000..bc5752eeff --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapMaybeEmptyPerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableConcatMapMaybeEmptyPerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable concatMapToObservableEmpty; + + Observable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.concatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.empty(); + } + }); + + concatMapToObservableEmpty = source.concatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Maybe.empty().toObservable(); + } + }); + + observableDedicated = source.concatMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.empty(); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return concatMapToObservableEmpty.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapMaybePerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapMaybePerf.java new file mode 100644 index 0000000000..e85e2708e4 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapMaybePerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableConcatMapMaybePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable observableConvert; + + Observable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.concatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.just(v); + } + }); + + observableConvert = source.concatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Maybe.just(v).toObservable(); + } + }); + + observableDedicated = source.concatMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapSinglePerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapSinglePerf.java new file mode 100644 index 0000000000..090e1fde96 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableConcatMapSinglePerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableConcatMapSinglePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable observableConvert; + + Observable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.concatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.just(v); + } + }); + + observableConvert = source.concatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Single.just(v).toObservable(); + } + }); + + observableDedicated = source.concatMapSingle(new Function>() { + @Override + public Single apply(Integer v) + throws Exception { + return Single.just(v); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapCompletablePerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapCompletablePerf.java new file mode 100644 index 0000000000..10bbed676e --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapCompletablePerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableFlatMapCompletablePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable observableConvert; + + Completable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.empty(); + } + }); + + observableConvert = source.flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Completable.complete().toObservable(); + } + }); + + observableDedicated = source.flatMapCompletable(new Function() { + @Override + public Completable apply(Integer v) + throws Exception { + return Completable.complete(); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapMaybeEmptyPerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapMaybeEmptyPerf.java new file mode 100644 index 0000000000..021ae89332 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapMaybeEmptyPerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableFlatMapMaybeEmptyPerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable observableConvert; + + Observable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.empty(); + } + }); + + observableConvert = source.flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Maybe.empty().toObservable(); + } + }); + + observableDedicated = source.flatMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.empty(); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapMaybePerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapMaybePerf.java new file mode 100644 index 0000000000..2c1eaccb00 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapMaybePerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableFlatMapMaybePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable observableConvert; + + Observable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.just(v); + } + }); + + observableConvert = source.flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Maybe.just(v).toObservable(); + } + }); + + observableDedicated = source.flatMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapSinglePerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapSinglePerf.java new file mode 100644 index 0000000000..46cd554792 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableFlatMapSinglePerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableFlatMapSinglePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable observableConvert; + + Observable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.just(v); + } + }); + + observableConvert = source.flatMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Single.just(v).toObservable(); + } + }); + + observableDedicated = source.flatMapSingle(new Function>() { + @Override + public Single apply(Integer v) + throws Exception { + return Single.just(v); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapCompletablePerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapCompletablePerf.java new file mode 100644 index 0000000000..e5a6c0336f --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapCompletablePerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableSwitchMapCompletablePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable switchMapToObservableEmpty; + + Completable switchMapCompletableEmpty; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.switchMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.empty(); + } + }); + + switchMapToObservableEmpty = source.switchMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Completable.complete().toObservable(); + } + }); + + switchMapCompletableEmpty = source.switchMapCompletable(new Function() { + @Override + public Completable apply(Integer v) + throws Exception { + return Completable.complete(); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object switchMapToObservableEmpty(Blackhole bh) { + return switchMapToObservableEmpty.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object switchMapCompletableEmpty(Blackhole bh) { + return switchMapCompletableEmpty.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapMaybeEmptyPerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapMaybeEmptyPerf.java new file mode 100644 index 0000000000..77657c69cb --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapMaybeEmptyPerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableSwitchMapMaybeEmptyPerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable observableConvert; + + Observable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.switchMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.empty(); + } + }); + + observableConvert = source.switchMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Maybe.empty().toObservable(); + } + }); + + observableDedicated = source.switchMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.empty(); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapMaybePerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapMaybePerf.java new file mode 100644 index 0000000000..5e80b84e36 --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapMaybePerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableSwitchMapMaybePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable observableConvert; + + Observable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.switchMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.just(v); + } + }); + + observableConvert = source.switchMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Maybe.just(v).toObservable(); + } + }); + + observableDedicated = source.switchMapMaybe(new Function>() { + @Override + public Maybe apply(Integer v) + throws Exception { + return Maybe.just(v); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapSinglePerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapSinglePerf.java new file mode 100644 index 0000000000..fcca79aa8b --- /dev/null +++ b/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapSinglePerf.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.xmapz; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class ObservableSwitchMapSinglePerf { + @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) + public int count; + + Observable observableConvert; + + Observable observableDedicated; + + Observable observablePlain; + + @Setup + public void setup() { + Integer[] sourceArray = new Integer[count]; + Arrays.fill(sourceArray, 777); + + Observable source = Observable.fromArray(sourceArray); + + observablePlain = source.switchMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Observable.just(v); + } + }); + + observableConvert = source.switchMap(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return Single.just(v).toObservable(); + } + }); + + observableDedicated = source.switchMapSingle(new Function>() { + @Override + public Single apply(Integer v) + throws Exception { + return Single.just(v); + } + }); + } + + @Benchmark + public Object observablePlain(Blackhole bh) { + return observablePlain.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); + } + + @Benchmark + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); + } +} From a5d99b726a0efa530b0e8578bcd8dacd0b0b11aa Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 15 Mar 2018 09:49:47 +0100 Subject: [PATCH 137/417] 2.x: Optimize ObservableConcatMapCompletable (#5915) --- .../mixed/ObservableConcatMapCompletable.java | 101 +++++++++++++----- src/test/java/io/reactivex/TestHelper.java | 95 ++++++++++++++++ .../ObservableConcatMapCompletableTest.java | 72 +++++++++++++ 3 files changed, 244 insertions(+), 24 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java index bc765d48b5..5416125366 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java @@ -13,16 +13,17 @@ package io.reactivex.internal.operators.mixed; +import java.util.concurrent.Callable; import java.util.concurrent.atomic.*; import io.reactivex.*; import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; -import io.reactivex.exceptions.*; +import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; -import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.disposables.*; import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.fuseable.SimplePlainQueue; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.queue.SpscLinkedArrayQueue; import io.reactivex.internal.util.*; import io.reactivex.plugins.RxJavaPlugins; @@ -56,7 +57,9 @@ public ObservableConcatMapCompletable(Observable source, @Override protected void subscribeActual(CompletableObserver s) { - source.subscribe(new ConcatMapCompletableObserver(s, mapper, errorMode, prefetch)); + if (!tryScalarSource(source, mapper, s)) { + source.subscribe(new ConcatMapCompletableObserver(s, mapper, errorMode, prefetch)); + } } static final class ConcatMapCompletableObserver @@ -77,7 +80,7 @@ static final class ConcatMapCompletableObserver final int prefetch; - final SimplePlainQueue queue; + SimpleQueue queue; Disposable upstream; @@ -96,20 +99,40 @@ static final class ConcatMapCompletableObserver this.prefetch = prefetch; this.errors = new AtomicThrowable(); this.inner = new ConcatMapInnerObserver(this); - this.queue = new SpscLinkedArrayQueue(prefetch); } @Override public void onSubscribe(Disposable s) { if (DisposableHelper.validate(upstream, s)) { this.upstream = s; + if (s instanceof QueueDisposable) { + @SuppressWarnings("unchecked") + QueueDisposable qd = (QueueDisposable) s; + + int m = qd.requestFusion(QueueDisposable.ANY); + if (m == QueueDisposable.SYNC) { + queue = qd; + done = true; + downstream.onSubscribe(this); + drain(); + return; + } + if (m == QueueDisposable.ASYNC) { + queue = qd; + downstream.onSubscribe(this); + return; + } + } + queue = new SpscLinkedArrayQueue(prefetch); downstream.onSubscribe(this); } } @Override public void onNext(T t) { - queue.offer(t); + if (t != null) { + queue.offer(t); + } drain(); } @@ -187,6 +210,9 @@ void drain() { return; } + AtomicThrowable errors = this.errors; + ErrorMode errorMode = this.errorMode; + do { if (disposed) { queue.clear(); @@ -206,8 +232,24 @@ void drain() { } boolean d = done; - T v = queue.poll(); - boolean empty = v == null; + boolean empty = true; + CompletableSource cs = null; + try { + T v = queue.poll(); + if (v != null) { + cs = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null CompletableSource"); + empty = false; + } + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + disposed = true; + queue.clear(); + upstream.dispose(); + errors.addThrowable(ex); + ex = errors.terminate(); + downstream.onError(ex); + return; + } if (d && empty) { disposed = true; @@ -221,21 +263,6 @@ void drain() { } if (!empty) { - - CompletableSource cs; - - try { - cs = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null CompletableSource"); - } catch (Throwable ex) { - Exceptions.throwIfFatal(ex); - disposed = true; - queue.clear(); - upstream.dispose(); - errors.addThrowable(ex); - ex = errors.terminate(); - downstream.onError(ex); - return; - } active = true; cs.subscribe(inner); } @@ -274,4 +301,30 @@ void dispose() { } } } + + static boolean tryScalarSource(Observable source, Function mapper, CompletableObserver observer) { + if (source instanceof Callable) { + @SuppressWarnings("unchecked") + Callable call = (Callable) source; + CompletableSource cs = null; + try { + T item = call.call(); + if (item != null) { + cs = ObjectHelper.requireNonNull(mapper.apply(item), "The mapper returned a null CompletableSource"); + } + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + EmptyDisposable.error(ex, observer); + return true; + } + + if (cs == null) { + EmptyDisposable.complete(observer); + } else { + cs.subscribe(observer); + } + return true; + } + return false; + } } diff --git a/src/test/java/io/reactivex/TestHelper.java b/src/test/java/io/reactivex/TestHelper.java index 2a4ac1ee58..9e31194f0f 100644 --- a/src/test/java/io/reactivex/TestHelper.java +++ b/src/test/java/io/reactivex/TestHelper.java @@ -2827,4 +2827,99 @@ public static void checkInvalidParallelSubscribers(ParallelFlowable sourc tss[i].assertFailure(IllegalArgumentException.class); } } + + public static Observable rejectObservableFusion() { + return new Observable() { + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(new QueueDisposable() { + + @Override + public int requestFusion(int mode) { + return 0; + } + + @Override + public boolean offer(T value) { + throw new IllegalStateException(); + } + + @Override + public boolean offer(T v1, T v2) { + throw new IllegalStateException(); + } + + @Override + public T poll() throws Exception { + return null; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public void clear() { + } + + @Override + public void dispose() { + } + + @Override + public boolean isDisposed() { + return false; + } + }); + } + }; + } + + public static Flowable rejectFlowableFusion() { + return new Flowable() { + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new QueueSubscription() { + + @Override + public int requestFusion(int mode) { + return 0; + } + + @Override + public boolean offer(T value) { + throw new IllegalStateException(); + } + + @Override + public boolean offer(T v1, T v2) { + throw new IllegalStateException(); + } + + @Override + public T poll() throws Exception { + return null; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public void clear() { + } + + @Override + public void cancel() { + } + + @Override + public void request(long n) { + } + }); + } + }; + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletableTest.java index 50c79bb01f..6f4ff458ab 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletableTest.java @@ -24,6 +24,7 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.*; @@ -112,6 +113,19 @@ public CompletableSource apply(Integer v) throws Exception { .assertFailure(TestException.class); } + @Test + public void mapperCrashHidden() { + Observable.just(1).hide() + .concatMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + @Test public void immediateError() { PublishSubject ps = PublishSubject.create(); @@ -359,4 +373,62 @@ public void doneButNotEmpty() { to.assertResult(); } + + @Test + public void asyncFused() { + final PublishSubject ps = PublishSubject.create(); + final CompletableSubject cs = CompletableSubject.create(); + + final TestObserver to = ps.observeOn(ImmediateThinScheduler.INSTANCE) + .concatMapCompletable( + Functions.justFunction(cs) + ) + .test(); + + ps.onNext(1); + ps.onComplete(); + + cs.onComplete(); + + to.assertResult(); + } + + @Test + public void fusionRejected() { + final CompletableSubject cs = CompletableSubject.create(); + + TestHelper.rejectObservableFusion() + .concatMapCompletable( + Functions.justFunction(cs) + ) + .test() + .assertEmpty(); + } + + @Test + public void emptyScalarSource() { + final CompletableSubject cs = CompletableSubject.create(); + + Observable.empty() + .concatMapCompletable(Functions.justFunction(cs)) + .test() + .assertResult(); + } + + @Test + public void justScalarSource() { + final CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = Observable.just(1) + .concatMapCompletable(Functions.justFunction(cs)) + .test(); + + to.assertEmpty(); + + assertTrue(cs.hasObservers()); + + cs.onComplete(); + + to.assertResult(); + } } From e25ab2441e13c7ec34eb6f868ea61a57846f7b6f Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 15 Mar 2018 11:35:56 +0100 Subject: [PATCH 138/417] 2.x: Improve the scalar source perf of Obs.(concat|switch)MapX (#5918) --- .../operators/maybe/MaybeToObservable.java | 19 ++- .../mixed/ObservableConcatMapCompletable.java | 31 +--- .../mixed/ObservableConcatMapMaybe.java | 4 +- .../mixed/ObservableConcatMapSingle.java | 4 +- .../mixed/ObservableSwitchMapCompletable.java | 4 +- .../mixed/ObservableSwitchMapMaybe.java | 4 +- .../mixed/ObservableSwitchMapSingle.java | 4 +- .../operators/mixed/ScalarXMapZHelper.java | 156 ++++++++++++++++++ .../operators/single/SingleToObservable.java | 15 +- .../mixed/ObservableConcatMapMaybeTest.java | 29 +++- .../mixed/ObservableConcatMapSingleTest.java | 29 +++- .../ObservableSwitchMapCompletableTest.java | 44 +++++ .../mixed/ObservableSwitchMapMaybeTest.java | 46 +++++- .../mixed/ObservableSwitchMapSingleTest.java | 48 +++++- .../mixed/ScalarXMapZHelperTest.java | 26 +++ 15 files changed, 420 insertions(+), 43 deletions(-) create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelper.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelperTest.java diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java index dabd8a0d1b..53f87e743c 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.maybe; import io.reactivex.*; +import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.fuseable.HasUpstreamMaybeSource; @@ -40,17 +41,29 @@ public MaybeSource source() { @Override protected void subscribeActual(Observer s) { - source.subscribe(new MaybeToFlowableSubscriber(s)); + source.subscribe(create(s)); } - static final class MaybeToFlowableSubscriber extends DeferredScalarDisposable + /** + * Creates a {@link MaybeObserver} wrapper around a {@link Observer}. + * @param the value type + * @param downstream the downstream {@code Observer} to talk to + * @return the new MaybeObserver instance + * @since 2.1.11 - experimental + */ + @Experimental + public static MaybeObserver create(Observer downstream) { + return new MaybeToObservableObserver(downstream); + } + + static final class MaybeToObservableObserver extends DeferredScalarDisposable implements MaybeObserver { private static final long serialVersionUID = 7603343402964826922L; Disposable d; - MaybeToFlowableSubscriber(Observer actual) { + MaybeToObservableObserver(Observer actual) { super(actual); } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java index 5416125366..da2f635437 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.mixed; -import java.util.concurrent.Callable; import java.util.concurrent.atomic.*; import io.reactivex.*; @@ -21,7 +20,7 @@ import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; -import io.reactivex.internal.disposables.*; +import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.fuseable.*; import io.reactivex.internal.queue.SpscLinkedArrayQueue; @@ -57,7 +56,7 @@ public ObservableConcatMapCompletable(Observable source, @Override protected void subscribeActual(CompletableObserver s) { - if (!tryScalarSource(source, mapper, s)) { + if (!ScalarXMapZHelper.tryAsCompletable(source, mapper, s)) { source.subscribe(new ConcatMapCompletableObserver(s, mapper, errorMode, prefetch)); } } @@ -301,30 +300,4 @@ void dispose() { } } } - - static boolean tryScalarSource(Observable source, Function mapper, CompletableObserver observer) { - if (source instanceof Callable) { - @SuppressWarnings("unchecked") - Callable call = (Callable) source; - CompletableSource cs = null; - try { - T item = call.call(); - if (item != null) { - cs = ObjectHelper.requireNonNull(mapper.apply(item), "The mapper returned a null CompletableSource"); - } - } catch (Throwable ex) { - Exceptions.throwIfFatal(ex); - EmptyDisposable.error(ex, observer); - return true; - } - - if (cs == null) { - EmptyDisposable.complete(observer); - } else { - cs.subscribe(observer); - } - return true; - } - return false; - } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java index 9d83c77e59..24e0b45027 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java @@ -59,7 +59,9 @@ public ObservableConcatMapMaybe(Observable source, @Override protected void subscribeActual(Observer s) { - source.subscribe(new ConcatMapMaybeMainObserver(s, mapper, prefetch, errorMode)); + if (!ScalarXMapZHelper.tryAsMaybe(source, mapper, s)) { + source.subscribe(new ConcatMapMaybeMainObserver(s, mapper, prefetch, errorMode)); + } } static final class ConcatMapMaybeMainObserver diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java index d29204ccc7..96a3443ad9 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java @@ -59,7 +59,9 @@ public ObservableConcatMapSingle(Observable source, @Override protected void subscribeActual(Observer s) { - source.subscribe(new ConcatMapSingleMainObserver(s, mapper, prefetch, errorMode)); + if (!ScalarXMapZHelper.tryAsSingle(source, mapper, s)) { + source.subscribe(new ConcatMapSingleMainObserver(s, mapper, prefetch, errorMode)); + } } static final class ConcatMapSingleMainObserver diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java index 650c9dfbd8..4b98e63bf2 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java @@ -51,7 +51,9 @@ public ObservableSwitchMapCompletable(Observable source, @Override protected void subscribeActual(CompletableObserver s) { - source.subscribe(new SwitchMapCompletableObserver(s, mapper, delayErrors)); + if (!ScalarXMapZHelper.tryAsCompletable(source, mapper, s)) { + source.subscribe(new SwitchMapCompletableObserver(s, mapper, delayErrors)); + } } static final class SwitchMapCompletableObserver implements Observer, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java index ef7f863603..57baef78ea 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java @@ -53,7 +53,9 @@ public ObservableSwitchMapMaybe(Observable source, @Override protected void subscribeActual(Observer s) { - source.subscribe(new SwitchMapMaybeMainObserver(s, mapper, delayErrors)); + if (!ScalarXMapZHelper.tryAsMaybe(source, mapper, s)) { + source.subscribe(new SwitchMapMaybeMainObserver(s, mapper, delayErrors)); + } } static final class SwitchMapMaybeMainObserver extends AtomicInteger diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java index c70bad0bcc..1000e1bd81 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java @@ -53,7 +53,9 @@ public ObservableSwitchMapSingle(Observable source, @Override protected void subscribeActual(Observer s) { - source.subscribe(new SwitchMapSingleMainObserver(s, mapper, delayErrors)); + if (!ScalarXMapZHelper.tryAsSingle(source, mapper, s)) { + source.subscribe(new SwitchMapSingleMainObserver(s, mapper, delayErrors)); + } } static final class SwitchMapSingleMainObserver extends AtomicInteger diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelper.java b/src/main/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelper.java new file mode 100644 index 0000000000..901cbd5cbf --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelper.java @@ -0,0 +1,156 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.Callable; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.EmptyDisposable; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.operators.maybe.MaybeToObservable; +import io.reactivex.internal.operators.single.SingleToObservable; + +/** + * Utility class to extract a value from a scalar source reactive type, + * map it to a 0-1 type then subscribe the output type's consumer to it, + * saving on the overhead of the regular subscription channel. + * @since 2.1.11 - experimental + */ +@Experimental +final class ScalarXMapZHelper { + + private ScalarXMapZHelper() { + throw new IllegalStateException("No instances!"); + } + + /** + * Try subscribing to a {@link CompletableSource} mapped from + * a scalar source (which implements {@link Callable}). + * @param the upstream value type + * @param source the source reactive type ({@code Flowable} or {@code Observable}) + * possibly implementing {@link Callable}. + * @param mapper the function that turns the scalar upstream value into a + * {@link CompletableSource} + * @param observer the consumer to subscribe to the mapped {@link CompletableSource} + * @return true if a subscription did happen and the regular path should be skipped + */ + static boolean tryAsCompletable(Object source, + Function mapper, + CompletableObserver observer) { + if (source instanceof Callable) { + @SuppressWarnings("unchecked") + Callable call = (Callable) source; + CompletableSource cs = null; + try { + T item = call.call(); + if (item != null) { + cs = ObjectHelper.requireNonNull(mapper.apply(item), "The mapper returned a null CompletableSource"); + } + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + EmptyDisposable.error(ex, observer); + return true; + } + + if (cs == null) { + EmptyDisposable.complete(observer); + } else { + cs.subscribe(observer); + } + return true; + } + return false; + } + + /** + * Try subscribing to a {@link MaybeSource} mapped from + * a scalar source (which implements {@link Callable}). + * @param the upstream value type + * @param source the source reactive type ({@code Flowable} or {@code Observable}) + * possibly implementing {@link Callable}. + * @param mapper the function that turns the scalar upstream value into a + * {@link MaybeSource} + * @param observer the consumer to subscribe to the mapped {@link MaybeSource} + * @return true if a subscription did happen and the regular path should be skipped + */ + static boolean tryAsMaybe(Object source, + Function> mapper, + Observer observer) { + if (source instanceof Callable) { + @SuppressWarnings("unchecked") + Callable call = (Callable) source; + MaybeSource cs = null; + try { + T item = call.call(); + if (item != null) { + cs = ObjectHelper.requireNonNull(mapper.apply(item), "The mapper returned a null MaybeSource"); + } + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + EmptyDisposable.error(ex, observer); + return true; + } + + if (cs == null) { + EmptyDisposable.complete(observer); + } else { + cs.subscribe(MaybeToObservable.create(observer)); + } + return true; + } + return false; + } + + /** + * Try subscribing to a {@link SingleSource} mapped from + * a scalar source (which implements {@link Callable}). + * @param the upstream value type + * @param source the source reactive type ({@code Flowable} or {@code Observable}) + * possibly implementing {@link Callable}. + * @param mapper the function that turns the scalar upstream value into a + * {@link SingleSource} + * @param observer the consumer to subscribe to the mapped {@link SingleSource} + * @return true if a subscription did happen and the regular path should be skipped + */ + static boolean tryAsSingle(Object source, + Function> mapper, + Observer observer) { + if (source instanceof Callable) { + @SuppressWarnings("unchecked") + Callable call = (Callable) source; + SingleSource cs = null; + try { + T item = call.call(); + if (item != null) { + cs = ObjectHelper.requireNonNull(mapper.apply(item), "The mapper returned a null SingleSource"); + } + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + EmptyDisposable.error(ex, observer); + return true; + } + + if (cs == null) { + EmptyDisposable.complete(observer); + } else { + cs.subscribe(SingleToObservable.create(observer)); + } + return true; + } + return false; + } +} diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java index b9a5ff9937..02844ece2c 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java @@ -13,6 +13,7 @@ package io.reactivex.internal.operators.single; import io.reactivex.*; +import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; @@ -31,7 +32,19 @@ public SingleToObservable(SingleSource source) { @Override public void subscribeActual(final Observer s) { - source.subscribe(new SingleToObservableObserver(s)); + source.subscribe(create(s)); + } + + /** + * Creates a {@link SingleObserver} wrapper around a {@link Observer}. + * @param the value type + * @param downstream the downstream {@code Observer} to talk to + * @return the new SingleObserver instance + * @since 2.1.11 - experimental + */ + @Experimental + public static SingleObserver create(Observer downstream) { + return new SingleToObservableObserver(downstream); } static final class SingleToObservableObserver diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java index bdedbd2055..c22c38db64 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java @@ -340,10 +340,37 @@ public MaybeSource apply(Integer v) assertFalse(ps.hasObservers()); } + @Test + public void scalarMapperCrash() { + TestObserver to = Observable.just(1) + .concatMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test(); + + to.assertFailure(TestException.class); + } + @Test public void disposed() { - TestHelper.checkDisposed(Observable.just(1) + TestHelper.checkDisposed(Observable.just(1).hide() .concatMapMaybe(Functions.justFunction(Maybe.never())) ); } + + @Test + public void scalarEmptySource() { + MaybeSubject ms = MaybeSubject.create(); + + Observable.empty() + .concatMapMaybe(Functions.justFunction(ms)) + .test() + .assertResult(); + + assertFalse(ms.hasObservers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java index 0a1ff4e1be..420cef2171 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java @@ -255,9 +255,24 @@ public SingleSource apply(Integer v) assertFalse(ps.hasObservers()); } + @Test + public void mapperCrashScalar() { + TestObserver to = Observable.just(1) + .concatMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test(); + + to.assertFailure(TestException.class); + } + @Test public void disposed() { - TestHelper.checkDisposed(Observable.just(1) + TestHelper.checkDisposed(Observable.just(1).hide() .concatMapSingle(Functions.justFunction(Single.never())) ); } @@ -283,4 +298,16 @@ public void mainCompletesWhileInnerActive() { to.assertResult(1, 1); } + + @Test + public void scalarEmptySource() { + SingleSubject ss = SingleSubject.create(); + + Observable.empty() + .concatMapSingle(Functions.justFunction(ss)) + .test() + .assertResult(); + + assertFalse(ss.hasObservers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java index 17edbf46e5..72d4af0d52 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java @@ -384,4 +384,48 @@ public void mainErrorDelayed() { to.assertFailure(TestException.class); } + + @Test + public void scalarMapperCrash() { + TestObserver to = Observable.just(1) + .switchMapCompletable(new Function() { + @Override + public CompletableSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test(); + + to.assertFailure(TestException.class); + } + + @Test + public void scalarEmptySource() { + CompletableSubject cs = CompletableSubject.create(); + + Observable.empty() + .switchMapCompletable(Functions.justFunction(cs)) + .test() + .assertResult(); + + assertFalse(cs.hasObservers()); + } + + @Test + public void scalarSource() { + CompletableSubject cs = CompletableSubject.create(); + + TestObserver to = Observable.just(1) + .switchMapCompletable(Functions.justFunction(cs)) + .test(); + + assertTrue(cs.hasObservers()); + + to.assertEmpty(); + + cs.onComplete(); + + to.assertResult(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java index 4b0046bb61..363f8c0614 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java @@ -268,7 +268,7 @@ public MaybeSource apply(Integer v) @Test public void mapperCrash() { - Observable.just(1) + Observable.just(1).hide() .switchMapMaybe(new Function>() { @Override public MaybeSource apply(Integer v) @@ -642,4 +642,48 @@ public MaybeSource apply(Integer v) to.assertResult(1, 2); } + + @Test + public void scalarMapperCrash() { + TestObserver to = Observable.just(1) + .switchMapMaybe(new Function>() { + @Override + public MaybeSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test(); + + to.assertFailure(TestException.class); + } + + @Test + public void scalarEmptySource() { + MaybeSubject ms = MaybeSubject.create(); + + Observable.empty() + .switchMapMaybe(Functions.justFunction(ms)) + .test() + .assertResult(); + + assertFalse(ms.hasObservers()); + } + + @Test + public void scalarSource() { + MaybeSubject ms = MaybeSubject.create(); + + TestObserver to = Observable.just(1) + .switchMapMaybe(Functions.justFunction(ms)) + .test(); + + assertTrue(ms.hasObservers()); + + to.assertEmpty(); + + ms.onSuccess(2); + + to.assertResult(2); + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java index 10b3dba8d8..92ec3c5523 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java @@ -237,7 +237,7 @@ public SingleSource apply(Integer v) @Test public void mapperCrash() { - Observable.just(1) + Observable.just(1).hide() .switchMapSingle(new Function>() { @Override public SingleSource apply(Integer v) @@ -253,7 +253,7 @@ public SingleSource apply(Integer v) public void disposeBeforeSwitchInOnNext() { final TestObserver to = new TestObserver(); - Observable.just(1) + Observable.just(1).hide() .switchMapSingle(new Function>() { @Override public SingleSource apply(Integer v) @@ -610,4 +610,48 @@ public SingleSource apply(Integer v) to.assertResult(1, 2); } + + @Test + public void scalarMapperCrash() { + TestObserver to = Observable.just(1) + .switchMapSingle(new Function>() { + @Override + public SingleSource apply(Integer v) + throws Exception { + throw new TestException(); + } + }) + .test(); + + to.assertFailure(TestException.class); + } + + @Test + public void scalarEmptySource() { + SingleSubject ss = SingleSubject.create(); + + Observable.empty() + .switchMapSingle(Functions.justFunction(ss)) + .test() + .assertResult(); + + assertFalse(ss.hasObservers()); + } + + @Test + public void scalarSource() { + SingleSubject ss = SingleSubject.create(); + + TestObserver to = Observable.just(1) + .switchMapSingle(Functions.justFunction(ss)) + .test(); + + assertTrue(ss.hasObservers()); + + to.assertEmpty(); + + ss.onSuccess(2); + + to.assertResult(2); + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelperTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelperTest.java new file mode 100644 index 0000000000..c30d0c4624 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelperTest.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import org.junit.Test; + +import io.reactivex.TestHelper; + +public class ScalarXMapZHelperTest { + + @Test + public void utilityClass() { + TestHelper.checkUtilityClass(ScalarXMapZHelper.class); + } +} From 8a6bf14fc9a61f7c1c0016ca217be02ca86211d2 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 15 Mar 2018 14:22:28 +0100 Subject: [PATCH 139/417] 2.x: Add fusion (perf++) to ObservableSwitchMap inner source (#5919) --- .../ObservableSwitchMapCompletablePerf.java | 16 +- .../observers/DeferredScalarDisposable.java | 5 +- .../completable/CompletableToObservable.java | 45 +++++- .../observable/ObservableSwitchMap.java | 150 ++++++++++++------ .../operators/single/SingleToObservable.java | 19 +-- .../CompletableToObservableTest.java | 71 +++++++++ .../observable/ObservableSwitchTest.java | 112 +++++++++++++ 7 files changed, 342 insertions(+), 76 deletions(-) create mode 100644 src/test/java/io/reactivex/internal/operators/completable/CompletableToObservableTest.java diff --git a/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapCompletablePerf.java b/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapCompletablePerf.java index e5a6c0336f..7b1b9e6925 100644 --- a/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapCompletablePerf.java +++ b/src/jmh/java/io/reactivex/xmapz/ObservableSwitchMapCompletablePerf.java @@ -32,9 +32,9 @@ public class ObservableSwitchMapCompletablePerf { @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) public int count; - Observable switchMapToObservableEmpty; + Observable observableConvert; - Completable switchMapCompletableEmpty; + Completable observableDedicated; Observable observablePlain; @@ -53,7 +53,7 @@ public Observable apply(Integer v) } }); - switchMapToObservableEmpty = source.switchMap(new Function>() { + observableConvert = source.switchMap(new Function>() { @Override public Observable apply(Integer v) throws Exception { @@ -61,7 +61,7 @@ public Observable apply(Integer v) } }); - switchMapCompletableEmpty = source.switchMapCompletable(new Function() { + observableDedicated = source.switchMapCompletable(new Function() { @Override public Completable apply(Integer v) throws Exception { @@ -76,12 +76,12 @@ public Object observablePlain(Blackhole bh) { } @Benchmark - public Object switchMapToObservableEmpty(Blackhole bh) { - return switchMapToObservableEmpty.subscribeWith(new PerfConsumer(bh)); + public Object observableConvert(Blackhole bh) { + return observableConvert.subscribeWith(new PerfConsumer(bh)); } @Benchmark - public Object switchMapCompletableEmpty(Blackhole bh) { - return switchMapCompletableEmpty.subscribeWith(new PerfConsumer(bh)); + public Object observableDedicated(Blackhole bh) { + return observableDedicated.subscribeWith(new PerfConsumer(bh)); } } diff --git a/src/main/java/io/reactivex/internal/observers/DeferredScalarDisposable.java b/src/main/java/io/reactivex/internal/observers/DeferredScalarDisposable.java index 8dd5084d7e..a517ed04b2 100644 --- a/src/main/java/io/reactivex/internal/observers/DeferredScalarDisposable.java +++ b/src/main/java/io/reactivex/internal/observers/DeferredScalarDisposable.java @@ -72,14 +72,15 @@ public final void complete(T value) { if ((state & (FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED)) != 0) { return; } + Observer a = actual; if (state == FUSED_EMPTY) { this.value = value; lazySet(FUSED_READY); + a.onNext(null); } else { lazySet(TERMINATED); + a.onNext(value); } - Observer a = actual; - a.onNext(value); if (get() != DISPOSED) { a.onComplete(); } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableToObservable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableToObservable.java index 9a0a555b84..f55a310b0a 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableToObservable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableToObservable.java @@ -15,6 +15,8 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.observers.BasicQueueDisposable; /** * Wraps a Completable and exposes it as an Observable. @@ -34,8 +36,12 @@ protected void subscribeActual(Observer observer) { source.subscribe(new ObserverCompletableObserver(observer)); } - static final class ObserverCompletableObserver implements CompletableObserver { - private final Observer observer; + static final class ObserverCompletableObserver extends BasicQueueDisposable + implements CompletableObserver { + + final Observer observer; + + Disposable upstream; ObserverCompletableObserver(Observer observer) { this.observer = observer; @@ -53,7 +59,40 @@ public void onError(Throwable e) { @Override public void onSubscribe(Disposable d) { - observer.onSubscribe(d); + if (DisposableHelper.validate(upstream, d)) { + this.upstream = d; + observer.onSubscribe(this); + } + } + + @Override + public int requestFusion(int mode) { + return mode & ASYNC; + } + + @Override + public Void poll() throws Exception { + return null; // always empty + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public void clear() { + // always empty + } + + @Override + public void dispose() { + upstream.dispose(); + } + + @Override + public boolean isDisposed() { + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java index f12ef78945..2d22639af6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java @@ -21,7 +21,8 @@ import io.reactivex.functions.Function; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.queue.*; +import io.reactivex.internal.fuseable.*; +import io.reactivex.internal.queue.SpscLinkedArrayQueue; import io.reactivex.internal.util.AtomicThrowable; import io.reactivex.plugins.RxJavaPlugins; @@ -181,6 +182,8 @@ void drain() { } final Observer a = actual; + final AtomicReference> active = this.active; + final boolean delayErrors = this.delayErrors; int missing = 1; @@ -218,66 +221,85 @@ void drain() { SwitchMapInnerObserver inner = active.get(); if (inner != null) { - SpscLinkedArrayQueue q = inner.queue; - - if (inner.done) { - boolean empty = q.isEmpty(); - if (delayErrors) { - if (empty) { - active.compareAndSet(inner, null); - continue; + SimpleQueue q = inner.queue; + + if (q != null) { + if (inner.done) { + boolean empty = q.isEmpty(); + if (delayErrors) { + if (empty) { + active.compareAndSet(inner, null); + continue; + } + } else { + Throwable ex = errors.get(); + if (ex != null) { + a.onError(errors.terminate()); + return; + } + if (empty) { + active.compareAndSet(inner, null); + continue; + } } - } else { - Throwable ex = errors.get(); - if (ex != null) { - a.onError(errors.terminate()); + } + + boolean retry = false; + + for (;;) { + if (cancelled) { return; } - if (empty) { - active.compareAndSet(inner, null); - continue; + if (inner != active.get()) { + retry = true; + break; } - } - } - boolean retry = false; + if (!delayErrors) { + Throwable ex = errors.get(); + if (ex != null) { + a.onError(errors.terminate()); + return; + } + } - for (;;) { - if (cancelled) { - return; - } - if (inner != active.get()) { - retry = true; - break; - } + boolean d = inner.done; + R v; - if (!delayErrors) { - Throwable ex = errors.get(); - if (ex != null) { - a.onError(errors.terminate()); - return; + try { + v = q.poll(); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + errors.addThrowable(ex); + active.compareAndSet(inner, null); + if (!delayErrors) { + disposeInner(); + s.dispose(); + done = true; + } else { + inner.cancel(); + } + v = null; + retry = true; } - } + boolean empty = v == null; - boolean d = inner.done; - R v = q.poll(); - boolean empty = v == null; + if (d && empty) { + active.compareAndSet(inner, null); + retry = true; + break; + } - if (d && empty) { - active.compareAndSet(inner, null); - retry = true; - break; - } + if (empty) { + break; + } - if (empty) { - break; + a.onNext(v); } - a.onNext(v); - } - - if (retry) { - continue; + if (retry) { + continue; + } } } @@ -306,25 +328,49 @@ static final class SwitchMapInnerObserver extends AtomicReference parent; final long index; - final SpscLinkedArrayQueue queue; + + final int bufferSize; + + volatile SimpleQueue queue; volatile boolean done; SwitchMapInnerObserver(SwitchMapObserver parent, long index, int bufferSize) { this.parent = parent; this.index = index; - this.queue = new SpscLinkedArrayQueue(bufferSize); + this.bufferSize = bufferSize; } @Override public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + if (DisposableHelper.setOnce(this, s)) { + if (s instanceof QueueDisposable) { + @SuppressWarnings("unchecked") + QueueDisposable qd = (QueueDisposable) s; + + int m = qd.requestFusion(QueueDisposable.ANY); + if (m == QueueDisposable.SYNC) { + queue = qd; + done = true; + parent.drain(); + return; + } + if (m == QueueDisposable.ASYNC) { + queue = qd; + return; + } + } + + queue = new SpscLinkedArrayQueue(bufferSize); + } } @Override public void onNext(R t) { if (index == parent.unique) { - queue.offer(t); + if (t != null) { + queue.offer(t); + } parent.drain(); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java index 02844ece2c..4515cf606a 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java @@ -16,6 +16,7 @@ import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.observers.DeferredScalarDisposable; /** * Wraps a Single and exposes it as an Observable. @@ -48,14 +49,14 @@ public static SingleObserver create(Observer downstream) { } static final class SingleToObservableObserver - implements SingleObserver, Disposable { - - final Observer actual; + extends DeferredScalarDisposable + implements SingleObserver { + private static final long serialVersionUID = 3786543492451018833L; Disposable d; SingleToObservableObserver(Observer actual) { - this.actual = actual; + super(actual); } @Override @@ -69,23 +70,19 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(T value) { - actual.onNext(value); - actual.onComplete(); + complete(value); } @Override public void onError(Throwable e) { - actual.onError(e); + error(e); } @Override public void dispose() { + super.dispose(); d.dispose(); } - @Override - public boolean isDisposed() { - return d.isDisposed(); - } } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableToObservableTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableToObservableTest.java new file mode 100644 index 0000000000..b1cda25ef8 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableToObservableTest.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.functions.Function; +import io.reactivex.internal.fuseable.QueueFuseable; +import io.reactivex.internal.operators.completable.CompletableToObservable.ObserverCompletableObserver; +import io.reactivex.observers.TestObserver; + +public class CompletableToObservableTest { + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeCompletableToObservable(new Function>() { + @Override + public Observable apply(Completable c) throws Exception { + return c.toObservable(); + } + }); + } + + @Test + public void fusion() throws Exception { + TestObserver to = new TestObserver(); + + ObserverCompletableObserver co = new ObserverCompletableObserver(to); + + Disposable d = Disposables.empty(); + + co.onSubscribe(d); + + assertEquals(QueueFuseable.NONE, co.requestFusion(QueueFuseable.SYNC)); + + assertEquals(QueueFuseable.ASYNC, co.requestFusion(QueueFuseable.ASYNC)); + + assertEquals(QueueFuseable.ASYNC, co.requestFusion(QueueFuseable.ANY)); + + assertTrue(co.isEmpty()); + + assertNull(co.poll()); + + co.clear(); + + assertFalse(co.isDisposed()); + + co.dispose(); + + assertTrue(d.isDisposed()); + + assertTrue(co.isDisposed()); + + TestHelper.assertNoOffer(co); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java index 680eb17753..00fb200378 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java @@ -29,6 +29,7 @@ import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.internal.util.ExceptionHelper; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; @@ -1054,4 +1055,115 @@ public void run() { } } } + + @Test + public void asyncFused() { + Observable.just(1).hide() + .switchMap(Functions.justFunction( + Observable.range(1, 5) + .observeOn(ImmediateThinScheduler.INSTANCE) + )) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void syncFusedMaybe() { + Observable.range(1, 5).hide() + .switchMap(Functions.justFunction( + Maybe.just(1).toObservable() + )) + .test() + .assertResult(1, 1, 1, 1, 1); + } + + @Test + public void syncFusedSingle() { + Observable.range(1, 5).hide() + .switchMap(Functions.justFunction( + Single.just(1).toObservable() + )) + .test() + .assertResult(1, 1, 1, 1, 1); + } + + @Test + public void syncFusedCompletable() { + Observable.range(1, 5).hide() + .switchMap(Functions.justFunction( + Completable.complete().toObservable() + )) + .test() + .assertResult(); + } + + @Test + public void asyncFusedRejecting() { + Observable.just(1).hide() + .switchMap(Functions.justFunction( + TestHelper.rejectObservableFusion() + )) + .test() + .assertEmpty(); + } + + @Test + public void asyncFusedPollCrash() { + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ps + .switchMap(Functions.justFunction( + Observable.range(1, 5) + .observeOn(ImmediateThinScheduler.INSTANCE) + .map(new Function() { + @Override + public Integer apply(Integer v) throws Exception { + throw new TestException(); + } + }) + )) + .test(); + + to.assertEmpty(); + + ps.onNext(1); + + to + .assertFailure(TestException.class); + + assertFalse(ps.hasObservers()); + } + + @Test + public void asyncFusedPollCrashDelayError() { + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ps + .switchMapDelayError(Functions.justFunction( + Observable.range(1, 5) + .observeOn(ImmediateThinScheduler.INSTANCE) + .map(new Function() { + @Override + public Integer apply(Integer v) throws Exception { + throw new TestException(); + } + }) + )) + .test(); + + to.assertEmpty(); + + ps.onNext(1); + + assertTrue(ps.hasObservers()); + + to.assertEmpty(); + + ps.onComplete(); + + to + .assertFailure(TestException.class); + + assertFalse(ps.hasObservers()); + } } From f671b57b11845af04cc110792550ecc4f5464712 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 19 Mar 2018 15:26:09 +0100 Subject: [PATCH 140/417] 2.x: Fix JavaDoc warnings of buffer(Publisher|Callable) (#5923) --- src/main/java/io/reactivex/Flowable.java | 11 ++++++----- src/main/java/io/reactivex/Observable.java | 11 ++++++----- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 445487ab7d..9297e6d5dc 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -6516,9 +6516,10 @@ public final > Flowable buffer(Publisher * - *
                - * If either the source Publisher or the boundary Publisher issues an onError notification the event is passed on + *

                + * If either the source {@code Publisher} or the boundary {@code Publisher} issues an {@code onError} notification the event is passed on * immediately without first emitting the buffer it is in the process of assembling. + *

                *
                Backpressure:
                *
                This operator does not support backpressure as it is instead controlled by the given Publishers and * buffers data. It requests {@code Long.MAX_VALUE} upstream and does not obey downstream requests.
                @@ -6540,7 +6541,6 @@ public final > Flowable buffer(Publisher Flowable> buffer(Callable> boundaryIndicatorSupplier) { return buffer(boundaryIndicatorSupplier, ArrayListSupplier.asCallable()); - } /** @@ -6549,9 +6549,10 @@ public final Flowable> buffer(Callable> bound * new buffer whenever the Publisher produced by the specified {@code boundaryIndicatorSupplier} emits an item. *

                * - *

                - * If either the source Publisher or the boundary Publisher issues an onError notification the event is passed on + *

                + * If either the source {@code Publisher} or the boundary {@code Publisher} issues an {@code onError} notification the event is passed on * immediately without first emitting the buffer it is in the process of assembling. + *

                *
                Backpressure:
                *
                This operator does not support backpressure as it is instead controlled by the given Publishers and * buffers data. It requests {@code Long.MAX_VALUE} upstream and does not obey downstream requests.
                diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index f4a5412a64..4a7db80741 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -5952,9 +5952,10 @@ public final > Observable buffer(Observabl * new buffer whenever the ObservableSource produced by the specified {@code boundarySupplier} emits an item. *

                * - *

                - * If either the source ObservableSource or the boundary ObservableSource issues an onError notification the event + *

                + * If either the source {@code ObservableSource} or the boundary {@code ObservableSource} issues an {@code onError} notification the event * is passed on immediately without first emitting the buffer it is in the process of assembling. + *

                *
                Scheduler:
                *
                This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -5972,7 +5973,6 @@ public final > Observable buffer(Observabl @SchedulerSupport(SchedulerSupport.NONE) public final Observable> buffer(Callable> boundarySupplier) { return buffer(boundarySupplier, ArrayListSupplier.asCallable()); - } /** @@ -5981,9 +5981,10 @@ public final Observable> buffer(Callable * - *
                - * If either the source ObservableSource or the boundary ObservableSource issues an onError notification the event + *

                + * If either the source {@code ObservableSource} or the boundary {@code ObservableSource} issues an {@code onError} notification the event * is passed on immediately without first emitting the buffer it is in the process of assembling. + *

                *
                Scheduler:
                *
                This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.
                *
                From 3a098c5e67274246b0b62018f0b92fd49b028359 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 20 Mar 2018 16:36:48 +0100 Subject: [PATCH 141/417] Release 2.1.11 --- CHANGES.md | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index f277c7b5c8..9c5247de67 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,53 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.11 - March 20, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.11%7C)) + +#### API changes + +- [Pull 5871](https://github.com/ReactiveX/RxJava/pull/5871): Add `Flowable.concatMapCompletable{DelayError}` operator. +- [Pull 5870](https://github.com/ReactiveX/RxJava/pull/5870): Add `Flowable.switchMapCompletable{DelayError}` operator. +- [Pull 5872](https://github.com/ReactiveX/RxJava/pull/5872): Add `Flowable.concatMap{Maybe,Single}{DelayError}` operators. +- [Pull 5873](https://github.com/ReactiveX/RxJava/pull/5873): Add `Flowable.switchMap{Maybe,Single}{DelayError}` operators. +- [Pull 5875](https://github.com/ReactiveX/RxJava/pull/5875): Add `Observable` `switchMapX` and `concatMapX` operators. +- [Pull 5906](https://github.com/ReactiveX/RxJava/pull/5906): Add public constructor for `TestScheduler` that takes the initial virtual time. + +#### Performance enhancements + +- [Pull 5915](https://github.com/ReactiveX/RxJava/pull/5915): Optimize `Observable.concatMapCompletable`. +- [Pull 5918](https://github.com/ReactiveX/RxJava/pull/5918): Improve the scalar source performance of `Observable.(concat|switch)Map{Completable|Single|Maybe}`. +- [Pull 5919](https://github.com/ReactiveX/RxJava/pull/5919): Add fusion to `Observable.switchMap` inner source. + +#### Documentation changes + +- [Pull 5863](https://github.com/ReactiveX/RxJava/pull/5863): Expand the documentation of the `Flowable.lift()` operator. +- [Pull 5865](https://github.com/ReactiveX/RxJava/pull/5865): Improve the JavaDoc of the other `lift()` operators. +- [Pull 5876](https://github.com/ReactiveX/RxJava/pull/5876): Add note about `NoSuchElementException` to `Single.zip()`. +- [Pull 5897](https://github.com/ReactiveX/RxJava/pull/5897): Clarify `dematerialize()` and terminal items/signals. +- [Pull 5895](https://github.com/ReactiveX/RxJava/pull/5895): Fix `buffer()` documentation to correctly describe `onError` behavior. + +#### Bugfixes + +- [Pull 5887](https://github.com/ReactiveX/RxJava/pull/5887): Fix `window(Observable|Callable)` upstream handling. +- [Pull 5888](https://github.com/ReactiveX/RxJava/pull/5888): Fix `Flowable.window(Publisher|Callable)` upstream handling. +- [Pull 5892](https://github.com/ReactiveX/RxJava/pull/5892): Fix the extra retention problem in `ReplaySubject`. +- [Pull 5900](https://github.com/ReactiveX/RxJava/pull/5900): Fix `Observable.flatMap` scalar `maxConcurrency` overflow. +- [Pull 5893](https://github.com/ReactiveX/RxJava/pull/5893): Fix `publish(-|Function)` subscriber swap possible data loss. +- [Pull 5898](https://github.com/ReactiveX/RxJava/pull/5898): Fix excess item retention in the other `replay` components. +- [Pull 5904](https://github.com/ReactiveX/RxJava/pull/5904): Fix `Flowable.singleOrError().toFlowable()` not signalling `NoSuchElementException`. +- [Pull 5883](https://github.com/ReactiveX/RxJava/pull/5883): Fix `FlowableWindowBoundary` not cancelling the upstream on a missing backpressure case, causing `NullPointerException`. + +#### Other changes + +- [Pull 5890](https://github.com/ReactiveX/RxJava/pull/5890): Added `@Nullable` annotations to subjects. +- [Pull 5886](https://github.com/ReactiveX/RxJava/pull/5886): Upgrade the algorithm of Observable.timeout(time|selector) operators. +- Coverage improvements + - [Pull 5883](https://github.com/ReactiveX/RxJava/pull/5883): Improve coverage and fix small mistakes/untaken paths in operators. + - [Pull 5889](https://github.com/ReactiveX/RxJava/pull/5889): Cleanup, coverage and related component fixes + - [Pull 5891](https://github.com/ReactiveX/RxJava/pull/5891): Improve coverage & related cleanup 03/05. + - [Pull 5905](https://github.com/ReactiveX/RxJava/pull/5905): Coverage improvements, logical fixes and cleanups 03/08. + - [Pull 5910](https://github.com/ReactiveX/RxJava/pull/5910): Improve coverage, fix operator logic 03/12. + ### Version 2.1.10 - February 24, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.10%7C)) #### API changes From 88aa8540fef43326628dbdd758043f689390fa2d Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 21 Mar 2018 10:39:41 +0100 Subject: [PATCH 142/417] 2.x: Update Single.flatMapPublisher marble (#5924) --- src/main/java/io/reactivex/Single.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index d3c1bf6aca..23bf593dfc 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2354,7 +2354,7 @@ public final Maybe flatMapMaybe(final Function - * + * *
                *
                Backpressure:
                *
                The returned {@code Flowable} honors the backpressure of the downstream consumer From f363ef0e0e39720672f2b9ca129aa26eea8d5e70 Mon Sep 17 00:00:00 2001 From: Aaron He Date: Thu, 22 Mar 2018 01:32:32 -0700 Subject: [PATCH 143/417] Add @Nullable annotations to Processors (#5925) --- src/main/java/io/reactivex/processors/AsyncProcessor.java | 2 ++ src/main/java/io/reactivex/processors/BehaviorProcessor.java | 2 ++ src/main/java/io/reactivex/processors/PublishProcessor.java | 1 + src/main/java/io/reactivex/processors/ReplayProcessor.java | 4 ++++ .../java/io/reactivex/processors/SerializedProcessor.java | 2 ++ src/main/java/io/reactivex/processors/UnicastProcessor.java | 1 + 6 files changed, 12 insertions(+) diff --git a/src/main/java/io/reactivex/processors/AsyncProcessor.java b/src/main/java/io/reactivex/processors/AsyncProcessor.java index 57ad766e5a..b03bef985d 100644 --- a/src/main/java/io/reactivex/processors/AsyncProcessor.java +++ b/src/main/java/io/reactivex/processors/AsyncProcessor.java @@ -138,6 +138,7 @@ public boolean hasComplete() { } @Override + @Nullable public Throwable getThrowable() { return subscribers.get() == TERMINATED ? error : null; } @@ -244,6 +245,7 @@ public boolean hasValue() { *

                The method is thread-safe. * @return a single value the Subject currently has or null if no such value exists */ + @Nullable public T getValue() { return subscribers.get() == TERMINATED ? value : null; } diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index bc0d416160..91aa77b942 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -348,6 +348,7 @@ public boolean hasSubscribers() { } @Override + @Nullable public Throwable getThrowable() { Object o = value.get(); if (NotificationLite.isError(o)) { @@ -361,6 +362,7 @@ public Throwable getThrowable() { *

                The method is thread-safe. * @return a single value the BehaviorProcessor currently has or null if no such value exists */ + @Nullable public T getValue() { Object o = value.get(); if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index 92af846040..d299bffea2 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -261,6 +261,7 @@ public boolean hasSubscribers() { } @Override + @Nullable public Throwable getThrowable() { if (subscribers.get() == TERMINATED) { return error; diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index 069e6628fd..839170fa27 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -354,6 +354,7 @@ public boolean hasSubscribers() { } @Override + @Nullable public Throwable getThrowable() { ReplayBuffer b = buffer; if (b.isDone()) { @@ -510,6 +511,7 @@ interface ReplayBuffer { int size(); + @Nullable T getValue(); T[] getValues(T[] array); @@ -598,6 +600,7 @@ public void trimHead() { } @Override + @Nullable public T getValue() { int s = size; if (s == 0) { @@ -1091,6 +1094,7 @@ public void complete() { } @Override + @Nullable public T getValue() { TimedNode h = head; diff --git a/src/main/java/io/reactivex/processors/SerializedProcessor.java b/src/main/java/io/reactivex/processors/SerializedProcessor.java index 7a755500b9..8c0a37e02a 100644 --- a/src/main/java/io/reactivex/processors/SerializedProcessor.java +++ b/src/main/java/io/reactivex/processors/SerializedProcessor.java @@ -13,6 +13,7 @@ package io.reactivex.processors; +import io.reactivex.annotations.Nullable; import org.reactivestreams.*; import io.reactivex.internal.util.*; @@ -187,6 +188,7 @@ public boolean hasThrowable() { } @Override + @Nullable public Throwable getThrowable() { return actual.getThrowable(); } diff --git a/src/main/java/io/reactivex/processors/UnicastProcessor.java b/src/main/java/io/reactivex/processors/UnicastProcessor.java index e51dcc4dcc..847060feb8 100644 --- a/src/main/java/io/reactivex/processors/UnicastProcessor.java +++ b/src/main/java/io/reactivex/processors/UnicastProcessor.java @@ -457,6 +457,7 @@ public boolean hasSubscribers() { } @Override + @Nullable public Throwable getThrowable() { if (done) { return error; From fd472650c011f6d73ad7570f99a2b793748f6179 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 23 Mar 2018 09:19:16 +0100 Subject: [PATCH 144/417] 2.x: Expand the Getting Started (#5926) * 2.x: Expand the Getting Started * Some text got accidentally deleted --- README.md | 339 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 330 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index fabb826636..45f332fd8f 100644 --- a/README.md +++ b/README.md @@ -33,12 +33,19 @@ See the differences between version 1.x and 2.x in the wiki article [What's diff ## Getting started +### Setting up the dependency + The first step is to include RxJava 2 into your project, for example, as a Gradle compile dependency: ```groovy compile "io.reactivex.rxjava2:rxjava:2.x.y" ``` +(Please replace `x` and `y` with the latest version numbers: [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.reactivex.rxjava2/rxjava/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.reactivex.rxjava2/rxjava) +) + +### Hello World + The second is to write the **Hello World** program: ```java @@ -66,13 +73,93 @@ Flowable.just("Hello world") }); ``` +### Base classes + RxJava 2 features several base classes you can discover operators on: - [`io.reactivex.Flowable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html): 0..N flows, supporting Reactive-Streams and backpressure - - [`io.reactivex.Observable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html): 0..N flows, no backpressure - - [`io.reactivex.Single`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Single.html): a flow of exactly 1 item or an error - - [`io.reactivex.Completable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Completable.html): a flow without items but only a completion or error signal - - [`io.reactivex.Maybe`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Maybe.html): a flow with no items, exactly one item or an error + - [`io.reactivex.Observable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html): 0..N flows, no backpressure, + - [`io.reactivex.Single`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Single.html): a flow of exactly 1 item or an error, + - [`io.reactivex.Completable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Completable.html): a flow without items but only a completion or error signal, + - [`io.reactivex.Maybe`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Maybe.html): a flow with no items, exactly one item or an error. + +### Some terminology + +#### Upstream, downstream + +The dataflows in RxJava consist of a source, zero or more intermediate steps followed by a data consumer or combinator step (where the step is responsible to consume the dataflow by some means): + +```java +source.operator1().operator2().operator3().subscribe(consumer); + +source.flatMap(value -> source.operator1().operator2().operator3()); +``` + +Here, if we imagine ourselves on `operator2`, looking to the left towards the source, is called the **upstream**. Looking to the right towards the subscriber/consumer, is called the **downstream**. This is often more apparent when each element is written on a separate line: + +```java +source + .operator1() + .operator2() + .operator3() + .subscribe(consumer) +``` + +#### Objects in motion + +In RxJava's documentation, **emission**, **emits**, **item**, **event**, **signal**, **data** and **message** are considered synonyms and represent the object traveling along the dataflow. + +#### Backpressure + +When the dataflow runs through asynchronous steps, each step may perform different things with different speed. To avoid overwhelming such steps, which usually would manifest itself as increased memory usage due to temporary buffering or the need for skipping/dropping data, a so-called backpressure is applied, which is a form of flow control where the steps can express how many items are they ready to process. This allows constraining the memory usage of the dataflows in situations where there is generally no way for a step to know how many items the upstream will send to it. + +In RxJava, the dedicated `Flowable` class is designated to support backpressure and `Observable` is dedicated for the non-backpressured operations (short sequences, GUI interactions, etc.). The other types, `Single`, `Maybe` and `Completable` don't support backpressure nor should they; there is always room to store one item temporarily. + +#### Assembly time + +The preparation of dataflows by applying various intermediate operators happens in the so-called **assembly time**: + +```java +Flowable flow = Flowable.range(1, 5) +.map(v -> v* v) +.filter(v -> v % 3 == 0) +; +``` + +At this point, the data is not flowing yet and no side-effects are happening. + +#### Subscription time + +This is a temporary state when `subscribe()` is called on a flow that establishes the chain of processing steps internally: + +```java +flow.subscribe(System.out::println) +```` + +This is when the **subscription side-effects** are triggered (see `doOnSubscribe`). Some sources block or start emitting items right away in this state. + +#### Runtime + +This is the state when the flows are actively emitting items, errors or completion signals: + +```java + +Observable.create(emitter -> { + while (!emitter.isDisposed()) { + long time = System.currentTimeMillis(); + emitter.onNext(time); + if (time % 2 != 0) { + emitter.onError(new IllegalStateException("Odd millisecond!"); + break; + } + } +}) +.subscribe(System.out::println, Throwable::printStackTrace); +``` + +Practically, this is when the body of the given example above executes. + +### Simple background computation One of the common use cases for RxJava is to run some computation, network request on a background thread and show the results (or error) on the UI thread: @@ -109,10 +196,23 @@ Thread.sleep(2000); Typically, you can move computations or blocking IO to some other thread via `subscribeOn`. Once the data is ready, you can make sure they get processed on the foreground or GUI thread via `observeOn`. -RxJava operators don't work with `Thread`s or `ExecutorService`s directly but with so called `Scheduler`s that abstract away sources of concurrency behind an uniform API. RxJava 2 features several standard schedulers accessible via `Schedulers` utility class. These are available on all JVM platforms but some specific platforms, such as Android, have their own typical `Scheduler`s defined: `AndroidSchedulers.mainThread()`, `SwingScheduler.instance()` or `JavaFXSchedulers.gui()`. +### Schedulers + +RxJava operators don't work with `Thread`s or `ExecutorService`s directly but with so called `Scheduler`s that abstract away sources of concurrency behind an uniform API. RxJava 2 features several standard schedulers accessible via `Schedulers` utility class. + +- `Schedulers.computation()`: Run computation intensive work on a fixed number of dedicated threads in the background. Most asynchronous operator use this as their default `Scheduler`. +- `Schedulers.io()`: Run I/O-like or blocking operations on a dynamically changing set of threads. +- `Schedulers.single()`: Run work on a single thread in a sequential and FIFO manner. +- `Schedulers.trampoline()`: Run work in a sequential and FIFO manner in one of the participating threads, usually for testing purposes. + +These are available on all JVM platforms but some specific platforms, such as Android, have their own typical `Scheduler`s defined: `AndroidSchedulers.mainThread()`, `SwingScheduler.instance()` or `JavaFXSchedulers.gui()`. + +In addition, there is option to wrap an existing `Executor` (and its subtypes such as `ExecutorService`) into a `Scheduler` via `Schedulers.from(Executor)`. This can be used, for example, to have a larger but still fixed pool of threads (unlike `computation()` and `io()` respectively). The `Thread.sleep(2000);` at the end is no accident. In RxJava the default `Scheduler`s run on daemon threads, which means once the Java main thread exits, they all get stopped and background computations may never happen. Sleeping for some time in this example situations lets you see the output of the flow on the console with time to spare. +### Concurrency within a flow + Flows in RxJava are sequential in nature split into processing stages that may run **concurrently** with each other: ```java @@ -124,6 +224,8 @@ Flowable.range(1, 10) This example flow squares the numbers from 1 to 10 on the **computation** `Scheduler` and consumes the results on the "main" thread (more precisely, the caller thread of `blockingSubscribe`). However, the lambda `v -> v * v` doesn't run in parallel for this flow; it receives the values 1 to 10 on the same computation thread one after the other. +### Parallel processing + Processing the numbers 1 to 10 in parallel is a bit more involved: ```java @@ -138,7 +240,12 @@ Flowable.range(1, 10) Practically, paralellism in RxJava means running independent flows and merging their results back into a single flow. The operator `flatMap` does this by first mapping each number from 1 to 10 into its own individual `Flowable`, runs them and merges the computed squares. -Starting from 2.0.5, there is an *experimental* operator `parallel()` and type `ParallelFlowable` that helps achieve the same parallel processing pattern: +Note, however, that `flatMap` doesn't guarantee any order and the end result from the inner flows may end up interleaved. There are alternative operators: + + - `concatMap` that maps and runs one inner flow at a time and + - `concatMapEager` which runs all inner flows "at once" but the output flow will be in the order those inner flows were created. + +Alternatively, there is a [*beta*](#beta) operator `Flowable.parallel()` and type `ParallelFlowable` that helps achieve the same parallel processing pattern: ```java Flowable.range(1, 10) @@ -149,6 +256,8 @@ Flowable.range(1, 10) .blockingSubscribe(System.out::println); ``` +### Dependend sub-flows + `flatMap` is a powerful operator and helps in a lot of situations. For example, given a service that returns a `Flowable`, we'd like to call another service with values emitted by the first service: ```java @@ -162,10 +271,222 @@ inventorySource.flatMap(inventoryItem -> .subscribe(); ``` -Note, however, that `flatMap` doesn't guarantee any order and the end result from the inner flows may end up interleaved. There are alternative operators: +### Continuations - - `concatMap` that maps and runs one inner flow at a time and - - `concatMapEager` which runs all inner flows "at once" but the output flow will be in the order those inner flows were created. +Sometimes, when an item has become available, one would like to perform some dependent computations on it. This is sometimes called **continuations** and, depending on what should happen and what types are involed, may involve various operators to accomplish. + +#### Dependent + +The most typical scenario is to given a value, invoke another service, await and continue with its result: + +```java +service.apiCall() +.flatMap(value -> service.anotherApiCall(value)) +.flatMap(next -> service.finalCall(next)) +``` + +It is often the case also that later sequences would require values from earlier mappings. This can be achieved by moving the outer `flatMap` into the inner parts of the previous `flatMap` for example: + +```java +service.apiCall() +.flatMap(value -> + service.anotherApiCall(value) + .flatMap(next -> service.finalCallBoth(value, next)) +) +``` + +Here, the original `value` will be available inside the inner `flatMap`, courtesy of lambda variable capture. + +#### Non-dependent + +In other scenarios, the result(s) of the first source/dataflow is irrelevant and one would like to continue with a quasi independent another source. Here, `flatMap` works as well: + +```java +Observable continued = sourceObservable.flatMapSingle(ignored -> someSingleSource) +continued.map(v -> v.toString()) + .subscribe(System.out::println, Throwable::printStackTrace); +``` + +however, the continuation in this case stays `Observable` instead of the likely more appropriate `Single`. (This is understandable because +from the perspective of `flatMapSingle`, `sourceObservable` is a multi-valued source and thus the mapping may result in multiple values as well). + +Often though there is a way that is somewhat more expressive (and also lower overhead) by using `Completable` as the mediator and its operator `andThen` to resume with something else: + +```java +sourceObservable + .ignoreElements() // returns Completable + .andThen(someSingleSource) + .map(v -> v.toString()) +``` + +The only dependency between the `sourceObservable` and the `someSingleSource` is that the former should complete normally in order for the latter to be consumed. + +#### Deferred-dependent + +Sometimes, there is an implicit data dependency between the previous sequence and the new sequence that, for some reason, was not flowing through the "regular channels". One would be inclined to write such continuations as follows: + +```java +AtomicInteger count = new AtomicInteger(); + +Observable.range(1, 10) + .doOnNext(ingored -> count.incrementAndGet()) + .ignoreElements() + .andThen(Single.just(count.get())) + .subscribe(System.out::println); +``` + +Unfortunately, this prints `0` because `Single.just(count.get())` is evaluated at **assembly time** when the dataflow hasn't even run yet. We need something that defers the evaluation of this `Single` source until **runtime** when the main source completes: + +```java +AtomicInteger count = new AtomicInteger(); + +Observable.range(1, 10) + .doOnNext(ingored -> count.incrementAndGet()) + .ignoreElements() + .andThen(Single.defer(() -> Single.just(count.get()))) + .subscribe(System.out::println); +``` + +or + +```java +AtomicInteger count = new AtomicInteger(); + +Observable.range(1, 10) + .doOnNext(ingored -> count.incrementAndGet()) + .ignoreElements() + .andThen(Single.fromCallable(() -> count.get())) + .subscribe(System.out::println); +``` + + +### Type conversions + +Sometimes, a source or service returns a different type than the flow that is supposed to work with it. For example, in the inventory example above, `getDemandAsync` could return a `Single`. If the code example is left unchanged, this will result in a compile time error (however, often with misleading error message about lack of overload). + +In such situations, there are usually two options to fix the transformation: 1) convert to the desired type or 2) find and use an overload of the specific operator supporting the different type. + +#### Converting to the desired type + +Each reactive base class features operators that can perform such conversions, including the protocol conversions, to match some other type. The following matrix shows the available conversion options: + +| | Flowable | Observable | Single | Maybe | Completable | +|----------|----------|------------|--------|-------|-------------| +|**Flowable** | | `toObservable` | `first`, `firstOrError`, `single`, `singleOrError`, `last`, `lastOrError`1 | `firstElement`, `singleElement`, `lastElement` | `ignoreElements` | +|**Observable**| `toFlowable`2 | | `first`, `firstOrError`, `single`, `singleOrError`, `last`, `lastOrError`1 | `firstElement`, `singleElement`, `lastElement` | `ignoreElements` | +|**Single** | `toFlowable`3 | `toObservable` | | `toMaybe` | `toCompletable` | +|**Maybe** | `toFlowable`3 | `toObservable` | `toSingle` | | `ignoreElement` | +|**Completable** | `toFlowable` | `toObservable` | `toSingle` | `toMaybe` | | + +1: When turning a multi-valued source into a single valued source, one should decide which of the many source values should be considered as the result. + +2: Turning an `Observable` into `Flowable` requires an additional decision: what to do with the potential unconstrained flow +of the source `Observable`? There are several strategies available (such as buffering, dropping, keeping the latest) via the `BackpressureStrategy` parameter or via standard `Flowable` operators such as `onBackpressureBuffer`, `onBackpressureDrop`, `onBackpressureLatest` which also +allow further customization of the backpressure behavior. + +3: When there is only (at most) one source item, there is no problem with backpressure as it can be always stored until the downstream is ready to consume. + + +#### Using an overload with the desired type + +Many frequently used operator has overloads that can deal with the other types. These are usually named with the suffix of the target type: + +| Operator | Overloads | +| `flatMap` | `flatMapSingle`, `flatMapMaybe`, `flatMapCompletable`, `flatMapIterable` | +| `concatMap` | `concatMapSingle`, `concatMapMaybe`, `concatMapCompletable`, `concatMapIterable` | +| `switchMap` | `switchMapSingle`, `switchMapMaybe`, `switchMapCompletable`, `switchMapIterable` | + +The reason these operators have a suffix instead of simply having the same name with different signature is type erasure. Java doesn't consider signatures such as `operator(Function>)` and `operator(Function>)` different (unlike C#) and due to erasure, the two `operator`s would end up as duplicate methods with the same signature. + +### Operator naming conventions + +Naming in programming is one of the hardest things as names are expected to be not long, expressive, capturing and easily memorable. Unfortunately, the target language (and pre-existing conventions) may not give too much help in this regard (unusable keywords, type erasure, type ambiguities, etc.). + +#### Unusable keywords + +In the original Rx.NET, the operator that emits a single item and then completes is called `Return(T)`. Since the Java convention is to have a lowercase letter start a method name, this would have been `return(T)` which is a keyword in Java and thus not available. Therefore, RxJava chose to name this operator `just(T)`. The same limitation exists for the operator `Switch`, which had to be named `switchOnNext`. Yet another example is `Catch` which was named `onErrorResumeNext`. + +#### Type erasure + +Many operators that expect the user to provide some function returning a reactive type can't be overloaded because the type erasure around a `Function` turns such method signatures into duplicates. RxJava chose to name such operators by appending the type as suffix as well: + +```java +Flowable flatMap(Function> mapper) + +Flowable flatMapMaybe(Function> mapper) +``` + +#### Type ambiguities + +Even though certain operators have no problems from type erasure, their signature may turn up being ambiguous, especially if one uses Java 8 and lambdas. For example, there are several overloads of `concatWith` taking the various other reactive base types as arguments (for providing convenience and performance benefits in the underlying implementation): + +```java +Flowable concatWith(Publisher other); + +Flowable concatWith(SingleSource other); +``` + +Both `Publisher` and `SingleSource` appear as functional interfaces (types with one abstract method) and may encourage users to try to provide a lambda expression: + +```java +someSource.concatWith(s -> Single.just(2)) +.subscribe(System.out::println, Throwable::printStackTrace); +``` + +Unfortunately, this approach doesn't work and the example does not print `2` at all. In fact, since version 2.1.10, it doesn't +even compile because at least 4 `concatWith` overloads exist and the compiler finds the code above ambiguous. + +The user in such situations probably wanted to defer some computation until the `sameSource` has completed, thus the correct +unambiguous operator should have been `defer`: + +```java +someSource.concatWith(Single.defer(() -> Single.just(2))) +.subscribe(System.out::println, Throwable::printStackTrace); +``` + +Sometimes, a suffix is added to avoid logical ambiguities that may compile but produce the wrong type in a flow: + +```java +Flowable merge(Publisher> sources); + +Flowable mergeArray(Publisher... sources); +``` + +This can get also ambiguous when functional interface types get involved as the type argument `T`. + +#### Error handling + +Dataflows can fail, at which point the error is emitted to the consumer(s). Sometimes though, multiple sources may fail at which point there is a choice wether or not wait for all of them to complete or fail. To indicate this opportunity, many operator names are suffixed with the `DelayError` words (while others feature a `delayError` or `delayErrors` boolean flag in one of their overloads): + +```java +Flowable concat(Publisher> sources); + +Flowable concatDelayError(Publisher> sources); +``` + +Of course, suffixes of various kinds may appear together: + +```java +Flowable concatArrayEagerDelayError(Publisher... sources); +``` + +#### Base class vs base type + +The base classes can be considered heavy due to the sheer number of static and instance methods on them. RxJava 2's design was heavily influenced by the [Reactive Streams](https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams) specification, therefore, the library features a class and an interface per each reactive type: + +| Type | Class | Interface | Consumer | +|------|-------|-----------|----------| +| 0..N backpressured | `Flowable` | `Publisher`1 | `Subscriber` | +| 0..N unbounded | `Observable` | `ObservableSource`2 | `Observer` | +| 1 element or error | `Single` | `SingleSource` | `SingleObserver` | +| 0..1 element or error | `Maybe` | `MaybeSource` | `MaybeObserver` | +| 0 element or error | `Completable` | `CompletableSource` | `CompletableObserver` | + +1The `org.reactivestreams.Publisher` is part of the external Reactive Streams library. It is the main type to interact with other reactive libraries through a standardized mechanism governed by the [Reactive Streams specification](https://github.com/reactive-streams/reactive-streams-jvm#specification). + +2The naming convention of the interface was to append `Source` to the semi-traditional class name. There is no `FlowableSource` since `Publisher` is provided by the Reactive Streams library (and subtyping it wouldn't have helped with interoperation either). These interfaces are, however, not standard in the sense of the Reactive Streams specification and are currently RxJava specific only. + +### Further reading For further details, consult the [wiki](https://github.com/ReactiveX/RxJava/wiki). From 63572c792182f0c2446ceeb3262d843f28558459 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 23 Mar 2018 09:31:50 +0100 Subject: [PATCH 145/417] Fix broken table in "Using an overload with ..." --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 45f332fd8f..1c09be8bfb 100644 --- a/README.md +++ b/README.md @@ -392,9 +392,10 @@ allow further customization of the backpressure behavior. Many frequently used operator has overloads that can deal with the other types. These are usually named with the suffix of the target type: | Operator | Overloads | +|----------|-----------| | `flatMap` | `flatMapSingle`, `flatMapMaybe`, `flatMapCompletable`, `flatMapIterable` | | `concatMap` | `concatMapSingle`, `concatMapMaybe`, `concatMapCompletable`, `concatMapIterable` | -| `switchMap` | `switchMapSingle`, `switchMapMaybe`, `switchMapCompletable`, `switchMapIterable` | +| `switchMap` | `switchMapSingle`, `switchMapMaybe`, `switchMapCompletable` | The reason these operators have a suffix instead of simply having the same name with different signature is type erasure. Java doesn't consider signatures such as `operator(Function>)` and `operator(Function>)` different (unlike C#) and due to erasure, the two `operator`s would end up as duplicate methods with the same signature. From 0fe6e55489aea9fd58ed1760b8fed206a8f842ca Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 23 Mar 2018 11:31:47 +0100 Subject: [PATCH 146/417] 2.x: Fix concatMapSingle & concatMapMaybe dispose-cleanup crash (#5928) --- .../mixed/FlowableConcatMapMaybe.java | 2 +- .../mixed/FlowableConcatMapSingle.java | 2 +- .../mixed/ObservableConcatMapMaybe.java | 2 +- .../mixed/ObservableConcatMapSingle.java | 2 +- .../mixed/FlowableConcatMapMaybeTest.java | 26 +++++++++++++++++++ .../mixed/FlowableConcatMapSingleTest.java | 26 +++++++++++++++++++ .../mixed/ObservableConcatMapMaybeTest.java | 26 +++++++++++++++++++ .../mixed/ObservableConcatMapSingleTest.java | 26 +++++++++++++++++++ 8 files changed, 108 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java index 8910e0c10a..0b7eb3bd7d 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java @@ -170,7 +170,7 @@ public void cancel() { cancelled = true; upstream.cancel(); inner.dispose(); - if (getAndIncrement() != 0) { + if (getAndIncrement() == 0) { queue.clear(); item = null; } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java index 6d0548a733..3164d16a4b 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java @@ -170,7 +170,7 @@ public void cancel() { cancelled = true; upstream.cancel(); inner.dispose(); - if (getAndIncrement() != 0) { + if (getAndIncrement() == 0) { queue.clear(); item = null; } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java index 24e0b45027..8331c38f23 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java @@ -148,7 +148,7 @@ public void dispose() { cancelled = true; upstream.dispose(); inner.dispose(); - if (getAndIncrement() != 0) { + if (getAndIncrement() == 0) { queue.clear(); item = null; } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java index 96a3443ad9..6f3f5d9333 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java @@ -148,7 +148,7 @@ public void dispose() { cancelled = true; upstream.dispose(); inner.dispose(); - if (getAndIncrement() != 0) { + if (getAndIncrement() == 0) { queue.clear(); item = null; } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java index 6c393acebb..334b2e4d69 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java @@ -27,7 +27,9 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.mixed.FlowableConcatMapMaybe.ConcatMapMaybeSubscriber; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.internal.util.ErrorMode; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; @@ -368,4 +370,28 @@ public MaybeSource apply(Integer v) assertFalse(pp.hasSubscribers()); } + + @Test(timeout = 10000) + public void cancelNoConcurrentClean() { + TestSubscriber ts = new TestSubscriber(); + ConcatMapMaybeSubscriber operator = + new ConcatMapMaybeSubscriber( + ts, Functions.justFunction(Maybe.never()), 16, ErrorMode.IMMEDIATE); + + operator.onSubscribe(new BooleanSubscription()); + + operator.queue.offer(1); + + operator.getAndIncrement(); + + ts.cancel(); + + assertFalse(operator.queue.isEmpty()); + + operator.addAndGet(-2); + + operator.cancel(); + + assertTrue(operator.queue.isEmpty()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java index 92779f725f..c572e9ba30 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java @@ -26,7 +26,9 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.mixed.FlowableConcatMapSingle.ConcatMapSingleSubscriber; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.internal.util.ErrorMode; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.subjects.SingleSubject; @@ -283,4 +285,28 @@ public SingleSource apply(Integer v) assertFalse(pp.hasSubscribers()); } + + @Test(timeout = 10000) + public void cancelNoConcurrentClean() { + TestSubscriber ts = new TestSubscriber(); + ConcatMapSingleSubscriber operator = + new ConcatMapSingleSubscriber( + ts, Functions.justFunction(Single.never()), 16, ErrorMode.IMMEDIATE); + + operator.onSubscribe(new BooleanSubscription()); + + operator.queue.offer(1); + + operator.getAndIncrement(); + + ts.cancel(); + + assertFalse(operator.queue.isEmpty()); + + operator.addAndGet(-2); + + operator.cancel(); + + assertTrue(operator.queue.isEmpty()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java index c22c38db64..f374ea23a2 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java @@ -26,6 +26,8 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.mixed.ObservableConcatMapMaybe.ConcatMapMaybeMainObserver; +import io.reactivex.internal.util.ErrorMode; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; @@ -373,4 +375,28 @@ public void scalarEmptySource() { assertFalse(ms.hasObservers()); } + + @Test(timeout = 10000) + public void cancelNoConcurrentClean() { + TestObserver to = new TestObserver(); + ConcatMapMaybeMainObserver operator = + new ConcatMapMaybeMainObserver( + to, Functions.justFunction(Maybe.never()), 16, ErrorMode.IMMEDIATE); + + operator.onSubscribe(Disposables.empty()); + + operator.queue.offer(1); + + operator.getAndIncrement(); + + to.dispose(); + + assertFalse(operator.queue.isEmpty()); + + operator.addAndGet(-2); + + operator.dispose(); + + assertTrue(operator.queue.isEmpty()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java index 420cef2171..be216649bb 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java @@ -25,6 +25,8 @@ import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.mixed.ObservableConcatMapSingle.ConcatMapSingleMainObserver; +import io.reactivex.internal.util.ErrorMode; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.*; @@ -310,4 +312,28 @@ public void scalarEmptySource() { assertFalse(ss.hasObservers()); } + + @Test(timeout = 10000) + public void cancelNoConcurrentClean() { + TestObserver to = new TestObserver(); + ConcatMapSingleMainObserver operator = + new ConcatMapSingleMainObserver( + to, Functions.justFunction(Single.never()), 16, ErrorMode.IMMEDIATE); + + operator.onSubscribe(Disposables.empty()); + + operator.queue.offer(1); + + operator.getAndIncrement(); + + to.cancel(); + + assertFalse(operator.queue.isEmpty()); + + operator.addAndGet(-2); + + operator.dispose(); + + assertTrue(operator.queue.isEmpty()); + } } From b0298abff608e3e8fc7afe9041d44361064686d8 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 23 Mar 2018 17:50:22 +0100 Subject: [PATCH 147/417] Release 2.1.12 --- CHANGES.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 9c5247de67..dd73829f8e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,12 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.12 - March 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.12%7C)) + +#### Bugfixes + +- [Pull 5928](https://github.com/ReactiveX/RxJava/pull/5928): Fix `concatMapSingle` & `concatMapMaybe` dispose-cleanup crash. + ### Version 2.1.11 - March 20, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.11%7C)) #### API changes From 5c58f826364ded0895d96413273d5456bc04f3c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Pri=C5=A1=C4=87an?= Date: Fri, 23 Mar 2018 21:55:58 +0100 Subject: [PATCH 148/417] Add @NonNull annotations to create methods of Subjects and Processors (#5930) --- .../java/io/reactivex/processors/BehaviorProcessor.java | 2 ++ src/main/java/io/reactivex/processors/PublishProcessor.java | 1 + src/main/java/io/reactivex/processors/ReplayProcessor.java | 5 +++++ src/main/java/io/reactivex/processors/UnicastProcessor.java | 6 ++++++ src/main/java/io/reactivex/subjects/AsyncSubject.java | 2 ++ src/main/java/io/reactivex/subjects/BehaviorSubject.java | 3 +++ src/main/java/io/reactivex/subjects/CompletableSubject.java | 2 ++ src/main/java/io/reactivex/subjects/MaybeSubject.java | 1 + src/main/java/io/reactivex/subjects/PublishSubject.java | 2 ++ src/main/java/io/reactivex/subjects/ReplaySubject.java | 5 +++++ src/main/java/io/reactivex/subjects/UnicastSubject.java | 6 ++++++ 11 files changed, 35 insertions(+) diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index 91aa77b942..55fb95fe8b 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -189,6 +189,7 @@ public final class BehaviorProcessor extends FlowableProcessor { * @return the constructed {@link BehaviorProcessor} */ @CheckReturnValue + @NonNull public static BehaviorProcessor create() { return new BehaviorProcessor(); } @@ -205,6 +206,7 @@ public static BehaviorProcessor create() { * @return the constructed {@link BehaviorProcessor} */ @CheckReturnValue + @NonNull public static BehaviorProcessor createDefault(T defaultValue) { ObjectHelper.requireNonNull(defaultValue, "defaultValue is null"); return new BehaviorProcessor(defaultValue); diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index d299bffea2..217d9c3a1e 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -76,6 +76,7 @@ public final class PublishProcessor extends FlowableProcessor { * @return the new PublishProcessor */ @CheckReturnValue + @NonNull public static PublishProcessor create() { return new PublishProcessor(); } diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index 839170fa27..dd47b9be24 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -117,6 +117,7 @@ public final class ReplayProcessor extends FlowableProcessor { * @return the created ReplayProcessor */ @CheckReturnValue + @NonNull public static ReplayProcessor create() { return new ReplayProcessor(new UnboundedReplayBuffer(16)); } @@ -137,6 +138,7 @@ public static ReplayProcessor create() { * @return the created subject */ @CheckReturnValue + @NonNull public static ReplayProcessor create(int capacityHint) { return new ReplayProcessor(new UnboundedReplayBuffer(capacityHint)); } @@ -162,6 +164,7 @@ public static ReplayProcessor create(int capacityHint) { * @return the created subject */ @CheckReturnValue + @NonNull public static ReplayProcessor createWithSize(int maxSize) { return new ReplayProcessor(new SizeBoundReplayBuffer(maxSize)); } @@ -216,6 +219,7 @@ public static ReplayProcessor createWithSize(int maxSize) { * @return the created subject */ @CheckReturnValue + @NonNull public static ReplayProcessor createWithTime(long maxAge, TimeUnit unit, Scheduler scheduler) { return new ReplayProcessor(new SizeAndTimeBoundReplayBuffer(Integer.MAX_VALUE, maxAge, unit, scheduler)); } @@ -255,6 +259,7 @@ public static ReplayProcessor createWithTime(long maxAge, TimeUnit unit, * @return the created subject */ @CheckReturnValue + @NonNull public static ReplayProcessor createWithTimeAndSize(long maxAge, TimeUnit unit, Scheduler scheduler, int maxSize) { return new ReplayProcessor(new SizeAndTimeBoundReplayBuffer(maxSize, maxAge, unit, scheduler)); } diff --git a/src/main/java/io/reactivex/processors/UnicastProcessor.java b/src/main/java/io/reactivex/processors/UnicastProcessor.java index 847060feb8..e712f1f5c8 100644 --- a/src/main/java/io/reactivex/processors/UnicastProcessor.java +++ b/src/main/java/io/reactivex/processors/UnicastProcessor.java @@ -18,6 +18,7 @@ import io.reactivex.annotations.Experimental; import io.reactivex.annotations.Nullable; +import io.reactivex.annotations.NonNull; import org.reactivestreams.*; import io.reactivex.internal.functions.ObjectHelper; @@ -74,6 +75,7 @@ public final class UnicastProcessor extends FlowableProcessor { * @return an UnicastSubject instance */ @CheckReturnValue + @NonNull public static UnicastProcessor create() { return new UnicastProcessor(bufferSize()); } @@ -85,6 +87,7 @@ public static UnicastProcessor create() { * @return an UnicastProcessor instance */ @CheckReturnValue + @NonNull public static UnicastProcessor create(int capacityHint) { return new UnicastProcessor(capacityHint); } @@ -98,6 +101,7 @@ public static UnicastProcessor create(int capacityHint) { */ @CheckReturnValue @Experimental + @NonNull public static UnicastProcessor create(boolean delayError) { return new UnicastProcessor(bufferSize(), null, delayError); } @@ -115,6 +119,7 @@ public static UnicastProcessor create(boolean delayError) { * @return an UnicastProcessor instance */ @CheckReturnValue + @NonNull public static UnicastProcessor create(int capacityHint, Runnable onCancelled) { ObjectHelper.requireNonNull(onCancelled, "onTerminate"); return new UnicastProcessor(capacityHint, onCancelled); @@ -136,6 +141,7 @@ public static UnicastProcessor create(int capacityHint, Runnable onCancel */ @CheckReturnValue @Experimental + @NonNull public static UnicastProcessor create(int capacityHint, Runnable onCancelled, boolean delayError) { ObjectHelper.requireNonNull(onCancelled, "onTerminate"); return new UnicastProcessor(capacityHint, onCancelled, delayError); diff --git a/src/main/java/io/reactivex/subjects/AsyncSubject.java b/src/main/java/io/reactivex/subjects/AsyncSubject.java index 519811a803..af5b6e5fdd 100644 --- a/src/main/java/io/reactivex/subjects/AsyncSubject.java +++ b/src/main/java/io/reactivex/subjects/AsyncSubject.java @@ -14,6 +14,7 @@ package io.reactivex.subjects; import io.reactivex.annotations.Nullable; +import io.reactivex.annotations.NonNull; import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; @@ -129,6 +130,7 @@ public final class AsyncSubject extends Subject { * @return the new AsyncProcessor instance */ @CheckReturnValue + @NonNull public static AsyncSubject create() { return new AsyncSubject(); } diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java index 3c006beb53..7199ba2d0c 100644 --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java @@ -15,6 +15,7 @@ import io.reactivex.annotations.CheckReturnValue; import io.reactivex.annotations.Nullable; +import io.reactivex.annotations.NonNull; import java.lang.reflect.Array; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.*; @@ -180,6 +181,7 @@ public final class BehaviorSubject extends Subject { * @return the constructed {@link BehaviorSubject} */ @CheckReturnValue + @NonNull public static BehaviorSubject create() { return new BehaviorSubject(); } @@ -196,6 +198,7 @@ public static BehaviorSubject create() { * @return the constructed {@link BehaviorSubject} */ @CheckReturnValue + @NonNull public static BehaviorSubject createDefault(T defaultValue) { return new BehaviorSubject(defaultValue); } diff --git a/src/main/java/io/reactivex/subjects/CompletableSubject.java b/src/main/java/io/reactivex/subjects/CompletableSubject.java index 93c626baa0..2e1b72ec9c 100644 --- a/src/main/java/io/reactivex/subjects/CompletableSubject.java +++ b/src/main/java/io/reactivex/subjects/CompletableSubject.java @@ -18,6 +18,7 @@ import io.reactivex.*; import io.reactivex.annotations.CheckReturnValue; +import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.plugins.RxJavaPlugins; @@ -101,6 +102,7 @@ public final class CompletableSubject extends Completable implements Completable * @return the new CompletableSubject instance */ @CheckReturnValue + @NonNull public static CompletableSubject create() { return new CompletableSubject(); } diff --git a/src/main/java/io/reactivex/subjects/MaybeSubject.java b/src/main/java/io/reactivex/subjects/MaybeSubject.java index 1fec546d7c..61b80445af 100644 --- a/src/main/java/io/reactivex/subjects/MaybeSubject.java +++ b/src/main/java/io/reactivex/subjects/MaybeSubject.java @@ -129,6 +129,7 @@ public final class MaybeSubject extends Maybe implements MaybeObserver * @return the new MaybeSubject instance */ @CheckReturnValue + @NonNull public static MaybeSubject create() { return new MaybeSubject(); } diff --git a/src/main/java/io/reactivex/subjects/PublishSubject.java b/src/main/java/io/reactivex/subjects/PublishSubject.java index 7d22a81d2d..0bcfe6452c 100644 --- a/src/main/java/io/reactivex/subjects/PublishSubject.java +++ b/src/main/java/io/reactivex/subjects/PublishSubject.java @@ -15,6 +15,7 @@ import io.reactivex.annotations.CheckReturnValue; import io.reactivex.annotations.Nullable; +import io.reactivex.annotations.NonNull; import java.util.concurrent.atomic.*; import io.reactivex.Observer; @@ -114,6 +115,7 @@ public final class PublishSubject extends Subject { * @return the new PublishSubject */ @CheckReturnValue + @NonNull public static PublishSubject create() { return new PublishSubject(); } diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java index 271a1f7b56..2a553f51d5 100644 --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java @@ -158,6 +158,7 @@ public final class ReplaySubject extends Subject { * @return the created subject */ @CheckReturnValue + @NonNull public static ReplaySubject create() { return new ReplaySubject(new UnboundedReplayBuffer(16)); } @@ -178,6 +179,7 @@ public static ReplaySubject create() { * @return the created subject */ @CheckReturnValue + @NonNull public static ReplaySubject create(int capacityHint) { return new ReplaySubject(new UnboundedReplayBuffer(capacityHint)); } @@ -203,6 +205,7 @@ public static ReplaySubject create(int capacityHint) { * @return the created subject */ @CheckReturnValue + @NonNull public static ReplaySubject createWithSize(int maxSize) { return new ReplaySubject(new SizeBoundReplayBuffer(maxSize)); } @@ -257,6 +260,7 @@ public static ReplaySubject createWithSize(int maxSize) { * @return the created subject */ @CheckReturnValue + @NonNull public static ReplaySubject createWithTime(long maxAge, TimeUnit unit, Scheduler scheduler) { return new ReplaySubject(new SizeAndTimeBoundReplayBuffer(Integer.MAX_VALUE, maxAge, unit, scheduler)); } @@ -296,6 +300,7 @@ public static ReplaySubject createWithTime(long maxAge, TimeUnit unit, Sc * @return the created subject */ @CheckReturnValue + @NonNull public static ReplaySubject createWithTimeAndSize(long maxAge, TimeUnit unit, Scheduler scheduler, int maxSize) { return new ReplaySubject(new SizeAndTimeBoundReplayBuffer(maxSize, maxAge, unit, scheduler)); } diff --git a/src/main/java/io/reactivex/subjects/UnicastSubject.java b/src/main/java/io/reactivex/subjects/UnicastSubject.java index 330e2de85a..61700dec55 100644 --- a/src/main/java/io/reactivex/subjects/UnicastSubject.java +++ b/src/main/java/io/reactivex/subjects/UnicastSubject.java @@ -15,6 +15,7 @@ import io.reactivex.annotations.Experimental; import io.reactivex.annotations.Nullable; +import io.reactivex.annotations.NonNull; import io.reactivex.plugins.RxJavaPlugins; import java.util.concurrent.atomic.*; @@ -180,6 +181,7 @@ public final class UnicastSubject extends Subject { * @return an UnicastSubject instance */ @CheckReturnValue + @NonNull public static UnicastSubject create() { return new UnicastSubject(bufferSize(), true); } @@ -191,6 +193,7 @@ public static UnicastSubject create() { * @return an UnicastSubject instance */ @CheckReturnValue + @NonNull public static UnicastSubject create(int capacityHint) { return new UnicastSubject(capacityHint, true); } @@ -208,6 +211,7 @@ public static UnicastSubject create(int capacityHint) { * @return an UnicastSubject instance */ @CheckReturnValue + @NonNull public static UnicastSubject create(int capacityHint, Runnable onTerminate) { return new UnicastSubject(capacityHint, onTerminate, true); } @@ -228,6 +232,7 @@ public static UnicastSubject create(int capacityHint, Runnable onTerminat */ @CheckReturnValue @Experimental + @NonNull public static UnicastSubject create(int capacityHint, Runnable onTerminate, boolean delayError) { return new UnicastSubject(capacityHint, onTerminate, delayError); } @@ -245,6 +250,7 @@ public static UnicastSubject create(int capacityHint, Runnable onTerminat */ @CheckReturnValue @Experimental + @NonNull public static UnicastSubject create(boolean delayError) { return new UnicastSubject(bufferSize(), delayError); } From 995a6f54d2c1c08363bfdf027a80d4fa753e64a9 Mon Sep 17 00:00:00 2001 From: "Artem Zinnatullin :slowpoke" Date: Tue, 27 Mar 2018 08:19:58 -0700 Subject: [PATCH 149/417] Fix Completable.toMaybe() @return javadoc. (#5936) --- src/main/java/io/reactivex/Completable.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index f0e57a6a11..4c4000838a 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -2182,7 +2182,8 @@ public final Flowable toFlowable() { *

                * * @param the value type - * @return a {@link Maybe} that emits a single item T or an error. + * @return a {@link Maybe} that only calls {@code onComplete} or {@code onError}, based on which one is + * called by the source Completable. */ @CheckReturnValue @SuppressWarnings("unchecked") From 5bd4ac2ccb25be1248dd71ff31a39b7e63884c05 Mon Sep 17 00:00:00 2001 From: Yuri Date: Fri, 30 Mar 2018 15:25:43 +0800 Subject: [PATCH 150/417] fix typo `ingored` (#5938) just fix few typo. --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1c09be8bfb..4d647a9f85 100644 --- a/README.md +++ b/README.md @@ -329,7 +329,7 @@ Sometimes, there is an implicit data dependency between the previous sequence an AtomicInteger count = new AtomicInteger(); Observable.range(1, 10) - .doOnNext(ingored -> count.incrementAndGet()) + .doOnNext(ignored -> count.incrementAndGet()) .ignoreElements() .andThen(Single.just(count.get())) .subscribe(System.out::println); @@ -341,7 +341,7 @@ Unfortunately, this prints `0` because `Single.just(count.get())` is evaluated a AtomicInteger count = new AtomicInteger(); Observable.range(1, 10) - .doOnNext(ingored -> count.incrementAndGet()) + .doOnNext(ignored -> count.incrementAndGet()) .ignoreElements() .andThen(Single.defer(() -> Single.just(count.get()))) .subscribe(System.out::println); @@ -353,7 +353,7 @@ or AtomicInteger count = new AtomicInteger(); Observable.range(1, 10) - .doOnNext(ingored -> count.incrementAndGet()) + .doOnNext(ignored -> count.incrementAndGet()) .ignoreElements() .andThen(Single.fromCallable(() -> count.get())) .subscribe(System.out::println); From 1706fe1e2fbe2ef12a8d8c12ce8e2c3a43e48b3c Mon Sep 17 00:00:00 2001 From: Niklas Baudy Date: Sat, 31 Mar 2018 08:37:25 +0200 Subject: [PATCH 151/417] 2.x: Also allow @SchedulerSupport on constructors. (#5940) --- src/main/java/io/reactivex/annotations/SchedulerSupport.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/annotations/SchedulerSupport.java b/src/main/java/io/reactivex/annotations/SchedulerSupport.java index f2c7be4d68..737c4dbf1e 100644 --- a/src/main/java/io/reactivex/annotations/SchedulerSupport.java +++ b/src/main/java/io/reactivex/annotations/SchedulerSupport.java @@ -28,7 +28,7 @@ */ @Retention(RetentionPolicy.RUNTIME) @Documented -@Target({ElementType.METHOD, ElementType.TYPE}) +@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE}) public @interface SchedulerSupport { /** * A special value indicating the operator/class doesn't use schedulers. From 2770e4dd0ee663f66af4c198daa10367d6c2478b Mon Sep 17 00:00:00 2001 From: Kevin Krumwiede Date: Sun, 1 Apr 2018 14:42:28 -0700 Subject: [PATCH 152/417] Removed TERMINATED check in onNext (#5942) * Removed pointless code. * Removed unnecessary TERMINATED check. --- src/main/java/io/reactivex/processors/PublishProcessor.java | 3 --- src/main/java/io/reactivex/subjects/PublishSubject.java | 4 ---- 2 files changed, 7 deletions(-) diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index 217d9c3a1e..8756a28e35 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -189,9 +189,6 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - if (subscribers.get() == TERMINATED) { - return; - } for (PublishSubscription s : subscribers.get()) { s.onNext(t); } diff --git a/src/main/java/io/reactivex/subjects/PublishSubject.java b/src/main/java/io/reactivex/subjects/PublishSubject.java index 0bcfe6452c..2b1bbc60ad 100644 --- a/src/main/java/io/reactivex/subjects/PublishSubject.java +++ b/src/main/java/io/reactivex/subjects/PublishSubject.java @@ -225,10 +225,6 @@ public void onSubscribe(Disposable s) { @Override public void onNext(T t) { ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - - if (subscribers.get() == TERMINATED) { - return; - } for (PublishDisposable s : subscribers.get()) { s.onNext(t); } From 54c281a3d106da4f3bcf2f59271b1c9034683a60 Mon Sep 17 00:00:00 2001 From: Roman Wuattier Date: Tue, 3 Apr 2018 11:09:37 +0200 Subject: [PATCH 153/417] Fix Observable javadoc (#5944) (#5948) * Replace `doOnCancel` by `doOnDispose` --- src/main/java/io/reactivex/Observable.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 4a7db80741..bbc57d1d08 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -1736,8 +1736,8 @@ public static Observable fromCallable(Callable supplier) { *

                * Important note: This ObservableSource is blocking; you cannot dispose it. *

                - * Unlike 1.x, cancelling the Observable won't cancel the future. If necessary, one can use composition to achieve the - * cancellation effect: {@code futureObservableSource.doOnCancel(() -> future.cancel(true));}. + * Unlike 1.x, disposing the Observable won't cancel the future. If necessary, one can use composition to achieve the + * cancellation effect: {@code futureObservableSource.doOnDispose(() -> future.cancel(true));}. *

                *
                Scheduler:
                *
                {@code fromFuture} does not operate by default on a particular {@link Scheduler}.
                @@ -1767,8 +1767,8 @@ public static Observable fromFuture(Future future) { * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} * method. *

                - * Unlike 1.x, cancelling the Observable won't cancel the future. If necessary, one can use composition to achieve the - * cancellation effect: {@code futureObservableSource.doOnCancel(() -> future.cancel(true));}. + * Unlike 1.x, disposing the Observable won't cancel the future. If necessary, one can use composition to achieve the + * cancellation effect: {@code futureObservableSource.doOnDispose(() -> future.cancel(true));}. *

                * Important note: This ObservableSource is blocking; you cannot dispose it. *

                @@ -1805,8 +1805,8 @@ public static Observable fromFuture(Future future, long time * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} * method. *

                - * Unlike 1.x, cancelling the Observable won't cancel the future. If necessary, one can use composition to achieve the - * cancellation effect: {@code futureObservableSource.doOnCancel(() -> future.cancel(true));}. + * Unlike 1.x, disposing the Observable won't cancel the future. If necessary, one can use composition to achieve the + * cancellation effect: {@code futureObservableSource.doOnDispose(() -> future.cancel(true));}. *

                * Important note: This ObservableSource is blocking; you cannot dispose it. *

                @@ -1846,8 +1846,8 @@ public static Observable fromFuture(Future future, long time * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} * method. *

                - * Unlike 1.x, cancelling the Observable won't cancel the future. If necessary, one can use composition to achieve the - * cancellation effect: {@code futureObservableSource.doOnCancel(() -> future.cancel(true));}. + * Unlike 1.x, disposing the Observable won't cancel the future. If necessary, one can use composition to achieve the + * cancellation effect: {@code futureObservableSource.doOnDispose(() -> future.cancel(true));}. *

                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                @@ -7497,7 +7497,7 @@ public final Observable delaySubscription(long delay, TimeUnit unit, Schedule * returned Observable cancels the flow and terminates with that type of terminal event: *
                
                      * Observable.just(createOnNext(1), createOnComplete(), createOnNext(2))
                -     * .doOnCancel(() -> System.out.println("Cancelled!"));
                +     * .doOnDispose(() -> System.out.println("Cancelled!"));
                      * .test()
                      * .assertResult(1);
                      * 
                From 3481424632b7a0ad27b1999ec9fe8c7e7e236d43 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 5 Apr 2018 20:38:41 +0200 Subject: [PATCH 154/417] 2.x: blockingX JavaDoc to mention wrapping of checked Exc (#5951) --- src/main/java/io/reactivex/Completable.java | 8 ++++++ src/main/java/io/reactivex/Flowable.java | 28 +++++++++++++++++++++ src/main/java/io/reactivex/Maybe.java | 8 ++++++ src/main/java/io/reactivex/Observable.java | 20 +++++++++++++++ src/main/java/io/reactivex/Single.java | 4 +++ 5 files changed, 68 insertions(+) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 4c4000838a..5f9eaa2ac1 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -989,6 +989,10 @@ public final R as(@NonNull CompletableConverter converter) { *
                *
                Scheduler:
                *
                {@code blockingAwait} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * @throws RuntimeException wrapping an InterruptedException if the current thread is interrupted */ @@ -1005,6 +1009,10 @@ public final void blockingAwait() { *
                *
                Scheduler:
                *
                {@code blockingAwait} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * @param timeout the timeout value * @param unit the timeout unit diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 9297e6d5dc..c79229912d 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -5416,6 +5416,10 @@ public final R as(@NonNull FlowableConverter converter) { * (i.e., no backpressure applied to it). *
                Scheduler:
                *
                {@code blockingFirst} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @return the first item emitted by this {@code Flowable} @@ -5445,6 +5449,10 @@ public final T blockingFirst() { * (i.e., no backpressure applied to it). *
                Scheduler:
                *
                {@code blockingFirst} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @param defaultItem @@ -5484,6 +5492,10 @@ public final T blockingFirst(T defaultItem) { * (i.e., no backpressure applied to it). *
                Scheduler:
                *
                {@code blockingForEach} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @param onNext @@ -5566,6 +5578,10 @@ public final Iterable blockingIterable(int bufferSize) { * (i.e., no backpressure applied to it). *
                Scheduler:
                *
                {@code blockingLast} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @return the last item emitted by this {@code Flowable} @@ -5597,6 +5613,10 @@ public final T blockingLast() { * (i.e., no backpressure applied to it). *
                Scheduler:
                *
                {@code blockingLast} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @param defaultItem @@ -5704,6 +5724,10 @@ public final Iterable blockingNext() { * (i.e., no backpressure applied to it). *
                Scheduler:
                *
                {@code blockingSingle} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @return the single item emitted by this {@code Flowable} @@ -5728,6 +5752,10 @@ public final T blockingSingle() { * (i.e., no backpressure applied to it). *
                Scheduler:
                *
                {@code blockingSingle} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @param defaultItem diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index cb3b18145d..5657315bc1 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -2180,6 +2180,10 @@ public final R as(@NonNull MaybeConverter converter) { *
                *
                Scheduler:
                *
                {@code blockingGet} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * @return the success value */ @@ -2197,6 +2201,10 @@ public final T blockingGet() { *
                *
                Scheduler:
                *
                {@code blockingGet} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * @param defaultValue the default item to return if this Maybe is empty * @return the success value diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index bbc57d1d08..64bb418818 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -5039,6 +5039,10 @@ public final T blockingFirst(T defaultItem) { *
                *
                Scheduler:
                *
                {@code blockingForEach} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @param onNext @@ -5108,6 +5112,10 @@ public final Iterable blockingIterable(int bufferSize) { *
                *
                Scheduler:
                *
                {@code blockingLast} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @return the last item emitted by this {@code Observable} @@ -5135,6 +5143,10 @@ public final T blockingLast() { *
                *
                Scheduler:
                *
                {@code blockingLast} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @param defaultItem @@ -5228,6 +5240,10 @@ public final Iterable blockingNext() { *
                *
                Scheduler:
                *
                {@code blockingSingle} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @return the single item emitted by this {@code Observable} @@ -5252,6 +5268,10 @@ public final T blockingSingle() { *
                *
                Scheduler:
                *
                {@code blockingSingle} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * * @param defaultItem diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 23bf593dfc..d3b67f211b 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2481,6 +2481,10 @@ public final Completable flatMapCompletable(final Function *
                Scheduler:
                *
                {@code blockingGet} does not operate by default on a particular {@link Scheduler}.
                + *
                Error handling:
                + *
                If the source signals an error, the operator wraps a checked {@link Exception} + * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and + * {@link Error}s are rethrown as they are.
                *
                * @return the success value */ From 9b44404b9f7845ea6c4c56eea7ba71525b4e8ad0 Mon Sep 17 00:00:00 2001 From: Viacheslav Makarov Date: Sat, 7 Apr 2018 14:03:23 +0300 Subject: [PATCH 155/417] Fixed conditional iteration breaking. (#5952) --- .../util/AppendOnlyLinkedArrayList.java | 2 +- .../reactivex/internal/util/MiscUtilTest.java | 22 ++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/internal/util/AppendOnlyLinkedArrayList.java b/src/main/java/io/reactivex/internal/util/AppendOnlyLinkedArrayList.java index 13ddd34bf7..fce0130657 100644 --- a/src/main/java/io/reactivex/internal/util/AppendOnlyLinkedArrayList.java +++ b/src/main/java/io/reactivex/internal/util/AppendOnlyLinkedArrayList.java @@ -91,7 +91,7 @@ public void forEachWhile(NonThrowingPredicate consumer) { break; } if (consumer.test((T)o)) { - break; + return; } } a = (Object[])a[c]; diff --git a/src/test/java/io/reactivex/internal/util/MiscUtilTest.java b/src/test/java/io/reactivex/internal/util/MiscUtilTest.java index e5129fe47b..464262bce9 100644 --- a/src/test/java/io/reactivex/internal/util/MiscUtilTest.java +++ b/src/test/java/io/reactivex/internal/util/MiscUtilTest.java @@ -75,6 +75,27 @@ public void appendOnlyLinkedArrayListForEachWhile() throws Exception { final List out = new ArrayList(); + list.forEachWhile(new NonThrowingPredicate() { + @Override + public boolean test(Integer t2) { + out.add(t2); + return t2 == 2; + } + }); + + assertEquals(Arrays.asList(1, 2), out); + } + + @Test + public void appendOnlyLinkedArrayListForEachWhileBi() throws Exception { + AppendOnlyLinkedArrayList list = new AppendOnlyLinkedArrayList(2); + + list.add(1); + list.add(2); + list.add(3); + + final List out = new ArrayList(); + list.forEachWhile(2, new BiPredicate() { @Override public boolean test(Integer t1, Integer t2) throws Exception { @@ -86,7 +107,6 @@ public boolean test(Integer t1, Integer t2) throws Exception { assertEquals(Arrays.asList(1, 2), out); } - @Test public void appendOnlyLinkedArrayListForEachWhilePreGrow() throws Exception { AppendOnlyLinkedArrayList list = new AppendOnlyLinkedArrayList(12); From eee45e02535b986c1701a8d4442d887931e69720 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Vicente=20Milack?= Date: Wed, 11 Apr 2018 15:32:27 -0300 Subject: [PATCH 156/417] Add missing parenthesis on README.md (#5955) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d647a9f85..75abbc25ca 100644 --- a/README.md +++ b/README.md @@ -149,7 +149,7 @@ Observable.create(emitter -> { long time = System.currentTimeMillis(); emitter.onNext(time); if (time % 2 != 0) { - emitter.onError(new IllegalStateException("Odd millisecond!"); + emitter.onError(new IllegalStateException("Odd millisecond!")); break; } } From 86902355bb8518e1e74f7c84c973697120e5d9f3 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 13 Apr 2018 09:53:38 +0200 Subject: [PATCH 157/417] 2.x: Add Single.ignoreElement, deprecate toCompletable (#5957) * 2.x: Add Single.ignoreElement, deprecate toCompletable * Fix javadoc method name * Have Single.ignoreElement standard from the start --- src/main/java/io/reactivex/Maybe.java | 2 +- src/main/java/io/reactivex/Single.java | 27 ++++++++++++++++--- .../operators/single/SingleMiscTest.java | 14 ++++++++++ 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 5657315bc1..3afe266025 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3084,7 +3084,7 @@ public final Maybe hide() { /** * Ignores the item emitted by the source Maybe and only calls {@code onComplete} or {@code onError}. *

                - * + * *

                *
                Scheduler:
                *
                {@code ignoreElement} does not operate by default on a particular {@link Scheduler}.
                diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index d3b67f211b..c270100f09 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -3491,9 +3491,7 @@ public final R to(Function, R> convert) { * and calls {@code onComplete} when this source {@link Single} calls * {@code onSuccess}. Error terminal event is propagated. *

                - * + * *

                *
                Scheduler:
                *
                {@code toCompletable} does not operate by default on a particular {@link Scheduler}.
                @@ -3503,13 +3501,36 @@ public final R to(Function, R> convert) { * calls {@code onSuccess}. * @see ReactiveX documentation: Completable * @since 2.0 + * @deprecated see {@link #ignoreElement()} instead, will be removed in 3.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) + @Deprecated public final Completable toCompletable() { return RxJavaPlugins.onAssembly(new CompletableFromSingle(this)); } + /** + * Returns a {@link Completable} that ignores the success value of this {@link Single} + * and calls {@code onComplete} instead on the returned {@code Completable}. + *

                + * + *

                + *
                Scheduler:
                + *
                {@code ignoreElement} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @return a {@link Completable} that calls {@code onComplete} on it's observer when the source {@link Single} + * calls {@code onSuccess}. + * @see ReactiveX documentation: Completable + * @since 2.1.13 + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final Completable ignoreElement() { + return RxJavaPlugins.onAssembly(new CompletableFromSingle(this)); + } + /** * Converts this Single into a {@link Flowable}. *

                diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java index 96f92a3d9e..160579aab1 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java @@ -254,6 +254,7 @@ public void timeoutOther() throws Exception { } @Test + @SuppressWarnings("deprecation") public void toCompletable() { Single.just(1) .toCompletable() @@ -266,6 +267,19 @@ public void toCompletable() { .assertFailure(TestException.class); } + @Test + public void ignoreElement() { + Single.just(1) + .ignoreElement() + .test() + .assertResult(); + + Single.error(new TestException()) + .ignoreElement() + .test() + .assertFailure(TestException.class); + } + @Test public void toObservable() { Single.just(1) From ca535ba384fe5c963f6cc8ee118c9da5222d965a Mon Sep 17 00:00:00 2001 From: Siddharth Jain Date: Fri, 13 Apr 2018 15:55:14 +0530 Subject: [PATCH 158/417] Fix typo (#5960) Update 'Dependend sub-flows' to 'Dependent sub-flows' --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75abbc25ca..5941e14e85 100644 --- a/README.md +++ b/README.md @@ -256,7 +256,7 @@ Flowable.range(1, 10) .blockingSubscribe(System.out::println); ``` -### Dependend sub-flows +### Dependent sub-flows `flatMap` is a powerful operator and helps in a lot of situations. For example, given a service that returns a `Flowable`, we'd like to call another service with values emitted by the first service: From b5b27d4d54fd6752613b99f77fe87c7a791b958c Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sat, 14 Apr 2018 16:44:25 +0200 Subject: [PATCH 159/417] 2.x: Fix some grammar mistakes (#5959) * 2.x: Fix some grammar mistakes * Fix additional a/an mistakes --- src/main/java/io/reactivex/Completable.java | 2 +- src/main/java/io/reactivex/Flowable.java | 460 +++++++++--------- src/main/java/io/reactivex/Maybe.java | 4 +- src/main/java/io/reactivex/Observable.java | 4 +- src/main/java/io/reactivex/Single.java | 4 +- .../mixed/FlowableConcatMapCompletable.java | 2 +- .../mixed/ObservableConcatMapCompletable.java | 2 +- .../reactivex/processors/ReplayProcessor.java | 2 +- .../java/io/reactivex/JavadocWording.java | 39 ++ 9 files changed, 279 insertions(+), 240 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 5f9eaa2ac1..7e83b11abe 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1397,7 +1397,7 @@ public final Completable doFinally(Action onFinally) { * * public final class CustomCompletableObserver implements CompletableObserver, Disposable { * - * // The donstream's CompletableObserver that will receive the onXXX events + * // The downstream's CompletableObserver that will receive the onXXX events * final CompletableObserver downstream; * * // The connection to the upstream source that will call this class' onXXX methods diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index c79229912d..318ae422d9 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -149,7 +149,7 @@ public static int bufferSize() { * {@code Function} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If the provided array of source Publishers is empty, the resulting sequence completes immediately without emitting @@ -193,7 +193,7 @@ public static Flowable combineLatest(Publisher[] sources, * {@code Function} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If there are no source Publishers provided, the resulting sequence completes immediately without emitting @@ -237,7 +237,7 @@ public static Flowable combineLatest(Function} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If the provided array of source Publishers is empty, the resulting sequence completes immediately without emitting @@ -289,7 +289,7 @@ public static Flowable combineLatest(Publisher[] sources, * {@code Function} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If the provided iterable of source Publishers is empty, the resulting sequence completes immediately without emitting @@ -334,7 +334,7 @@ public static Flowable combineLatest(Iterable} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If the provided iterable of source Publishers is empty, the resulting sequence completes immediately without emitting any items and @@ -384,7 +384,7 @@ public static Flowable combineLatest(Iterable} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If the provided array of source Publishers is empty, the resulting sequence completes immediately without emitting @@ -430,7 +430,7 @@ public static Flowable combineLatestDelayError(Publisher[ * {@code Function} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If there are no source Publishers provided, the resulting sequence completes immediately without emitting @@ -476,7 +476,7 @@ public static Flowable combineLatestDelayError(Function} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If there are no source Publishers provided, the resulting sequence completes immediately without emitting @@ -524,7 +524,7 @@ public static Flowable combineLatestDelayError(Function} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If the provided array of source Publishers is empty, the resulting sequence completes immediately without emitting @@ -578,7 +578,7 @@ public static Flowable combineLatestDelayError(Publisher[ * {@code Function} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If the provided iterable of source Publishers is empty, the resulting sequence completes immediately without emitting @@ -624,7 +624,7 @@ public static Flowable combineLatestDelayError(Iterable} passed to the method would trigger a {@code ClassCastException}. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * If the provided iterable of source Publishers is empty, the resulting sequence completes immediately without emitting @@ -670,7 +670,7 @@ public static Flowable combineLatestDelayError(Iterable * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * @@ -715,7 +715,7 @@ public static Flowable combineLatest( * aggregation is defined by a specified function. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * @@ -764,7 +764,7 @@ public static Flowable combineLatest( * aggregation is defined by a specified function. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * @@ -817,7 +817,7 @@ public static Flowable combineLatest( * aggregation is defined by a specified function. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * @@ -875,7 +875,7 @@ public static Flowable combineLatest( * aggregation is defined by a specified function. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * @@ -937,7 +937,7 @@ public static Flowable combineLatest( * aggregation is defined by a specified function. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * @@ -1004,7 +1004,7 @@ public static Flowable combineLatest( * aggregation is defined by a specified function. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * @@ -1075,7 +1075,7 @@ public static Flowable combineLatest( * aggregation is defined by a specified function. *

                * If any of the sources never produces an item but only terminates (normally or with an error), the - * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). + * resulting sequence terminates immediately (normally or with all the errors accumulated until that point). * If that input source is also synchronous, other sources after it will not be subscribed to. *

                * @@ -1182,7 +1182,7 @@ public static Flowable concat(Iterable> *

                Backpressure:
                *
                The operator honors backpressure from downstream. Both the outer and inner {@code Publisher} * sources are expected to honor backpressure as well. If the outer violates this, a - * {@code MissingBackpressureException} is signalled. If any of the inner {@code Publisher}s violates + * {@code MissingBackpressureException} is signaled. If any of the inner {@code Publisher}s violates * this, it may throw an {@code IllegalStateException} when an inner {@code Publisher} completes.
                *
                Scheduler:
                *
                {@code concat} does not operate by default on a particular {@link Scheduler}.
                @@ -1211,7 +1211,7 @@ public static Flowable concat(Publisher> *
                Backpressure:
                *
                The operator honors backpressure from downstream. Both the outer and inner {@code Publisher} * sources are expected to honor backpressure as well. If the outer violates this, a - * {@code MissingBackpressureException} is signalled. If any of the inner {@code Publisher}s violates + * {@code MissingBackpressureException} is signaled. If any of the inner {@code Publisher}s violates * this, it may throw an {@code IllegalStateException} when an inner {@code Publisher} completes.
                *
                Scheduler:
                *
                {@code concat} does not operate by default on a particular {@link Scheduler}.
                @@ -1459,7 +1459,7 @@ public static Flowable concatArrayEager(Publisher... sources * @param the value type * @param sources a sequence of Publishers that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrent subscriptions at a time, Integer.MAX_VALUE - * is interpreted as indication to subscribe to all sources at once + * is interpreted as an indication to subscribe to all sources at once * @param prefetch the number of elements to prefetch from each Publisher source * @return the new Publisher instance with the specified concatenation behavior * @since 2.0 @@ -1483,7 +1483,7 @@ public static Flowable concatArrayEager(int maxConcurrency, int prefetch, *
                Backpressure:
                *
                The operator honors backpressure from downstream. Both the outer and inner {@code Publisher} * sources are expected to honor backpressure as well. If the outer violates this, a - * {@code MissingBackpressureException} is signalled. If any of the inner {@code Publisher}s violates + * {@code MissingBackpressureException} is signaled. If any of the inner {@code Publisher}s violates * this, it may throw an {@code IllegalStateException} when an inner {@code Publisher} completes.
                *
                Scheduler:
                *
                {@code concatDelayError} does not operate by default on a particular {@link Scheduler}.
                @@ -1730,7 +1730,7 @@ public static Flowable create(FlowableOnSubscribe source, Backpressure *

                * *

                - * The defer Subscriber allows you to defer or delay emitting items from a Publisher until such time as an + * The defer Subscriber allows you to defer or delay emitting items from a Publisher until such time as a * Subscriber subscribes to the Publisher. This allows a {@link Subscriber} to easily obtain updates or a * refreshed version of the sequence. *

                @@ -1911,12 +1911,12 @@ public static Flowable fromCallable(Callable supplier) { * *

                * You can convert any object that supports the {@link Future} interface into a Publisher that emits the - * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} + * return value of the {@link Future#get} method of that object by passing the object into the {@code from} * method. *

                * Important note: This Publisher is blocking on the thread it gets subscribed on; you cannot cancel it. *

                - * Unlike 1.x, cancelling the Flowable won't cancel the future. If necessary, one can use composition to achieve the + * Unlike 1.x, canceling the Flowable won't cancel the future. If necessary, one can use composition to achieve the * cancellation effect: {@code futurePublisher.doOnCancel(() -> future.cancel(true));}. *

                *
                Backpressure:
                @@ -1947,10 +1947,10 @@ public static Flowable fromFuture(Future future) { * *

                * You can convert any object that supports the {@link Future} interface into a Publisher that emits the - * return value of the {@link Future#get} method of that object, by passing the object into the {@code fromFuture} + * return value of the {@link Future#get} method of that object by passing the object into the {@code fromFuture} * method. *

                - * Unlike 1.x, cancelling the Flowable won't cancel the future. If necessary, one can use composition to achieve the + * Unlike 1.x, canceling the Flowable won't cancel the future. If necessary, one can use composition to achieve the * cancellation effect: {@code futurePublisher.doOnCancel(() -> future.cancel(true));}. *

                * Important note: This Publisher is blocking on the thread it gets subscribed on; you cannot cancel it. @@ -1988,10 +1988,10 @@ public static Flowable fromFuture(Future future, long timeou * *

                * You can convert any object that supports the {@link Future} interface into a Publisher that emits the - * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} + * return value of the {@link Future#get} method of that object by passing the object into the {@code from} * method. *

                - * Unlike 1.x, cancelling the Flowable won't cancel the future. If necessary, one can use composition to achieve the + * Unlike 1.x, canceling the Flowable won't cancel the future. If necessary, one can use composition to achieve the * cancellation effect: {@code futurePublisher.doOnCancel(() -> future.cancel(true));}. *

                * Important note: This Publisher is blocking; you cannot cancel it. @@ -2032,10 +2032,10 @@ public static Flowable fromFuture(Future future, long timeou * *

                * You can convert any object that supports the {@link Future} interface into a Publisher that emits the - * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} + * return value of the {@link Future#get} method of that object by passing the object into the {@code from} * method. *

                - * Unlike 1.x, cancelling the Flowable won't cancel the future. If necessary, one can use composition to achieve the + * Unlike 1.x, canceling the Flowable won't cancel the future. If necessary, one can use composition to achieve the * cancellation effect: {@code futurePublisher.doOnCancel(() -> future.cancel(true));}. *

                *
                Backpressure:
                @@ -2116,7 +2116,7 @@ public static Flowable fromIterable(Iterable source) { * @param the value type of the flow * @param source the Publisher to convert * @return the new Flowable instance - * @throws NullPointerException if publisher is null + * @throws NullPointerException if the {@code source} {@code Publisher} is null * @see #create(FlowableOnSubscribe, BackpressureStrategy) */ @CheckReturnValue @@ -2144,7 +2144,7 @@ public static Flowable fromPublisher(final Publisher source) * @param the generated value type * @param generator the Consumer called whenever a particular downstream Subscriber has * requested a value. The callback then should call {@code onNext}, {@code onError} or - * {@code onComplete} to signal a value or a terminal event. Signalling multiple {@code onNext} + * {@code onComplete} to signal a value or a terminal event. Signaling multiple {@code onNext} * in a call will make the operator signal {@code IllegalStateException}. * @return the new Flowable instance */ @@ -2172,7 +2172,7 @@ public static Flowable generate(final Consumer> generator) { * @param initialState the Callable to generate the initial state for each Subscriber * @param generator the Consumer called with the current state whenever a particular downstream Subscriber has * requested a value. The callback then should call {@code onNext}, {@code onError} or - * {@code onComplete} to signal a value or a terminal event. Signalling multiple {@code onNext} + * {@code onComplete} to signal a value or a terminal event. Signaling multiple {@code onNext} * in a call will make the operator signal {@code IllegalStateException}. * @return the new Flowable instance */ @@ -2199,10 +2199,10 @@ public static Flowable generate(Callable initialState, final BiCons * @param initialState the Callable to generate the initial state for each Subscriber * @param generator the Consumer called with the current state whenever a particular downstream Subscriber has * requested a value. The callback then should call {@code onNext}, {@code onError} or - * {@code onComplete} to signal a value or a terminal event. Signalling multiple {@code onNext} + * {@code onComplete} to signal a value or a terminal event. Signaling multiple {@code onNext} * in a call will make the operator signal {@code IllegalStateException}. * @param disposeState the Consumer that is called with the current state when the generator - * terminates the sequence or it gets cancelled + * terminates the sequence or it gets canceled * @return the new Flowable instance */ @CheckReturnValue @@ -2229,7 +2229,7 @@ public static Flowable generate(Callable initialState, final BiCons * @param generator the Function called with the current state whenever a particular downstream Subscriber has * requested a value. The callback then should call {@code onNext}, {@code onError} or * {@code onComplete} to signal a value or a terminal event and should return a (new) state for - * the next invocation. Signalling multiple {@code onNext} + * the next invocation. Signaling multiple {@code onNext} * in a call will make the operator signal {@code IllegalStateException}. * @return the new Flowable instance */ @@ -2255,10 +2255,10 @@ public static Flowable generate(Callable initialState, BiFunction Flowable generate(Callable initialState, BiFunction * @@ -2291,7 +2291,7 @@ public static Flowable generate(Callable initialState, BiFunctionReactiveX operators documentation: Interval * @since 1.0.12 @@ -2304,7 +2304,7 @@ public static Flowable interval(long initialDelay, long period, TimeUnit u } /** - * Returns a Flowable that emits a {@code 0L} after the {@code initialDelay} and ever increasing numbers + * Returns a Flowable that emits a {@code 0L} after the {@code initialDelay} and ever-increasing numbers * after each {@code period} of time thereafter, on a specified {@link Scheduler}. *

                * @@ -2325,7 +2325,7 @@ public static Flowable interval(long initialDelay, long period, TimeUnit u * the time unit for both {@code initialDelay} and {@code period} * @param scheduler * the Scheduler on which the waiting happens and items are emitted - * @return a Flowable that emits a 0L after the {@code initialDelay} and ever increasing numbers after + * @return a Flowable that emits a 0L after the {@code initialDelay} and ever-increasing numbers after * each {@code period} of time thereafter, while running on the given Scheduler * @see ReactiveX operators documentation: Interval * @since 1.0.12 @@ -2407,7 +2407,7 @@ public static Flowable interval(long period, TimeUnit unit, Scheduler sche *

                * @param start that start value of the range * @param count the number of values to emit in total, if zero, the operator emits an onComplete after the initial delay. - * @param initialDelay the initial delay before signalling the first value (the start) + * @param initialDelay the initial delay before signaling the first value (the start) * @param period the period between subsequent values * @param unit the unit of measure of the initialDelay and period amounts * @return the new Flowable instance @@ -2431,7 +2431,7 @@ public static Flowable intervalRange(long start, long count, long initialD *
                * @param start that start value of the range * @param count the number of values to emit in total, if zero, the operator emits an onComplete after the initial delay. - * @param initialDelay the initial delay before signalling the first value (the start) + * @param initialDelay the initial delay before signaling the first value (the start) * @param period the period between subsequent values * @param unit the unit of measure of the initialDelay and period amounts * @param scheduler the target scheduler where the values and terminal signals will be emitted @@ -2899,13 +2899,13 @@ public static Flowable just(T item1, T item2, T item3, T item4, T item5, *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                *
                Error handling:
                *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are canceled. * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Flowable} has been canceled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable, int, int)} to merge sources and terminate only when all source {@code Publisher}s * have completed or failed with an error. @@ -2950,13 +2950,13 @@ public static Flowable merge(Iterable> s *
                {@code mergeArray} does not operate by default on a particular {@link Scheduler}.
                *
                Error handling:
                *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are canceled. * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Flowable} has been canceled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeArrayDelayError(int, int, Publisher[])} to merge sources and terminate only when all source {@code Publisher}s * have completed or failed with an error. @@ -3000,13 +3000,13 @@ public static Flowable mergeArray(int maxConcurrency, int bufferSize, Pub *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                *
                Error handling:
                *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are canceled. * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Flowable} has been canceled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code Publisher}s * have completed or failed with an error. @@ -3045,13 +3045,13 @@ public static Flowable merge(Iterable> s *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                *
                Error handling:
                *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are canceled. * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Flowable} has been canceled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable, int)} to merge sources and terminate only when all source {@code Publisher}s * have completed or failed with an error. @@ -3095,13 +3095,13 @@ public static Flowable merge(Iterable> s *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                *
                Error handling:
                *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are canceled. * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Flowable} has been canceled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Publisher)} to merge sources and terminate only when all source {@code Publisher}s * have completed or failed with an error. @@ -3140,13 +3140,13 @@ public static Flowable merge(Publisher> *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                *
                Error handling:
                *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are canceled. * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Flowable} has been canceled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Publisher, int)} to merge sources and terminate only when all source {@code Publisher}s * have completed or failed with an error. @@ -3189,13 +3189,13 @@ public static Flowable merge(Publisher> *
                {@code mergeArray} does not operate by default on a particular {@link Scheduler}.
                *
                Error handling:
                *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are canceled. * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Flowable} has been canceled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeArrayDelayError(Publisher...)} to merge sources and terminate only when all source {@code Publisher}s * have completed or failed with an error. @@ -3232,13 +3232,13 @@ public static Flowable mergeArray(Publisher... sources) { *
                {@code merge} does not operate by default on a particular {@link Scheduler}.
                *
                Error handling:
                *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are canceled. * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Flowable} has been canceled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Publisher, Publisher)} to merge sources and terminate only when all source {@code Publisher}s * have completed or failed with an error. @@ -3279,13 +3279,13 @@ public static Flowable merge(Publisher source1, Publisher{@code merge} does not operate by default on a particular {@link Scheduler}.
                *
                Error handling:
                *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are canceled. * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Flowable} has been canceled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Publisher, Publisher, Publisher)} to merge sources and terminate only when all source {@code Publisher}s * have completed or failed with an error. @@ -3329,13 +3329,13 @@ public static Flowable merge(Publisher source1, Publisher{@code merge} does not operate by default on a particular {@link Scheduler}.
                *
                Error handling:
                *
                If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are canceled. * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Flowable} has been canceled or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Publisher, Publisher, Publisher, Publisher)} to merge sources and terminate only when all source {@code Publisher}s * have completed or failed with an error. @@ -4024,7 +4024,7 @@ public static Single sequenceEqual(Publisher source1, * from the earlier-emitted Publisher and begins emitting items from the new one. *

                * The resulting Publisher completes if both the outer Publisher and the last inner Publisher, if any, complete. - * If the outer Publisher signals an onError, the inner Publisher is cancelled and the error delivered in-sequence. + * If the outer Publisher signals an onError, the inner Publisher is canceled and the error delivered in-sequence. *

                *
                Backpressure:
                *
                The operator honors backpressure from downstream. The outer {@code Publisher} is consumed in an @@ -4064,7 +4064,7 @@ public static Flowable switchOnNext(Publisher * The resulting Publisher completes if both the outer Publisher and the last inner Publisher, if any, complete. - * If the outer Publisher signals an onError, the inner Publisher is cancelled and the error delivered in-sequence. + * If the outer Publisher signals an onError, the inner Publisher is canceled and the error delivered in-sequence. *
                *
                Backpressure:
                *
                The operator honors backpressure from downstream. The outer {@code Publisher} is consumed in an @@ -4103,7 +4103,7 @@ public static Flowable switchOnNext(Publisher * The resulting Publisher completes if both the main Publisher and the last inner Publisher, if any, complete. * If the main Publisher signals an onError, the termination of the last inner Publisher will emit that error as is - * or wrapped into a CompositeException along with the other possible errors the former inner Publishers signalled. + * or wrapped into a CompositeException along with the other possible errors the former inner Publishers signaled. *
                *
                Backpressure:
                *
                The operator honors backpressure from downstream. The outer {@code Publisher} is consumed in an @@ -4142,7 +4142,7 @@ public static Flowable switchOnNextDelayError(Publisher * The resulting Publisher completes if both the main Publisher and the last inner Publisher, if any, complete. * If the main Publisher signals an onError, the termination of the last inner Publisher will emit that error as is - * or wrapped into a CompositeException along with the other possible errors the former inner Publishers signalled. + * or wrapped into a CompositeException along with the other possible errors the former inner Publishers signaled. *
                *
                Backpressure:
                *
                The operator honors backpressure from downstream. The outer {@code Publisher} is consumed in an @@ -4292,7 +4292,7 @@ public static Flowable using(Callable resourceSupplier, /** * Constructs a Publisher that creates a dependent resource object which is disposed of just before * termination if you have set {@code disposeEagerly} to {@code true} and cancellation does not occur - * before termination. Otherwise resource disposal will occur on cancellation. Eager disposal is + * before termination. Otherwise, resource disposal will occur on cancellation. Eager disposal is * particularly appropriate for a synchronous Publisher that reuses resources. {@code disposeAction} will * only be called once per subscription. *

                @@ -4344,8 +4344,8 @@ public static Flowable using(Callable resourceSupplier, * The resulting {@code Publisher} returned from {@code zip} will invoke {@code onNext} as many times as * the number of {@code onNext} invocations of the source Publisher that emits the fewest items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -4397,7 +4397,7 @@ public static Flowable zip(Iterable> * The resulting {@code Publisher} returned from {@code zip} will invoke {@code onNext} as many times as * the number of {@code onNext} invocations of the source Publisher that emits the fewest items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if + * The operator subscribes to its sources in the order they are specified and completes eagerly if * one of the sources is shorter than the rest while cancel the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if @@ -4454,8 +4454,8 @@ public static Flowable zip(Publisher> * as many times as the number of {@code onNext} invocations of the source Publisher that emits the fewest * items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -4514,8 +4514,8 @@ public static Flowable zip( * as many times as the number of {@code onNext} invocations of the source Publisher that emits the fewest * items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -4576,8 +4576,8 @@ public static Flowable zip( * as many times as the number of {@code onNext} invocations of the source Publisher that emits the fewest * items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -4639,8 +4639,8 @@ public static Flowable zip( * as many times as the number of {@code onNext} invocations of the source Publisher that emits the fewest * items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -4704,8 +4704,8 @@ public static Flowable zip( * as many times as the number of {@code onNext} invocations of the source Publisher that emits the fewest * items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -4774,8 +4774,8 @@ public static Flowable zip( * as many times as the number of {@code onNext} invocations of the source Publisher that emits the fewest * items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -4847,8 +4847,8 @@ public static Flowable zip( * as many times as the number of {@code onNext} invocations of the source Publisher that emits the fewest * items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -4924,8 +4924,8 @@ public static Flowable zip( * as many times as the number of {@code onNext} invocations of the source Publisher that emits the fewest * items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -5006,8 +5006,8 @@ public static Flowable zip( * as many times as the number of {@code onNext} invocations of the source Publisher that emits the fewest * items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -5092,8 +5092,8 @@ public static Flowable zip( * as many times as the number of {@code onNext} invocations of the source Publisher that emits the fewest * items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -5180,8 +5180,8 @@ public static Flowable zip( * The resulting {@code Publisher} returned from {@code zip} will invoke {@code onNext} as many times as * the number of {@code onNext} invocations of the source Publisher that emits the fewest items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -5211,7 +5211,7 @@ public static Flowable zip( * a function that, when applied to an item emitted by each of the source Publishers, results in * an item that will be emitted by the resulting Publisher * @param delayError - * delay errors signalled by any of the source Publisher until all Publishers terminate + * delay errors signaled by any of the source Publisher until all Publishers terminate * @param bufferSize * the number of elements to prefetch from each source Publisher * @return a Flowable that emits the zipped results @@ -5242,8 +5242,8 @@ public static Flowable zipArray(Function} returned from {@code zip} will invoke {@code onNext} as many times as * the number of {@code onNext} invocations of the source Publisher that emits the fewest items. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -5271,7 +5271,7 @@ public static Flowable zipArray(Function the common source value type @@ -5358,7 +5358,7 @@ public final Flowable ambWith(Publisher other) { *

                * *

                - * In Rx.Net this is the {@code any} Subscriber but we renamed it in RxJava to better match Java naming + * In Rx.Net this is the {@code any} operator but we renamed it in RxJava to better match Java naming * idioms. *

                *
                Backpressure:
                @@ -5776,7 +5776,7 @@ public final T blockingSingle(T defaultItem) { *

                * If the {@link Flowable} emits more than one item, {@link java.util.concurrent.Future} will receive an * {@link java.lang.IllegalArgumentException}. If the {@link Flowable} is empty, {@link java.util.concurrent.Future} - * will receive an {@link java.util.NoSuchElementException}. + * will receive a {@link java.util.NoSuchElementException}. *

                * If the {@code Flowable} may emit more than one item, use {@code Flowable.toList().toFuture()}. *

                @@ -6885,7 +6885,7 @@ public final Flowable compose(FlowableTransformer * * @param the type of the inner Publisher sources and thus the output type * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @return a Flowable that emits the result of applying the transformation function to each item emitted * by the source Publisher and concatenating the Publishers obtained from this transformation @@ -6917,7 +6917,7 @@ public final Flowable concatMap(Function the type of the inner Publisher sources and thus the output type * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @param prefetch * the number of elements to prefetch from the current Flowable @@ -7155,7 +7155,7 @@ public final Flowable concatMapDelayError(Function Flowable concatMapEager(Function Flowable concatMapSingleDelayError(Function * @@ -8007,7 +8007,7 @@ public final Flowable debounce(long timeout, TimeUnit unit, Scheduler schedul *

                Backpressure:
                *
                If the source {@code Publisher} is empty, this operator is guaranteed to honor backpressure from downstream. * If the source {@code Publisher} is non-empty, it is expected to honor backpressure as well; if the rule is violated, - * a {@code MissingBackpressureException} may get signalled somewhere downstream. + * a {@code MissingBackpressureException} may get signaled somewhere downstream. *
                *
                Scheduler:
                *
                {@code defaultIfEmpty} does not operate by default on a particular {@link Scheduler}.
                @@ -8105,8 +8105,8 @@ public final Flowable delay(long delay, TimeUnit unit) { * @param unit * the {@link TimeUnit} in which {@code period} is defined * @param delayError - * if true, the upstream exception is signalled with the given delay, after all preceding normal elements, - * if false, the upstream exception is signalled immediately + * if true, the upstream exception is signaled with the given delay, after all preceding normal elements, + * if false, the upstream exception is signaled immediately * @return the source Publisher shifted in time by the specified delay * @see ReactiveX operators documentation: Delay */ @@ -8164,8 +8164,8 @@ public final Flowable delay(long delay, TimeUnit unit, Scheduler scheduler) { * @param scheduler * the {@link Scheduler} to use for delaying * @param delayError - * if true, the upstream exception is signalled with the given delay, after all preceding normal elements, - * if false, the upstream exception is signalled immediately + * if true, the upstream exception is signaled with the given delay, after all preceding normal elements, + * if false, the upstream exception is signaled immediately * @return the source Publisher shifted in time by the specified delay * @see ReactiveX operators documentation: Delay */ @@ -8353,7 +8353,7 @@ public final Flowable dematerialize() { * *

                * It is recommended the elements' class {@code T} in the flow overrides the default {@code Object.equals()} and {@link Object#hashCode()} to provide - * meaningful comparison between items as the default Java implementation only considers reference equivalence. + * a meaningful comparison between items as the default Java implementation only considers reference equivalence. *

                * By default, {@code distinct()} uses an internal {@link java.util.HashSet} per Subscriber to remember * previously seen items and uses {@link java.util.Set#add(Object)} returning {@code false} as the @@ -8395,7 +8395,7 @@ public final Flowable distinct() { * *

                * It is recommended the keys' class {@code K} overrides the default {@code Object.equals()} and {@link Object#hashCode()} to provide - * meaningful comparison between the key objects as the default Java implementation only considers reference equivalence. + * a meaningful comparison between the key objects as the default Java implementation only considers reference equivalence. *

                * By default, {@code distinct()} uses an internal {@link java.util.HashSet} per Subscriber to remember * previously seen keys and uses {@link java.util.Set#add(Object)} returning {@code false} as the @@ -8438,7 +8438,7 @@ public final Flowable distinct(Function keySelector) { * *

                * It is recommended the keys' class {@code K} overrides the default {@code Object.equals()} and {@link Object#hashCode()} to provide - * meaningful comparison between the key objects as the default Java implementation only considers reference equivalence. + * a meaningful comparison between the key objects as the default Java implementation only considers reference equivalence. *

                *
                Backpressure:
                *
                The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -8474,7 +8474,7 @@ public final Flowable distinct(Function keySelector, * *

                * It is recommended the elements' class {@code T} in the flow overrides the default {@code Object.equals()} to provide - * meaningful comparison between items as the default Java implementation only considers reference equivalence. + * a meaningful comparison between items as the default Java implementation only considers reference equivalence. * Alternatively, use the {@link #distinctUntilChanged(BiPredicate)} overload and provide a comparison function * in case the class {@code T} can't be overridden with custom {@code equals()} or the comparison itself * should happen on different terms or properties of the class {@code T}. @@ -8509,7 +8509,7 @@ public final Flowable distinctUntilChanged() { * *

                * It is recommended the keys' class {@code K} overrides the default {@code Object.equals()} to provide - * meaningful comparison between the key objects as the default Java implementation only considers reference equivalence. + * a meaningful comparison between the key objects as the default Java implementation only considers reference equivalence. * Alternatively, use the {@link #distinctUntilChanged(BiPredicate)} overload and provide a comparison function * in case the class {@code K} can't be overridden with custom {@code equals()} or the comparison itself * should happen on different terms or properties of the item class {@code T} (for which the keys can be @@ -8573,7 +8573,7 @@ public final Flowable distinctUntilChanged(BiPredicate } /** - * Calls the specified action after this Flowable signals onError or onCompleted or gets cancelled by + * Calls the specified action after this Flowable signals onError or onCompleted or gets canceled by * the downstream. *

                In case of a race between a terminal event and a cancellation, the provided {@code onFinally} action * is executed once per subscription. @@ -8590,7 +8590,7 @@ public final Flowable distinctUntilChanged(BiPredicate * synchronous or asynchronous queue-fusion.

                *
                *

                History: 2.0.1 - experimental - * @param onFinally the action called when this Flowable terminates or gets cancelled + * @param onFinally the action called when this Flowable terminates or gets canceled * @return the new Flowable instance * @since 2.1 */ @@ -8661,7 +8661,7 @@ public final Flowable doAfterTerminate(Action onAfterTerminate) { * Calls the cancel {@code Action} if the downstream cancels the sequence. *

                * The action is shared between subscriptions and thus may be called concurrently from multiple - * threads; the action must be thread safe. + * threads; the action must be thread-safe. *

                * If the action throws a runtime exception, that exception is rethrown by the {@code onCancel()} call, * sometimes as a {@code CompositeException} if there were multiple exceptions along the way. @@ -8678,7 +8678,7 @@ public final Flowable doAfterTerminate(Action onAfterTerminate) { *

                * * @param onCancel - * the action that gets called when the source {@code Publisher}'s Subscription is cancelled + * the action that gets called when the source {@code Publisher}'s Subscription is canceled * @return the source {@code Publisher} modified so as to call this Action when appropriate * @see ReactiveX operators documentation: Do */ @@ -9190,7 +9190,7 @@ public final Single firstOrError() { * * @param the value type of the inner Publishers and the output type * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @return a Flowable that emits the result of applying the transformation function to each item emitted * by the source Publisher and merging the results of the Publishers obtained from this @@ -9222,11 +9222,11 @@ public final Flowable flatMap(Function the value type of the inner Publishers and the output type * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @param delayErrors * if true, exceptions from the current Flowable and all inner Publishers are delayed until all of them terminate - * if false, the first one signalling an exception will terminate the whole sequence immediately + * if false, the first one signaling an exception will terminate the whole sequence immediately * @return a Flowable that emits the result of applying the transformation function to each item emitted * by the source Publisher and merging the results of the Publishers obtained from this * transformation @@ -9258,7 +9258,7 @@ public final Flowable flatMap(Function the value type of the inner Publishers and the output type * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @param maxConcurrency * the maximum number of Publishers that may be subscribed to concurrently @@ -9294,13 +9294,13 @@ public final Flowable flatMap(Function the value type of the inner Publishers and the output type * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @param maxConcurrency * the maximum number of Publishers that may be subscribed to concurrently * @param delayErrors * if true, exceptions from the current Flowable and all inner Publishers are delayed until all of them terminate - * if false, the first one signalling an exception will terminate the whole sequence immediately + * if false, the first one signaling an exception will terminate the whole sequence immediately * @return a Flowable that emits the result of applying the transformation function to each item emitted * by the source Publisher and merging the results of the Publishers obtained from this * transformation @@ -9333,13 +9333,13 @@ public final Flowable flatMap(Function the value type of the inner Publishers and the output type * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @param maxConcurrency * the maximum number of Publishers that may be subscribed to concurrently * @param delayErrors * if true, exceptions from the current Flowable and all inner Publishers are delayed until all of them terminate - * if false, the first one signalling an exception will terminate the whole sequence immediately + * if false, the first one signaling an exception will terminate the whole sequence immediately * @param bufferSize * the number of elements to prefetch from each inner Publisher * @return a Flowable that emits the result of applying the transformation function to each item emitted @@ -9519,7 +9519,7 @@ public final Flowable flatMap(FunctionReactiveX operators documentation: FlatMap @@ -9561,7 +9561,7 @@ public final Flowable flatMap(FunctionReactiveX operators documentation: FlatMap @@ -9604,7 +9604,7 @@ public final Flowable flatMap(Function *
                Backpressure:
                *
                If {@code maxConcurrency == Integer.MAX_VALUE} the operator consumes the upstream in an unbounded manner. - * Otherwise the operator expects the upstream to honor backpressure. If the upstream doesn't support backpressure + * Otherwise, the operator expects the upstream to honor backpressure. If the upstream doesn't support backpressure * the operator behaves as if {@code maxConcurrency == Integer.MAX_VALUE} was used.
                *
                Scheduler:
                *
                {@code flatMapCompletable} does not operate by default on a particular {@link Scheduler}.
                @@ -9879,7 +9879,7 @@ public final Flowable flatMapMaybe(Function *
                Backpressure:
                *
                If {@code maxConcurrency == Integer.MAX_VALUE} the operator consumes the upstream in an unbounded manner. - * Otherwise the operator expects the upstream to honor backpressure. If the upstream doesn't support backpressure + * Otherwise, the operator expects the upstream to honor backpressure. If the upstream doesn't support backpressure * the operator behaves as if {@code maxConcurrency == Integer.MAX_VALUE} was used.
                *
                Scheduler:
                *
                {@code flatMapMaybe} does not operate by default on a particular {@link Scheduler}.
                @@ -9927,7 +9927,7 @@ public final Flowable flatMapSingle(Function *
                Backpressure:
                *
                If {@code maxConcurrency == Integer.MAX_VALUE} the operator consumes the upstream in an unbounded manner. - * Otherwise the operator expects the upstream to honor backpressure. If the upstream doesn't support backpressure + * Otherwise, the operator expects the upstream to honor backpressure. If the upstream doesn't support backpressure * the operator behaves as if {@code maxConcurrency == Integer.MAX_VALUE} was used.
                *
                Scheduler:
                *
                {@code flatMapSingle} does not operate by default on a particular {@link Scheduler}.
                @@ -9963,7 +9963,7 @@ public final Flowable flatMapSingle(FunctionReactiveX operators documentation: Subscribe @@ -9993,7 +9993,7 @@ public final Disposable forEach(Consumer onNext) { * @param onNext * {@link Predicate} to execute for each item. * @return - * a {@link Disposable} that allows cancelling an asynchronous sequence + * a {@link Disposable} that allows canceling an asynchronous sequence * @throws NullPointerException * if {@code onNext} is null * @see ReactiveX operators documentation: Subscribe @@ -10021,7 +10021,7 @@ public final Disposable forEachWhile(Predicate onNext) { * @param onError * {@link Consumer} to execute when an error is emitted. * @return - * a {@link Disposable} that allows cancelling an asynchronous sequence + * a {@link Disposable} that allows canceling an asynchronous sequence * @throws NullPointerException * if {@code onNext} is null, or * if {@code onError} is null @@ -10050,9 +10050,9 @@ public final Disposable forEachWhile(Predicate onNext, Consumer Flowable> groupBy(Function} with the entry value (not the key!) when an entry in this - * map has been evicted. The next source emission will bring about the completion of the evicted + * map has been evicted. The next source emission will bring about the completion of the evicted * {@link GroupedFlowable}s and the arrival of an item with the same key as a completed {@link GroupedFlowable} * will prompt the creation and emission of a new {@link GroupedFlowable} with that key. * @@ -10676,7 +10676,7 @@ public final Single lastOrError() { * * public final class CustomSubscriber<T> implements FlowableSubscriber<T>, Subscription { * - * // The donstream's Subscriber that will receive the onXXX events + * // The downstream's Subscriber that will receive the onXXX events * final Subscriber<? super String> downstream; * * // The connection to the upstream source that will call this class' onXXX methods @@ -10738,7 +10738,7 @@ public final Single lastOrError() { * // Some operators may use their own resources which should be cleaned up if * // the downstream cancels the flow before it completed. Operators without * // resources can simply forward the cancellation to the upstream. - * // In some cases, a cancelled flag may be set by this method so that other parts + * // In some cases, a canceled flag may be set by this method so that other parts * // of this class may detect the cancellation and stop sending events * // to the downstream. * @Override @@ -10966,7 +10966,7 @@ public final Flowable mergeWith(@NonNull SingleSource other) { /** * Merges the sequence of items of this Flowable with the success value of the other MaybeSource - * or waits both to complete normally if the MaybeSource is empty. + * or waits for both to complete normally if the MaybeSource is empty. *

                * *

                @@ -11195,7 +11195,7 @@ public final Flowable onBackpressureBuffer() { *

                * @param delayError * if true, an exception from the current Flowable is delayed until all buffered elements have been - * consumed by the downstream; if false, an exception is immediately signalled to the downstream, skipping + * consumed by the downstream; if false, an exception is immediately signaled to the downstream, skipping * any buffered element * @return the source Publisher modified to buffer items to the extent system resources allow * @see ReactiveX operators documentation: backpressure operators @@ -11209,9 +11209,9 @@ public final Flowable onBackpressureBuffer(boolean delayError) { /** * Instructs a Publisher that is emitting items faster than its Subscriber can consume them to buffer up to - * a given amount of items until they can be emitted. The resulting Publisher will {@code onError} emitting - * a {@code BufferOverflowException} as soon as the buffer's capacity is exceeded, dropping all undelivered - * items, and cancelling the source. + * a given amount of items until they can be emitted. The resulting Publisher will signal + * a {@code BufferOverflowException} via {@code onError} as soon as the buffer's capacity is exceeded, dropping all undelivered + * items, and canceling the source. *

                * *

                @@ -11236,9 +11236,9 @@ public final Flowable onBackpressureBuffer(int capacity) { /** * Instructs a Publisher that is emitting items faster than its Subscriber can consume them to buffer up to - * a given amount of items until they can be emitted. The resulting Publisher will {@code onError} emitting - * a {@code BufferOverflowException} as soon as the buffer's capacity is exceeded, dropping all undelivered - * items, and cancelling the source. + * a given amount of items until they can be emitted. The resulting Publisher will signal + * a {@code BufferOverflowException} via {@code onError} as soon as the buffer's capacity is exceeded, dropping all undelivered + * items, and canceling the source. *

                * *

                @@ -11252,7 +11252,7 @@ public final Flowable onBackpressureBuffer(int capacity) { * @param capacity number of slots available in the buffer. * @param delayError * if true, an exception from the current Flowable is delayed until all buffered elements have been - * consumed by the downstream; if false, an exception is immediately signalled to the downstream, skipping + * consumed by the downstream; if false, an exception is immediately signaled to the downstream, skipping * any buffered element * @return the source {@code Publisher} modified to buffer items up to the given capacity. * @see ReactiveX operators documentation: backpressure operators @@ -11267,9 +11267,9 @@ public final Flowable onBackpressureBuffer(int capacity, boolean delayError) /** * Instructs a Publisher that is emitting items faster than its Subscriber can consume them to buffer up to - * a given amount of items until they can be emitted. The resulting Publisher will {@code onError} emitting - * a {@code BufferOverflowException} as soon as the buffer's capacity is exceeded, dropping all undelivered - * items, and cancelling the source. + * a given amount of items until they can be emitted. The resulting Publisher will signal + * a {@code BufferOverflowException} via {@code onError} as soon as the buffer's capacity is exceeded, dropping all undelivered + * items, and canceling the source. *

                * *

                @@ -11283,7 +11283,7 @@ public final Flowable onBackpressureBuffer(int capacity, boolean delayError) * @param capacity number of slots available in the buffer. * @param delayError * if true, an exception from the current Flowable is delayed until all buffered elements have been - * consumed by the downstream; if false, an exception is immediately signalled to the downstream, skipping + * consumed by the downstream; if false, an exception is immediately signaled to the downstream, skipping * any buffered element * @param unbounded * if true, the capacity value is interpreted as the internal "island" size of the unbounded buffer @@ -11301,9 +11301,9 @@ public final Flowable onBackpressureBuffer(int capacity, boolean delayError, /** * Instructs a Publisher that is emitting items faster than its Subscriber can consume them to buffer up to - * a given amount of items until they can be emitted. The resulting Publisher will {@code onError} emitting - * a {@code BufferOverflowException} as soon as the buffer's capacity is exceeded, dropping all undelivered - * items, cancelling the source, and notifying the producer with {@code onOverflow}. + * a given amount of items until they can be emitted. The resulting Publisher will signal + * a {@code BufferOverflowException} via {@code onError} as soon as the buffer's capacity is exceeded, dropping all undelivered + * items, canceling the source, and notifying the producer with {@code onOverflow}. *

                * *

                @@ -11317,7 +11317,7 @@ public final Flowable onBackpressureBuffer(int capacity, boolean delayError, * @param capacity number of slots available in the buffer. * @param delayError * if true, an exception from the current Flowable is delayed until all buffered elements have been - * consumed by the downstream; if false, an exception is immediately signalled to the downstream, skipping + * consumed by the downstream; if false, an exception is immediately signaled to the downstream, skipping * any buffered element * @param unbounded * if true, the capacity value is interpreted as the internal "island" size of the unbounded buffer @@ -11338,9 +11338,9 @@ public final Flowable onBackpressureBuffer(int capacity, boolean delayError, /** * Instructs a Publisher that is emitting items faster than its Subscriber can consume them to buffer up to - * a given amount of items until they can be emitted. The resulting Publisher will {@code onError} emitting - * a {@code BufferOverflowException} as soon as the buffer's capacity is exceeded, dropping all undelivered - * items, cancelling the source, and notifying the producer with {@code onOverflow}. + * a given amount of items until they can be emitted. The resulting Publisher will signal + * a {@code BufferOverflowException} via {@code onError} as soon as the buffer's capacity is exceeded, dropping all undelivered + * items, canceling the source, and notifying the producer with {@code onOverflow}. *

                * *

                @@ -11370,10 +11370,10 @@ public final Flowable onBackpressureBuffer(int capacity, Action onOverflow) { * by {@code overflowStrategy} if the buffer capacity is exceeded. * *
                  - *
                • {@code BackpressureOverflow.Strategy.ON_OVERFLOW_ERROR} (default) will {@code onError} dropping all undelivered items, - * cancelling the source, and notifying the producer with {@code onOverflow}.
                • + *
                • {@code BackpressureOverflow.Strategy.ON_OVERFLOW_ERROR} (default) will call {@code onError} dropping all undelivered items, + * canceling the source, and notifying the producer with {@code onOverflow}.
                • *
                • {@code BackpressureOverflow.Strategy.ON_OVERFLOW_DROP_LATEST} will drop any new items emitted by the producer while - * the buffer is full, without generating any {@code onError}. Each drop will however invoke {@code onOverflow} + * the buffer is full, without generating any {@code onError}. Each drop will, however, invoke {@code onOverflow} * to signal the overflow to the producer.
                • *
                • {@code BackpressureOverflow.Strategy.ON_OVERFLOW_DROP_OLDEST} will drop the oldest items in the buffer in order to make * room for newly emitted ones. Overflow will not generate an{@code onError}, but each drop will invoke @@ -11517,7 +11517,7 @@ public final Flowable onBackpressureLatest() { * are expected to honor backpressure as well. * If any of them violate this expectation, the operator may throw an * {@code IllegalStateException} when the source {@code Publisher} completes or - * a {@code MissingBackpressureException} is signalled somewhere downstream.
                + * a {@code MissingBackpressureException} is signaled somewhere downstream.
                *
                Scheduler:
                *
                {@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -11560,7 +11560,7 @@ public final Flowable onErrorResumeNext(Functionmay throw an * {@code IllegalStateException} when the source {@code Publisher} completes or - * {@code MissingBackpressureException} is signalled somewhere downstream.
                + * {@code MissingBackpressureException} is signaled somewhere downstream.
                *
                Scheduler:
                *
                {@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -11599,7 +11599,7 @@ public final Flowable onErrorResumeNext(final Publisher next) { *
                The operator honors backpressure from downstream. The source {@code Publisher}s is expected to honor * backpressure as well. If it this expectation is violated, the operator may throw * {@code IllegalStateException} when the source {@code Publisher} completes or - * {@code MissingBackpressureException} is signalled somewhere downstream.
                + * {@code MissingBackpressureException} is signaled somewhere downstream. *
                Scheduler:
                *
                {@code onErrorReturn} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -11638,7 +11638,7 @@ public final Flowable onErrorReturn(Function *
                The operator honors backpressure from downstream. The source {@code Publisher}s is expected to honor * backpressure as well. If it this expectation is violated, the operator may throw * {@code IllegalStateException} when the source {@code Publisher} completes or - * {@code MissingBackpressureException} is signalled somewhere downstream.
                + * {@code MissingBackpressureException} is signaled somewhere downstream. *
                Scheduler:
                *
                {@code onErrorReturnItem} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -11684,7 +11684,7 @@ public final Flowable onErrorReturnItem(final T item) { * are expected to honor backpressure as well. * If any of them violate this expectation, the operator may throw an * {@code IllegalStateException} when the source {@code Publisher} completes or - * {@code MissingBackpressureException} is signalled somewhere downstream. + * {@code MissingBackpressureException} is signaled somewhere downstream. *
                Scheduler:
                *
                {@code onExceptionResumeNext} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -11857,7 +11857,7 @@ public final ConnectableFlowable publish() { *
                The operator expects the source {@code Publisher} to honor backpressure and if this expectation is * violated, the operator will signal a {@code MissingBackpressureException} through the {@code Publisher} * provided to the function. Since the {@code Publisher} returned by the {@code selector} may be - * independent from the provided {@code Publisher} to the function, the output's backpressure behavior + * independent of the provided {@code Publisher} to the function, the output's backpressure behavior * is determined by this returned {@code Publisher}.
                *
                Scheduler:
                *
                {@code publish} does not operate by default on a particular {@link Scheduler}.
                @@ -11889,7 +11889,7 @@ public final Flowable publish(Function, ? extends Pub *
                The operator expects the source {@code Publisher} to honor backpressure and if this expectation is * violated, the operator will signal a {@code MissingBackpressureException} through the {@code Publisher} * provided to the function. Since the {@code Publisher} returned by the {@code selector} may be - * independent from the provided {@code Publisher} to the function, the output's backpressure behavior + * independent of the provided {@code Publisher} to the function, the output's backpressure behavior * is determined by this returned {@code Publisher}.
                *
                Scheduler:
                *
                {@code publish} does not operate by default on a particular {@link Scheduler}.
                @@ -11975,7 +11975,7 @@ public final Flowable rebatchRequests(int n) { * Publisher into the same function, and so on until all items have been emitted by the finite source Publisher, * and emits the final result from the final call to your function as its sole item. *

                - * If the source is empty, a {@code NoSuchElementException} is signalled. + * If the source is empty, a {@code NoSuchElementException} is signaled. *

                * *

                @@ -13027,7 +13027,7 @@ public final Flowable retryUntil(final BooleanSupplier stop) { * Note that the inner {@code Publisher} returned by the handler function should signal * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to - * the operator is asynchronous, signalling onNext followed by onComplete immediately may + * the operator is asynchronous, signaling onNext followed by onComplete immediately may * result in the sequence to be completed immediately. Similarly, if this inner * {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is * active, the sequence is terminated with the same signal immediately. @@ -13314,7 +13314,7 @@ public final Flowable sample(Publisher sampler, boolean emitLast) { *

                *
                Backpressure:
                *
                The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well. - * Violating this expectation, a {@code MissingBackpressureException} may get signalled somewhere downstream.
                + * Violating this expectation, a {@code MissingBackpressureException} may get signaled somewhere downstream. *
                Scheduler:
                *
                {@code scan} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -13363,7 +13363,7 @@ public final Flowable scan(BiFunction accumulator) { *
                *
                Backpressure:
                *
                The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well. - * Violating this expectation, a {@code MissingBackpressureException} may get signalled somewhere downstream.
                + * Violating this expectation, a {@code MissingBackpressureException} may get signaled somewhere downstream. *
                Scheduler:
                *
                {@code scan} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -13402,7 +13402,7 @@ public final Flowable scan(final R initialValue, BiFunction *
                Backpressure:
                *
                The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well. - * Violating this expectation, a {@code MissingBackpressureException} may get signalled somewhere downstream.
                + * Violating this expectation, a {@code MissingBackpressureException} may get signaled somewhere downstream. *
                Scheduler:
                *
                {@code scanWith} does not operate by default on a particular {@link Scheduler}.
                *
                @@ -13460,14 +13460,14 @@ public final Flowable serialize() { /** * Returns a new {@link Publisher} that multicasts (and shares a single subscription to) the original {@link Publisher}. As long as * there is at least one {@link Subscriber} this {@link Publisher} will be subscribed and emitting data. - * When all subscribers have cancelled it will cancel the source {@link Publisher}. + * When all subscribers have canceled it will cancel the source {@link Publisher}. *

                * This is an alias for {@link #publish()}.{@link ConnectableFlowable#refCount() refCount()}. *

                * *

                *
                Backpressure:
                - *
                The operator honors backpressure and and expects the source {@code Publisher} to honor backpressure as well. + *
                The operator honors backpressure and expects the source {@code Publisher} to honor backpressure as well. * If this expectation is violated, the operator will signal a {@code MissingBackpressureException} to * its {@code Subscriber}s.
                *
                Scheduler:
                @@ -13512,7 +13512,7 @@ public final Maybe singleElement() { /** * Returns a Single that emits the single item emitted by the source Publisher, if that Publisher * emits only a single item, or a default item if the source Publisher emits no items. If the source - * Publisher emits more than one item, an {@code IllegalArgumentException} is signalled instead. + * Publisher emits more than one item, an {@code IllegalArgumentException} is signaled instead. *

                * *

                @@ -13540,8 +13540,8 @@ public final Single single(T defaultItem) { /** * Returns a Single that emits the single item emitted by this Flowable, if this Flowable * emits only a single item, otherwise - * if this Flowable completes without emitting any items a {@link NoSuchElementException} will be signalled and - * if this Flowable emits more than one item, an {@code IllegalArgumentException} will be signalled. + * if this Flowable completes without emitting any items a {@link NoSuchElementException} will be signaled and + * if this Flowable emits more than one item, an {@code IllegalArgumentException} will be signaled. *

                * *

                @@ -13598,7 +13598,7 @@ public final Flowable skip(long count) { * *
                *
                Backpressure:
                - *
                The operator doesn't support backpressure as it uses time to skip arbitrary number of elements and + *
                The operator doesn't support backpressure as it uses time to skip an arbitrary number of elements and * thus has to consume the source {@code Publisher} in an unbounded manner (i.e., no backpressure applied to it).
                *
                Scheduler:
                *
                {@code skip} does not operate on any particular scheduler but uses the current time @@ -13627,7 +13627,7 @@ public final Flowable skip(long time, TimeUnit unit) { * *
                *
                Backpressure:
                - *
                The operator doesn't support backpressure as it uses time to skip arbitrary number of elements and + *
                The operator doesn't support backpressure as it uses time to skip an arbitrary number of elements and * thus has to consume the source {@code Publisher} in an unbounded manner (i.e., no backpressure applied to it).
                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use for the timed skipping
                @@ -13697,7 +13697,7 @@ public final Flowable skipLast(int count) { * Note: this action will cache the latest items arriving in the specified time window. *
                *
                Backpressure:
                - *
                The operator doesn't support backpressure as it uses time to skip arbitrary number of elements and + *
                The operator doesn't support backpressure as it uses time to skip an arbitrary number of elements and * thus has to consume the source {@code Publisher} in an unbounded manner (i.e., no backpressure applied to it).
                *
                Scheduler:
                *
                {@code skipLast} does not operate on any particular scheduler but uses the current time @@ -13728,7 +13728,7 @@ public final Flowable skipLast(long time, TimeUnit unit) { * Note: this action will cache the latest items arriving in the specified time window. *
                *
                Backpressure:
                - *
                The operator doesn't support backpressure as it uses time to skip arbitrary number of elements and + *
                The operator doesn't support backpressure as it uses time to skip an arbitrary number of elements and * thus has to consume the source {@code Publisher} in an unbounded manner (i.e., no backpressure applied to it).
                *
                Scheduler:
                *
                {@code skipLast} does not operate on any particular scheduler but uses the current time @@ -13740,8 +13740,8 @@ public final Flowable skipLast(long time, TimeUnit unit) { * @param unit * the time unit of {@code time} * @param delayError - * if true, an exception signalled by the current Flowable is delayed until the regular elements are consumed - * by the downstream; if false, an exception is immediately signalled and all regular elements dropped + * if true, an exception signaled by the current Flowable is delayed until the regular elements are consumed + * by the downstream; if false, an exception is immediately signaled and all regular elements dropped * @return a Flowable that drops those items emitted by the source Publisher in a time window before the * source completes defined by {@code time} * @see ReactiveX operators documentation: SkipLast @@ -13762,7 +13762,7 @@ public final Flowable skipLast(long time, TimeUnit unit, boolean delayError) * Note: this action will cache the latest items arriving in the specified time window. *
                *
                Backpressure:
                - *
                The operator doesn't support backpressure as it uses time to skip arbitrary number of elements and + *
                The operator doesn't support backpressure as it uses time to skip an arbitrary number of elements and * thus has to consume the source {@code Publisher} in an unbounded manner (i.e., no backpressure applied to it).
                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use for tracking the current time
                @@ -13794,7 +13794,7 @@ public final Flowable skipLast(long time, TimeUnit unit, Scheduler scheduler) * Note: this action will cache the latest items arriving in the specified time window. *
                *
                Backpressure:
                - *
                The operator doesn't support backpressure as it uses time to skip arbitrary number of elements and + *
                The operator doesn't support backpressure as it uses time to skip an arbitrary number of elements and * thus has to consume the source {@code Publisher} in an unbounded manner (i.e., no backpressure applied to it).
                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use to track the current time
                @@ -13807,8 +13807,8 @@ public final Flowable skipLast(long time, TimeUnit unit, Scheduler scheduler) * @param scheduler * the scheduler used as the time source * @param delayError - * if true, an exception signalled by the current Flowable is delayed until the regular elements are consumed - * by the downstream; if false, an exception is immediately signalled and all regular elements dropped + * if true, an exception signaled by the current Flowable is delayed until the regular elements are consumed + * by the downstream; if false, an exception is immediately signaled and all regular elements dropped * @return a Flowable that drops those items emitted by the source Publisher in a time window before the * source completes defined by {@code time} and {@code scheduler} * @see ReactiveX operators documentation: SkipLast @@ -13829,7 +13829,7 @@ public final Flowable skipLast(long time, TimeUnit unit, Scheduler scheduler, * Note: this action will cache the latest items arriving in the specified time window. *
                *
                Backpressure:
                - *
                The operator doesn't support backpressure as it uses time to skip arbitrary number of elements and + *
                The operator doesn't support backpressure as it uses time to skip an arbitrary number of elements and * thus has to consume the source {@code Publisher} in an unbounded manner (i.e., no backpressure applied to it).
                *
                Scheduler:
                *
                You specify which {@link Scheduler} this operator will use.
                @@ -13842,8 +13842,8 @@ public final Flowable skipLast(long time, TimeUnit unit, Scheduler scheduler, * @param scheduler * the scheduler used as the time source * @param delayError - * if true, an exception signalled by the current Flowable is delayed until the regular elements are consumed - * by the downstream; if false, an exception is immediately signalled and all regular elements dropped + * if true, an exception signaled by the current Flowable is delayed until the regular elements are consumed + * by the downstream; if false, an exception is immediately signaled and all regular elements dropped * @param bufferSize * the hint about how many elements to expect to be skipped * @return a Flowable that drops those items emitted by the source Publisher in a time window before the @@ -14456,7 +14456,7 @@ public final Flowable subscribeOn(@NonNull Scheduler scheduler, boolean reque *
                If the source {@code Publisher} is empty, the alternate {@code Publisher} is expected to honor backpressure. * If the source {@code Publisher} is non-empty, it is expected to honor backpressure as instead. * In either case, if violated, a {@code MissingBackpressureException} may get - * signalled somewhere downstream. + * signaled somewhere downstream. *
                *
                Scheduler:
                *
                {@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.
                @@ -14482,7 +14482,7 @@ public final Flowable switchIfEmpty(Publisher other) { * of these Publishers. *

                * The resulting Publisher completes if both the upstream Publisher and the last inner Publisher, if any, complete. - * If the upstream Publisher signals an onError, the inner Publisher is cancelled and the error delivered in-sequence. + * If the upstream Publisher signals an onError, the inner Publisher is canceled and the error delivered in-sequence. *

                * *

                @@ -14497,7 +14497,7 @@ public final Flowable switchIfEmpty(Publisher other) { * * @param the element type of the inner Publishers and the output * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @return a Flowable that emits the items emitted by the Publisher returned from applying {@code func} to the most recently emitted item emitted by the source Publisher * @see ReactiveX operators documentation: FlatMap @@ -14515,7 +14515,7 @@ public final Flowable switchMap(Function * The resulting Publisher completes if both the upstream Publisher and the last inner Publisher, if any, complete. - * If the upstream Publisher signals an onError, the inner Publisher is cancelled and the error delivered in-sequence. + * If the upstream Publisher signals an onError, the inner Publisher is canceled and the error delivered in-sequence. *

                * *

                @@ -14530,7 +14530,7 @@ public final Flowable switchMap(Function the element type of the inner Publishers and the output * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @param bufferSize * the number of elements to prefetch from the current active inner Publisher @@ -14570,7 +14570,7 @@ public final Flowable switchMap(Function *
                @@ -14612,11 +14612,11 @@ public final Completable switchMapCompletable(@NonNull FunctionErrors of this {@code Flowable} and all the {@code CompletableSource}s, who had the chance * to run to their completion, are delayed until * all of them terminate in some fashion. At this point, if there was only one failure, the respective - * {@code Throwable} is emitted to the dowstream. It there were more than one failures, the + * {@code Throwable} is emitted to the downstream. If there was more than one failure, the * operator combines all {@code Throwable}s into a {@link io.reactivex.exceptions.CompositeException CompositeException} * and signals that to the downstream. * If any inactivated (switched out) {@code CompletableSource} - * signals an {@code onError} late, the {@code Throwable}s will be signalled to the global error handler via + * signals an {@code onError} late, the {@code Throwable}s will be signaled to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. *
                *
                @@ -14643,7 +14643,7 @@ public final Completable switchMapCompletableDelayError(@NonNull Function * The resulting Publisher completes if both the upstream Publisher and the last inner Publisher, if any, complete. * If the upstream Publisher signals an onError, the termination of the last inner Publisher will emit that error as is - * or wrapped into a CompositeException along with the other possible errors the former inner Publishers signalled. + * or wrapped into a CompositeException along with the other possible errors the former inner Publishers signaled. *

                * *

                @@ -14658,7 +14658,7 @@ public final Completable switchMapCompletableDelayError(@NonNull Function the element type of the inner Publishers and the output * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @return a Flowable that emits the items emitted by the Publisher returned from applying {@code func} to the most recently emitted item emitted by the source Publisher * @see ReactiveX operators documentation: FlatMap @@ -14678,7 +14678,7 @@ public final Flowable switchMapDelayError(Function * The resulting Publisher completes if both the upstream Publisher and the last inner Publisher, if any, complete. * If the upstream Publisher signals an onError, the termination of the last inner Publisher will emit that error as is - * or wrapped into a CompositeException along with the other possible errors the former inner Publishers signalled. + * or wrapped into a CompositeException along with the other possible errors the former inner Publishers signaled. *

                * *

                @@ -14693,7 +14693,7 @@ public final Flowable switchMapDelayError(Function the element type of the inner Publishers and the output * @param mapper - * a function that, when applied to an item emitted by the source Publisher, returns an + * a function that, when applied to an item emitted by the source Publisher, returns a * Publisher * @param bufferSize * the number of elements to prefetch from the current active inner Publisher @@ -15086,8 +15086,8 @@ public final Flowable takeLast(long count, long time, TimeUnit unit, Schedule * @param scheduler * the {@link Scheduler} that provides the timestamps for the observed items * @param delayError - * if true, an exception signalled by the current Flowable is delayed until the regular elements are consumed - * by the downstream; if false, an exception is immediately signalled and all regular elements dropped + * if true, an exception signaled by the current Flowable is delayed until the regular elements are consumed + * by the downstream; if false, an exception is immediately signaled and all regular elements dropped * @param bufferSize * the hint about how many elements to expect to be last * @return a Flowable that emits at most {@code count} items from the source Publisher that were emitted @@ -15160,8 +15160,8 @@ public final Flowable takeLast(long time, TimeUnit unit) { * @param unit * the time unit of {@code time} * @param delayError - * if true, an exception signalled by the current Flowable is delayed until the regular elements are consumed - * by the downstream; if false, an exception is immediately signalled and all regular elements dropped + * if true, an exception signaled by the current Flowable is delayed until the regular elements are consumed + * by the downstream; if false, an exception is immediately signaled and all regular elements dropped * @return a Flowable that emits the items from the source Publisher that were emitted in the window of * time before the Publisher completed specified by {@code time} * @see ReactiveX operators documentation: TakeLast @@ -15230,8 +15230,8 @@ public final Flowable takeLast(long time, TimeUnit unit, Scheduler scheduler) * @param scheduler * the Scheduler that provides the timestamps for the Observed items * @param delayError - * if true, an exception signalled by the current Flowable is delayed until the regular elements are consumed - * by the downstream; if false, an exception is immediately signalled and all regular elements dropped + * if true, an exception signaled by the current Flowable is delayed until the regular elements are consumed + * by the downstream; if false, an exception is immediately signaled and all regular elements dropped * @return a Flowable that emits the items from the source Publisher that were emitted in the window of * time before the Publisher completed specified by {@code time}, where the timing information is * provided by {@code scheduler} @@ -15267,8 +15267,8 @@ public final Flowable takeLast(long time, TimeUnit unit, Scheduler scheduler, * @param scheduler * the Scheduler that provides the timestamps for the Observed items * @param delayError - * if true, an exception signalled by the current Flowable is delayed until the regular elements are consumed - * by the downstream; if false, an exception is immediately signalled and all regular elements dropped + * if true, an exception signaled by the current Flowable is delayed until the regular elements are consumed + * by the downstream; if false, an exception is immediately signaled and all regular elements dropped * @param bufferSize * the hint about how many elements to expect to be last * @return a Flowable that emits the items from the source Publisher that were emitted in the window of @@ -15377,7 +15377,7 @@ public final Flowable takeWhile(Predicate predicate) { * Returns a Flowable that emits only the first item emitted by the source Publisher during sequential * time windows of a specified duration. *

                - * This differs from {@link #throttleLast} in that this only tracks passage of time whereas + * This differs from {@link #throttleLast} in that this only tracks the passage of time whereas * {@link #throttleLast} ticks at scheduled intervals. *

                * @@ -15407,7 +15407,7 @@ public final Flowable throttleFirst(long windowDuration, TimeUnit unit) { * Returns a Flowable that emits only the first item emitted by the source Publisher during sequential * time windows of a specified duration, where the windows are managed by a specified Scheduler. *

                - * This differs from {@link #throttleLast} in that this only tracks passage of time whereas + * This differs from {@link #throttleLast} in that this only tracks the passage of time whereas * {@link #throttleLast} ticks at scheduled intervals. *

                * @@ -15443,7 +15443,7 @@ public final Flowable throttleFirst(long skipDuration, TimeUnit unit, Schedul * time windows of a specified duration. *

                * This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas - * {@link #throttleFirst} does not tick, it just tracks passage of time. + * {@link #throttleFirst} does not tick, it just tracks the passage of time. *

                * *

                @@ -15475,7 +15475,7 @@ public final Flowable throttleLast(long intervalDuration, TimeUnit unit) { * time windows of a specified duration, where the duration is governed by a specified Scheduler. *

                * This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas - * {@link #throttleFirst} does not tick, it just tracks passage of time. + * {@link #throttleFirst} does not tick, it just tracks the passage of time. *

                * *

                @@ -15868,7 +15868,7 @@ public final Flowable timeout(long timeout, TimeUnit timeUnit, Scheduler sche /** * Returns a Flowable that mirrors the source Publisher but applies a timeout policy for each emitted - * item, where this policy is governed on a specified Scheduler. If the next item isn't emitted within the + * item, where this policy is governed by a specified Scheduler. If the next item isn't emitted within the * specified timeout duration starting from its predecessor, the resulting Publisher terminates and * notifies Subscribers of a {@code TimeoutException}. *

                @@ -15910,7 +15910,7 @@ public final Flowable timeout(long timeout, TimeUnit timeUnit, Scheduler sche * are expected to honor backpressure as well. If any of then violates this rule, it may throw an * {@code IllegalStateException} when the {@code Publisher} completes.

                *
                Scheduler:
                - *
                {@code timeout} does not operates by default on any {@link Scheduler}.
                + *
                {@code timeout} does not operate by default on any {@link Scheduler}.
                *
                * * @param @@ -15951,7 +15951,7 @@ public final Flowable timeout(Publisher firstTimeoutIndicator, * If any of the source {@code Publisher}s violate this, it may throw an * {@code IllegalStateException} when the source {@code Publisher} completes.
                *
                Scheduler:
                - *
                {@code timeout} does not operates by default on any {@link Scheduler}.
                + *
                {@code timeout} does not operate by default on any {@link Scheduler}.
                *
                * * @param @@ -17668,8 +17668,8 @@ public final Flowable zipWith(Iterable other, BiFunction - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -17715,8 +17715,8 @@ public final Flowable zipWith(Publisher other, BiFunction * Returns a Flowable that emits items that are the result of applying a specified function to pairs of * values, one each from the source Publisher and another specified Publisher. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -17765,8 +17765,8 @@ public final Flowable zipWith(Publisher other, * Returns a Flowable that emits items that are the result of applying a specified function to pairs of * values, one each from the source Publisher and another specified Publisher. *

                - * The operator subscribes to its sources in order they are specified and completes eagerly if - * one of the sources is shorter than the rest while cancelling the other sources. Therefore, it + * The operator subscribes to its sources in the order they are specified and completes eagerly if + * one of the sources is shorter than the rest while canceling the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't @@ -17870,7 +17870,7 @@ public final TestSubscriber test(long initialRequest) { // NoPMD *

                {@code test} does not operate by default on a particular {@link Scheduler}.
                *
                * @param initialRequest the initial request amount, positive - * @param cancel should the TestSubscriber be cancelled before the subscription? + * @param cancel should the TestSubscriber be canceled before the subscription? * @return the new TestSubscriber instance * @since 2.0 */ diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 3afe266025..4f5ced8de3 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -2978,7 +2978,7 @@ public final Observable flatMapObservable(Function the result value type * @param mapper - * a function that, when applied to the item emitted by the source Maybe, returns an + * a function that, when applied to the item emitted by the source Maybe, returns a * Flowable * @return the Flowable returned from {@code func} when applied to the item emitted by the source Maybe * @see ReactiveX operators documentation: FlatMap @@ -3139,7 +3139,7 @@ public final Single isEmpty() { * * public final class CustomMaybeObserver<T> implements MaybeObserver<T>, Disposable { * - * // The donstream's MaybeObserver that will receive the onXXX events + * // The downstream's MaybeObserver that will receive the onXXX events * final MaybeObserver<? super String> downstream; * * // The connection to the upstream source that will call this class' onXXX methods diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 64bb418818..dbc7dfd1ad 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -9386,7 +9386,7 @@ public final Single lastOrError() { * * public final class CustomObserver<T> implements Observer<T>, Disposable { * - * // The donstream's Observer that will receive the onXXX events + * // The downstream's Observer that will receive the onXXX events * final Observer<? super String> downstream; * * // The connection to the upstream source that will call this class' onXXX methods @@ -12250,7 +12250,7 @@ public final Completable switchMapCompletable(@NonNull FunctionErrors of this {@code Observable} and all the {@code CompletableSource}s, who had the chance * to run to their completion, are delayed until * all of them terminate in some fashion. At this point, if there was only one failure, the respective - * {@code Throwable} is emitted to the dowstream. It there were more than one failures, the + * {@code Throwable} is emitted to the downstream. It there were more than one failures, the * operator combines all {@code Throwable}s into a {@link io.reactivex.exceptions.CompositeException CompositeException} * and signals that to the downstream. * If any inactivated (switched out) {@code CompletableSource} diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index c270100f09..d18170b221 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2365,7 +2365,7 @@ public final Maybe flatMapMaybe(final Function the result value type * @param mapper - * a function that, when applied to the item emitted by the source Single, returns an + * a function that, when applied to the item emitted by the source Single, returns a * Flowable * @return the Flowable returned from {@code func} when applied to the item emitted by the source Single * @see ReactiveX operators documentation: FlatMap @@ -2517,7 +2517,7 @@ public final T blockingGet() { * * public final class CustomSingleObserver<T> implements SingleObserver<T>, Disposable { * - * // The donstream's SingleObserver that will receive the onXXX events + * // The downstream's SingleObserver that will receive the onXXX events * final SingleObserver<? super String> downstream; * * // The connection to the upstream source that will call this class' onXXX methods diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java index 1482c137b4..17e32779eb 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java @@ -31,7 +31,7 @@ import io.reactivex.plugins.RxJavaPlugins; /** - * Maps the upstream intems into {@link CompletableSource}s and subscribes to them one after the + * Maps the upstream items into {@link CompletableSource}s and subscribes to them one after the * other completes or terminates (in error-delaying mode). * @param the upstream value type * @since 2.1.11 - experimental diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java index da2f635437..30b463c666 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java @@ -28,7 +28,7 @@ import io.reactivex.plugins.RxJavaPlugins; /** - * Maps the upstream intems into {@link CompletableSource}s and subscribes to them one after the + * Maps the upstream items into {@link CompletableSource}s and subscribes to them one after the * other completes or terminates (in error-delaying mode). * @param the upstream value type * @since 2.1.11 - experimental diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index dd47b9be24..3d2fc83f5d 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -49,7 +49,7 @@ *

                * * - *

              • {@link #createWithTimeAndSize(long, TimeUnit, Scheduler, int)}: retaims no more than the given number of items + *
              • {@link #createWithTimeAndSize(long, TimeUnit, Scheduler, int)}: retains no more than the given number of items * which are also no older than the specified time and replays them to new {@code Subscriber}s (which could mean all items age out). *

                * diff --git a/src/test/java/io/reactivex/JavadocWording.java b/src/test/java/io/reactivex/JavadocWording.java index 3d53fad38f..cdc87fe028 100644 --- a/src/test/java/io/reactivex/JavadocWording.java +++ b/src/test/java/io/reactivex/JavadocWording.java @@ -816,6 +816,7 @@ static void aOrAn(StringBuilder e, RxMethod m, String wrongPre, String word, Str } } + jdx = 0; for (;;) { idx = m.javadoc.indexOf(wrongPre + " {@link " + word, jdx); if (idx >= 0) { @@ -832,6 +833,7 @@ static void aOrAn(StringBuilder e, RxMethod m, String wrongPre, String word, Str } } + jdx = 0; for (;;) { idx = m.javadoc.indexOf(wrongPre + " {@linkplain " + word, jdx); if (idx >= 0) { @@ -848,6 +850,7 @@ static void aOrAn(StringBuilder e, RxMethod m, String wrongPre, String word, Str } } + jdx = 0; for (;;) { idx = m.javadoc.indexOf(wrongPre + " {@code " + word, jdx); if (idx >= 0) { @@ -863,7 +866,43 @@ static void aOrAn(StringBuilder e, RxMethod m, String wrongPre, String word, Str break; } } + + // remove linebreaks and multi-spaces + String javadoc2 = m.javadoc.replace("\n", " ").replace("\r", " ") + .replace(" * ", " ") + .replaceAll("\\s+", " "); + + // strip {@xxx } tags + int kk = 0; + for (;;) { + int jj = javadoc2.indexOf("{@", kk); + if (jj < 0) { + break; + } + int nn = javadoc2.indexOf(" ", jj + 2); + int mm = javadoc2.indexOf("}", jj + 2); + + javadoc2 = javadoc2.substring(0, jj) + javadoc2.substring(nn + 1, mm) + javadoc2.substring(mm + 1); + kk = mm + 1; + } + + jdx = 0; + for (;;) { + idx = javadoc2.indexOf(wrongPre + " " + word, jdx); + if (idx >= 0) { + e.append("java.lang.RuntimeException: a/an typo ") + .append(word) + .append("\r\n at io.reactivex.") + .append(baseTypeName) + .append(" (") + .append(baseTypeName) + .append(".java:").append(m.javadocLine).append(")\r\n\r\n"); + jdx = idx + wrongPre.length() + 1 + word.length(); + } else { + break; + } + } } static void missingClosingDD(StringBuilder e, RxMethod m, String baseTypeName) { From 0072c305613d122a5cf2e488ea724f662d43afc3 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 20 Apr 2018 15:04:40 +0200 Subject: [PATCH 160/417] 2.x: Workaround for Objects.requireNonNull inserted by javac (#5966) --- src/test/java/io/reactivex/processors/UnicastProcessorTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java index c822d61a00..fdd8d4e2a9 100644 --- a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java @@ -430,7 +430,7 @@ public void alreadyCancelled() { public void unicastSubscriptionBadRequest() { UnicastProcessor us = UnicastProcessor.create(false); - UnicastProcessor.UnicastQueueSubscription usc = us.new UnicastQueueSubscription(); + UnicastProcessor.UnicastQueueSubscription usc = (UnicastProcessor.UnicastQueueSubscription)us.wip; List errors = TestHelper.trackPluginErrors(); try { From 63877ae8499b8bc8152ec38246c4cbdf876b50be Mon Sep 17 00:00:00 2001 From: Ankit Saliya Date: Sat, 21 Apr 2018 22:30:09 +0530 Subject: [PATCH 161/417] Fix few typos in readme. (#5967) --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5941e14e85..c1d75b3401 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ Flowable.range(1, 10) .blockingSubscribe(System.out::println); ``` -Practically, paralellism in RxJava means running independent flows and merging their results back into a single flow. The operator `flatMap` does this by first mapping each number from 1 to 10 into its own individual `Flowable`, runs them and merges the computed squares. +Practically, parallelism in RxJava means running independent flows and merging their results back into a single flow. The operator `flatMap` does this by first mapping each number from 1 to 10 into its own individual `Flowable`, runs them and merges the computed squares. Note, however, that `flatMap` doesn't guarantee any order and the end result from the inner flows may end up interleaved. There are alternative operators: @@ -273,7 +273,7 @@ inventorySource.flatMap(inventoryItem -> ### Continuations -Sometimes, when an item has become available, one would like to perform some dependent computations on it. This is sometimes called **continuations** and, depending on what should happen and what types are involed, may involve various operators to accomplish. +Sometimes, when an item has become available, one would like to perform some dependent computations on it. This is sometimes called **continuations** and, depending on what should happen and what types are involved, may involve various operators to accomplish. #### Dependent @@ -457,7 +457,7 @@ This can get also ambiguous when functional interface types get involved as the #### Error handling -Dataflows can fail, at which point the error is emitted to the consumer(s). Sometimes though, multiple sources may fail at which point there is a choice wether or not wait for all of them to complete or fail. To indicate this opportunity, many operator names are suffixed with the `DelayError` words (while others feature a `delayError` or `delayErrors` boolean flag in one of their overloads): +Dataflows can fail, at which point the error is emitted to the consumer(s). Sometimes though, multiple sources may fail at which point there is a choice whether or not wait for all of them to complete or fail. To indicate this opportunity, many operator names are suffixed with the `DelayError` words (while others feature a `delayError` or `delayErrors` boolean flag in one of their overloads): ```java Flowable concat(Publisher> sources); From 05b0d40bdd4d21dee887bc4bbdd739aabac1aa60 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Tue, 24 Apr 2018 10:06:15 +0200 Subject: [PATCH 162/417] 2.x: Fix Observable.concatMapSingle dropping upstream items (#5972) --- .../mixed/ObservableConcatMapSingle.java | 6 +++--- .../mixed/ObservableConcatMapMaybeTest.java | 17 +++++++++++++++++ .../mixed/ObservableConcatMapSingleTest.java | 17 +++++++++++++++++ 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java index 6f3f5d9333..45799e8916 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java @@ -18,12 +18,12 @@ import io.reactivex.*; import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; -import io.reactivex.exceptions.*; +import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.fuseable.SimplePlainQueue; -import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.internal.queue.SpscLinkedArrayQueue; import io.reactivex.internal.util.*; import io.reactivex.plugins.RxJavaPlugins; @@ -107,7 +107,7 @@ static final class ConcatMapSingleMainObserver this.errorMode = errorMode; this.errors = new AtomicThrowable(); this.inner = new ConcatMapSingleObserver(this); - this.queue = new SpscArrayQueue(prefetch); + this.queue = new SpscLinkedArrayQueue(prefetch); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java index f374ea23a2..887c18e62e 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java @@ -399,4 +399,21 @@ public void cancelNoConcurrentClean() { assertTrue(operator.queue.isEmpty()); } + + @Test + public void checkUnboundedInnerQueue() { + MaybeSubject ms = MaybeSubject.create(); + + @SuppressWarnings("unchecked") + TestObserver to = Observable + .fromArray(ms, Maybe.just(2), Maybe.just(3), Maybe.just(4)) + .concatMapMaybe(Functions.>identity(), 2) + .test(); + + to.assertEmpty(); + + ms.onSuccess(1); + + to.assertResult(1, 2, 3, 4); + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java index be216649bb..843d05ab2c 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java @@ -336,4 +336,21 @@ public void cancelNoConcurrentClean() { assertTrue(operator.queue.isEmpty()); } + + @Test + public void checkUnboundedInnerQueue() { + SingleSubject ss = SingleSubject.create(); + + @SuppressWarnings("unchecked") + TestObserver to = Observable + .fromArray(ss, Single.just(2), Single.just(3), Single.just(4)) + .concatMapSingle(Functions.>identity(), 2) + .test(); + + to.assertEmpty(); + + ss.onSuccess(1); + + to.assertResult(1, 2, 3, 4); + } } From be12fe2ff996cf5744b87705555c40bb769fd125 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 27 Apr 2018 11:09:37 +0200 Subject: [PATCH 163/417] Release 2.1.13 --- CHANGES.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index dd73829f8e..57b1ce1056 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,30 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.13 - April 27, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.13%7C)) + +#### API changes + +- [Pull 5957](https://github.com/ReactiveX/RxJava/pull/5957): Add `Single.ignoreElement`, deprecate `Single.toCompletable` (will be removed in 3.0). + +#### Documentation changes + +- [Pull 5936](https://github.com/ReactiveX/RxJava/pull/5936): Fix `Completable.toMaybe()` `@return` javadoc. +- [Pull 5948](https://github.com/ReactiveX/RxJava/pull/5948): Fix `Observable` javadoc mentioning `doOnCancel` instead of `doOnDispose`. +- [Pull 5951](https://github.com/ReactiveX/RxJava/pull/5951): Update `blockingX` JavaDoc to mention wrapping of checked Exceptions. + +#### Bugfixes + +- [Pull 5952](https://github.com/ReactiveX/RxJava/pull/5952): Fixed conditional iteration breaking in `AppendOnlyLinkedArrayList.forEachWhile`. +- [Pull 5972](https://github.com/ReactiveX/RxJava/pull/5972): Fix `Observable.concatMapSingle` dropping upstream items. + +#### Other changes + +- [Pull 5930](https://github.com/ReactiveX/RxJava/pull/5930): Add `@NonNull` annotations to create methods of `Subject`s and `Processor`s. +- [Pull 5940](https://github.com/ReactiveX/RxJava/pull/5940): Allow `@SchedulerSupport` annotation on constructors. +- [Pull 5942](https://github.com/ReactiveX/RxJava/pull/5942): Removed `TERMINATED` check in `PublishSubject.onNext` and `PublishProcessor.onNext`. +- [Pull 5959](https://github.com/ReactiveX/RxJava/pull/5959): Fix some typos and grammar mistakes. + ### Version 2.1.12 - March 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.12%7C)) #### Bugfixes From 99366ee3f1b91a0981066898c8c0284b0aa4b97f Mon Sep 17 00:00:00 2001 From: Desislav-Petrov Date: Sun, 29 Apr 2018 09:23:20 +0100 Subject: [PATCH 164/417] Adding eager concats to Single (#5976) * Adding eager concats to Single * Removing unnecessary class - the utility already exists * Covering publisher sequence * Correcting javadoc * Correcting javadoc * Fixing javadoc "Single sources" -> "SingleSources" * Fixing javadoc "Maybe sources" -> "MaybeSources" --- src/main/java/io/reactivex/Maybe.java | 6 +- src/main/java/io/reactivex/Single.java | 88 +++++++++++++++++-- .../operators/single/SingleConcatTest.java | 60 +++++++++++++ 3 files changed, 144 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 4f5ced8de3..23c787a5c7 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -49,7 +49,7 @@ public abstract class Maybe implements MaybeSource { /** - * Runs multiple Maybe sources and signals the events of the first one that signals (cancelling + * Runs multiple MaybeSources and signals the events of the first one that signals (cancelling * the rest). *

                *
                Scheduler:
                @@ -68,7 +68,7 @@ public static Maybe amb(final Iterable } /** - * Runs multiple Maybe sources and signals the events of the first one that signals (cancelling + * Runs multiple MaybeSources and signals the events of the first one that signals (cancelling * the rest). *
                *
                Scheduler:
                @@ -412,7 +412,7 @@ public static Flowable concatEager(Iterable * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source Publishers as they are observed. The operator buffers the values emitted by these diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index d18170b221..fd9ad9870b 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -60,7 +60,7 @@ public abstract class Single implements SingleSource { /** - * Runs multiple Single sources and signals the events of the first one that signals (cancelling + * Runs multiple SingleSources and signals the events of the first one that signals (cancelling * the rest). *
                *
                Scheduler:
                @@ -80,7 +80,7 @@ public static Single amb(final Iterable *
                Scheduler:
                @@ -106,7 +106,7 @@ public static Single ambArray(final SingleSource... sources) } /** - * Concatenate the single values, in a non-overlapping fashion, of the Single sources provided by + * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided by * an Iterable sequence. *
                *
                Backpressure:
                @@ -127,7 +127,7 @@ public static Flowable concat(Iterable *
                Scheduler:
                @@ -147,7 +147,7 @@ public static Observable concat(ObservableSource *
                Backpressure:
                @@ -169,7 +169,7 @@ public static Flowable concat(Publisher *
                Backpressure:
                @@ -299,7 +299,7 @@ public static Flowable concat( } /** - * Concatenate the single values, in a non-overlapping fashion, of the Single sources provided in + * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided in * an array. *
                *
                Backpressure:
                @@ -320,6 +320,80 @@ public static Flowable concatArray(SingleSource... sources) return RxJavaPlugins.onAssembly(new FlowableConcatMap(Flowable.fromArray(sources), SingleInternalHelper.toFlowable(), 2, ErrorMode.BOUNDARY)); } + /** + * Concatenates a sequence of SingleSource eagerly into a single stream of values. + *

                + * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the + * source SingleSources. The operator buffers the value emitted by these SingleSources and then drains them + * in order, each one after the previous one completes. + *

                + *
                Backpressure:
                + *
                The operator honors backpressure from downstream.
                + *
                Scheduler:
                + *
                This method does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the value type + * @param sources a sequence of Single that need to be eagerly concatenated + * @return the new Flowable instance with the specified concatenation behavior + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @BackpressureSupport(BackpressureKind.FULL) + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public static Flowable concatArrayEager(SingleSource... sources) { + return Flowable.fromArray(sources).concatMapEager(SingleInternalHelper.toFlowable()); + } + + /** + * Concatenates a Publisher sequence of SingleSources eagerly into a single stream of values. + *

                + * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the + * emitted source Publishers as they are observed. The operator buffers the values emitted by these + * Publishers and then drains them in order, each one after the previous one completes. + *

                + *
                Backpressure:
                + *
                Backpressure is honored towards the downstream and the outer Publisher is + * expected to support backpressure. Violating this assumption, the operator will + * signal {@link io.reactivex.exceptions.MissingBackpressureException}.
                + *
                Scheduler:
                + *
                This method does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the value type + * @param sources a sequence of Publishers that need to be eagerly concatenated + * @return the new Publisher instance with the specified concatenation behavior + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @BackpressureSupport(BackpressureKind.FULL) + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public static Flowable concatEager(Publisher> sources) { + return Flowable.fromPublisher(sources).concatMapEager(SingleInternalHelper.toFlowable()); + } + + /** + * Concatenates a sequence of SingleSources eagerly into a single stream of values. + *

                + * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the + * source SingleSources. The operator buffers the values emitted by these SingleSources and then drains them + * in order, each one after the previous one completes. + *

                + *
                Backpressure:
                + *
                Backpressure is honored towards the downstream.
                + *
                Scheduler:
                + *
                This method does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param the value type + * @param sources a sequence of SingleSource that need to be eagerly concatenated + * @return the new Flowable instance with the specified concatenation behavior + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @BackpressureSupport(BackpressureKind.FULL) + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public static Flowable concatEager(Iterable> sources) { + return Flowable.fromIterable(sources).concatMapEager(SingleInternalHelper.toFlowable()); + } + /** * Provides an API (via a cold Completable) that bridges the reactive world with the callback-style world. *

                diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java index 8068f9e5bd..6031eeeb9e 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java @@ -14,9 +14,12 @@ package io.reactivex.internal.operators.single; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.Arrays; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subscribers.TestSubscriber; import org.junit.Test; import io.reactivex.*; @@ -67,6 +70,63 @@ public void concatArray() { } } + @SuppressWarnings("unchecked") + @Test + public void concatArrayEagerTest() { + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); + + TestSubscriber ts = Single.concatArrayEager(pp1.single("1"), pp2.single("2")).test(); + + assertTrue(pp1.hasSubscribers()); + assertTrue(pp2.hasSubscribers()); + + pp2.onComplete(); + ts.assertEmpty(); + pp1.onComplete(); + + ts.assertResult("1", "2"); + ts.assertComplete(); + } + + @SuppressWarnings("unchecked") + @Test + public void concatEagerIterableTest() { + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); + + TestSubscriber ts = Single.concatEager(Arrays.asList(pp1.single("2"), pp2.single("1"))).test(); + + assertTrue(pp1.hasSubscribers()); + assertTrue(pp2.hasSubscribers()); + + pp2.onComplete(); + ts.assertEmpty(); + pp1.onComplete(); + + ts.assertResult("2", "1"); + ts.assertComplete(); + } + + @SuppressWarnings("unchecked") + @Test + public void concatEagerPublisherTest() { + PublishProcessor pp1 = PublishProcessor.create(); + PublishProcessor pp2 = PublishProcessor.create(); + + TestSubscriber ts = Single.concatEager(Flowable.just(pp1.single("1"), pp2.single("2"))).test(); + + assertTrue(pp1.hasSubscribers()); + assertTrue(pp2.hasSubscribers()); + + pp2.onComplete(); + ts.assertEmpty(); + pp1.onComplete(); + + ts.assertResult("1", "2"); + ts.assertComplete(); + } + @SuppressWarnings("unchecked") @Test public void concatObservable() { From 5b929c4cd756c681343004244ad7d5804d25bdef Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 29 Apr 2018 10:39:43 +0200 Subject: [PATCH 165/417] 2.x: Fix refCount() connect/subscribe/cancel deadlock (#5975) * 2.x: Fix refCount() connect/subscribe/cancel deadlock * Add more coverage. * Improve logic and coverage. * Factor out common cleanup code. * Fix termination cleanup. --- .../operators/flowable/FlowableRefCount.java | 322 ++++++++--------- .../observable/ObservableRefCount.java | 292 +++++++-------- .../flowable/FlowableRefCountTest.java | 333 +++++++++++++++++- .../observable/ObservableRefCountTest.java | 333 +++++++++++++++++- 4 files changed, 973 insertions(+), 307 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java index 565c94221d..c9f03fdf2c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java @@ -13,16 +13,19 @@ package io.reactivex.internal.operators.flowable; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.*; -import java.util.concurrent.locks.ReentrantLock; import org.reactivestreams.*; -import io.reactivex.FlowableSubscriber; -import io.reactivex.disposables.*; +import io.reactivex.*; +import io.reactivex.disposables.Disposable; import io.reactivex.flowables.ConnectableFlowable; import io.reactivex.functions.Consumer; +import io.reactivex.internal.disposables.*; import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; /** * Returns an observable sequence that stays connected to the source as long as @@ -31,199 +34,202 @@ * @param * the value type */ -public final class FlowableRefCount extends AbstractFlowableWithUpstream { +public final class FlowableRefCount extends Flowable { + final ConnectableFlowable source; - volatile CompositeDisposable baseDisposable = new CompositeDisposable(); - final AtomicInteger subscriptionCount = new AtomicInteger(); - - /** - * Use this lock for every subscription and disconnect action. - */ - final ReentrantLock lock = new ReentrantLock(); - - final class ConnectionSubscriber - extends AtomicReference - implements FlowableSubscriber, Subscription { - - private static final long serialVersionUID = 152064694420235350L; - final Subscriber subscriber; - final CompositeDisposable currentBase; - final Disposable resource; - - final AtomicLong requested; - - ConnectionSubscriber(Subscriber subscriber, - CompositeDisposable currentBase, Disposable resource) { - this.subscriber = subscriber; - this.currentBase = currentBase; - this.resource = resource; - this.requested = new AtomicLong(); - } - @Override - public void onSubscribe(Subscription s) { - SubscriptionHelper.deferredSetOnce(this, requested, s); - } + final int n; - @Override - public void onError(Throwable e) { - cleanup(); - subscriber.onError(e); - } + final long timeout; - @Override - public void onNext(T t) { - subscriber.onNext(t); - } + final TimeUnit unit; - @Override - public void onComplete() { - cleanup(); - subscriber.onComplete(); - } - - @Override - public void request(long n) { - SubscriptionHelper.deferredRequest(this, requested, n); - } + final Scheduler scheduler; - @Override - public void cancel() { - SubscriptionHelper.cancel(this); - resource.dispose(); - } + RefConnection connection; - void cleanup() { - // on error or completion we need to dispose the base CompositeDisposable - // and set the subscriptionCount to 0 - lock.lock(); - try { - if (baseDisposable == currentBase) { - if (source instanceof Disposable) { - ((Disposable)source).dispose(); - } - baseDisposable.dispose(); - baseDisposable = new CompositeDisposable(); - subscriptionCount.set(0); - } - } finally { - lock.unlock(); - } - } + public FlowableRefCount(ConnectableFlowable source) { + this(source, 1, 0L, TimeUnit.NANOSECONDS, Schedulers.trampoline()); } - /** - * Constructor. - * - * @param source - * observable to apply ref count to - */ - public FlowableRefCount(ConnectableFlowable source) { - super(source); + public FlowableRefCount(ConnectableFlowable source, int n, long timeout, TimeUnit unit, + Scheduler scheduler) { this.source = source; + this.n = n; + this.timeout = timeout; + this.unit = unit; + this.scheduler = scheduler; } @Override - public void subscribeActual(final Subscriber subscriber) { - - lock.lock(); - if (subscriptionCount.incrementAndGet() == 1) { - - final AtomicBoolean writeLocked = new AtomicBoolean(true); - - try { - // need to use this overload of connect to ensure that - // baseSubscription is set in the case that source is a - // synchronous Observable - source.connect(onSubscribe(subscriber, writeLocked)); - } finally { - // need to cover the case where the source is subscribed to - // outside of this class thus preventing the Consumer passed - // to source.connect above being called - if (writeLocked.get()) { - // Consumer passed to source.connect was not called - lock.unlock(); - } + protected void subscribeActual(Subscriber s) { + + RefConnection conn; + + boolean connect = false; + synchronized (this) { + conn = connection; + if (conn == null) { + conn = new RefConnection(this); + connection = conn; + } + + long c = conn.subscriberCount; + if (c == 0L && conn.timer != null) { + conn.timer.dispose(); } - } else { - try { - // ready to subscribe to source so do it - doSubscribe(subscriber, baseDisposable); - } finally { - // release the read lock - lock.unlock(); + conn.subscriberCount = c + 1; + if (!conn.connected && c + 1 == n) { + connect = true; + conn.connected = true; } } + source.subscribe(new RefCountSubscriber(s, this, conn)); + + if (connect) { + source.connect(conn); + } } - private Consumer onSubscribe(final Subscriber subscriber, - final AtomicBoolean writeLocked) { - return new DisposeConsumer(subscriber, writeLocked); + void cancel(RefConnection rc) { + SequentialDisposable sd; + synchronized (this) { + if (connection == null) { + return; + } + long c = rc.subscriberCount - 1; + rc.subscriberCount = c; + if (c != 0L || !rc.connected) { + return; + } + if (timeout == 0L) { + timeout(rc); + return; + } + sd = new SequentialDisposable(); + rc.timer = sd; + } + + sd.replace(scheduler.scheduleDirect(rc, timeout, unit)); } - void doSubscribe(final Subscriber subscriber, final CompositeDisposable currentBase) { - // handle disposing from the base subscription - Disposable d = disconnect(currentBase); - ConnectionSubscriber connection = new ConnectionSubscriber(subscriber, currentBase, d); - subscriber.onSubscribe(connection); + void terminated(RefConnection rc) { + synchronized (this) { + if (connection != null) { + connection = null; + if (rc.timer != null) { + rc.timer.dispose(); + } + if (source instanceof Disposable) { + ((Disposable)source).dispose(); + } + } + } + } - source.subscribe(connection); + void timeout(RefConnection rc) { + synchronized (this) { + if (rc.subscriberCount == 0 && rc == connection) { + connection = null; + DisposableHelper.dispose(rc); + if (source instanceof Disposable) { + ((Disposable)source).dispose(); + } + } + } } - private Disposable disconnect(final CompositeDisposable current) { - return Disposables.fromRunnable(new DisposeTask(current)); + static final class RefConnection extends AtomicReference + implements Runnable, Consumer { + + private static final long serialVersionUID = -4552101107598366241L; + + final FlowableRefCount parent; + + Disposable timer; + + long subscriberCount; + + boolean connected; + + RefConnection(FlowableRefCount parent) { + this.parent = parent; + } + + @Override + public void run() { + parent.timeout(this); + } + + @Override + public void accept(Disposable t) throws Exception { + DisposableHelper.replace(this, t); + } } - final class DisposeConsumer implements Consumer { - private final Subscriber subscriber; - private final AtomicBoolean writeLocked; + static final class RefCountSubscriber + extends AtomicBoolean implements FlowableSubscriber, Subscription { + + private static final long serialVersionUID = -7419642935409022375L; + + final Subscriber actual; + + final FlowableRefCount parent; + + final RefConnection connection; - DisposeConsumer(Subscriber subscriber, AtomicBoolean writeLocked) { - this.subscriber = subscriber; - this.writeLocked = writeLocked; + Subscription upstream; + + RefCountSubscriber(Subscriber actual, FlowableRefCount parent, RefConnection connection) { + this.actual = actual; + this.parent = parent; + this.connection = connection; + } + + @Override + public void onNext(T t) { + actual.onNext(t); } @Override - public void accept(Disposable subscription) { - try { - baseDisposable.add(subscription); - // ready to subscribe to source so do it - doSubscribe(subscriber, baseDisposable); - } finally { - // release the write lock - lock.unlock(); - writeLocked.set(false); + public void onError(Throwable t) { + if (compareAndSet(false, true)) { + parent.terminated(connection); + actual.onError(t); + } else { + RxJavaPlugins.onError(t); } } - } - final class DisposeTask implements Runnable { - private final CompositeDisposable current; + @Override + public void onComplete() { + if (compareAndSet(false, true)) { + parent.terminated(connection); + actual.onComplete(); + } + } - DisposeTask(CompositeDisposable current) { - this.current = current; + @Override + public void request(long n) { + upstream.request(n); } @Override - public void run() { - lock.lock(); - try { - if (baseDisposable == current) { - if (subscriptionCount.decrementAndGet() == 0) { - if (source instanceof Disposable) { - ((Disposable)source).dispose(); - } - - baseDisposable.dispose(); - // need a new baseDisposable because once - // disposed stays that way - baseDisposable = new CompositeDisposable(); - } - } - } finally { - lock.unlock(); + public void cancel() { + upstream.cancel(); + if (compareAndSet(false, true)) { + parent.cancel(connection); + } + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(upstream, s)) { + this.upstream = s; + + actual.onSubscribe(this); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java index 58a3141b4c..fd62c1ae60 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java @@ -13,14 +13,16 @@ package io.reactivex.internal.operators.observable; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.*; -import java.util.concurrent.locks.ReentrantLock; import io.reactivex.*; -import io.reactivex.disposables.*; +import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; -import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.disposables.*; import io.reactivex.observables.ConnectableObservable; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; /** * Returns an observable sequence that stays connected to the source as long as @@ -29,201 +31,201 @@ * @param * the value type */ -public final class ObservableRefCount extends AbstractObservableWithUpstream { +public final class ObservableRefCount extends Observable { - final ConnectableObservable source; + final ConnectableObservable source; - volatile CompositeDisposable baseDisposable = new CompositeDisposable(); + final int n; - final AtomicInteger subscriptionCount = new AtomicInteger(); + final long timeout; - /** - * Use this lock for every subscription and disconnect action. - */ - final ReentrantLock lock = new ReentrantLock(); + final TimeUnit unit; + + final Scheduler scheduler; + + RefConnection connection; - /** - * Constructor. - * - * @param source - * observable to apply ref count to - */ public ObservableRefCount(ConnectableObservable source) { - super(source); + this(source, 1, 0L, TimeUnit.NANOSECONDS, Schedulers.trampoline()); + } + + public ObservableRefCount(ConnectableObservable source, int n, long timeout, TimeUnit unit, + Scheduler scheduler) { this.source = source; + this.n = n; + this.timeout = timeout; + this.unit = unit; + this.scheduler = scheduler; } @Override - public void subscribeActual(final Observer subscriber) { - - lock.lock(); - if (subscriptionCount.incrementAndGet() == 1) { - - final AtomicBoolean writeLocked = new AtomicBoolean(true); - - try { - // need to use this overload of connect to ensure that - // baseDisposable is set in the case that source is a - // synchronous Observable - source.connect(onSubscribe(subscriber, writeLocked)); - } finally { - // need to cover the case where the source is subscribed to - // outside of this class thus preventing the Consumer passed - // to source.connect above being called - if (writeLocked.get()) { - // Consumer passed to source.connect was not called - lock.unlock(); - } + protected void subscribeActual(Observer s) { + + RefConnection conn; + + boolean connect = false; + synchronized (this) { + conn = connection; + if (conn == null) { + conn = new RefConnection(this); + connection = conn; } - } else { - try { - // ready to subscribe to source so do it - doSubscribe(subscriber, baseDisposable); - } finally { - // release the read lock - lock.unlock(); + + long c = conn.subscriberCount; + if (c == 0L && conn.timer != null) { + conn.timer.dispose(); + } + conn.subscriberCount = c + 1; + if (!conn.connected && c + 1 == n) { + connect = true; + conn.connected = true; } } - } + source.subscribe(new RefCountObserver(s, this, conn)); - private Consumer onSubscribe(final Observer observer, - final AtomicBoolean writeLocked) { - return new DisposeConsumer(observer, writeLocked); + if (connect) { + source.connect(conn); + } } - void doSubscribe(final Observer observer, final CompositeDisposable currentBase) { - // handle disposing from the base CompositeDisposable - Disposable d = disconnect(currentBase); + void cancel(RefConnection rc) { + SequentialDisposable sd; + synchronized (this) { + if (connection == null) { + return; + } + long c = rc.subscriberCount - 1; + rc.subscriberCount = c; + if (c != 0L || !rc.connected) { + return; + } + if (timeout == 0L) { + timeout(rc); + return; + } + sd = new SequentialDisposable(); + rc.timer = sd; + } - ConnectionObserver s = new ConnectionObserver(observer, currentBase, d); - observer.onSubscribe(s); + sd.replace(scheduler.scheduleDirect(rc, timeout, unit)); + } - source.subscribe(s); + void terminated(RefConnection rc) { + synchronized (this) { + if (connection != null) { + connection = null; + if (rc.timer != null) { + rc.timer.dispose(); + } + if (source instanceof Disposable) { + ((Disposable)source).dispose(); + } + } + } } - private Disposable disconnect(final CompositeDisposable current) { - return Disposables.fromRunnable(new DisposeTask(current)); + void timeout(RefConnection rc) { + synchronized (this) { + if (rc.subscriberCount == 0 && rc == connection) { + connection = null; + DisposableHelper.dispose(rc); + if (source instanceof Disposable) { + ((Disposable)source).dispose(); + } + } + } } - final class ConnectionObserver - extends AtomicReference - implements Observer, Disposable { + static final class RefConnection extends AtomicReference + implements Runnable, Consumer { - private static final long serialVersionUID = 3813126992133394324L; + private static final long serialVersionUID = -4552101107598366241L; - final Observer subscriber; - final CompositeDisposable currentBase; - final Disposable resource; + final ObservableRefCount parent; - ConnectionObserver(Observer subscriber, - CompositeDisposable currentBase, Disposable resource) { - this.subscriber = subscriber; - this.currentBase = currentBase; - this.resource = resource; - } + Disposable timer; - @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); - } + long subscriberCount; - @Override - public void onError(Throwable e) { - cleanup(); - subscriber.onError(e); + boolean connected; + + RefConnection(ObservableRefCount parent) { + this.parent = parent; } @Override - public void onNext(T t) { - subscriber.onNext(t); + public void run() { + parent.timeout(this); } @Override - public void onComplete() { - cleanup(); - subscriber.onComplete(); + public void accept(Disposable t) throws Exception { + DisposableHelper.replace(this, t); } + } - @Override - public void dispose() { - DisposableHelper.dispose(this); - resource.dispose(); + static final class RefCountObserver + extends AtomicBoolean implements Observer, Disposable { + + private static final long serialVersionUID = -7419642935409022375L; + + final Observer actual; + + final ObservableRefCount parent; + + final RefConnection connection; + + Disposable upstream; + + RefCountObserver(Observer actual, ObservableRefCount parent, RefConnection connection) { + this.actual = actual; + this.parent = parent; + this.connection = connection; } @Override - public boolean isDisposed() { - return DisposableHelper.isDisposed(get()); + public void onNext(T t) { + actual.onNext(t); } - void cleanup() { - // on error or completion we need to dispose the base CompositeDisposable - // and set the subscriptionCount to 0 - lock.lock(); - try { - if (baseDisposable == currentBase) { - if (source instanceof Disposable) { - ((Disposable)source).dispose(); - } - - baseDisposable.dispose(); - baseDisposable = new CompositeDisposable(); - subscriptionCount.set(0); - } - } finally { - lock.unlock(); + @Override + public void onError(Throwable t) { + if (compareAndSet(false, true)) { + parent.terminated(connection); + actual.onError(t); + } else { + RxJavaPlugins.onError(t); } } - } - final class DisposeConsumer implements Consumer { - private final Observer observer; - private final AtomicBoolean writeLocked; - - DisposeConsumer(Observer observer, AtomicBoolean writeLocked) { - this.observer = observer; - this.writeLocked = writeLocked; + @Override + public void onComplete() { + if (compareAndSet(false, true)) { + parent.terminated(connection); + actual.onComplete(); + } } @Override - public void accept(Disposable subscription) { - try { - baseDisposable.add(subscription); - // ready to subscribe to source so do it - doSubscribe(observer, baseDisposable); - } finally { - // release the write lock - lock.unlock(); - writeLocked.set(false); + public void dispose() { + upstream.dispose(); + if (compareAndSet(false, true)) { + parent.cancel(connection); } } - } - - final class DisposeTask implements Runnable { - private final CompositeDisposable current; - DisposeTask(CompositeDisposable current) { - this.current = current; + @Override + public boolean isDisposed() { + return upstream.isDisposed(); } @Override - public void run() { - lock.lock(); - try { - if (baseDisposable == current) { - if (subscriptionCount.decrementAndGet() == 0) { - if (source instanceof Disposable) { - ((Disposable)source).dispose(); - } - - baseDisposable.dispose(); - // need a new baseDisposable because once - // disposed stays that way - baseDisposable = new CompositeDisposable(); - } - } - } finally { - lock.unlock(); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + this.upstream = d; + + actual.onSubscribe(this); } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index eafd7873f8..01a6d9396e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -17,6 +17,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +import java.io.IOException; import java.lang.management.ManagementFactory; import java.util.*; import java.util.concurrent.*; @@ -28,13 +29,15 @@ import io.reactivex.*; import io.reactivex.disposables.*; -import io.reactivex.exceptions.TestException; +import io.reactivex.exceptions.*; import io.reactivex.flowables.ConnectableFlowable; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.flowable.FlowableRefCount.RefConnection; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.internal.util.ExceptionHelper; -import io.reactivex.processors.ReplayProcessor; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.*; import io.reactivex.schedulers.*; import io.reactivex.subscribers.TestSubscriber; @@ -829,6 +832,7 @@ public void connect(Consumer connection) { @Override protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); } } @@ -962,4 +966,329 @@ public void badSourceCompleteDisconnect() { assertTrue(ex.getCause() instanceof TestException); } } + + @Test(timeout = 7500) + public void blockingSourceAsnycCancel() throws Exception { + BehaviorProcessor bp = BehaviorProcessor.createDefault(1); + + Flowable f = bp + .replay(1) + .refCount(); + + f.subscribe(); + + final AtomicBoolean interrupted = new AtomicBoolean(); + + f.switchMap(new Function>() { + @Override + public Publisher apply(Integer v) throws Exception { + return Flowable.create(new FlowableOnSubscribe() { + @Override + public void subscribe(FlowableEmitter emitter) throws Exception { + while (!emitter.isCancelled()) { + Thread.sleep(100); + } + interrupted.set(true); + } + }, BackpressureStrategy.MISSING); + } + }) + .takeUntil(Flowable.timer(500, TimeUnit.MILLISECONDS)) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(); + + assertTrue(interrupted.get()); + } + + static FlowableTransformer refCount(final int n) { + return refCount(n, 0, TimeUnit.NANOSECONDS, Schedulers.trampoline()); + } + + static FlowableTransformer refCount(final long time, final TimeUnit unit) { + return refCount(1, time, unit, Schedulers.computation()); + } + + static FlowableTransformer refCount(final long time, final TimeUnit unit, final Scheduler scheduler) { + return refCount(1, time, unit, scheduler); + } + + static FlowableTransformer refCount(final int n, final long time, final TimeUnit unit) { + return refCount(1, time, unit, Schedulers.computation()); + } + + static FlowableTransformer refCount(final int n, final long time, final TimeUnit unit, final Scheduler scheduler) { + return new FlowableTransformer() { + @Override + public Publisher apply(Flowable f) { + return new FlowableRefCount((ConnectableFlowable)f, n, time, unit, scheduler); + } + }; + } + + @Test + public void byCount() { + final int[] subscriptions = { 0 }; + + Flowable source = Flowable.range(1, 5) + .doOnSubscribe(new Consumer() { + @Override + public void accept(Subscription s) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .compose(FlowableRefCountTest.refCount(2)); + + for (int i = 0; i < 3; i++) { + TestSubscriber ts1 = source.test(); + + ts1.assertEmpty(); + + TestSubscriber ts2 = source.test(); + + ts1.assertResult(1, 2, 3, 4, 5); + ts2.assertResult(1, 2, 3, 4, 5); + } + + assertEquals(3, subscriptions[0]); + } + + @Test + public void resubscribeBeforeTimeout() throws Exception { + final int[] subscriptions = { 0 }; + + PublishProcessor pp = PublishProcessor.create(); + + Flowable source = pp + .doOnSubscribe(new Consumer() { + @Override + public void accept(Subscription s) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .compose(FlowableRefCountTest.refCount(500, TimeUnit.MILLISECONDS)); + + TestSubscriber ts1 = source.test(0); + + assertEquals(1, subscriptions[0]); + + ts1.cancel(); + + Thread.sleep(100); + + ts1 = source.test(0); + + assertEquals(1, subscriptions[0]); + + Thread.sleep(500); + + assertEquals(1, subscriptions[0]); + + pp.onNext(1); + pp.onNext(2); + pp.onNext(3); + pp.onNext(4); + pp.onNext(5); + pp.onComplete(); + + ts1.requestMore(5) + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void letitTimeout() throws Exception { + final int[] subscriptions = { 0 }; + + PublishProcessor pp = PublishProcessor.create(); + + Flowable source = pp + .doOnSubscribe(new Consumer() { + @Override + public void accept(Subscription s) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .compose(FlowableRefCountTest.refCount(1, 100, TimeUnit.MILLISECONDS)); + + TestSubscriber ts1 = source.test(0); + + assertEquals(1, subscriptions[0]); + + ts1.cancel(); + + assertTrue(pp.hasSubscribers()); + + Thread.sleep(200); + + assertFalse(pp.hasSubscribers()); + } + + @Test + public void error() { + Flowable.error(new IOException()) + .publish() + .compose(FlowableRefCountTest.refCount(500, TimeUnit.MILLISECONDS)) + .test() + .assertFailure(IOException.class); + } + + @Test(expected = ClassCastException.class) + public void badUpstream() { + Flowable.range(1, 5) + .compose(FlowableRefCountTest.refCount(500, TimeUnit.MILLISECONDS, Schedulers.single())) + ; + } + + @Test + public void comeAndGo() { + PublishProcessor pp = PublishProcessor.create(); + + Flowable source = pp + .publish() + .compose(FlowableRefCountTest.refCount(1)); + + TestSubscriber ts1 = source.test(0); + + assertTrue(pp.hasSubscribers()); + + for (int i = 0; i < 3; i++) { + TestSubscriber ts2 = source.test(); + ts1.cancel(); + ts1 = ts2; + } + + ts1.cancel(); + + assertFalse(pp.hasSubscribers()); + } + + @Test + public void unsubscribeSubscribeRace() { + for (int i = 0; i < 1000; i++) { + + final Flowable source = Flowable.range(1, 5) + .replay() + .compose(FlowableRefCountTest.refCount(1)) + ; + + final TestSubscriber ts1 = source.test(0); + + final TestSubscriber ts2 = new TestSubscriber(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts1.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + source.subscribe(ts2); + } + }; + + TestHelper.race(r1, r2, Schedulers.single()); + + ts2.requestMore(6) // FIXME RxJava replay() doesn't issue onComplete without request + .withTag("Round: " + i) + .assertResult(1, 2, 3, 4, 5); + } + } + + static final class BadFlowableDoubleOnX extends ConnectableFlowable + implements Disposable { + + @Override + public void connect(Consumer connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Subscriber observer) { + observer.onSubscribe(new BooleanSubscription()); + observer.onSubscribe(new BooleanSubscription()); + observer.onComplete(); + observer.onComplete(); + observer.onError(new TestException()); + } + + @Override + public void dispose() { + } + + @Override + public boolean isDisposed() { + return false; + } + } + + @Test + public void doubleOnX() { + List errors = TestHelper.trackPluginErrors(); + try { + new BadFlowableDoubleOnX() + .refCount() + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void cancelTerminateStateExclusion() { + FlowableRefCount o = (FlowableRefCount)PublishProcessor.create() + .publish() + .refCount(); + + o.cancel(null); + + RefConnection rc = new RefConnection(o); + o.connection = null; + rc.subscriberCount = 0; + o.timeout(rc); + + rc.subscriberCount = 1; + o.timeout(rc); + + o.connection = rc; + o.timeout(rc); + + rc.subscriberCount = 0; + o.timeout(rc); + + // ------------------- + + rc.subscriberCount = 2; + rc.connected = false; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 1; + rc.connected = false; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 2; + rc.connected = true; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 1; + rc.connected = true; + o.connection = rc; + o.cancel(rc); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index 4df48c59ac..7648cc69b5 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -17,6 +17,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +import java.io.IOException; import java.lang.management.ManagementFactory; import java.util.*; import java.util.concurrent.*; @@ -29,14 +30,16 @@ import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.*; -import io.reactivex.exceptions.TestException; +import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.observable.ObservableRefCount.RefConnection; import io.reactivex.internal.util.ExceptionHelper; import io.reactivex.observables.ConnectableObservable; import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; -import io.reactivex.subjects.ReplaySubject; +import io.reactivex.subjects.*; public class ObservableRefCountTest { @@ -813,6 +816,7 @@ public void connect(Consumer connection) { @Override protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); } } @@ -946,4 +950,329 @@ public void badSourceCompleteDisconnect() { assertTrue(ex.getCause() instanceof TestException); } } + + @Test(timeout = 7500) + public void blockingSourceAsnycCancel() throws Exception { + BehaviorSubject bs = BehaviorSubject.createDefault(1); + + Observable o = bs + .replay(1) + .refCount(); + + o.subscribe(); + + final AtomicBoolean interrupted = new AtomicBoolean(); + + o.switchMap(new Function>() { + @Override + public ObservableSource apply(Integer v) throws Exception { + return Observable.create(new ObservableOnSubscribe() { + @Override + public void subscribe(ObservableEmitter emitter) throws Exception { + while (!emitter.isDisposed()) { + Thread.sleep(100); + } + interrupted.set(true); + } + }); + } + }) + .take(500, TimeUnit.MILLISECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(); + + assertTrue(interrupted.get()); + } + + static ObservableTransformer refCount(final int n) { + return refCount(n, 0, TimeUnit.NANOSECONDS, Schedulers.trampoline()); + } + + static ObservableTransformer refCount(final long time, final TimeUnit unit) { + return refCount(1, time, unit, Schedulers.computation()); + } + + static ObservableTransformer refCount(final long time, final TimeUnit unit, final Scheduler scheduler) { + return refCount(1, time, unit, scheduler); + } + + static ObservableTransformer refCount(final int n, final long time, final TimeUnit unit) { + return refCount(1, time, unit, Schedulers.computation()); + } + + static ObservableTransformer refCount(final int n, final long time, final TimeUnit unit, final Scheduler scheduler) { + return new ObservableTransformer() { + @Override + public Observable apply(Observable f) { + return new ObservableRefCount((ConnectableObservable)f, n, time, unit, scheduler); + } + }; + } + + @Test + public void byCount() { + final int[] subscriptions = { 0 }; + + Observable source = Observable.range(1, 5) + .doOnSubscribe(new Consumer() { + @Override + public void accept(Disposable s) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .compose(ObservableRefCountTest.refCount(2)); + + for (int i = 0; i < 3; i++) { + TestObserver to1 = source.test(); + + to1.assertEmpty(); + + TestObserver to2 = source.test(); + + to1.assertResult(1, 2, 3, 4, 5); + to2.assertResult(1, 2, 3, 4, 5); + } + + assertEquals(3, subscriptions[0]); + } + + @Test + public void resubscribeBeforeTimeout() throws Exception { + final int[] subscriptions = { 0 }; + + PublishSubject ps = PublishSubject.create(); + + Observable source = ps + .doOnSubscribe(new Consumer() { + @Override + public void accept(Disposable s) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .compose(ObservableRefCountTest.refCount(500, TimeUnit.MILLISECONDS)); + + TestObserver to1 = source.test(); + + assertEquals(1, subscriptions[0]); + + to1.cancel(); + + Thread.sleep(100); + + to1 = source.test(); + + assertEquals(1, subscriptions[0]); + + Thread.sleep(500); + + assertEquals(1, subscriptions[0]); + + ps.onNext(1); + ps.onNext(2); + ps.onNext(3); + ps.onNext(4); + ps.onNext(5); + ps.onComplete(); + + to1 + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void letitTimeout() throws Exception { + final int[] subscriptions = { 0 }; + + PublishSubject ps = PublishSubject.create(); + + Observable source = ps + .doOnSubscribe(new Consumer() { + @Override + public void accept(Disposable s) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .compose(ObservableRefCountTest.refCount(1, 100, TimeUnit.MILLISECONDS)); + + TestObserver to1 = source.test(); + + assertEquals(1, subscriptions[0]); + + to1.cancel(); + + assertTrue(ps.hasObservers()); + + Thread.sleep(200); + + assertFalse(ps.hasObservers()); + } + + @Test + public void error() { + Observable.error(new IOException()) + .publish() + .compose(ObservableRefCountTest.refCount(500, TimeUnit.MILLISECONDS)) + .test() + .assertFailure(IOException.class); + } + + @Test(expected = ClassCastException.class) + public void badUpstream() { + Observable.range(1, 5) + .compose(ObservableRefCountTest.refCount(500, TimeUnit.MILLISECONDS, Schedulers.single())) + ; + } + + @Test + public void comeAndGo() { + PublishSubject ps = PublishSubject.create(); + + Observable source = ps + .publish() + .compose(ObservableRefCountTest.refCount(1)); + + TestObserver to1 = source.test(); + + assertTrue(ps.hasObservers()); + + for (int i = 0; i < 3; i++) { + TestObserver to2 = source.test(); + to1.cancel(); + to1 = to2; + } + + to1.cancel(); + + assertFalse(ps.hasObservers()); + } + + @Test + public void unsubscribeSubscribeRace() { + for (int i = 0; i < 1000; i++) { + + final Observable source = Observable.range(1, 5) + .replay() + .compose(ObservableRefCountTest.refCount(1)) + ; + + final TestObserver to1 = source.test(); + + final TestObserver to2 = new TestObserver(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to1.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + source.subscribe(to2); + } + }; + + TestHelper.race(r1, r2, Schedulers.single()); + + to2 + .withTag("Round: " + i) + .assertResult(1, 2, 3, 4, 5); + } + } + + static final class BadObservableDoubleOnX extends ConnectableObservable + implements Disposable { + + @Override + public void connect(Consumer connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Observer observer) { + observer.onSubscribe(Disposables.empty()); + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); + observer.onComplete(); + observer.onError(new TestException()); + } + + @Override + public void dispose() { + } + + @Override + public boolean isDisposed() { + return false; + } + } + + @Test + public void doubleOnX() { + List errors = TestHelper.trackPluginErrors(); + try { + new BadObservableDoubleOnX() + .refCount() + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void cancelTerminateStateExclusion() { + ObservableRefCount o = (ObservableRefCount)PublishSubject.create() + .publish() + .refCount(); + + o.cancel(null); + + RefConnection rc = new RefConnection(o); + o.connection = null; + rc.subscriberCount = 0; + o.timeout(rc); + + rc.subscriberCount = 1; + o.timeout(rc); + + o.connection = rc; + o.timeout(rc); + + rc.subscriberCount = 0; + o.timeout(rc); + + // ------------------- + + rc.subscriberCount = 2; + rc.connected = false; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 1; + rc.connected = false; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 2; + rc.connected = true; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 1; + rc.connected = true; + o.connection = rc; + o.cancel(rc); + } } From dc94f561abdc674462c42c5033e799340214d65c Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 29 Apr 2018 12:00:08 +0200 Subject: [PATCH 166/417] 2.x: Maybe/Single Javadoc; annotation cleanup (#5977) --- src/main/java/io/reactivex/Maybe.java | 38 +++++++++---------- src/main/java/io/reactivex/Single.java | 7 +--- .../java/io/reactivex/JavadocWording.java | 8 ++-- .../mixed/ObservableConcatMapMaybeTest.java | 2 +- .../mixed/ObservableConcatMapSingleTest.java | 2 +- .../operators/single/SingleConcatTest.java | 1 - 6 files changed, 27 insertions(+), 31 deletions(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 23c787a5c7..49daf38cbe 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3503,7 +3503,7 @@ public final Maybe onErrorComplete(final Predicate predica } /** - * Instructs a Maybe to pass control to another MaybeSource rather than invoking + * Instructs a Maybe to pass control to another {@link MaybeSource} rather than invoking * {@link MaybeObserver#onError onError} if it encounters an error. *

                * @@ -3516,7 +3516,7 @@ public final Maybe onErrorComplete(final Predicate predica * * * @param next - * the next Maybe source that will take over if the source Maybe encounters + * the next {@code MaybeSource} that will take over if the source Maybe encounters * an error * @return the new Maybe instance * @see ReactiveX operators documentation: Catch @@ -4348,14 +4348,14 @@ public final Maybe timeout(long timeout, TimeUnit timeUnit, Scheduler schedul } /** - * If this Maybe source didn't signal an event before the timeoutIndicator MaybeSource signals, a - * TimeoutException is signalled instead. + * If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link MaybeSource} signals, a + * {@link TimeoutException} is signaled instead. *

                *
                Scheduler:
                *
                {@code timeout} does not operate by default on a particular {@link Scheduler}.
                *
                * @param the value type of the - * @param timeoutIndicator the MaybeSource that indicates the timeout by signalling onSuccess + * @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling onSuccess * or onComplete. * @return the new Maybe instance */ @@ -4367,17 +4367,17 @@ public final Maybe timeout(MaybeSource timeoutIndicator) { } /** - * If the current Maybe source didn't signal an event before the timeoutIndicator MaybeSource signals, - * the current Maybe is cancelled and the {@code fallback} MaybeSource subscribed to + * If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link MaybeSource} signals, + * the current {@code Maybe} is cancelled and the {@code fallback} {@code MaybeSource} subscribed to * as a continuation. *
                *
                Scheduler:
                *
                {@code timeout} does not operate by default on a particular {@link Scheduler}.
                *
                * @param the value type of the - * @param timeoutIndicator the MaybeSource that indicates the timeout by signalling onSuccess - * or onComplete. - * @param fallback the MaybeSource that is subscribed to if the current Maybe times out + * @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling {@code onSuccess} + * or {@code onComplete}. + * @param fallback the {@code MaybeSource} that is subscribed to if the current {@code Maybe} times out * @return the new Maybe instance */ @CheckReturnValue @@ -4389,8 +4389,8 @@ public final Maybe timeout(MaybeSource timeoutIndicator, MaybeSource *
                Backpressure:
                *
                The {@code timeoutIndicator} {@link Publisher} is consumed in an unbounded manner and @@ -4399,8 +4399,8 @@ public final Maybe timeout(MaybeSource timeoutIndicator, MaybeSource{@code timeout} does not operate by default on a particular {@link Scheduler}.
                * * @param the value type of the - * @param timeoutIndicator the MaybeSource that indicates the timeout by signalling onSuccess - * or onComplete. + * @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling {@code onSuccess} + * or {@code onComplete}. * @return the new Maybe instance */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @@ -4412,8 +4412,8 @@ public final Maybe timeout(Publisher timeoutIndicator) { } /** - * If the current Maybe source didn't signal an event before the timeoutIndicator Publisher signals, - * the current Maybe is cancelled and the {@code fallback} MaybeSource subscribed to + * If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link Publisher} signals, + * the current {@code Maybe} is cancelled and the {@code fallback} {@code MaybeSource} subscribed to * as a continuation. *
                *
                Backpressure:
                @@ -4423,9 +4423,9 @@ public final Maybe timeout(Publisher timeoutIndicator) { *
                {@code timeout} does not operate by default on a particular {@link Scheduler}.
                *
                * @param the value type of the - * @param timeoutIndicator the MaybeSource that indicates the timeout by signalling onSuccess - * or onComplete - * @param fallback the MaybeSource that is subscribed to if the current Maybe times out + * @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling {@code onSuccess} + * or {@code onComplete} + * @param fallback the {@code MaybeSource} that is subscribed to if the current {@code Maybe} times out * @return the new Maybe instance */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index fd9ad9870b..b3ede60c4e 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -336,7 +336,6 @@ public static Flowable concatArray(SingleSource... sources) * @param sources a sequence of Single that need to be eagerly concatenated * @return the new Flowable instance with the specified concatenation behavior */ - @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -362,7 +361,6 @@ public static Flowable concatArrayEager(SingleSource... sour * @param sources a sequence of Publishers that need to be eagerly concatenated * @return the new Publisher instance with the specified concatenation behavior */ - @SuppressWarnings({ "rawtypes", "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -386,7 +384,6 @@ public static Flowable concatEager(Publisher Single create(SingleOnSubscribe source) { } /** - * Calls a Callable for each individual SingleObserver to return the actual Single source to + * Calls a {@link Callable} for each individual {@link SingleObserver} to return the actual {@link SingleSource} to * be subscribed to. *
                *
                Scheduler:
                *
                {@code defer} does not operate by default on a particular {@link Scheduler}.
                *
                * @param the value type - * @param singleSupplier the Callable that is called for each individual SingleObserver and + * @param singleSupplier the {@code Callable} that is called for each individual {@code SingleObserver} and * returns a SingleSource instance to subscribe to * @return the new Single instance */ diff --git a/src/test/java/io/reactivex/JavadocWording.java b/src/test/java/io/reactivex/JavadocWording.java index cdc87fe028..41d50e8d25 100644 --- a/src/test/java/io/reactivex/JavadocWording.java +++ b/src/test/java/io/reactivex/JavadocWording.java @@ -866,12 +866,12 @@ static void aOrAn(StringBuilder e, RxMethod m, String wrongPre, String word, Str break; } } - + // remove linebreaks and multi-spaces String javadoc2 = m.javadoc.replace("\n", " ").replace("\r", " ") .replace(" * ", " ") .replaceAll("\\s+", " "); - + // strip {@xxx } tags int kk = 0; for (;;) { @@ -881,12 +881,12 @@ static void aOrAn(StringBuilder e, RxMethod m, String wrongPre, String word, Str } int nn = javadoc2.indexOf(" ", jj + 2); int mm = javadoc2.indexOf("}", jj + 2); - + javadoc2 = javadoc2.substring(0, jj) + javadoc2.substring(nn + 1, mm) + javadoc2.substring(mm + 1); kk = mm + 1; } - + jdx = 0; for (;;) { idx = javadoc2.indexOf(wrongPre + " " + word, jdx); diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java index 887c18e62e..8fbd2937f1 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java @@ -403,7 +403,7 @@ public void cancelNoConcurrentClean() { @Test public void checkUnboundedInnerQueue() { MaybeSubject ms = MaybeSubject.create(); - + @SuppressWarnings("unchecked") TestObserver to = Observable .fromArray(ms, Maybe.just(2), Maybe.just(3), Maybe.just(4)) diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java index 843d05ab2c..bdd4f9e4cc 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java @@ -340,7 +340,7 @@ public void cancelNoConcurrentClean() { @Test public void checkUnboundedInnerQueue() { SingleSubject ss = SingleSubject.create(); - + @SuppressWarnings("unchecked") TestObserver to = Observable .fromArray(ss, Single.just(2), Single.just(3), Single.just(4)) diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java index 6031eeeb9e..52d67e742a 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java @@ -108,7 +108,6 @@ public void concatEagerIterableTest() { ts.assertComplete(); } - @SuppressWarnings("unchecked") @Test public void concatEagerPublisherTest() { PublishProcessor pp1 = PublishProcessor.create(); From a1b96283f4c34faca14dc42d47a87afb4ce5015d Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 29 Apr 2018 15:56:28 +0200 Subject: [PATCH 167/417] 2.x: Flowable.take to route post-cancel errors to plugin error handler (#5978) --- .../operators/flowable/FlowableTake.java | 3 +++ .../operators/flowable/FlowableLimitTest.java | 15 +++++++++++++ .../operators/flowable/FlowableTakeTest.java | 19 ++++++++++++++++- .../observable/ObservableTakeTest.java | 21 ++++++++++++++++++- 4 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java index 67c2a49c21..e15abaef84 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java @@ -19,6 +19,7 @@ import io.reactivex.*; import io.reactivex.internal.subscriptions.*; +import io.reactivex.plugins.RxJavaPlugins; public final class FlowableTake extends AbstractFlowableWithUpstream { final long limit; @@ -75,6 +76,8 @@ public void onError(Throwable t) { done = true; subscription.cancel(); actual.onError(t); + } else { + RxJavaPlugins.onError(t); } } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java index 471b0e818d..9150bab4ad 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableLimitTest.java @@ -207,4 +207,19 @@ public void run() { ts.assertResult(1, 2, 3, 4, 5); } } + + @Test + public void errorAfterLimitReached() { + List errors = TestHelper.trackPluginErrors(); + try { + Flowable.error(new TestException()) + .limit(0) + .test() + .assertResult(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java index c19b2108b1..345282bfbd 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java @@ -14,9 +14,10 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; -import java.util.Arrays; +import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; @@ -28,6 +29,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; @@ -495,4 +497,19 @@ public void run() { ts.assertResult(1, 2); } } + + @Test + public void errorAfterLimitReached() { + List errors = TestHelper.trackPluginErrors(); + try { + Flowable.error(new TestException()) + .take(0) + .test() + .assertResult(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java index f966cd8647..f1f5851fd3 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java @@ -14,9 +14,10 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; -import java.util.Arrays; +import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.*; @@ -24,10 +25,13 @@ import org.mockito.InOrder; import io.reactivex.*; +import io.reactivex.Observable; +import io.reactivex.Observer; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; @@ -389,4 +393,19 @@ public ObservableSource apply(Observable o) throws Exception { } }); } + + @Test + public void errorAfterLimitReached() { + List errors = TestHelper.trackPluginErrors(); + try { + Observable.error(new TestException()) + .take(0) + .test() + .assertResult(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } From d07dfa1fe59e71e2f231246374c9c2009599ef62 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 29 Apr 2018 19:47:25 +0200 Subject: [PATCH 168/417] 2.x: improve JavaDocs of the subscribeActual methods (#5981) --- src/main/java/io/reactivex/Completable.java | 5 ++++- src/main/java/io/reactivex/Flowable.java | 7 ++++--- src/main/java/io/reactivex/Maybe.java | 5 ++++- src/main/java/io/reactivex/Observable.java | 7 ++++--- src/main/java/io/reactivex/Single.java | 5 ++++- 5 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 7e83b11abe..8fca56c910 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1927,8 +1927,11 @@ public final void subscribe(CompletableObserver s) { } /** - * Implement this to handle the incoming CompletableObserver and + * Implement this method to handle the incoming {@link CompletableObserver}s and * perform the business logic in your operator. + *

                There is no need to call any of the plugin hooks on the current {@code Completable} instance or + * the {@code CompletableObserver}; all hooks and basic safeguards have been + * applied by {@link #subscribe(CompletableObserver)} before this method gets called. * @param s the CompletableObserver instance, never null */ protected abstract void subscribeActual(CompletableObserver s); diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 318ae422d9..840c87804c 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -14333,9 +14333,10 @@ public final void subscribe(FlowableSubscriber s) { /** * Operator implementations (both source and intermediate) should implement this method that - * performs the necessary business logic. - *

                There is no need to call any of the plugin hooks on the current Flowable instance or - * the Subscriber. + * performs the necessary business logic and handles the incoming {@link Subscriber}s. + *

                There is no need to call any of the plugin hooks on the current {@code Flowable} instance or + * the {@code Subscriber}; all hooks and basic safeguards have been + * applied by {@link #subscribe(Subscriber)} before this method gets called. * @param s the incoming Subscriber, never null */ protected abstract void subscribeActual(Subscriber s); diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 49daf38cbe..d965108efe 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -4082,7 +4082,10 @@ public final void subscribe(MaybeObserver observer) { } /** - * Override this method in subclasses to handle the incoming MaybeObservers. + * Implement this method in subclasses to handle the incoming {@link MaybeObserver}s. + *

                There is no need to call any of the plugin hooks on the current {@code Maybe} instance or + * the {@code MaybeObserver}; all hooks and basic safeguards have been + * applied by {@link #subscribe(MaybeObserver)} before this method gets called. * @param observer the MaybeObserver to handle, not null */ protected abstract void subscribeActual(MaybeObserver observer); diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index dbc7dfd1ad..ad60243113 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -12039,9 +12039,10 @@ public final void subscribe(Observer observer) { /** * Operator implementations (both source and intermediate) should implement this method that - * performs the necessary business logic. - *

                There is no need to call any of the plugin hooks on the current Observable instance or - * the Subscriber. + * performs the necessary business logic and handles the incoming {@link Observer}s. + *

                There is no need to call any of the plugin hooks on the current {@code Observable} instance or + * the {@code Observer}; all hooks and basic safeguards have been + * applied by {@link #subscribe(Observer)} before this method gets called. * @param observer the incoming Observer, never null */ protected abstract void subscribeActual(Observer observer); diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index b3ede60c4e..a8c57ca7db 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -3304,7 +3304,10 @@ public final void subscribe(SingleObserver subscriber) { } /** - * Override this method in subclasses to handle the incoming SingleObservers. + * Implement this method in subclasses to handle the incoming {@link SingleObserver}s. + *

                There is no need to call any of the plugin hooks on the current {@code Single} instance or + * the {@code SingleObserver}; all hooks and basic safeguards have been + * applied by {@link #subscribe(SingleObserver)} before this method gets called. * @param observer the SingleObserver to handle, not null */ protected abstract void subscribeActual(@NonNull SingleObserver observer); From 70f9a831e9d43a14f89fd4d799e6ab55f0176c17 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 30 Apr 2018 11:16:17 +0200 Subject: [PATCH 169/417] 2.x: deprecate getValues() in Subjects/Processors (#5982) --- .../io/reactivex/processors/AsyncProcessor.java | 4 ++++ .../reactivex/processors/BehaviorProcessor.java | 4 ++++ .../java/io/reactivex/subjects/AsyncSubject.java | 4 ++++ .../io/reactivex/subjects/BehaviorSubject.java | 4 ++++ .../processors/SerializedProcessorTest.java | 15 +++++++++++++++ .../subjects/SerializedSubjectTest.java | 16 ++++++++++++++++ 6 files changed, 47 insertions(+) diff --git a/src/main/java/io/reactivex/processors/AsyncProcessor.java b/src/main/java/io/reactivex/processors/AsyncProcessor.java index b03bef985d..37d6937e49 100644 --- a/src/main/java/io/reactivex/processors/AsyncProcessor.java +++ b/src/main/java/io/reactivex/processors/AsyncProcessor.java @@ -254,7 +254,9 @@ public T getValue() { * Returns an Object array containing snapshot all values of the Subject. *

                The method is thread-safe. * @return the array containing the snapshot of all values of the Subject + * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x */ + @Deprecated public Object[] getValues() { T v = getValue(); return v != null ? new Object[] { v } : new Object[0]; @@ -267,7 +269,9 @@ public Object[] getValues() { *

                The method is thread-safe. * @param array the target array to copy values into if it fits * @return the given array if the values fit into it or a new array containing all values + * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x */ + @Deprecated public T[] getValues(T[] array) { T v = getValue(); if (v == null) { diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index 55fb95fe8b..4c407a7e7f 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -377,7 +377,9 @@ public T getValue() { * Returns an Object array containing snapshot all values of the BehaviorProcessor. *

                The method is thread-safe. * @return the array containing the snapshot of all values of the BehaviorProcessor + * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x */ + @Deprecated public Object[] getValues() { @SuppressWarnings("unchecked") T[] a = (T[])EMPTY_ARRAY; @@ -396,7 +398,9 @@ public Object[] getValues() { *

                The method is thread-safe. * @param array the target array to copy values into if it fits * @return the given array if the values fit into it or a new array containing all values + * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x */ + @Deprecated @SuppressWarnings("unchecked") public T[] getValues(T[] array) { Object o = value.get(); diff --git a/src/main/java/io/reactivex/subjects/AsyncSubject.java b/src/main/java/io/reactivex/subjects/AsyncSubject.java index af5b6e5fdd..2a99ab03ad 100644 --- a/src/main/java/io/reactivex/subjects/AsyncSubject.java +++ b/src/main/java/io/reactivex/subjects/AsyncSubject.java @@ -325,7 +325,9 @@ public T getValue() { * Returns an Object array containing snapshot all values of the Subject. *

                The method is thread-safe. * @return the array containing the snapshot of all values of the Subject + * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x */ + @Deprecated public Object[] getValues() { T v = getValue(); return v != null ? new Object[] { v } : new Object[0]; @@ -338,7 +340,9 @@ public Object[] getValues() { *

                The method is thread-safe. * @param array the target array to copy values into if it fits * @return the given array if the values fit into it or a new array containing all values + * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x */ + @Deprecated public T[] getValues(T[] array) { T v = getValue(); if (v == null) { diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java index 7199ba2d0c..d147f24b85 100644 --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java @@ -331,7 +331,9 @@ public T getValue() { * Returns an Object array containing snapshot all values of the Subject. *

                The method is thread-safe. * @return the array containing the snapshot of all values of the Subject + * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x */ + @Deprecated public Object[] getValues() { @SuppressWarnings("unchecked") T[] a = (T[])EMPTY_ARRAY; @@ -350,7 +352,9 @@ public Object[] getValues() { *

                The method is thread-safe. * @param array the target array to copy values into if it fits * @return the given array if the values fit into it or a new array containing all values + * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x */ + @Deprecated @SuppressWarnings("unchecked") public T[] getValues(T[] array) { Object o = value.get(); diff --git a/src/test/java/io/reactivex/processors/SerializedProcessorTest.java b/src/test/java/io/reactivex/processors/SerializedProcessorTest.java index 790419220e..efbfe02a69 100644 --- a/src/test/java/io/reactivex/processors/SerializedProcessorTest.java +++ b/src/test/java/io/reactivex/processors/SerializedProcessorTest.java @@ -38,6 +38,7 @@ public void testBasic() { ts.assertValue("hello"); } + @SuppressWarnings("deprecation") @Test public void testAsyncSubjectValueRelay() { AsyncProcessor async = AsyncProcessor.create(); @@ -56,6 +57,8 @@ public void testAsyncSubjectValueRelay() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testAsyncSubjectValueEmpty() { AsyncProcessor async = AsyncProcessor.create(); @@ -73,6 +76,8 @@ public void testAsyncSubjectValueEmpty() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testAsyncSubjectValueError() { AsyncProcessor async = AsyncProcessor.create(); @@ -91,6 +96,7 @@ public void testAsyncSubjectValueError() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testPublishSubjectValueRelay() { PublishProcessor async = PublishProcessor.create(); @@ -128,6 +134,7 @@ public void testPublishSubjectValueError() { assertSame(te, serial.getThrowable()); } + @SuppressWarnings("deprecation") @Test public void testBehaviorSubjectValueRelay() { BehaviorProcessor async = BehaviorProcessor.create(); @@ -146,6 +153,8 @@ public void testBehaviorSubjectValueRelay() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testBehaviorSubjectValueRelayIncomplete() { BehaviorProcessor async = BehaviorProcessor.create(); @@ -163,6 +172,8 @@ public void testBehaviorSubjectValueRelayIncomplete() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testBehaviorSubjectIncompleteEmpty() { BehaviorProcessor async = BehaviorProcessor.create(); @@ -179,6 +190,8 @@ public void testBehaviorSubjectIncompleteEmpty() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testBehaviorSubjectEmpty() { BehaviorProcessor async = BehaviorProcessor.create(); @@ -196,6 +209,8 @@ public void testBehaviorSubjectEmpty() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testBehaviorSubjectError() { BehaviorProcessor async = BehaviorProcessor.create(); diff --git a/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java b/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java index e1042c8680..31498d7a04 100644 --- a/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java @@ -39,6 +39,7 @@ public void testBasic() { to.assertValue("hello"); } + @SuppressWarnings("deprecation") @Test public void testAsyncSubjectValueRelay() { AsyncSubject async = AsyncSubject.create(); @@ -57,6 +58,8 @@ public void testAsyncSubjectValueRelay() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testAsyncSubjectValueEmpty() { AsyncSubject async = AsyncSubject.create(); @@ -74,6 +77,8 @@ public void testAsyncSubjectValueEmpty() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testAsyncSubjectValueError() { AsyncSubject async = AsyncSubject.create(); @@ -92,6 +97,7 @@ public void testAsyncSubjectValueError() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testPublishSubjectValueRelay() { PublishSubject async = PublishSubject.create(); @@ -129,6 +135,7 @@ public void testPublishSubjectValueError() { assertSame(te, serial.getThrowable()); } + @SuppressWarnings("deprecation") @Test public void testBehaviorSubjectValueRelay() { BehaviorSubject async = BehaviorSubject.create(); @@ -147,6 +154,8 @@ public void testBehaviorSubjectValueRelay() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testBehaviorSubjectValueRelayIncomplete() { BehaviorSubject async = BehaviorSubject.create(); @@ -164,6 +173,8 @@ public void testBehaviorSubjectValueRelayIncomplete() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testBehaviorSubjectIncompleteEmpty() { BehaviorSubject async = BehaviorSubject.create(); @@ -180,6 +191,8 @@ public void testBehaviorSubjectIncompleteEmpty() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testBehaviorSubjectEmpty() { BehaviorSubject async = BehaviorSubject.create(); @@ -197,6 +210,8 @@ public void testBehaviorSubjectEmpty() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + + @SuppressWarnings("deprecation") @Test public void testBehaviorSubjectError() { BehaviorSubject async = BehaviorSubject.create(); @@ -234,6 +249,7 @@ public void testReplaySubjectValueRelay() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectValueRelayIncomplete() { ReplaySubject async = ReplaySubject.create(); From 59cf89c2e4d101765d7abf69d3b3d9a7bf7e6ce4 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 30 Apr 2018 12:28:40 +0200 Subject: [PATCH 170/417] 2.x: Cleanup in the Scheduler class (#5985) --- src/main/java/io/reactivex/Scheduler.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/Scheduler.java b/src/main/java/io/reactivex/Scheduler.java index 44a5b1830f..0f4806d4a0 100644 --- a/src/main/java/io/reactivex/Scheduler.java +++ b/src/main/java/io/reactivex/Scheduler.java @@ -510,12 +510,15 @@ public Runnable getWrappedRunnable() { } } - static class PeriodicDirectTask + static final class PeriodicDirectTask implements Disposable, Runnable, SchedulerRunnableIntrospection { + + @NonNull final Runnable run; + @NonNull final Worker worker; - @NonNull + volatile boolean disposed; PeriodicDirectTask(@NonNull Runnable run, @NonNull Worker worker) { @@ -554,12 +557,17 @@ public Runnable getWrappedRunnable() { } static final class DisposeTask implements Disposable, Runnable, SchedulerRunnableIntrospection { + + @NonNull final Runnable decoratedRun; + + @NonNull final Worker w; + @Nullable Thread runner; - DisposeTask(Runnable decoratedRun, Worker w) { + DisposeTask(@NonNull Runnable decoratedRun, @NonNull Worker w) { this.decoratedRun = decoratedRun; this.w = w; } From d57af5af671f13d29177984c57092379da30f9b3 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Mon, 30 Apr 2018 12:47:07 +0200 Subject: [PATCH 171/417] 2.x: Add blockingSubscribe JavaDoc clarifications (#5984) --- src/main/java/io/reactivex/Flowable.java | 32 ++++++++++++++++- src/main/java/io/reactivex/Observable.java | 40 +++++++++++++++++++--- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 840c87804c..800cfa5ea5 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -5801,6 +5801,10 @@ public final Future toFuture() { /** * Runs the source Flowable to a terminal event, ignoring any values and rethrowing any exception. + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. *

                *
                Backpressure:
                *
                The operator consumes the source {@code Flowable} in an unbounded manner @@ -5809,6 +5813,9 @@ public final Future toFuture() { *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                *
                * @since 2.0 + * @see #blockingSubscribe(Consumer) + * @see #blockingSubscribe(Consumer, Consumer) + * @see #blockingSubscribe(Consumer, Consumer, Action) */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) @@ -5822,6 +5829,12 @@ public final void blockingSubscribe() { * If the Flowable emits an error, it is wrapped into an * {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} * and routed to the RxJavaPlugins.onError handler. + * Using the overloads {@link #blockingSubscribe(Consumer, Consumer)} + * or {@link #blockingSubscribe(Consumer, Consumer, Action)} instead is recommended. + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. *

                *
                Backpressure:
                *
                The operator consumes the source {@code Flowable} in an unbounded manner @@ -5831,6 +5844,8 @@ public final void blockingSubscribe() { *
                * @param onNext the callback action for each source value * @since 2.0 + * @see #blockingSubscribe(Consumer, Consumer) + * @see #blockingSubscribe(Consumer, Consumer, Action) */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) @@ -5840,6 +5855,10 @@ public final void blockingSubscribe(Consumer onNext) { /** * Subscribes to the source and calls the given callbacks on the current thread. + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. *

                *
                Backpressure:
                *
                The operator consumes the source {@code Flowable} in an unbounded manner @@ -5850,6 +5869,7 @@ public final void blockingSubscribe(Consumer onNext) { * @param onNext the callback action for each source value * @param onError the callback action for an error event * @since 2.0 + * @see #blockingSubscribe(Consumer, Consumer, Action) */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) @@ -5860,6 +5880,10 @@ public final void blockingSubscribe(Consumer onNext, Consumeron the current thread. + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. *

                *
                Backpressure:
                *
                The operator consumes the source {@code Flowable} in an unbounded manner @@ -5879,7 +5903,13 @@ public final void blockingSubscribe(Consumer onNext, Consumeron the current thread. + * Subscribes to the source and calls the {@link Subscriber} methods on the current thread. + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally, with an error or the {@code Subscriber} cancels the {@link Subscription} it receives via + * {@link Subscriber#onSubscribe(Subscription)}. + * Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. *

                *
                Backpressure:
                *
                The supplied {@code Subscriber} determines how backpressure is applied.
                diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index ad60243113..2c32920c2e 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -5314,11 +5314,18 @@ public final Future toFuture() { * Runs the source observable to a terminal event, ignoring any values and rethrowing any exception. *

                * + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. *

                *
                Scheduler:
                *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                *
                * @since 2.0 + * @see #blockingSubscribe(Consumer) + * @see #blockingSubscribe(Consumer, Consumer) + * @see #blockingSubscribe(Consumer, Consumer, Action) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe() { @@ -5330,15 +5337,23 @@ public final void blockingSubscribe() { *

                * *

                - * If the Observable emits an error, it is wrapped into an + * If the {@code Observable} emits an error, it is wrapped into an * {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} * and routed to the RxJavaPlugins.onError handler. + * Using the overloads {@link #blockingSubscribe(Consumer, Consumer)} + * or {@link #blockingSubscribe(Consumer, Consumer, Action)} instead is recommended. + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. *

                *
                Scheduler:
                *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                *
                * @param onNext the callback action for each source value * @since 2.0 + * @see #blockingSubscribe(Consumer, Consumer) + * @see #blockingSubscribe(Consumer, Consumer, Action) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe(Consumer onNext) { @@ -5349,6 +5364,10 @@ public final void blockingSubscribe(Consumer onNext) { * Subscribes to the source and calls the given callbacks on the current thread. *

                * + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. *

                *
                Scheduler:
                *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                @@ -5356,6 +5375,7 @@ public final void blockingSubscribe(Consumer onNext) { * @param onNext the callback action for each source value * @param onError the callback action for an error event * @since 2.0 + * @see #blockingSubscribe(Consumer, Consumer, Action) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe(Consumer onNext, Consumer onError) { @@ -5367,6 +5387,10 @@ public final void blockingSubscribe(Consumer onNext, Consumeron the current thread. *

                * + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. *

                *
                Scheduler:
                *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                @@ -5382,18 +5406,24 @@ public final void blockingSubscribe(Consumer onNext, Consumeron the current thread. + * Subscribes to the source and calls the {@link Observer} methods on the current thread. + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally, with an error or the {@code Observer} disposes the {@link Disposable} it receives via + * {@link Observer#onSubscribe(Disposable)}. + * Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. *

                *
                Scheduler:
                *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                *
                * The a dispose() call is composed through. - * @param subscriber the subscriber to forward events and calls to in the current thread + * @param observer the {@code Observer} instance to forward events and calls to in the current thread * @since 2.0 */ @SchedulerSupport(SchedulerSupport.NONE) - public final void blockingSubscribe(Observer subscriber) { - ObservableBlockingSubscribe.subscribe(this, subscriber); + public final void blockingSubscribe(Observer observer) { + ObservableBlockingSubscribe.subscribe(this, observer); } /** From fbba23e3dfa99e195ceda68cd7fef7bfc41fccc6 Mon Sep 17 00:00:00 2001 From: VeskoI Date: Tue, 1 May 2018 10:43:29 +0100 Subject: [PATCH 172/417] Add marble diagrams to a few Single.doOnX methods. (#5987) * Add marble diagrams to a few Single.doOnX methods. * Use correct marble diagram urls for couple of Single.doOnXX methods --- src/main/java/io/reactivex/Single.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index a8c57ca7db..6ecdb5409c 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2244,6 +2244,9 @@ public final Single doAfterTerminate(Action onAfterTerminate) { * is executed once per subscription. *

                Note that the {@code onFinally} action is shared between subscriptions and as such * should be thread-safe. + *

                + * + *

                *
                *
                Scheduler:
                *
                {@code doFinally} does not operate by default on a particular {@link Scheduler}.
                @@ -2263,6 +2266,9 @@ public final Single doFinally(Action onFinally) { /** * Calls the shared consumer with the Disposable sent through the onSubscribe for each * SingleObserver that subscribes to the current Single. + *

                + * + *

                *
                *
                Scheduler:
                *
                {@code doOnSubscribe} does not operate by default on a particular {@link Scheduler}.
                @@ -2281,6 +2287,9 @@ public final Single doOnSubscribe(final Consumer onSubscr /** * Calls the shared consumer with the success value sent via onSuccess for each * SingleObserver that subscribes to the current Single. + *

                + * + *

                *
                *
                Scheduler:
                *
                {@code doOnSuccess} does not operate by default on a particular {@link Scheduler}.
                @@ -2317,6 +2326,9 @@ public final Single doOnEvent(final BiConsumer /** * Calls the shared consumer with the error sent via onError for each * SingleObserver that subscribes to the current Single. + *

                + * + *

                *
                *
                Scheduler:
                *
                {@code doOnError} does not operate by default on a particular {@link Scheduler}.
                @@ -2335,6 +2347,9 @@ public final Single doOnError(final Consumer onError) { /** * Calls the shared {@code Action} if a SingleObserver subscribed to the current Single * disposes the common Disposable it received via onSubscribe. + *

                + * + *

                *
                *
                Scheduler:
                *
                {@code doOnDispose} does not operate by default on a particular {@link Scheduler}.
                From 214181f2c0a89e9a8759f5f330cc56324df30e93 Mon Sep 17 00:00:00 2001 From: Anthony Musyoki Date: Fri, 4 May 2018 17:25:30 +0300 Subject: [PATCH 173/417] Observable javadoc cleanup (#5992) The sample code in the Observable javadoc erroneously uses onNext(Integer t) for a DisposableObserver This has been corrected to be onNext(String t) --- src/main/java/io/reactivex/Observable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 2c32920c2e..e7c7bb7f67 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -74,7 +74,7 @@ * @Override public void onStart() { * System.out.println("Start!"); * } - * @Override public void onNext(Integer t) { + * @Override public void onNext(String t) { * System.out.println(t); * } * @Override public void onError(Throwable t) { From 90203b6f6962e7aa8259780b94fb591e4232ddba Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 4 May 2018 17:47:21 +0200 Subject: [PATCH 174/417] 2.x: Fix switchMap to indicate boundary fusion (#5991) --- .../operators/flowable/FlowableSwitchMap.java | 2 +- .../observable/ObservableSwitchMap.java | 2 +- src/test/java/io/reactivex/TestHelper.java | 210 ++++++++++++++++++ .../flowable/FlowableSwitchTest.java | 44 +++- .../observable/ObservableSwitchTest.java | 36 ++- 5 files changed, 281 insertions(+), 13 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java index 03ddb6c0ce..b7cbe1d3fc 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java @@ -359,7 +359,7 @@ public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") QueueSubscription qs = (QueueSubscription) s; - int m = qs.requestFusion(QueueSubscription.ANY); + int m = qs.requestFusion(QueueSubscription.ANY | QueueSubscription.BOUNDARY); if (m == QueueSubscription.SYNC) { fusionMode = m; queue = qs; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java index 2d22639af6..032f84dbc6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java @@ -348,7 +348,7 @@ public void onSubscribe(Disposable s) { @SuppressWarnings("unchecked") QueueDisposable qd = (QueueDisposable) s; - int m = qd.requestFusion(QueueDisposable.ANY); + int m = qd.requestFusion(QueueDisposable.ANY | QueueDisposable.BOUNDARY); if (m == QueueDisposable.SYNC) { queue = qd; done = true; diff --git a/src/test/java/io/reactivex/TestHelper.java b/src/test/java/io/reactivex/TestHelper.java index 9e31194f0f..60a7fdfd81 100644 --- a/src/test/java/io/reactivex/TestHelper.java +++ b/src/test/java/io/reactivex/TestHelper.java @@ -2922,4 +2922,214 @@ public void request(long n) { } }; } + + static final class FlowableStripBoundary extends Flowable implements FlowableTransformer { + + final Flowable source; + + FlowableStripBoundary(Flowable source) { + this.source = source; + } + + @Override + public Flowable apply(Flowable upstream) { + return new FlowableStripBoundary(upstream); + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new StripBoundarySubscriber(s)); + } + + static final class StripBoundarySubscriber implements FlowableSubscriber, QueueSubscription { + + final Subscriber actual; + + Subscription upstream; + + QueueSubscription qs; + + StripBoundarySubscriber(Subscriber actual) { + this.actual = actual; + } + + @SuppressWarnings("unchecked") + @Override + public void onSubscribe(Subscription subscription) { + this.upstream = subscription; + if (subscription instanceof QueueSubscription) { + qs = (QueueSubscription)subscription; + } + actual.onSubscribe(this); + } + + @Override + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public void onError(Throwable throwable) { + actual.onError(throwable); + } + + @Override + public void onComplete() { + actual.onComplete(); + } + + @Override + public int requestFusion(int mode) { + QueueSubscription fs = qs; + if (fs != null) { + return fs.requestFusion(mode & ~BOUNDARY); + } + return NONE; + } + + @Override + public boolean offer(T value) { + throw new UnsupportedOperationException("Should not be called"); + } + + @Override + public boolean offer(T v1, T v2) { + throw new UnsupportedOperationException("Should not be called"); + } + + @Override + public T poll() throws Exception { + return qs.poll(); + } + + @Override + public void clear() { + qs.clear(); + } + + @Override + public boolean isEmpty() { + return qs.isEmpty(); + } + + @Override + public void request(long n) { + upstream.request(n); + } + + @Override + public void cancel() { + upstream.cancel(); + } + } + } + + public static FlowableTransformer flowableStripBoundary() { + return new FlowableStripBoundary(null); + } + + static final class ObservableStripBoundary extends Observable implements ObservableTransformer { + + final Observable source; + + ObservableStripBoundary(Observable source) { + this.source = source; + } + + @Override + public Observable apply(Observable upstream) { + return new ObservableStripBoundary(upstream); + } + + @Override + protected void subscribeActual(Observer s) { + source.subscribe(new StripBoundaryObserver(s)); + } + + static final class StripBoundaryObserver implements Observer, QueueDisposable { + + final Observer actual; + + Disposable upstream; + + QueueDisposable qd; + + StripBoundaryObserver(Observer actual) { + this.actual = actual; + } + + @SuppressWarnings("unchecked") + @Override + public void onSubscribe(Disposable d) { + this.upstream = d; + if (d instanceof QueueDisposable) { + qd = (QueueDisposable)d; + } + actual.onSubscribe(this); + } + + @Override + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public void onError(Throwable throwable) { + actual.onError(throwable); + } + + @Override + public void onComplete() { + actual.onComplete(); + } + + @Override + public int requestFusion(int mode) { + QueueDisposable fs = qd; + if (fs != null) { + return fs.requestFusion(mode & ~BOUNDARY); + } + return NONE; + } + + @Override + public boolean offer(T value) { + throw new UnsupportedOperationException("Should not be called"); + } + + @Override + public boolean offer(T v1, T v2) { + throw new UnsupportedOperationException("Should not be called"); + } + + @Override + public T poll() throws Exception { + return qd.poll(); + } + + @Override + public void clear() { + qd.clear(); + } + + @Override + public boolean isEmpty() { + return qd.isEmpty(); + } + + @Override + public void dispose() { + upstream.dispose(); + } + + @Override + public boolean isDisposed() { + return upstream.isDisposed(); + } + } + } + + public static ObservableTransformer observableStripBoundary() { + return new ObservableStripBoundary(null); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java index 8aeda04f47..28f599e487 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java @@ -33,7 +33,7 @@ import io.reactivex.internal.util.ExceptionHelper; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; -import io.reactivex.schedulers.TestScheduler; +import io.reactivex.schedulers.*; import io.reactivex.subscribers.*; public class FlowableSwitchTest { @@ -1144,12 +1144,16 @@ public void run() { @Test public void fusedInnerCrash() { Flowable.just(1).hide() - .switchMap(Functions.justFunction(Flowable.just(1).map(new Function() { - @Override - public Object apply(Integer v) throws Exception { - throw new TestException(); - } - }))) + .switchMap(Functions.justFunction(Flowable.just(1) + .map(new Function() { + @Override + public Object apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .compose(TestHelper.flowableStripBoundary()) + ) + ) .test() .assertFailure(TestException.class); } @@ -1174,4 +1178,30 @@ public void innerCancelledOnMainError() { ts.assertFailure(TestException.class); } + + @Test + public void fusedBoundary() { + String thread = Thread.currentThread().getName(); + + Flowable.range(1, 10000) + .switchMap(new Function>() { + @Override + public Flowable apply(Integer v) + throws Exception { + return Flowable.just(2).hide() + .observeOn(Schedulers.single()) + .map(new Function() { + @Override + public Object apply(Integer w) throws Exception { + return Thread.currentThread().getName(); + } + }); + } + }) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertNever(thread) + .assertNoErrors() + .assertComplete(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java index 00fb200378..beae5a788c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.List; @@ -26,15 +27,14 @@ import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.*; -import io.reactivex.functions.Consumer; -import io.reactivex.functions.Function; +import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.internal.util.ExceptionHelper; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.TestScheduler; -import io.reactivex.subjects.PublishSubject; +import io.reactivex.schedulers.*; +import io.reactivex.subjects.*; public class ObservableSwitchTest { @@ -1121,6 +1121,7 @@ public Integer apply(Integer v) throws Exception { throw new TestException(); } }) + .compose(TestHelper.observableStripBoundary()) )) .test(); @@ -1148,6 +1149,7 @@ public Integer apply(Integer v) throws Exception { throw new TestException(); } }) + .compose(TestHelper.observableStripBoundary()) )) .test(); @@ -1166,4 +1168,30 @@ public Integer apply(Integer v) throws Exception { assertFalse(ps.hasObservers()); } + + @Test + public void fusedBoundary() { + String thread = Thread.currentThread().getName(); + + Observable.range(1, 10000) + .switchMap(new Function>() { + @Override + public ObservableSource apply(Integer v) + throws Exception { + return Observable.just(2).hide() + .observeOn(Schedulers.single()) + .map(new Function() { + @Override + public Object apply(Integer w) throws Exception { + return Thread.currentThread().getName(); + } + }); + } + }) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertNever(thread) + .assertNoErrors() + .assertComplete(); + } } From 416771e66d18374348ae4a5287c3ebd4785f8e65 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 6 May 2018 16:31:08 +0200 Subject: [PATCH 175/417] 2.x: Automatically publish the generated JavaDocs from CI (#5996) * Experiment: auto publish JavaDocs * Fix script error, add logging * Have all package-list staged * Fix another scripting error * Fix copy paths * Real pushback on snapshot builds. * Pull requests should not trigger snapshot pushbacks * Rename push.sh to push_javadoc.sh --- .travis.yml | 1 + gradle/push_javadoc.sh | 120 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 gradle/push_javadoc.sh diff --git a/.travis.yml b/.travis.yml index 972c0c4cc0..83835caeba 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,6 +20,7 @@ script: gradle/buildViaTravis.sh # Code coverage after_success: - bash <(curl -s https://codecov.io/bash) + - bash gradle/push_javadoc.sh # cache between builds cache: diff --git a/gradle/push_javadoc.sh b/gradle/push_javadoc.sh new file mode 100644 index 0000000000..8bd3ef0f87 --- /dev/null +++ b/gradle/push_javadoc.sh @@ -0,0 +1,120 @@ +#!/bin/bash +# ---------------------------------------------------------- +# Automatically push back the generated JavaDocs to gh-pages +# ---------------------------------------------------------- +# based on https://gist.github.com/willprice/e07efd73fb7f13f917ea + +# specify the common address for the repository +targetRepo=github.com/ReactiveX/RxJava.git +# ======================================================================= + +# only for main pushes, for now +if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then + echo -e "Pull request detected, skipping JavaDocs pushback." + exit 0 +fi + +# get the current build tag if any +buildTag="$TRAVIS_TAG" +echo -e "Travis tag: '$buildTag'" + +if [ "$buildTag" == "" ]; then + buildTag="snapshot" +else + buildTag="${buildTag:1}" +fi + +echo -e "JavaDocs pushback for tag: $buildTag" + +# check if the token is actually there +if [ "$GITHUB_TOKEN" == "" ]; then + echo -e "No access to GitHub, skipping JavaDocs pushback." + exit 0 +fi + +# prepare the git information +git config --global user.email "travis@travis-ci.org" +git config --global user.name "Travis CI" + +# setup the remote +echo -e "Adding the target repository to git" +git remote add origin-pages https://${GITHUB_TOKEN}@${targetRepo} > /dev/null 2>&1 + +# stash changes due to chmod +echo -e "Stashing any local non-ignored changes" +git stash + +# get the gh-pages +echo -e "Update branches and checking out gh-pages" +git fetch --all +git branch -a +git checkout -b gh-pages origin-pages/gh-pages + +# releases should update 2 extra locations +if [ "$buildTag" != "snapshot" ]; then + # for releases, add a new directory with the new version + # and carefully replace the others + + # 1.) main javadoc + # ---------------- + # remove the io subdir + echo -e "Removing javadoc/io" + rm -r javadoc/io + + # remove the html files + echo -e "Removing javadoc/*.html" + rm javadoc/*.html + + # copy the new doc + echo -e "Copying to javadoc/" + yes | cp -rf ./build/docs/javadoc/ . + + # 2.) 2.x javadoc + # remove the io subdir + echo -e "Removing 2.x/javadoc/io" + rm -r 2.x/javadoc/io + + # remove the html files + echo -e "Removing 2.x/javadoc/*.html" + rm 2.x/javadoc/*.html + + # copy the new doc + echo -e "Copying to 2.x/javadoc/" + yes | cp -rf ./build/docs/javadoc/ 2.x/ +fi + +# 3.) create a version/snapshot specific copy of the docs +# clear the existing tag +echo -e "Removing to 2.x/javadoc/${buildTag}" +rm -r 2.x/javadoc/${buildTag} + +# copy the new doc +echo -e "Copying to 2.x/javadoc/${buildTag}" +yes | cp -rf ./build/docs/javadoc/ 2.x/javadoc/${buildTag}/ + + +# stage all changed and new files +echo -e "Staging new files" +git add *.html +git add *.css +git add *.js +git add *package-list* + +# remove tracked but deleted files +echo -e "Removing deleted files" +git add -u + +# commit all +echo -e "commit Travis build: $TRAVIS_BUILD_NUMBER for $buildTag" +git commit --message "Travis build: $TRAVIS_BUILD_NUMBER for $buildTag" + +# debug file list +#find -name "*.html" + +# push it +echo -e "Pushing back changes." +git push --quiet --set-upstream origin-pages gh-pages + + +# we are done +echo -e "JavaDocs pushback complete." \ No newline at end of file From a957c789495304c0de79689a07575977f59afc7d Mon Sep 17 00:00:00 2001 From: Dmitry Strekha Date: Sun, 6 May 2018 22:33:10 +0300 Subject: [PATCH 176/417] Implement 'toString' method for some Emitters (#5995) * Implement 'toString' method for Emitters * Add tests to check that toString method of Emitters contains class name * Add 'assertEmpty' to prevent catching assertions by 'onError' * Add test to ensure that SerializedEmitter delegates 'toString' to parent emitter * Override emitter's 'toString' method * Add tests to check 'toString' method contains Emitter's class name * Add test for 'toString' method of SerializedEmitter --- .../completable/CompletableCreate.java | 5 ++++ .../operators/flowable/FlowableCreate.java | 10 ++++++++ .../internal/operators/maybe/MaybeCreate.java | 5 ++++ .../observable/ObservableCreate.java | 10 ++++++++ .../operators/single/SingleCreate.java | 5 ++++ .../completable/CompletableCreateTest.java | 10 ++++++++ .../flowable/FlowableCreateTest.java | 24 +++++++++++++++++++ .../operators/maybe/MaybeCreateTest.java | 10 ++++++++ .../observable/ObservableCreateTest.java | 11 +++++++++ .../operators/single/SingleCreateTest.java | 10 ++++++++ 10 files changed, 100 insertions(+) diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java index c9035e7033..8e0cc20438 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java @@ -118,5 +118,10 @@ public void dispose() { public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } + + @Override + public String toString() { + return String.format("%s{%s}", getClass().getSimpleName(), super.toString()); + } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java index a729b8dc0f..c1f506abc1 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java @@ -233,6 +233,11 @@ public boolean isCancelled() { public FlowableEmitter serialize() { return this; } + + @Override + public String toString() { + return emitter.toString(); + } } abstract static class BaseEmitter @@ -338,6 +343,11 @@ public final long requested() { public final FlowableEmitter serialize() { return new SerializedEmitter(this); } + + @Override + public String toString() { + return String.format("%s{%s}", getClass().getSimpleName(), super.toString()); + } } static final class MissingEmitter extends BaseEmitter { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java index 21f06e2109..e0c42b68ca 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java @@ -145,5 +145,10 @@ public void dispose() { public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } + + @Override + public String toString() { + return String.format("%s{%s}", getClass().getSimpleName(), super.toString()); + } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java index 153e44aef0..68ffd7ed82 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java @@ -126,6 +126,11 @@ public void dispose() { public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } + + @Override + public String toString() { + return String.format("%s{%s}", getClass().getSimpleName(), super.toString()); + } } /** @@ -279,6 +284,11 @@ public boolean isDisposed() { public ObservableEmitter serialize() { return this; } + + @Override + public String toString() { + return emitter.toString(); + } } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java b/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java index 69cac3c393..8bb129bda2 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java @@ -123,5 +123,10 @@ public void dispose() { public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } + + @Override + public String toString() { + return String.format("%s{%s}", getClass().getSimpleName(), super.toString()); + } } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableCreateTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableCreateTest.java index d64484081c..13b64091fe 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableCreateTest.java @@ -297,4 +297,14 @@ public void subscribe(CompletableEmitter e) throws Exception { RxJavaPlugins.reset(); } } + + @Test + public void emitterHasToString() { + Completable.create(new CompletableOnSubscribe() { + @Override + public void subscribe(CompletableEmitter emitter) throws Exception { + assertTrue(emitter.toString().contains(CompletableCreate.Emitter.class.getSimpleName())); + } + }).test().assertEmpty(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java index 786dd5cb1e..edc31e5b37 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java @@ -16,7 +16,9 @@ import static org.junit.Assert.*; import java.io.IOException; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.junit.Test; import org.reactivestreams.*; @@ -931,4 +933,26 @@ public void subscribe(FlowableEmitter e) throws Exception { } } } + + @Test + public void emittersHasToString() { + Map> emitterMap = + new HashMap>(); + + emitterMap.put(BackpressureStrategy.MISSING, FlowableCreate.MissingEmitter.class); + emitterMap.put(BackpressureStrategy.ERROR, FlowableCreate.ErrorAsyncEmitter.class); + emitterMap.put(BackpressureStrategy.DROP, FlowableCreate.DropAsyncEmitter.class); + emitterMap.put(BackpressureStrategy.LATEST, FlowableCreate.LatestAsyncEmitter.class); + emitterMap.put(BackpressureStrategy.BUFFER, FlowableCreate.BufferAsyncEmitter.class); + + for (final Map.Entry> entry : emitterMap.entrySet()) { + Flowable.create(new FlowableOnSubscribe() { + @Override + public void subscribe(FlowableEmitter emitter) throws Exception { + assertTrue(emitter.toString().contains(entry.getValue().getSimpleName())); + assertTrue(emitter.serialize().toString().contains(entry.getValue().getSimpleName())); + } + }, entry.getKey()).test().assertEmpty(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeCreateTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeCreateTest.java index 477562310b..1e114a2ac3 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeCreateTest.java @@ -335,4 +335,14 @@ public void subscribe(MaybeEmitter e) throws Exception { RxJavaPlugins.reset(); } } + + @Test + public void emitterHasToString() { + Maybe.create(new MaybeOnSubscribe() { + @Override + public void subscribe(MaybeEmitter emitter) throws Exception { + assertTrue(emitter.toString().contains(MaybeCreate.Emitter.class.getSimpleName())); + } + }).test().assertEmpty(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCreateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCreateTest.java index 4933a70fb7..a3e86e18e9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCreateTest.java @@ -643,4 +643,15 @@ public void subscribe(ObservableEmitter e) throws Exception { RxJavaPlugins.reset(); } } + + @Test + public void emitterHasToString() { + Observable.create(new ObservableOnSubscribe() { + @Override + public void subscribe(ObservableEmitter emitter) throws Exception { + assertTrue(emitter.toString().contains(ObservableCreate.CreateEmitter.class.getSimpleName())); + assertTrue(emitter.serialize().toString().contains(ObservableCreate.CreateEmitter.class.getSimpleName())); + } + }).test().assertEmpty(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleCreateTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleCreateTest.java index 51603819eb..2aee2b0f6f 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleCreateTest.java @@ -307,4 +307,14 @@ public void subscribe(SingleEmitter e) throws Exception { RxJavaPlugins.reset(); } } + + @Test + public void emitterHasToString() { + Single.create(new SingleOnSubscribe() { + @Override + public void subscribe(SingleEmitter emitter) throws Exception { + assertTrue(emitter.toString().contains(SingleCreate.Emitter.class.getSimpleName())); + } + }).test().assertEmpty(); + } } From cedfc538d05f8bdc5bfc6c644e258bdad946333f Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 9 May 2018 09:44:34 +0200 Subject: [PATCH 177/417] 2.x: Add refCount with count & disconnect timeout (#5986) * 2.x: Add refCount with count & disconnect timeout * Ensure coverage --- .../flowables/ConnectableFlowable.java | 150 +++++++++++++++++- .../observables/ConnectableObservable.java | 123 +++++++++++++- .../flowable/FlowableRefCountTest.java | 76 ++++----- .../observable/ObservableRefCountTest.java | 76 ++++----- 4 files changed, 342 insertions(+), 83 deletions(-) diff --git a/src/main/java/io/reactivex/flowables/ConnectableFlowable.java b/src/main/java/io/reactivex/flowables/ConnectableFlowable.java index 9ab9ca1c04..e62ea61494 100644 --- a/src/main/java/io/reactivex/flowables/ConnectableFlowable.java +++ b/src/main/java/io/reactivex/flowables/ConnectableFlowable.java @@ -13,16 +13,19 @@ package io.reactivex.flowables; -import io.reactivex.annotations.NonNull; +import java.util.concurrent.TimeUnit; + import org.reactivestreams.Subscriber; -import io.reactivex.Flowable; +import io.reactivex.*; +import io.reactivex.annotations.*; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; -import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.functions.*; import io.reactivex.internal.operators.flowable.*; import io.reactivex.internal.util.ConnectConsumer; import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; /** * A {@code ConnectableFlowable} resembles an ordinary {@link Flowable}, except that it does not begin @@ -68,15 +71,154 @@ public final Disposable connect() { /** * Returns a {@code Flowable} that stays connected to this {@code ConnectableFlowable} as long as there * is at least one subscription to this {@code ConnectableFlowable}. - * + *
                + *
                Backpressure:
                + *
                The operator itself doesn't interfere with backpressure which is determined by the upstream + * {@code ConnectableFlowable}'s backpressure behavior.
                + *
                Scheduler:
                + *
                This {@code refCount} overload does not operate on any particular {@link Scheduler}.
                + *
                * @return a {@link Flowable} * @see ReactiveX documentation: RefCount + * @see #refCount(int) + * @see #refCount(long, TimeUnit) + * @see #refCount(int, long, TimeUnit) */ @NonNull + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.PASS_THROUGH) public Flowable refCount() { return RxJavaPlugins.onAssembly(new FlowableRefCount(this)); } + /** + * Connects to the upstream {@code ConnectableFlowable} if the number of subscribed + * subscriber reaches the specified count and disconnect if all subscribers have unsubscribed. + *
                + *
                Backpressure:
                + *
                The operator itself doesn't interfere with backpressure which is determined by the upstream + * {@code ConnectableFlowable}'s backpressure behavior.
                + *
                Scheduler:
                + *
                This {@code refCount} overload does not operate on any particular {@link Scheduler}.
                + *
                + * @param subscriberCount the number of subscribers required to connect to the upstream + * @return the new Flowable instance + * @since 2.1.14 - experimental + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.PASS_THROUGH) + public final Flowable refCount(int subscriberCount) { + return refCount(subscriberCount, 0, TimeUnit.NANOSECONDS, Schedulers.trampoline()); + } + + /** + * Connects to the upstream {@code ConnectableFlowable} if the number of subscribed + * subscriber reaches 1 and disconnect after the specified + * timeout if all subscribers have unsubscribed. + *
                + *
                Backpressure:
                + *
                The operator itself doesn't interfere with backpressure which is determined by the upstream + * {@code ConnectableFlowable}'s backpressure behavior.
                + *
                Scheduler:
                + *
                This {@code refCount} overload operates on the {@code computation} {@link Scheduler}.
                + *
                + * @param timeout the time to wait before disconnecting after all subscribers unsubscribed + * @param unit the time unit of the timeout + * @return the new Flowable instance + * @since 2.1.14 - experimental + * @see #refCount(long, TimeUnit, Scheduler) + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.COMPUTATION) + @BackpressureSupport(BackpressureKind.PASS_THROUGH) + public final Flowable refCount(long timeout, TimeUnit unit) { + return refCount(1, timeout, unit, Schedulers.computation()); + } + + /** + * Connects to the upstream {@code ConnectableFlowable} if the number of subscribed + * subscriber reaches 1 and disconnect after the specified + * timeout if all subscribers have unsubscribed. + *
                + *
                Backpressure:
                + *
                The operator itself doesn't interfere with backpressure which is determined by the upstream + * {@code ConnectableFlowable}'s backpressure behavior.
                + *
                Scheduler:
                + *
                This {@code refCount} overload operates on the specified {@link Scheduler}.
                + *
                + * @param timeout the time to wait before disconnecting after all subscribers unsubscribed + * @param unit the time unit of the timeout + * @param scheduler the target scheduler to wait on before disconnecting + * @return the new Flowable instance + * @since 2.1.14 - experimental + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.CUSTOM) + @BackpressureSupport(BackpressureKind.PASS_THROUGH) + public final Flowable refCount(long timeout, TimeUnit unit, Scheduler scheduler) { + return refCount(1, timeout, unit, scheduler); + } + + /** + * Connects to the upstream {@code ConnectableFlowable} if the number of subscribed + * subscriber reaches the specified count and disconnect after the specified + * timeout if all subscribers have unsubscribed. + *
                + *
                Backpressure:
                + *
                The operator itself doesn't interfere with backpressure which is determined by the upstream + * {@code ConnectableFlowable}'s backpressure behavior.
                + *
                Scheduler:
                + *
                This {@code refCount} overload operates on the {@code computation} {@link Scheduler}.
                + *
                + * @param subscriberCount the number of subscribers required to connect to the upstream + * @param timeout the time to wait before disconnecting after all subscribers unsubscribed + * @param unit the time unit of the timeout + * @return the new Flowable instance + * @since 2.1.14 - experimental + * @see #refCount(int, long, TimeUnit, Scheduler) + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.COMPUTATION) + @BackpressureSupport(BackpressureKind.PASS_THROUGH) + public final Flowable refCount(int subscriberCount, long timeout, TimeUnit unit) { + return refCount(subscriberCount, timeout, unit, Schedulers.computation()); + } + + /** + * Connects to the upstream {@code ConnectableFlowable} if the number of subscribed + * subscriber reaches the specified count and disconnect after the specified + * timeout if all subscribers have unsubscribed. + *
                + *
                Backpressure:
                + *
                The operator itself doesn't interfere with backpressure which is determined by the upstream + * {@code ConnectableFlowable}'s backpressure behavior.
                + *
                Scheduler:
                + *
                This {@code refCount} overload operates on the specified {@link Scheduler}.
                + *
                + * @param subscriberCount the number of subscribers required to connect to the upstream + * @param timeout the time to wait before disconnecting after all subscribers unsubscribed + * @param unit the time unit of the timeout + * @param scheduler the target scheduler to wait on before disconnecting + * @return the new Flowable instance + * @since 2.1.14 - experimental + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.CUSTOM) + @BackpressureSupport(BackpressureKind.PASS_THROUGH) + public final Flowable refCount(int subscriberCount, long timeout, TimeUnit unit, Scheduler scheduler) { + ObjectHelper.verifyPositive(subscriberCount, "subscriberCount"); + ObjectHelper.requireNonNull(unit, "unit is null"); + ObjectHelper.requireNonNull(scheduler, "scheduler is null"); + return RxJavaPlugins.onAssembly(new FlowableRefCount(this, subscriberCount, timeout, unit, scheduler)); + } + /** * Returns a Flowable that automatically connects (at most once) to this ConnectableFlowable * when the first Subscriber subscribes. diff --git a/src/main/java/io/reactivex/observables/ConnectableObservable.java b/src/main/java/io/reactivex/observables/ConnectableObservable.java index 62c76ab9a6..04d1648077 100644 --- a/src/main/java/io/reactivex/observables/ConnectableObservable.java +++ b/src/main/java/io/reactivex/observables/ConnectableObservable.java @@ -13,15 +13,17 @@ package io.reactivex.observables; -import io.reactivex.annotations.NonNull; +import java.util.concurrent.TimeUnit; import io.reactivex.*; +import io.reactivex.annotations.*; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; -import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.functions.*; import io.reactivex.internal.operators.observable.*; import io.reactivex.internal.util.ConnectConsumer; import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; /** * A {@code ConnectableObservable} resembles an ordinary {@link Observable}, except that it does not begin @@ -67,15 +69,130 @@ public final Disposable connect() { /** * Returns an {@code Observable} that stays connected to this {@code ConnectableObservable} as long as there * is at least one subscription to this {@code ConnectableObservable}. - * + *
                + *
                Scheduler:
                + *
                This {@code refCount} overload does not operate on any particular {@link Scheduler}.
                + *
                * @return an {@link Observable} * @see ReactiveX documentation: RefCount + * @see #refCount(int) + * @see #refCount(long, TimeUnit) + * @see #refCount(int, long, TimeUnit) */ @NonNull + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) public Observable refCount() { return RxJavaPlugins.onAssembly(new ObservableRefCount(this)); } + /** + * Connects to the upstream {@code ConnectableObservable} if the number of subscribed + * subscriber reaches the specified count and disconnect if all subscribers have unsubscribed. + *
                + *
                Scheduler:
                + *
                This {@code refCount} overload does not operate on any particular {@link Scheduler}.
                + *
                + * @param subscriberCount the number of subscribers required to connect to the upstream + * @return the new Observable instance + * @since 2.1.14 - experimental + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.NONE) + public final Observable refCount(int subscriberCount) { + return refCount(subscriberCount, 0, TimeUnit.NANOSECONDS, Schedulers.trampoline()); + } + + /** + * Connects to the upstream {@code ConnectableObservable} if the number of subscribed + * subscriber reaches 1 and disconnect after the specified + * timeout if all subscribers have unsubscribed. + *
                + *
                Scheduler:
                + *
                This {@code refCount} overload operates on the {@code computation} {@link Scheduler}.
                + *
                + * @param timeout the time to wait before disconnecting after all subscribers unsubscribed + * @param unit the time unit of the timeout + * @return the new Observable instance + * @since 2.1.14 - experimental + * @see #refCount(long, TimeUnit, Scheduler) + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.COMPUTATION) + public final Observable refCount(long timeout, TimeUnit unit) { + return refCount(1, timeout, unit, Schedulers.computation()); + } + + /** + * Connects to the upstream {@code ConnectableObservable} if the number of subscribed + * subscriber reaches 1 and disconnect after the specified + * timeout if all subscribers have unsubscribed. + *
                + *
                Scheduler:
                + *
                This {@code refCount} overload operates on the specified {@link Scheduler}.
                + *
                + * @param timeout the time to wait before disconnecting after all subscribers unsubscribed + * @param unit the time unit of the timeout + * @param scheduler the target scheduler to wait on before disconnecting + * @return the new Observable instance + * @since 2.1.14 - experimental + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.CUSTOM) + public final Observable refCount(long timeout, TimeUnit unit, Scheduler scheduler) { + return refCount(1, timeout, unit, scheduler); + } + + /** + * Connects to the upstream {@code ConnectableObservable} if the number of subscribed + * subscriber reaches the specified count and disconnect after the specified + * timeout if all subscribers have unsubscribed. + *
                + *
                Scheduler:
                + *
                This {@code refCount} overload operates on the {@code computation} {@link Scheduler}.
                + *
                + * @param subscriberCount the number of subscribers required to connect to the upstream + * @param timeout the time to wait before disconnecting after all subscribers unsubscribed + * @param unit the time unit of the timeout + * @return the new Observable instance + * @since 2.1.14 - experimental + * @see #refCount(int, long, TimeUnit, Scheduler) + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.COMPUTATION) + public final Observable refCount(int subscriberCount, long timeout, TimeUnit unit) { + return refCount(subscriberCount, timeout, unit, Schedulers.computation()); + } + + /** + * Connects to the upstream {@code ConnectableObservable} if the number of subscribed + * subscriber reaches the specified count and disconnect after the specified + * timeout if all subscribers have unsubscribed. + *
                + *
                Scheduler:
                + *
                This {@code refCount} overload operates on the specified {@link Scheduler}.
                + *
                + * @param subscriberCount the number of subscribers required to connect to the upstream + * @param timeout the time to wait before disconnecting after all subscribers unsubscribed + * @param unit the time unit of the timeout + * @param scheduler the target scheduler to wait on before disconnecting + * @return the new Observable instance + * @since 2.1.14 - experimental + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.CUSTOM) + public final Observable refCount(int subscriberCount, long timeout, TimeUnit unit, Scheduler scheduler) { + ObjectHelper.verifyPositive(subscriberCount, "subscriberCount"); + ObjectHelper.requireNonNull(unit, "unit is null"); + ObjectHelper.requireNonNull(scheduler, "scheduler is null"); + return RxJavaPlugins.onAssembly(new ObservableRefCount(this, subscriberCount, timeout, unit, scheduler)); + } + /** * Returns an Observable that automatically connects (at most once) to this ConnectableObservable * when the first Observer subscribes. diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index 01a6d9396e..d91f4706d6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -1001,31 +1001,6 @@ public void subscribe(FlowableEmitter emitter) throws Exception { assertTrue(interrupted.get()); } - static FlowableTransformer refCount(final int n) { - return refCount(n, 0, TimeUnit.NANOSECONDS, Schedulers.trampoline()); - } - - static FlowableTransformer refCount(final long time, final TimeUnit unit) { - return refCount(1, time, unit, Schedulers.computation()); - } - - static FlowableTransformer refCount(final long time, final TimeUnit unit, final Scheduler scheduler) { - return refCount(1, time, unit, scheduler); - } - - static FlowableTransformer refCount(final int n, final long time, final TimeUnit unit) { - return refCount(1, time, unit, Schedulers.computation()); - } - - static FlowableTransformer refCount(final int n, final long time, final TimeUnit unit, final Scheduler scheduler) { - return new FlowableTransformer() { - @Override - public Publisher apply(Flowable f) { - return new FlowableRefCount((ConnectableFlowable)f, n, time, unit, scheduler); - } - }; - } - @Test public void byCount() { final int[] subscriptions = { 0 }; @@ -1038,7 +1013,7 @@ public void accept(Subscription s) throws Exception { } }) .publish() - .compose(FlowableRefCountTest.refCount(2)); + .refCount(2); for (int i = 0; i < 3; i++) { TestSubscriber ts1 = source.test(); @@ -1068,7 +1043,7 @@ public void accept(Subscription s) throws Exception { } }) .publish() - .compose(FlowableRefCountTest.refCount(500, TimeUnit.MILLISECONDS)); + .refCount(500, TimeUnit.MILLISECONDS); TestSubscriber ts1 = source.test(0); @@ -1111,7 +1086,7 @@ public void accept(Subscription s) throws Exception { } }) .publish() - .compose(FlowableRefCountTest.refCount(1, 100, TimeUnit.MILLISECONDS)); + .refCount(1, 100, TimeUnit.MILLISECONDS); TestSubscriber ts1 = source.test(0); @@ -1130,25 +1105,18 @@ public void accept(Subscription s) throws Exception { public void error() { Flowable.error(new IOException()) .publish() - .compose(FlowableRefCountTest.refCount(500, TimeUnit.MILLISECONDS)) + .refCount(500, TimeUnit.MILLISECONDS) .test() .assertFailure(IOException.class); } - @Test(expected = ClassCastException.class) - public void badUpstream() { - Flowable.range(1, 5) - .compose(FlowableRefCountTest.refCount(500, TimeUnit.MILLISECONDS, Schedulers.single())) - ; - } - @Test public void comeAndGo() { PublishProcessor pp = PublishProcessor.create(); Flowable source = pp .publish() - .compose(FlowableRefCountTest.refCount(1)); + .refCount(1); TestSubscriber ts1 = source.test(0); @@ -1171,7 +1139,7 @@ public void unsubscribeSubscribeRace() { final Flowable source = Flowable.range(1, 5) .replay() - .compose(FlowableRefCountTest.refCount(1)) + .refCount(1) ; final TestSubscriber ts1 = source.test(0); @@ -1247,6 +1215,38 @@ public void doubleOnX() { } } + @Test + public void doubleOnXCount() { + List errors = TestHelper.trackPluginErrors(); + try { + new BadFlowableDoubleOnX() + .refCount(1) + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void doubleOnXTime() { + List errors = TestHelper.trackPluginErrors(); + try { + new BadFlowableDoubleOnX() + .refCount(5, TimeUnit.SECONDS, Schedulers.single()) + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + @Test public void cancelTerminateStateExclusion() { FlowableRefCount o = (FlowableRefCount)PublishProcessor.create() diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index 7648cc69b5..d46ae8b204 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -985,31 +985,6 @@ public void subscribe(ObservableEmitter emitter) throws Exception { assertTrue(interrupted.get()); } - static ObservableTransformer refCount(final int n) { - return refCount(n, 0, TimeUnit.NANOSECONDS, Schedulers.trampoline()); - } - - static ObservableTransformer refCount(final long time, final TimeUnit unit) { - return refCount(1, time, unit, Schedulers.computation()); - } - - static ObservableTransformer refCount(final long time, final TimeUnit unit, final Scheduler scheduler) { - return refCount(1, time, unit, scheduler); - } - - static ObservableTransformer refCount(final int n, final long time, final TimeUnit unit) { - return refCount(1, time, unit, Schedulers.computation()); - } - - static ObservableTransformer refCount(final int n, final long time, final TimeUnit unit, final Scheduler scheduler) { - return new ObservableTransformer() { - @Override - public Observable apply(Observable f) { - return new ObservableRefCount((ConnectableObservable)f, n, time, unit, scheduler); - } - }; - } - @Test public void byCount() { final int[] subscriptions = { 0 }; @@ -1022,7 +997,7 @@ public void accept(Disposable s) throws Exception { } }) .publish() - .compose(ObservableRefCountTest.refCount(2)); + .refCount(2); for (int i = 0; i < 3; i++) { TestObserver to1 = source.test(); @@ -1052,7 +1027,7 @@ public void accept(Disposable s) throws Exception { } }) .publish() - .compose(ObservableRefCountTest.refCount(500, TimeUnit.MILLISECONDS)); + .refCount(500, TimeUnit.MILLISECONDS); TestObserver to1 = source.test(); @@ -1095,7 +1070,7 @@ public void accept(Disposable s) throws Exception { } }) .publish() - .compose(ObservableRefCountTest.refCount(1, 100, TimeUnit.MILLISECONDS)); + .refCount(1, 100, TimeUnit.MILLISECONDS); TestObserver to1 = source.test(); @@ -1114,25 +1089,18 @@ public void accept(Disposable s) throws Exception { public void error() { Observable.error(new IOException()) .publish() - .compose(ObservableRefCountTest.refCount(500, TimeUnit.MILLISECONDS)) + .refCount(500, TimeUnit.MILLISECONDS) .test() .assertFailure(IOException.class); } - @Test(expected = ClassCastException.class) - public void badUpstream() { - Observable.range(1, 5) - .compose(ObservableRefCountTest.refCount(500, TimeUnit.MILLISECONDS, Schedulers.single())) - ; - } - @Test public void comeAndGo() { PublishSubject ps = PublishSubject.create(); Observable source = ps .publish() - .compose(ObservableRefCountTest.refCount(1)); + .refCount(1); TestObserver to1 = source.test(); @@ -1155,7 +1123,7 @@ public void unsubscribeSubscribeRace() { final Observable source = Observable.range(1, 5) .replay() - .compose(ObservableRefCountTest.refCount(1)) + .refCount(1) ; final TestObserver to1 = source.test(); @@ -1231,6 +1199,38 @@ public void doubleOnX() { } } + @Test + public void doubleOnXCount() { + List errors = TestHelper.trackPluginErrors(); + try { + new BadObservableDoubleOnX() + .refCount(1) + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void doubleOnXTime() { + List errors = TestHelper.trackPluginErrors(); + try { + new BadObservableDoubleOnX() + .refCount(5, TimeUnit.SECONDS, Schedulers.single()) + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + @Test public void cancelTerminateStateExclusion() { ObservableRefCount o = (ObservableRefCount)PublishSubject.create() From d2941f4007e58f8b251e7432ec6df235ca869d23 Mon Sep 17 00:00:00 2001 From: antego Date: Wed, 9 May 2018 13:32:41 +0300 Subject: [PATCH 178/417] Fix typo (#6003) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c1d75b3401..a6b82c0391 100644 --- a/README.md +++ b/README.md @@ -437,7 +437,7 @@ someSource.concatWith(s -> Single.just(2)) Unfortunately, this approach doesn't work and the example does not print `2` at all. In fact, since version 2.1.10, it doesn't even compile because at least 4 `concatWith` overloads exist and the compiler finds the code above ambiguous. -The user in such situations probably wanted to defer some computation until the `sameSource` has completed, thus the correct +The user in such situations probably wanted to defer some computation until the `someSource` has completed, thus the correct unambiguous operator should have been `defer`: ```java From fefcfed4877e8481bf9e0f46fe56f42299e58553 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 9 May 2018 12:55:22 +0200 Subject: [PATCH 179/417] 2.x: readme: mention 1.x eol; 2.x snapshot javadoc url (#5997) --- README.md | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index a6b82c0391..4d3b6533eb 100644 --- a/README.md +++ b/README.md @@ -8,15 +8,6 @@ RxJava is a Java VM implementation of [Reactive Extensions](http://reactivex.io) It extends the [observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) to support sequences of data/events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety and concurrent data structures. -#### Version 1.x ([Javadoc](http://reactivex.io/RxJava/1.x/javadoc/)) - -Looking for version 1.x? Jump [to the 1.x branch](https://github.com/ReactiveX/RxJava/tree/1.x). - -Timeline plans for the 1.x line: - - - **June 1, 2017** - feature freeze (no new operators), only bugfixes - - **March 31, 2018** - end of life, no further development - #### Version 2.x ([Javadoc](http://reactivex.io/RxJava/2.x/javadoc/)) - single dependency: [Reactive-Streams](https://github.com/reactive-streams/reactive-streams-jvm) @@ -31,6 +22,10 @@ Version 2.x and 1.x will live side-by-side for several years. They will have dif See the differences between version 1.x and 2.x in the wiki article [What's different in 2.0](https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0). Learn more about RxJava in general on the Wiki Home. +#### Version 1.x + +The [1.x version](https://github.com/ReactiveX/RxJava/tree/1.x) is end-of-life as of **March 31, 2018**. No further development, support, maintenance, PRs and updates will happen. The [Javadoc]([Javadoc](http://reactivex.io/RxJava/1.x/javadoc/)) of the very last version, **1.3.8**, will remain accessible. + ## Getting started ### Setting up the dependency @@ -527,6 +522,8 @@ All code inside the `io.reactivex.internal.*` packages is considered private API - [Wiki](https://github.com/ReactiveX/RxJava/wiki) - [Javadoc](http://reactivex.io/RxJava/2.x/javadoc/) +- [Latest snaphot Javadoc](http://reactivex.io/RxJava/2.x/javadoc/snapshot/) +- Javadoc of a specific [release version](https://github.com/ReactiveX/RxJava/tags): `http://reactivex.io/RxJava/2.x/javadoc/2.x.y/` ## Binaries From 8a281698442d6adbc6680275022dd0dd8722926b Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 9 May 2018 19:13:17 +0200 Subject: [PATCH 180/417] 2.x: Javadoc space cleanup (#6005) * 2.x: Remove excessive whitespaces from generated javadocs on build * Fix html before javadocJar, fix other space patterns * Fix replay subject/processor html --- build.gradle | 1 + gradle/javadoc_cleanup.gradle | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 gradle/javadoc_cleanup.gradle diff --git a/build.gradle b/build.gradle index f3f16d4eb4..d39826e76d 100644 --- a/build.gradle +++ b/build.gradle @@ -369,3 +369,4 @@ if (rootProject.hasProperty("releaseMode")) { } } +apply from: file("gradle/javadoc_cleanup.gradle") diff --git a/gradle/javadoc_cleanup.gradle b/gradle/javadoc_cleanup.gradle new file mode 100644 index 0000000000..32db33b963 --- /dev/null +++ b/gradle/javadoc_cleanup.gradle @@ -0,0 +1,33 @@ +// remove the excessive whitespaces between method arguments in the javadocs +task javadocCleanup(dependsOn: "javadoc") doLast { + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/Flowable.html')); + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/Observable.html')); + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/Single.html')); + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/Maybe.html')); + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/Completable.html')); + + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/flowables/ConnectableFlowable.html')); + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/observables/ConnectableObservable.html')); + + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/subjects/ReplaySubject.html')); + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/processors/ReplayProcessor.html')); +} + +def fixJavadocFile(file) { + println("Cleaning up: " + file); + String fileContents = file.getText('UTF-8') + + // lots of spaces after the previous method argument + fileContents = fileContents.replaceAll(",\\s{4,}", ",\n "); + + // lots of spaces after the @NonNull annotations + fileContents = fileContents.replaceAll("@NonNull\\s{4,}", "@NonNull "); + + // lots of spaces after the @Nullable annotations + fileContents = fileContents.replaceAll("@Nullable\\s{4,}", "@Nullable "); + + file.setText(fileContents, 'UTF-8'); +} + +javadocJar.dependsOn javadocCleanup +build.dependsOn javadocCleanup \ No newline at end of file From 5ce21f49465143c48a5bcbd32d73721aded05e78 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 17 May 2018 10:11:13 +0200 Subject: [PATCH 181/417] 2.x: Add throttleLatest operator (#5979) --- src/main/java/io/reactivex/Flowable.java | 152 ++++++++++ src/main/java/io/reactivex/Observable.java | 128 ++++++++ .../flowable/FlowableThrottleLatest.java | 248 ++++++++++++++++ .../observable/ObservableThrottleLatest.java | 216 ++++++++++++++ .../reactivex/ParamValidationCheckerTest.java | 10 + .../flowable/FlowableThrottleLatestTest.java | 281 ++++++++++++++++++ .../ObservableThrottleLatestTest.java | 224 ++++++++++++++ 7 files changed, 1259 insertions(+) create mode 100644 src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatest.java create mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatestTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservableThrottleLatestTest.java diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 800cfa5ea5..b37e123bc8 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -15536,6 +15536,158 @@ public final Flowable throttleLast(long intervalDuration, TimeUnit unit, Sche return sample(intervalDuration, unit, scheduler); } + /** + * Throttles items from the upstream {@code Flowable} by first emitting the next + * item from upstream, then periodically emitting the latest item (if any) when + * the specified timeout elapses between them. + *

                + * + *

                + * Unlike the option with {@link #throttleLatest(long, TimeUnit, boolean)}, the very last item being held back + * (if any) is not emitted when the upstream completes. + *

                + * If no items were emitted from the upstream during this timeout phase, the next + * upstream item is emitted immediately and the timeout window starts from then. + *

                + *
                Backpressure:
                + *
                This operator does not support backpressure as it uses time to control data flow. + * If the downstream is not ready to receive items, a + * {@link io.reactivex.exceptions.MissingBackpressureException MissingBackpressureException} + * will be signaled.
                + *
                Scheduler:
                + *
                {@code throttleLatest} operates by default on the {@code computation} {@link Scheduler}.
                + *
                + * @param timeout the time to wait after an item emission towards the downstream + * before trying to emit the latest item from upstream again + * @param unit the time unit + * @return the new Flowable instance + * @since 2.1.14 - experimental + * @see #throttleLatest(long, TimeUnit, boolean) + * @see #throttleLatest(long, TimeUnit, Scheduler) + */ + @Experimental + @CheckReturnValue + @BackpressureSupport(BackpressureKind.ERROR) + @SchedulerSupport(SchedulerSupport.COMPUTATION) + public final Flowable throttleLatest(long timeout, TimeUnit unit) { + return throttleLatest(timeout, unit, Schedulers.computation(), false); + } + + /** + * Throttles items from the upstream {@code Flowable} by first emitting the next + * item from upstream, then periodically emitting the latest item (if any) when + * the specified timeout elapses between them. + *

                + * + *

                + * If no items were emitted from the upstream during this timeout phase, the next + * upstream item is emitted immediately and the timeout window starts from then. + *

                + *
                Backpressure:
                + *
                This operator does not support backpressure as it uses time to control data flow. + * If the downstream is not ready to receive items, a + * {@link io.reactivex.exceptions.MissingBackpressureException MissingBackpressureException} + * will be signaled.
                + *
                Scheduler:
                + *
                {@code throttleLatest} operates by default on the {@code computation} {@link Scheduler}.
                + *
                + * @param timeout the time to wait after an item emission towards the downstream + * before trying to emit the latest item from upstream again + * @param unit the time unit + * @param emitLast If {@code true}, the very last item from the upstream will be emitted + * immediately when the upstream completes, regardless if there is + * a timeout window active or not. If {@code false}, the very last + * upstream item is ignored and the flow terminates. + * @return the new Flowable instance + * @since 2.1.14 - experimental + * @see #throttleLatest(long, TimeUnit, Scheduler, boolean) + */ + @Experimental + @CheckReturnValue + @BackpressureSupport(BackpressureKind.ERROR) + @SchedulerSupport(SchedulerSupport.COMPUTATION) + public final Flowable throttleLatest(long timeout, TimeUnit unit, boolean emitLast) { + return throttleLatest(timeout, unit, Schedulers.computation(), emitLast); + } + + /** + * Throttles items from the upstream {@code Flowable} by first emitting the next + * item from upstream, then periodically emitting the latest item (if any) when + * the specified timeout elapses between them. + *

                + * + *

                + * Unlike the option with {@link #throttleLatest(long, TimeUnit, Scheduler, boolean)}, the very last item being held back + * (if any) is not emitted when the upstream completes. + *

                + * If no items were emitted from the upstream during this timeout phase, the next + * upstream item is emitted immediately and the timeout window starts from then. + *

                + *
                Backpressure:
                + *
                This operator does not support backpressure as it uses time to control data flow. + * If the downstream is not ready to receive items, a + * {@link io.reactivex.exceptions.MissingBackpressureException MissingBackpressureException} + * will be signaled.
                + *
                Scheduler:
                + *
                You specify which {@link Scheduler} this operator will use.
                + *
                + * @param timeout the time to wait after an item emission towards the downstream + * before trying to emit the latest item from upstream again + * @param unit the time unit + * @param scheduler the {@link Scheduler} where the timed wait and latest item + * emission will be performed + * @return the new Flowable instance + * @since 2.1.14 - experimental + * @see #throttleLatest(long, TimeUnit, Scheduler, boolean) + */ + @Experimental + @CheckReturnValue + @BackpressureSupport(BackpressureKind.ERROR) + @SchedulerSupport(SchedulerSupport.CUSTOM) + public final Flowable throttleLatest(long timeout, TimeUnit unit, Scheduler scheduler) { + return throttleLatest(timeout, unit, scheduler, false); + } + + /** + * Throttles items from the upstream {@code Flowable} by first emitting the next + * item from upstream, then periodically emitting the latest item (if any) when + * the specified timeout elapses between them. + *

                + * + *

                + * If no items were emitted from the upstream during this timeout phase, the next + * upstream item is emitted immediately and the timeout window starts from then. + *

                + *
                Backpressure:
                + *
                This operator does not support backpressure as it uses time to control data flow. + * If the downstream is not ready to receive items, a + * {@link io.reactivex.exceptions.MissingBackpressureException MissingBackpressureException} + * will be signaled.
                + *
                Scheduler:
                + *
                You specify which {@link Scheduler} this operator will use.
                + *
                + * @param timeout the time to wait after an item emission towards the downstream + * before trying to emit the latest item from upstream again + * @param unit the time unit + * @param scheduler the {@link Scheduler} where the timed wait and latest item + * emission will be performed + * @param emitLast If {@code true}, the very last item from the upstream will be emitted + * immediately when the upstream completes, regardless if there is + * a timeout window active or not. If {@code false}, the very last + * upstream item is ignored and the flow terminates. + * @return the new Flowable instance + * @since 2.1.14 - experimental + */ + @Experimental + @CheckReturnValue + @BackpressureSupport(BackpressureKind.ERROR) + @SchedulerSupport(SchedulerSupport.CUSTOM) + public final Flowable throttleLatest(long timeout, TimeUnit unit, Scheduler scheduler, boolean emitLast) { + ObjectHelper.requireNonNull(unit, "unit is null"); + ObjectHelper.requireNonNull(scheduler, "scheduler is null"); + return RxJavaPlugins.onAssembly(new FlowableThrottleLatest(this, timeout, unit, scheduler, emitLast)); + } + /** * Returns a Flowable that only emits those items emitted by the source Publisher that are not followed * by another emitted item within a specified time window. diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index e7c7bb7f67..e6438a46e5 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -13055,6 +13055,134 @@ public final Observable throttleLast(long intervalDuration, TimeUnit unit, Sc return sample(intervalDuration, unit, scheduler); } + /** + * Throttles items from the upstream {@code Observable} by first emitting the next + * item from upstream, then periodically emitting the latest item (if any) when + * the specified timeout elapses between them. + *

                + * + *

                + * Unlike the option with {@link #throttleLatest(long, TimeUnit, boolean)}, the very last item being held back + * (if any) is not emitted when the upstream completes. + *

                + * If no items were emitted from the upstream during this timeout phase, the next + * upstream item is emitted immediately and the timeout window starts from then. + *

                + *
                Scheduler:
                + *
                {@code throttleLatest} operates by default on the {@code computation} {@link Scheduler}.
                + *
                + * @param timeout the time to wait after an item emission towards the downstream + * before trying to emit the latest item from upstream again + * @param unit the time unit + * @return the new Observable instance + * @since 2.1.14 - experimental + * @see #throttleLatest(long, TimeUnit, boolean) + * @see #throttleLatest(long, TimeUnit, Scheduler) + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.COMPUTATION) + public final Observable throttleLatest(long timeout, TimeUnit unit) { + return throttleLatest(timeout, unit, Schedulers.computation(), false); + } + + /** + * Throttles items from the upstream {@code Observable} by first emitting the next + * item from upstream, then periodically emitting the latest item (if any) when + * the specified timeout elapses between them. + *

                + * + *

                + * If no items were emitted from the upstream during this timeout phase, the next + * upstream item is emitted immediately and the timeout window starts from then. + *

                + *
                Scheduler:
                + *
                {@code throttleLatest} operates by default on the {@code computation} {@link Scheduler}.
                + *
                + * @param timeout the time to wait after an item emission towards the downstream + * before trying to emit the latest item from upstream again + * @param unit the time unit + * @param emitLast If {@code true}, the very last item from the upstream will be emitted + * immediately when the upstream completes, regardless if there is + * a timeout window active or not. If {@code false}, the very last + * upstream item is ignored and the flow terminates. + * @return the new Observable instance + * @since 2.1.14 - experimental + * @see #throttleLatest(long, TimeUnit, Scheduler, boolean) + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.COMPUTATION) + public final Observable throttleLatest(long timeout, TimeUnit unit, boolean emitLast) { + return throttleLatest(timeout, unit, Schedulers.computation(), emitLast); + } + + /** + * Throttles items from the upstream {@code Observable} by first emitting the next + * item from upstream, then periodically emitting the latest item (if any) when + * the specified timeout elapses between them. + *

                + * + *

                + * Unlike the option with {@link #throttleLatest(long, TimeUnit, Scheduler, boolean)}, the very last item being held back + * (if any) is not emitted when the upstream completes. + *

                + * If no items were emitted from the upstream during this timeout phase, the next + * upstream item is emitted immediately and the timeout window starts from then. + *

                + *
                Scheduler:
                + *
                You specify which {@link Scheduler} this operator will use.
                + *
                + * @param timeout the time to wait after an item emission towards the downstream + * before trying to emit the latest item from upstream again + * @param unit the time unit + * @param scheduler the {@link Scheduler} where the timed wait and latest item + * emission will be performed + * @return the new Observable instance + * @since 2.1.14 - experimental + * @see #throttleLatest(long, TimeUnit, Scheduler, boolean) + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.CUSTOM) + public final Observable throttleLatest(long timeout, TimeUnit unit, Scheduler scheduler) { + return throttleLatest(timeout, unit, scheduler, false); + } + + /** + * Throttles items from the upstream {@code Observable} by first emitting the next + * item from upstream, then periodically emitting the latest item (if any) when + * the specified timeout elapses between them. + *

                + * + *

                + * If no items were emitted from the upstream during this timeout phase, the next + * upstream item is emitted immediately and the timeout window starts from then. + *

                + *
                Scheduler:
                + *
                You specify which {@link Scheduler} this operator will use.
                + *
                + * @param timeout the time to wait after an item emission towards the downstream + * before trying to emit the latest item from upstream again + * @param unit the time unit + * @param scheduler the {@link Scheduler} where the timed wait and latest item + * emission will be performed + * @param emitLast If {@code true}, the very last item from the upstream will be emitted + * immediately when the upstream completes, regardless if there is + * a timeout window active or not. If {@code false}, the very last + * upstream item is ignored and the flow terminates. + * @return the new Observable instance + * @since 2.1.14 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.CUSTOM) + public final Observable throttleLatest(long timeout, TimeUnit unit, Scheduler scheduler, boolean emitLast) { + ObjectHelper.requireNonNull(unit, "unit is null"); + ObjectHelper.requireNonNull(scheduler, "scheduler is null"); + return RxJavaPlugins.onAssembly(new ObservableThrottleLatest(this, timeout, unit, scheduler, emitLast)); + } + /** * Returns an Observable that only emits those items emitted by the source ObservableSource that are not followed * by another emitted item within a specified time window. diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatest.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatest.java new file mode 100644 index 0000000000..1ce2dddc25 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatest.java @@ -0,0 +1,248 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.exceptions.MissingBackpressureException; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.BackpressureHelper; + +/** + * Emits the next or latest item when the given time elapses. + *

                + * The operator emits the next item, then starts a timer. When the timer fires, + * it tries to emit the latest item from upstream. If there was no upstream item, + * in the meantime, the next upstream item is emitted immediately and the + * timed process repeats. + * + * @param the upstream and downstream value type + * @since 2.1.14 - experimental + */ +@Experimental +public final class FlowableThrottleLatest extends AbstractFlowableWithUpstream { + + final long timeout; + + final TimeUnit unit; + + final Scheduler scheduler; + + final boolean emitLast; + + public FlowableThrottleLatest(Flowable source, + long timeout, TimeUnit unit, Scheduler scheduler, + boolean emitLast) { + super(source); + this.timeout = timeout; + this.unit = unit; + this.scheduler = scheduler; + this.emitLast = emitLast; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new ThrottleLatestSubscriber(s, timeout, unit, scheduler.createWorker(), emitLast)); + } + + static final class ThrottleLatestSubscriber + extends AtomicInteger + implements FlowableSubscriber, Subscription, Runnable { + + private static final long serialVersionUID = -8296689127439125014L; + + final Subscriber downstream; + + final long timeout; + + final TimeUnit unit; + + final Scheduler.Worker worker; + + final boolean emitLast; + + final AtomicReference latest; + + final AtomicLong requested; + + Subscription upstream; + + volatile boolean done; + Throwable error; + + volatile boolean cancelled; + + volatile boolean timerFired; + + long emitted; + + boolean timerRunning; + + ThrottleLatestSubscriber(Subscriber downstream, + long timeout, TimeUnit unit, Scheduler.Worker worker, + boolean emitLast) { + this.downstream = downstream; + this.timeout = timeout; + this.unit = unit; + this.worker = worker; + this.emitLast = emitLast; + this.latest = new AtomicReference(); + this.requested = new AtomicLong(); + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(upstream, s)) { + upstream = s; + downstream.onSubscribe(this); + s.request(Long.MAX_VALUE); + } + } + + @Override + public void onNext(T t) { + latest.set(t); + drain(); + } + + @Override + public void onError(Throwable t) { + error = t; + done = true; + drain(); + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @Override + public void request(long n) { + if (SubscriptionHelper.validate(n)) { + BackpressureHelper.add(requested, n); + } + } + + @Override + public void cancel() { + cancelled = true; + upstream.cancel(); + worker.dispose(); + if (getAndIncrement() == 0) { + latest.lazySet(null); + } + } + + @Override + public void run() { + timerFired = true; + drain(); + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + + AtomicReference latest = this.latest; + AtomicLong requested = this.requested; + Subscriber downstream = this.downstream; + + for (;;) { + + for (;;) { + if (cancelled) { + latest.lazySet(null); + return; + } + + boolean d = done; + + if (d && error != null) { + latest.lazySet(null); + downstream.onError(error); + worker.dispose(); + return; + } + + T v = latest.get(); + boolean empty = v == null; + + if (d) { + if (!empty && emitLast) { + v = latest.getAndSet(null); + long e = emitted; + if (e != requested.get()) { + emitted = e + 1; + downstream.onNext(v); + downstream.onComplete(); + } else { + downstream.onError(new MissingBackpressureException( + "Could not emit final value due to lack of requests")); + } + } else { + latest.lazySet(null); + downstream.onComplete(); + } + worker.dispose(); + return; + } + + if (empty) { + if (timerFired) { + timerRunning = false; + timerFired = false; + } + break; + } + + if (!timerRunning || timerFired) { + v = latest.getAndSet(null); + long e = emitted; + if (e != requested.get()) { + downstream.onNext(v); + emitted = e + 1; + } else { + upstream.cancel(); + downstream.onError(new MissingBackpressureException( + "Could not emit value due to lack of requests")); + worker.dispose(); + return; + } + + timerFired = false; + timerRunning = true; + worker.schedule(this, timeout, unit); + } else { + break; + } + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java new file mode 100644 index 0000000000..51df6abd1f --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java @@ -0,0 +1,216 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; + +/** + * Emits the next or latest item when the given time elapses. + *

                + * The operator emits the next item, then starts a timer. When the timer fires, + * it tries to emit the latest item from upstream. If there was no upstream item, + * in the meantime, the next upstream item is emitted immediately and the + * timed process repeats. + * + * @param the upstream and downstream value type + * @since 2.1.14 - experimental + */ +@Experimental +public final class ObservableThrottleLatest extends AbstractObservableWithUpstream { + + final long timeout; + + final TimeUnit unit; + + final Scheduler scheduler; + + final boolean emitLast; + + public ObservableThrottleLatest(Observable source, + long timeout, TimeUnit unit, Scheduler scheduler, + boolean emitLast) { + super(source); + this.timeout = timeout; + this.unit = unit; + this.scheduler = scheduler; + this.emitLast = emitLast; + } + + @Override + protected void subscribeActual(Observer s) { + source.subscribe(new ThrottleLatestObserver(s, timeout, unit, scheduler.createWorker(), emitLast)); + } + + static final class ThrottleLatestObserver + extends AtomicInteger + implements Observer, Disposable, Runnable { + + private static final long serialVersionUID = -8296689127439125014L; + + final Observer downstream; + + final long timeout; + + final TimeUnit unit; + + final Scheduler.Worker worker; + + final boolean emitLast; + + final AtomicReference latest; + + Disposable upstream; + + volatile boolean done; + Throwable error; + + volatile boolean cancelled; + + volatile boolean timerFired; + + boolean timerRunning; + + ThrottleLatestObserver(Observer downstream, + long timeout, TimeUnit unit, Scheduler.Worker worker, + boolean emitLast) { + this.downstream = downstream; + this.timeout = timeout; + this.unit = unit; + this.worker = worker; + this.emitLast = emitLast; + this.latest = new AtomicReference(); + } + + @Override + public void onSubscribe(Disposable s) { + if (DisposableHelper.validate(upstream, s)) { + upstream = s; + downstream.onSubscribe(this); + } + } + + @Override + public void onNext(T t) { + latest.set(t); + drain(); + } + + @Override + public void onError(Throwable t) { + error = t; + done = true; + drain(); + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @Override + public void dispose() { + cancelled = true; + upstream.dispose(); + worker.dispose(); + if (getAndIncrement() == 0) { + latest.lazySet(null); + } + } + + @Override + public boolean isDisposed() { + return cancelled; + } + + @Override + public void run() { + timerFired = true; + drain(); + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + + AtomicReference latest = this.latest; + Observer downstream = this.downstream; + + for (;;) { + + for (;;) { + if (cancelled) { + latest.lazySet(null); + return; + } + + boolean d = done; + + if (d && error != null) { + latest.lazySet(null); + downstream.onError(error); + worker.dispose(); + return; + } + + T v = latest.get(); + boolean empty = v == null; + + if (d) { + v = latest.getAndSet(null); + if (!empty && emitLast) { + downstream.onNext(v); + } + downstream.onComplete(); + worker.dispose(); + return; + } + + if (empty) { + if (timerFired) { + timerRunning = false; + timerFired = false; + } + break; + } + + if (!timerRunning || timerFired) { + v = latest.getAndSet(null); + downstream.onNext(v); + + timerFired = false; + timerRunning = true; + worker.schedule(this, timeout, unit); + } else { + break; + } + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + } +} diff --git a/src/test/java/io/reactivex/ParamValidationCheckerTest.java b/src/test/java/io/reactivex/ParamValidationCheckerTest.java index d129d14aa4..6a3a430c12 100644 --- a/src/test/java/io/reactivex/ParamValidationCheckerTest.java +++ b/src/test/java/io/reactivex/ParamValidationCheckerTest.java @@ -226,6 +226,11 @@ public void checkParallelFlowable() { addOverride(new ParamOverride(Flowable.class, 0, ParamMode.ANY, "throttleLast", Long.TYPE, TimeUnit.class)); addOverride(new ParamOverride(Flowable.class, 0, ParamMode.ANY, "throttleLast", Long.TYPE, TimeUnit.class, Scheduler.class)); + // negative time is considered as zero time + addOverride(new ParamOverride(Flowable.class, 0, ParamMode.ANY, "throttleLatest", Long.TYPE, TimeUnit.class)); + addOverride(new ParamOverride(Flowable.class, 0, ParamMode.ANY, "throttleLatest", Long.TYPE, TimeUnit.class, Scheduler.class)); + addOverride(new ParamOverride(Flowable.class, 0, ParamMode.ANY, "throttleLatest", Long.TYPE, TimeUnit.class, Boolean.TYPE)); + addOverride(new ParamOverride(Flowable.class, 0, ParamMode.ANY, "throttleLatest", Long.TYPE, TimeUnit.class, Scheduler.class, Boolean.TYPE)); // negative buffer time is considered as zero buffer time addOverride(new ParamOverride(Flowable.class, 0, ParamMode.ANY, "window", Long.TYPE, TimeUnit.class)); @@ -470,6 +475,11 @@ public void checkParallelFlowable() { addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "throttleLast", Long.TYPE, TimeUnit.class)); addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "throttleLast", Long.TYPE, TimeUnit.class, Scheduler.class)); + // negative time is considered as zero time + addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "throttleLatest", Long.TYPE, TimeUnit.class)); + addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "throttleLatest", Long.TYPE, TimeUnit.class, Scheduler.class)); + addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "throttleLatest", Long.TYPE, TimeUnit.class, Boolean.TYPE)); + addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "throttleLatest", Long.TYPE, TimeUnit.class, Scheduler.class, Boolean.TYPE)); // negative buffer time is considered as zero buffer time addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "window", Long.TYPE, TimeUnit.class)); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatestTest.java new file mode 100644 index 0000000000..2b07d178d9 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatestTest.java @@ -0,0 +1,281 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import java.util.concurrent.TimeUnit; + +import static org.mockito.Mockito.*; + +import org.junit.Test; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableThrottleLatestTest { + + @Test + public void just() { + Flowable.just(1) + .throttleLatest(1, TimeUnit.MINUTES) + .test() + .assertResult(1); + } + + @Test + public void range() { + Flowable.range(1, 5) + .throttleLatest(1, TimeUnit.MINUTES) + .test() + .assertResult(1); + } + + @Test + public void rangeEmitLatest() { + Flowable.range(1, 5) + .throttleLatest(1, TimeUnit.MINUTES, true) + .test() + .assertResult(1, 5); + } + + @Test + public void error() { + Flowable.error(new TestException()) + .throttleLatest(1, TimeUnit.MINUTES) + .test() + .assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeFlowable(new Function, Publisher>() { + @Override + public Publisher apply(Flowable f) throws Exception { + return f.throttleLatest(1, TimeUnit.MINUTES); + } + }); + } + + @Test + public void badRequest() { + TestHelper.assertBadRequestReported( + Flowable.never() + .throttleLatest(1, TimeUnit.MINUTES) + ); + } + + @Test + public void normal() { + TestScheduler sch = new TestScheduler(); + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = pp.throttleLatest(1, TimeUnit.SECONDS, sch).test(); + + pp.onNext(1); + + ts.assertValuesOnly(1); + + pp.onNext(2); + + ts.assertValuesOnly(1); + + pp.onNext(3); + + ts.assertValuesOnly(1); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertValuesOnly(1, 3); + + pp.onNext(4); + + ts.assertValuesOnly(1, 3); + + pp.onNext(5); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertValuesOnly(1, 3, 5); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertValuesOnly(1, 3, 5); + + pp.onNext(6); + + ts.assertValuesOnly(1, 3, 5, 6); + + pp.onNext(7); + pp.onComplete(); + + ts.assertResult(1, 3, 5, 6); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertResult(1, 3, 5, 6); + } + + + @Test + public void normalEmitLast() { + TestScheduler sch = new TestScheduler(); + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = pp.throttleLatest(1, TimeUnit.SECONDS, sch, true).test(); + + pp.onNext(1); + + ts.assertValuesOnly(1); + + pp.onNext(2); + + ts.assertValuesOnly(1); + + pp.onNext(3); + + ts.assertValuesOnly(1); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertValuesOnly(1, 3); + + pp.onNext(4); + + ts.assertValuesOnly(1, 3); + + pp.onNext(5); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertValuesOnly(1, 3, 5); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertValuesOnly(1, 3, 5); + + pp.onNext(6); + + ts.assertValuesOnly(1, 3, 5, 6); + + pp.onNext(7); + pp.onComplete(); + + ts.assertResult(1, 3, 5, 6, 7); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertResult(1, 3, 5, 6, 7); + } + + @Test + public void missingBackpressureExceptionFirst() throws Exception { + TestScheduler sch = new TestScheduler(); + Action onCancel = mock(Action.class); + + Flowable.just(1, 2) + .doOnCancel(onCancel) + .throttleLatest(1, TimeUnit.MINUTES, sch) + .test(0) + .assertFailure(MissingBackpressureException.class); + + verify(onCancel).run(); + } + + @Test + public void missingBackpressureExceptionLatest() throws Exception { + TestScheduler sch = new TestScheduler(); + Action onCancel = mock(Action.class); + + TestSubscriber ts = Flowable.just(1, 2) + .concatWith(Flowable.never()) + .doOnCancel(onCancel) + .throttleLatest(1, TimeUnit.SECONDS, sch, true) + .test(1); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertFailure(MissingBackpressureException.class, 1); + + verify(onCancel).run(); + } + + @Test + public void missingBackpressureExceptionLatestComplete() throws Exception { + TestScheduler sch = new TestScheduler(); + Action onCancel = mock(Action.class); + + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = pp + .doOnCancel(onCancel) + .throttleLatest(1, TimeUnit.SECONDS, sch, true) + .test(1); + + pp.onNext(1); + pp.onNext(2); + + ts.assertValuesOnly(1); + + pp.onComplete(); + + ts.assertFailure(MissingBackpressureException.class, 1); + + verify(onCancel, never()).run(); + } + + @Test + public void take() throws Exception { + Action onCancel = mock(Action.class); + + Flowable.range(1, 5) + .doOnCancel(onCancel) + .throttleLatest(1, TimeUnit.MINUTES) + .take(1) + .test() + .assertResult(1); + + verify(onCancel).run(); + } + + @Test + public void reentrantComplete() { + TestScheduler sch = new TestScheduler(); + final PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + pp.onNext(2); + } + if (t == 2) { + pp.onComplete(); + } + } + }; + + pp.throttleLatest(1, TimeUnit.SECONDS, sch).subscribe(ts); + + pp.onNext(1); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertResult(1, 2); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableThrottleLatestTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableThrottleLatestTest.java new file mode 100644 index 0000000000..9d60e5d232 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableThrottleLatestTest.java @@ -0,0 +1,224 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import static org.mockito.Mockito.*; + +import java.util.concurrent.TimeUnit; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.*; +import io.reactivex.observers.TestObserver; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subjects.PublishSubject; + +public class ObservableThrottleLatestTest { + + @Test + public void just() { + Observable.just(1) + .throttleLatest(1, TimeUnit.MINUTES) + .test() + .assertResult(1); + } + + @Test + public void range() { + Observable.range(1, 5) + .throttleLatest(1, TimeUnit.MINUTES) + .test() + .assertResult(1); + } + + @Test + public void rangeEmitLatest() { + Observable.range(1, 5) + .throttleLatest(1, TimeUnit.MINUTES, true) + .test() + .assertResult(1, 5); + } + + @Test + public void error() { + Observable.error(new TestException()) + .throttleLatest(1, TimeUnit.MINUTES) + .test() + .assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function, Observable>() { + @Override + public Observable apply(Observable f) throws Exception { + return f.throttleLatest(1, TimeUnit.MINUTES); + } + }); + } + + @Test + public void disposed() { + TestHelper.checkDisposed( + Observable.never() + .throttleLatest(1, TimeUnit.MINUTES) + ); + } + + @Test + public void normal() { + TestScheduler sch = new TestScheduler(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ps.throttleLatest(1, TimeUnit.SECONDS, sch).test(); + + ps.onNext(1); + + to.assertValuesOnly(1); + + ps.onNext(2); + + to.assertValuesOnly(1); + + ps.onNext(3); + + to.assertValuesOnly(1); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + to.assertValuesOnly(1, 3); + + ps.onNext(4); + + to.assertValuesOnly(1, 3); + + ps.onNext(5); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + to.assertValuesOnly(1, 3, 5); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + to.assertValuesOnly(1, 3, 5); + + ps.onNext(6); + + to.assertValuesOnly(1, 3, 5, 6); + + ps.onNext(7); + ps.onComplete(); + + to.assertResult(1, 3, 5, 6); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + to.assertResult(1, 3, 5, 6); + } + + + @Test + public void normalEmitLast() { + TestScheduler sch = new TestScheduler(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ps.throttleLatest(1, TimeUnit.SECONDS, sch, true).test(); + + ps.onNext(1); + + to.assertValuesOnly(1); + + ps.onNext(2); + + to.assertValuesOnly(1); + + ps.onNext(3); + + to.assertValuesOnly(1); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + to.assertValuesOnly(1, 3); + + ps.onNext(4); + + to.assertValuesOnly(1, 3); + + ps.onNext(5); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + to.assertValuesOnly(1, 3, 5); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + to.assertValuesOnly(1, 3, 5); + + ps.onNext(6); + + to.assertValuesOnly(1, 3, 5, 6); + + ps.onNext(7); + ps.onComplete(); + + to.assertResult(1, 3, 5, 6, 7); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + to.assertResult(1, 3, 5, 6, 7); + } + + @Test + public void take() throws Exception { + Action onCancel = mock(Action.class); + + Observable.range(1, 5) + .doOnDispose(onCancel) + .throttleLatest(1, TimeUnit.MINUTES) + .take(1) + .test() + .assertResult(1); + + verify(onCancel).run(); + } + + @Test + public void reentrantComplete() { + TestScheduler sch = new TestScheduler(); + final PublishSubject ps = PublishSubject.create(); + + TestObserver to = new TestObserver() { + @Override + public void onNext(Integer t) { + super.onNext(t); + if (t == 1) { + ps.onNext(2); + } + if (t == 2) { + ps.onComplete(); + } + } + }; + + ps.throttleLatest(1, TimeUnit.SECONDS, sch).subscribe(to); + + ps.onNext(1); + + sch.advanceTimeBy(1, TimeUnit.SECONDS); + + to.assertResult(1, 2); + } +} From f87879d6da0bca65e2b58e4a9696586362a2b100 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Thu, 17 May 2018 23:17:54 +0200 Subject: [PATCH 182/417] 2.x: Add MulticastProcessor (#6002) * 2.x: Add MulticastProcessor * Improve coverage, fix NPE before upstream arrives * Address review feedback. --- .../processors/MulticastProcessor.java | 640 ++++++++++++++ .../processors/MulticastProcessorTest.java | 789 ++++++++++++++++++ 2 files changed, 1429 insertions(+) create mode 100644 src/main/java/io/reactivex/processors/MulticastProcessor.java create mode 100644 src/test/java/io/reactivex/processors/MulticastProcessorTest.java diff --git a/src/main/java/io/reactivex/processors/MulticastProcessor.java b/src/main/java/io/reactivex/processors/MulticastProcessor.java new file mode 100644 index 0000000000..fdc1652dc2 --- /dev/null +++ b/src/main/java/io/reactivex/processors/MulticastProcessor.java @@ -0,0 +1,640 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.processors; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.annotations.*; +import io.reactivex.exceptions.*; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.fuseable.*; +import io.reactivex.internal.queue.*; +import io.reactivex.internal.subscriptions.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * A {@link FlowableProcessor} implementation that coordinates downstream requests through + * a front-buffer and stable-prefetching, optionally canceling the upstream if all + * subscribers have cancelled. + *

                + * + *

                + * This processor does not have a public constructor by design; a new empty instance of this + * {@code MulticastProcessor} can be created via the following {@code create} methods that + * allow configuring it: + *

                  + *
                • {@link #create()}: create an empty {@code MulticastProcessor} with + * {@link io.reactivex.Flowable#bufferSize() Flowable.bufferSize()} prefetch amount + * and no reference counting behavior.
                • + *
                • {@link #create(int)}: create an empty {@code MulticastProcessor} with + * the given prefetch amount and no reference counting behavior.
                • + *
                • {@link #create(boolean)}: create an empty {@code MulticastProcessor} with + * {@link io.reactivex.Flowable#bufferSize() Flowable.bufferSize()} prefetch amount + * and no reference counting behavior.
                • + *
                • {@link #create(int, boolean)}: create an empty {@code MulticastProcessor} with + * the given prefetch amount and an optional reference counting behavior.
                • + *
                + *

                + * When the reference counting behavior is enabled, the {@code MulticastProcessor} cancels its + * upstream when all {@link Subscriber}s have cancelled. Late {@code Subscriber}s will then be + * immediately completed. + *

                + * Because {@code MulticastProcessor} implements the {@link Subscriber} interface, calling + * {@code onSubscribe} is mandatory (Rule 2.12). + * If {@code MulticastProcessor} should run standalone, i.e., without subscribing the {@code MulticastProcessor} to another {@link Publisher}, + * use {@link #start()} or {@link #startUnbounded()} methods to initialize the internal buffer. + * Failing to do so will lead to a {@link NullPointerException} at runtime. + *

                + * Use {@link #offer(Object)} to try and offer/emit items but don't fail if the + * internal buffer is full. + *

                + * A {@code MulticastProcessor} is a {@link Processor} type in the Reactive Streams specification, + * {@code null}s are not allowed (Rule 2.13) as + * parameters to {@link #onSubscribe(Subscription)}, {@link #offer(Object)}, {@link #onNext(Object)} and {@link #onError(Throwable)}. + * Such calls will result in a {@link NullPointerException} being thrown and the processor's state is not changed. + *

                + * Since a {@code MulticastProcessor} is a {@link io.reactivex.Flowable}, it supports backpressure. + * The backpressure from the currently subscribed {@link Subscriber}s are coordinated by emitting upstream + * items only if all of those {@code Subscriber}s have requested at least one item. This behavior + * is also called lockstep-mode because even if some {@code Subscriber}s can take any number + * of items, other {@code Subscriber}s requesting less or infrequently will slow down the overall + * throughput of the flow. + *

                + * Calling {@link #onNext(Object)}, {@link #offer(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@link FlowableProcessor}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} + * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). + *

                + * This {@code MulticastProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasSubscribers()}. This processor doesn't allow peeking into its buffer. + *

                + * When this {@code MulticastProcessor} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, + * all previously signaled but not yet consumed items will be still available to {@code Subscriber}s and the respective + * terminal even is only emitted when all previous items have been successfully delivered to {@code Subscriber}s. + * If there are no {@code Subscriber}s, the remaining items will be buffered indefinitely. + *

                + * The {@code MulticastProcessor} does not support clearing its cached events (to appear empty again). + *

                + *
                Backpressure:
                + *
                The backpressure from the currently subscribed {@code Subscriber}s are coordinated by emitting upstream + * items only if all of those {@code Subscriber}s have requested at least one item. This behavior + * is also called lockstep-mode because even if some {@code Subscriber}s can take any number + * of items, other {@code Subscriber}s requesting less or infrequently will slow down the overall + * throughput of the flow.
                + *
                Scheduler:
                + *
                {@code MulticastProcessor} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code Subscriber}s get notified on an arbitrary thread in a serialized fashion.
                + *
                + *

                + * Example: + *

                
                +    MulticastProcessor<Integer> mp = Flowable.range(1, 10)
                +    .subscribeWith(MulticastProcessor.create());
                +
                +    mp.test().assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
                +
                +    // --------------------
                +
                +    MulticastProcessor<Integer> mp2 = MulticastProcessor.create(4);
                +    mp2.start();
                +
                +    assertTrue(mp2.offer(1));
                +    assertTrue(mp2.offer(2));
                +    assertTrue(mp2.offer(3));
                +    assertTrue(mp2.offer(4));
                +
                +    assertFalse(mp2.offer(5));
                +
                +    mp2.onComplete();
                +
                +    mp2.test().assertResult(1, 2, 3, 4);
                + * 
                + * @param the input and output value type + * @since 2.1.14 - experimental + */ +@Experimental +@BackpressureSupport(BackpressureKind.FULL) +@SchedulerSupport(SchedulerSupport.NONE) +public final class MulticastProcessor extends FlowableProcessor { + + final AtomicInteger wip; + + final AtomicReference upstream; + + final AtomicReference[]> subscribers; + + final AtomicBoolean once; + + final int bufferSize; + + final int limit; + + final boolean refcount; + + volatile SimpleQueue queue; + + volatile boolean done; + volatile Throwable error; + + int consumed; + + int fusionMode; + + @SuppressWarnings("rawtypes") + static final MulticastSubscription[] EMPTY = new MulticastSubscription[0]; + + @SuppressWarnings("rawtypes") + static final MulticastSubscription[] TERMINATED = new MulticastSubscription[0]; + + /** + * Constructs a fresh instance with the default Flowable.bufferSize() prefetch + * amount and no refCount-behavior. + * @param the input and output value type + * @return the new MulticastProcessor instance + */ + @CheckReturnValue + @NonNull + public static MulticastProcessor create() { + return new MulticastProcessor(bufferSize(), false); + } + + /** + * Constructs a fresh instance with the default Flowable.bufferSize() prefetch + * amount and no refCount-behavior. + * @param the input and output value type + * @param refCount if true and if all Subscribers have canceled, the upstream + * is cancelled + * @return the new MulticastProcessor instance + */ + @CheckReturnValue + @NonNull + public static MulticastProcessor create(boolean refCount) { + return new MulticastProcessor(bufferSize(), refCount); + } + + /** + * Constructs a fresh instance with the given prefetch amount and no refCount behavior. + * @param bufferSize the prefetch amount + * @param the input and output value type + * @return the new MulticastProcessor instance + */ + @CheckReturnValue + @NonNull + public static MulticastProcessor create(int bufferSize) { + return new MulticastProcessor(bufferSize, false); + } + + /** + * Constructs a fresh instance with the given prefetch amount and the optional + * refCount-behavior. + * @param bufferSize the prefetch amount + * @param refCount if true and if all Subscribers have canceled, the upstream + * is cancelled + * @param the input and output value type + * @return the new MulticastProcessor instance + */ + @CheckReturnValue + @NonNull + public static MulticastProcessor create(int bufferSize, boolean refCount) { + return new MulticastProcessor(bufferSize, refCount); + } + + /** + * Constructs a fresh instance with the given prefetch amount and the optional + * refCount-behavior. + * @param bufferSize the prefetch amount + * @param refCount if true and if all Subscribers have canceled, the upstream + * is cancelled + */ + @SuppressWarnings("unchecked") + MulticastProcessor(int bufferSize, boolean refCount) { + ObjectHelper.verifyPositive(bufferSize, "bufferSize"); + this.bufferSize = bufferSize; + this.limit = bufferSize - (bufferSize >> 2); + this.wip = new AtomicInteger(); + this.subscribers = new AtomicReference[]>(EMPTY); + this.upstream = new AtomicReference(); + this.refcount = refCount; + this.once = new AtomicBoolean(); + } + + /** + * Initializes this Processor by setting an upstream Subscription that + * ignores request amounts, uses a fixed buffer + * and allows using the onXXX and offer methods + * afterwards. + */ + public void start() { + if (SubscriptionHelper.setOnce(upstream, EmptySubscription.INSTANCE)) { + queue = new SpscArrayQueue(bufferSize); + } + } + + /** + * Initializes this Processor by setting an upstream Subscription that + * ignores request amounts, uses an unbounded buffer + * and allows using the onXXX and offer methods + * afterwards. + */ + public void startUnbounded() { + if (SubscriptionHelper.setOnce(upstream, EmptySubscription.INSTANCE)) { + queue = new SpscLinkedArrayQueue(bufferSize); + } + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.setOnce(upstream, s)) { + if (s instanceof QueueSubscription) { + @SuppressWarnings("unchecked") + QueueSubscription qs = (QueueSubscription)s; + + int m = qs.requestFusion(QueueSubscription.ANY); + if (m == QueueSubscription.SYNC) { + fusionMode = m; + queue = qs; + done = true; + drain(); + return; + } + if (m == QueueSubscription.ASYNC) { + fusionMode = m; + queue = qs; + + s.request(bufferSize); + return; + } + } + + queue = new SpscArrayQueue(bufferSize); + + s.request(bufferSize); + } + } + + @Override + public void onNext(T t) { + if (once.get()) { + return; + } + if (fusionMode == QueueSubscription.NONE) { + ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); + if (!queue.offer(t)) { + SubscriptionHelper.cancel(upstream); + onError(new MissingBackpressureException()); + return; + } + } + drain(); + } + + /** + * Tries to offer an item into the internal queue and returns false + * if the queue is full. + * @param t the item to offer, not null + * @return true if successful, false if the queue is full + */ + public boolean offer(T t) { + if (once.get()) { + return false; + } + ObjectHelper.requireNonNull(t, "offer called with null. Null values are generally not allowed in 2.x operators and sources."); + if (fusionMode == QueueSubscription.NONE) { + if (queue.offer(t)) { + drain(); + return true; + } + } + return false; + } + + @Override + public void onError(Throwable t) { + ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); + if (once.compareAndSet(false, true)) { + error = t; + done = true; + drain(); + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + if (once.compareAndSet(false, true)) { + done = true; + drain(); + } + } + + @Override + public boolean hasSubscribers() { + return subscribers.get().length != 0; + } + + @Override + public boolean hasThrowable() { + return once.get() && error != null; + } + + @Override + public boolean hasComplete() { + return once.get() && error == null; + } + + @Override + public Throwable getThrowable() { + return once.get() ? error : null; + } + + @Override + protected void subscribeActual(Subscriber s) { + MulticastSubscription ms = new MulticastSubscription(s, this); + s.onSubscribe(ms); + if (add(ms)) { + if (ms.get() == Long.MIN_VALUE) { + remove(ms); + } else { + drain(); + } + } else { + if (once.get() || !refcount) { + Throwable ex = error; + if (ex != null) { + s.onError(ex); + return; + } + } + s.onComplete(); + } + } + + boolean add(MulticastSubscription inner) { + for (;;) { + MulticastSubscription[] a = subscribers.get(); + if (a == TERMINATED) { + return false; + } + int n = a.length; + @SuppressWarnings("unchecked") + MulticastSubscription[] b = new MulticastSubscription[n + 1]; + System.arraycopy(a, 0, b, 0, n); + b[n] = inner; + if (subscribers.compareAndSet(a, b)) { + return true; + } + } + } + + @SuppressWarnings("unchecked") + void remove(MulticastSubscription inner) { + for (;;) { + MulticastSubscription[] a = subscribers.get(); + int n = a.length; + if (n == 0) { + return; + } + + int j = -1; + for (int i = 0; i < n; i++) { + if (a[i] == inner) { + j = i; + break; + } + } + + if (j < 0) { + break; + } + + if (n == 1) { + if (refcount) { + if (subscribers.compareAndSet(a, TERMINATED)) { + SubscriptionHelper.cancel(upstream); + once.set(true); + break; + } + } else { + if (subscribers.compareAndSet(a, EMPTY)) { + break; + } + } + } else { + MulticastSubscription[] b = new MulticastSubscription[n - 1]; + System.arraycopy(a, 0, b, 0, j); + System.arraycopy(a, j + 1, b, j, n - j - 1); + if (subscribers.compareAndSet(a, b)) { + break; + } + } + } + } + + @SuppressWarnings("unchecked") + void drain() { + if (wip.getAndIncrement() != 0) { + return; + } + + int missed = 1; + AtomicReference[]> subs = subscribers; + int c = consumed; + int lim = limit; + int fm = fusionMode; + + outer: + for (;;) { + + SimpleQueue q = queue; + + if (q != null) { + MulticastSubscription[] as = subs.get(); + int n = as.length; + + if (n != 0) { + long r = -1L; + + for (MulticastSubscription a : as) { + long ra = a.get(); + if (ra >= 0L) { + if (r == -1L) { + r = ra - a.emitted; + } else { + r = Math.min(r, ra - a.emitted); + } + } + } + + while (r > 0L) { + MulticastSubscription[] bs = subs.get(); + + if (bs == TERMINATED) { + q.clear(); + return; + } + + if (as != bs) { + continue outer; + } + + boolean d = done; + + T v; + + try { + v = q.poll(); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + SubscriptionHelper.cancel(upstream); + d = true; + v = null; + error = ex; + done = true; + } + boolean empty = v == null; + + if (d && empty) { + Throwable ex = error; + if (ex != null) { + for (MulticastSubscription inner : subs.getAndSet(TERMINATED)) { + inner.onError(ex); + } + } else { + for (MulticastSubscription inner : subs.getAndSet(TERMINATED)) { + inner.onComplete(); + } + } + return; + } + + if (empty) { + break; + } + + for (MulticastSubscription inner : as) { + inner.onNext(v); + } + + r--; + + if (fm != QueueSubscription.SYNC) { + if (++c == lim) { + c = 0; + upstream.get().request(lim); + } + } + } + + if (r == 0) { + MulticastSubscription[] bs = subs.get(); + + if (bs == TERMINATED) { + q.clear(); + return; + } + + if (as != bs) { + continue outer; + } + + if (done && q.isEmpty()) { + Throwable ex = error; + if (ex != null) { + for (MulticastSubscription inner : subs.getAndSet(TERMINATED)) { + inner.onError(ex); + } + } else { + for (MulticastSubscription inner : subs.getAndSet(TERMINATED)) { + inner.onComplete(); + } + } + return; + } + } + } + } + + missed = wip.addAndGet(-missed); + if (missed == 0) { + break; + } + } + } + + static final class MulticastSubscription extends AtomicLong implements Subscription { + + private static final long serialVersionUID = -363282618957264509L; + + final Subscriber actual; + + final MulticastProcessor parent; + + long emitted; + + MulticastSubscription(Subscriber actual, MulticastProcessor parent) { + this.actual = actual; + this.parent = parent; + } + + @Override + public void request(long n) { + if (SubscriptionHelper.validate(n)) { + for (;;) { + long r = get(); + if (r == Long.MIN_VALUE || r == Long.MAX_VALUE) { + break; + } + long u = r + n; + if (u < 0L) { + u = Long.MAX_VALUE; + } + if (compareAndSet(r, u)) { + parent.drain(); + break; + } + } + } + } + + @Override + public void cancel() { + if (getAndSet(Long.MIN_VALUE) != Long.MIN_VALUE) { + parent.remove(this); + } + } + + void onNext(T t) { + if (get() != Long.MIN_VALUE) { + emitted++; + actual.onNext(t); + } + } + + void onError(Throwable t) { + if (get() != Long.MIN_VALUE) { + actual.onError(t); + } + } + + void onComplete() { + if (get() != Long.MIN_VALUE) { + actual.onComplete(); + } + } + } +} diff --git a/src/test/java/io/reactivex/processors/MulticastProcessorTest.java b/src/test/java/io/reactivex/processors/MulticastProcessorTest.java new file mode 100644 index 0000000000..c85665eacd --- /dev/null +++ b/src/test/java/io/reactivex/processors/MulticastProcessorTest.java @@ -0,0 +1,789 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.processors; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.junit.Test; +import org.reactivestreams.Subscription; + +import io.reactivex.*; +import io.reactivex.exceptions.*; +import io.reactivex.functions.Function; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subscribers.TestSubscriber; + +public class MulticastProcessorTest { + + @Test + public void complete() { + MulticastProcessor mp = MulticastProcessor.create(); + mp.start(); + + assertFalse(mp.hasSubscribers()); + assertFalse(mp.hasComplete()); + assertFalse(mp.hasThrowable()); + assertNull(mp.getThrowable()); + + TestSubscriber ts = mp.test(); + + assertTrue(mp.hasSubscribers()); + assertFalse(mp.hasComplete()); + assertFalse(mp.hasThrowable()); + assertNull(mp.getThrowable()); + + mp.onNext(1); + mp.onComplete(); + + ts.assertResult(1); + + assertFalse(mp.hasSubscribers()); + assertTrue(mp.hasComplete()); + assertFalse(mp.hasThrowable()); + assertNull(mp.getThrowable()); + + mp.test().assertResult(); + } + + @Test + public void error() { + MulticastProcessor mp = MulticastProcessor.create(); + mp.start(); + + assertFalse(mp.hasSubscribers()); + assertFalse(mp.hasComplete()); + assertFalse(mp.hasThrowable()); + assertNull(mp.getThrowable()); + + TestSubscriber ts = mp.test(); + + assertTrue(mp.hasSubscribers()); + assertFalse(mp.hasComplete()); + assertFalse(mp.hasThrowable()); + assertNull(mp.getThrowable()); + + mp.onNext(1); + mp.onError(new IOException()); + + ts.assertFailure(IOException.class, 1); + + assertFalse(mp.hasSubscribers()); + assertFalse(mp.hasComplete()); + assertTrue(mp.hasThrowable()); + assertNotNull(mp.getThrowable()); + assertTrue("" + mp.getThrowable(), mp.getThrowable() instanceof IOException); + + mp.test().assertFailure(IOException.class); + } + + @Test + public void overflow() { + MulticastProcessor mp = MulticastProcessor.create(1); + mp.start(); + + TestSubscriber ts = mp.test(0); + + assertTrue(mp.offer(1)); + assertFalse(mp.offer(2)); + + mp.onNext(3); + + ts.assertEmpty(); + + ts.request(1); + + ts.assertFailure(MissingBackpressureException.class, 1); + + mp.test().assertFailure(MissingBackpressureException.class); + } + + @Test + public void backpressure() { + MulticastProcessor mp = MulticastProcessor.create(16, false); + mp.start(); + + for (int i = 0; i < 10; i++) { + mp.onNext(i); + } + mp.onComplete(); + + mp.test(0) + .assertEmpty() + .requestMore(1) + .assertValuesOnly(0) + .requestMore(2) + .assertValuesOnly(0, 1, 2) + .requestMore(3) + .assertValuesOnly(0, 1, 2, 3, 4, 5) + .requestMore(4) + .assertResult(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + } + + @Test + public void refCounted() { + MulticastProcessor mp = MulticastProcessor.create(true); + BooleanSubscription bs = new BooleanSubscription(); + + mp.onSubscribe(bs); + + assertFalse(bs.isCancelled()); + + mp.test().cancel(); + + assertTrue(bs.isCancelled()); + + assertFalse(mp.hasSubscribers()); + assertTrue(mp.hasComplete()); + assertFalse(mp.hasThrowable()); + assertNull(mp.getThrowable()); + + mp.test().assertResult(); + } + + @Test + public void refCounted2() { + MulticastProcessor mp = MulticastProcessor.create(16, true); + BooleanSubscription bs = new BooleanSubscription(); + + mp.onSubscribe(bs); + + assertFalse(bs.isCancelled()); + + mp.test(1, true); + + assertTrue(bs.isCancelled()); + + assertFalse(mp.hasSubscribers()); + assertTrue(mp.hasComplete()); + assertFalse(mp.hasThrowable()); + assertNull(mp.getThrowable()); + + mp.test().assertResult(); + } + + @Test + public void longRunning() { + MulticastProcessor mp = MulticastProcessor.create(16); + Flowable.range(1, 1000).subscribe(mp); + + mp.test().assertValueCount(1000).assertNoErrors().assertComplete(); + } + + + @Test + public void oneByOne() { + MulticastProcessor mp = MulticastProcessor.create(16); + Flowable.range(1, 1000).subscribe(mp); + + mp + .rebatchRequests(1) + .test() + .assertValueCount(1000) + .assertNoErrors() + .assertComplete(); + } + + @Test + public void take() { + MulticastProcessor mp = MulticastProcessor.create(16); + Flowable.range(1, 1000).subscribe(mp); + + mp.take(10).test().assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + + @Test + public void takeRefCount() { + MulticastProcessor mp = MulticastProcessor.create(16, true); + Flowable.range(1, 1000).subscribe(mp); + + mp.take(10).test().assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + + @Test + public void takeRefCountExact() { + MulticastProcessor mp = MulticastProcessor.create(16, true); + Flowable.range(1, 10).subscribe(mp); + + mp + .rebatchRequests(10) + .take(10) + .test().assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + + @Test + public void crossCancel() { + + final TestSubscriber ts1 = new TestSubscriber(); + + TestSubscriber ts2 = new TestSubscriber() { + @Override + public void onNext(Integer t) { + super.onNext(t); + ts1.cancel(); + ts1.onComplete(); + } + }; + + MulticastProcessor mp = MulticastProcessor.create(false); + + mp.subscribe(ts2); + mp.subscribe(ts1); + + mp.start(); + + mp.onNext(1); + mp.onComplete(); + + ts1.assertResult(); + ts2.assertResult(1); + } + + @Test + public void crossCancelError() { + + final TestSubscriber ts1 = new TestSubscriber(); + + TestSubscriber ts2 = new TestSubscriber() { + @Override + public void onError(Throwable t) { + super.onError(t); + ts1.cancel(); + ts1.onComplete(); + } + }; + + MulticastProcessor mp = MulticastProcessor.create(false); + + mp.subscribe(ts2); + mp.subscribe(ts1); + + mp.start(); + + mp.onNext(1); + mp.onError(new IOException()); + + ts1.assertResult(1); + ts2.assertFailure(IOException.class, 1); + } + + @Test + public void crossCancelComplete() { + + final TestSubscriber ts1 = new TestSubscriber(); + + TestSubscriber ts2 = new TestSubscriber() { + @Override + public void onComplete() { + super.onComplete(); + ts1.cancel(); + ts1.onNext(2); + ts1.onComplete(); + } + }; + + MulticastProcessor mp = MulticastProcessor.create(false); + + mp.subscribe(ts2); + mp.subscribe(ts1); + + mp.start(); + + mp.onNext(1); + mp.onComplete(); + + ts1.assertResult(1, 2); + ts2.assertResult(1); + } + + @Test + public void crossCancel1() { + + final TestSubscriber ts1 = new TestSubscriber(1); + + TestSubscriber ts2 = new TestSubscriber(1) { + @Override + public void onNext(Integer t) { + super.onNext(t); + ts1.cancel(); + ts1.onComplete(); + } + }; + + MulticastProcessor mp = MulticastProcessor.create(false); + + mp.subscribe(ts2); + mp.subscribe(ts1); + + mp.start(); + + mp.onNext(1); + mp.onComplete(); + + ts1.assertResult(); + ts2.assertResult(1); + } + + @Test + public void requestCancel() { + List errors = TestHelper.trackPluginErrors(); + try { + MulticastProcessor mp = MulticastProcessor.create(false); + + mp.subscribe(new FlowableSubscriber() { + + @Override + public void onNext(Integer t) { + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onComplete() { + } + + @Override + public void onSubscribe(Subscription t) { + t.request(-1); + t.request(1); + t.request(Long.MAX_VALUE); + t.request(Long.MAX_VALUE); + t.cancel(); + t.cancel(); + t.request(2); + } + }); + + TestHelper.assertError(errors, 0, IllegalArgumentException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void unbounded() { + MulticastProcessor mp = MulticastProcessor.create(4, false); + mp.startUnbounded(); + + for (int i = 0; i < 10; i++) { + assertTrue(mp.offer(i)); + } + mp.onComplete(); + + mp.test().assertResult(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + } + + @Test + public void multiStart() { + List errors = TestHelper.trackPluginErrors(); + try { + MulticastProcessor mp = MulticastProcessor.create(4, false); + + mp.start(); + mp.start(); + mp.startUnbounded(); + BooleanSubscription bs = new BooleanSubscription(); + mp.onSubscribe(bs); + + assertTrue(bs.isCancelled()); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertError(errors, 1, ProtocolViolationException.class); + TestHelper.assertError(errors, 2, ProtocolViolationException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test(expected = NullPointerException.class) + public void onNextNull() { + MulticastProcessor mp = MulticastProcessor.create(4, false); + mp.start(); + mp.onNext(null); + } + + + @Test(expected = NullPointerException.class) + public void onOfferNull() { + MulticastProcessor mp = MulticastProcessor.create(4, false); + mp.start(); + mp.offer(null); + } + + @Test(expected = NullPointerException.class) + public void onErrorNull() { + MulticastProcessor mp = MulticastProcessor.create(4, false); + mp.start(); + mp.onError(null); + } + + @Test + public void afterTerminated() { + List errors = TestHelper.trackPluginErrors(); + try { + MulticastProcessor mp = MulticastProcessor.create(); + mp.start(); + mp.onComplete(); + mp.onComplete(); + mp.onError(new IOException()); + mp.onNext(1); + mp.offer(1); + + mp.test().assertResult(); + + TestHelper.assertUndeliverable(errors, 0, IOException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void asyncFused() { + UnicastProcessor up = UnicastProcessor.create(); + MulticastProcessor mp = MulticastProcessor.create(4); + + up.subscribe(mp); + + TestSubscriber ts = mp.test(); + + for (int i = 0; i < 10; i++) { + up.onNext(i); + } + + assertFalse(mp.offer(10)); + + up.onComplete(); + + ts.assertResult(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + } + + @Test + public void fusionCrash() { + MulticastProcessor mp = Flowable.range(1, 5) + .map(new Function() { + @Override + public Integer apply(Integer v) throws Exception { + throw new IOException(); + } + }) + .subscribeWith(MulticastProcessor.create()); + + mp.test().assertFailure(IOException.class); + } + + @Test + public void lockstep() { + MulticastProcessor mp = MulticastProcessor.create(); + + TestSubscriber ts1 = mp.test(); + mp.start(); + + mp.onNext(1); + mp.onNext(2); + + ts1.assertValues(1, 2); + + TestSubscriber ts2 = mp.test(0); + + ts2.assertEmpty(); + + mp.onNext(3); + + ts1.assertValues(1, 2); + ts2.assertEmpty(); + + mp.onComplete(); + + ts1.assertValues(1, 2); + ts2.assertEmpty(); + + ts2.request(1); + + ts1.assertResult(1, 2, 3); + ts2.assertResult(3); + } + + @Test + public void rejectedFusion() { + + MulticastProcessor mp = MulticastProcessor.create(); + + TestHelper.rejectFlowableFusion() + .subscribe(mp); + + mp.test().assertEmpty(); + } + + @Test + public void addRemoveRaceNoRefCount() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final MulticastProcessor mp = MulticastProcessor.create(); + + final TestSubscriber ts = mp.test(); + final TestSubscriber ts2 = new TestSubscriber(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + mp.subscribe(ts2); + } + }; + + TestHelper.race(r1, r2); + + assertTrue(mp.hasSubscribers()); + } + } + + @Test + public void addRemoveRaceNoRefCountNonEmpty() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final MulticastProcessor mp = MulticastProcessor.create(); + + mp.test(); + final TestSubscriber ts = mp.test(); + final TestSubscriber ts2 = new TestSubscriber(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + mp.subscribe(ts2); + } + }; + + TestHelper.race(r1, r2); + + assertTrue(mp.hasSubscribers()); + } + } + + @Test + public void addRemoveRaceWitRefCount() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final MulticastProcessor mp = MulticastProcessor.create(true); + + final TestSubscriber ts = mp.test(); + final TestSubscriber ts2 = new TestSubscriber(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + mp.subscribe(ts2); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void cancelUpfront() { + MulticastProcessor mp = MulticastProcessor.create(); + + mp.test(0, true).assertEmpty(); + + assertFalse(mp.hasSubscribers()); + } + + + @Test + public void cancelUpfrontOtherConsumersPresent() { + MulticastProcessor mp = MulticastProcessor.create(); + + mp.test(); + + mp.test(0, true).assertEmpty(); + + assertTrue(mp.hasSubscribers()); + } + + @Test + public void consumerRequestRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final MulticastProcessor mp = MulticastProcessor.create(true); + mp.startUnbounded(); + mp.onNext(1); + mp.onNext(2); + + final TestSubscriber ts = mp.test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts.request(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.request(1); + } + }; + + TestHelper.race(r1, r2); + + ts.assertValuesOnly(1, 2); + } + } + + @Test + public void consumerUpstreamRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final MulticastProcessor mp = MulticastProcessor.create(true); + + final Flowable source = Flowable.range(1, 5); + + final TestSubscriber ts = mp.test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts.request(5); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + source.subscribe(mp); + } + }; + + TestHelper.race(r1, r2); + + ts + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1, 2, 3, 4, 5); + } + } + + @Test + public void emitCancelRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final MulticastProcessor mp = MulticastProcessor.create(true); + mp.startUnbounded(); + + final TestSubscriber ts = mp.test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + mp.onNext(1); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void cancelCancelDrain() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final MulticastProcessor mp = MulticastProcessor.create(true); + + final TestSubscriber ts1 = mp.test(); + final TestSubscriber ts2 = mp.test(); + + mp.test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts1.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts2.cancel(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void requestCancelRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final MulticastProcessor mp = MulticastProcessor.create(true); + + final TestSubscriber ts1 = mp.test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts1.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts1.request(1); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void noUpstream() { + MulticastProcessor mp = MulticastProcessor.create(); + + TestSubscriber ts = mp.test(0); + + ts.request(1); + + assertTrue(mp.hasSubscribers()); + } + +} From 5f1ce20a1159a8464bfae2d8b2106039ac520eb2 Mon Sep 17 00:00:00 2001 From: Niklas Baudy Date: Fri, 18 May 2018 10:58:50 +0200 Subject: [PATCH 183/417] 2.x: Add assertValueSetOnly and assertValueSequenceOnly to TestObserver + TestSubscriber (#6010) * 2.x: Add assertValueSetOnly and assertValueSequenceOnly to TestObserver + TestSubscriber. * Experimental * Lowercase --- .../reactivex/observers/BaseTestConsumer.java | 30 ++++ .../reactivex/observers/TestObserverTest.java | 132 ++++++++++++++- .../subscribers/TestSubscriberTest.java | 160 ++++++++++++++++-- 3 files changed, 300 insertions(+), 22 deletions(-) diff --git a/src/main/java/io/reactivex/observers/BaseTestConsumer.java b/src/main/java/io/reactivex/observers/BaseTestConsumer.java index a1598c5732..84a6fe889d 100644 --- a/src/main/java/io/reactivex/observers/BaseTestConsumer.java +++ b/src/main/java/io/reactivex/observers/BaseTestConsumer.java @@ -587,6 +587,21 @@ public final U assertValueSet(Collection expected) { return (U)this; } + /** + * Assert that the TestObserver/TestSubscriber received only the specified values in any order without terminating. + * @param expected the collection of values expected in any order + * @return this; + * @since 2.1.14 - experimental + */ + @SuppressWarnings("unchecked") + @Experimental + public final U assertValueSetOnly(Collection expected) { + return assertSubscribed() + .assertValueSet(expected) + .assertNoErrors() + .assertNotComplete(); + } + /** * Assert that the TestObserver/TestSubscriber received only the specified sequence of values in the same order. * @param sequence the sequence of expected values in order @@ -625,6 +640,21 @@ public final U assertValueSequence(Iterable sequence) { return (U)this; } + /** + * Assert that the TestObserver/TestSubscriber received only the specified values in the specified order without terminating. + * @param sequence the sequence of expected values in order + * @return this; + * @since 2.1.14 - experimental + */ + @SuppressWarnings("unchecked") + @Experimental + public final U assertValueSequenceOnly(Iterable sequence) { + return assertSubscribed() + .assertValueSequence(sequence) + .assertNoErrors() + .assertNotComplete(); + } + /** * Assert that the TestObserver/TestSubscriber terminated (i.e., the terminal latch reached zero). * @return this; diff --git a/src/test/java/io/reactivex/observers/TestObserverTest.java b/src/test/java/io/reactivex/observers/TestObserverTest.java index cca65c0b72..c183451348 100644 --- a/src/test/java/io/reactivex/observers/TestObserverTest.java +++ b/src/test/java/io/reactivex/observers/TestObserverTest.java @@ -1434,7 +1434,7 @@ public void withTag() { .assertResult(1) ; } - fail("Should have thrown!"); + throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { assertTrue(ex.toString(), ex.toString().contains("testing with item=2")); } @@ -1466,7 +1466,7 @@ public void assertValuesOnlyThrowsOnUnexpectedValue() { try { to.assertValuesOnly(5); - fail(); + throw new RuntimeException(); } catch (AssertionError ex) { // expected } @@ -1481,7 +1481,7 @@ public void assertValuesOnlyThrowsWhenCompleted() { try { to.assertValuesOnly(); - fail(); + throw new RuntimeException(); } catch (AssertionError ex) { // expected } @@ -1496,7 +1496,131 @@ public void assertValuesOnlyThrowsWhenErrored() { try { to.assertValuesOnly(); - fail(); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSetOnly() { + TestObserver to = TestObserver.create(); + to.onSubscribe(Disposables.empty()); + to.assertValueSetOnly(Collections.emptySet()); + + to.onNext(5); + to.assertValueSetOnly(Collections.singleton(5)); + + to.onNext(-1); + to.assertValueSetOnly(new HashSet(Arrays.asList(5, -1))); + } + + @Test + public void assertValueSetOnlyThrowsOnUnexpectedValue() { + TestObserver to = TestObserver.create(); + to.onSubscribe(Disposables.empty()); + to.assertValueSetOnly(Collections.emptySet()); + + to.onNext(5); + to.assertValueSetOnly(Collections.singleton(5)); + + to.onNext(-1); + + try { + to.assertValueSetOnly(Collections.singleton(5)); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSetOnlyThrowsWhenCompleted() { + TestObserver to = TestObserver.create(); + to.onSubscribe(Disposables.empty()); + + to.onComplete(); + + try { + to.assertValueSetOnly(Collections.emptySet()); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSetOnlyThrowsWhenErrored() { + TestObserver to = TestObserver.create(); + to.onSubscribe(Disposables.empty()); + + to.onError(new TestException()); + + try { + to.assertValueSetOnly(Collections.emptySet()); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSequenceOnly() { + TestObserver to = TestObserver.create(); + to.onSubscribe(Disposables.empty()); + to.assertValueSequenceOnly(Collections.emptyList()); + + to.onNext(5); + to.assertValueSequenceOnly(Collections.singletonList(5)); + + to.onNext(-1); + to.assertValueSequenceOnly(Arrays.asList(5, -1)); + } + + @Test + public void assertValueSequenceOnlyThrowsOnUnexpectedValue() { + TestObserver to = TestObserver.create(); + to.onSubscribe(Disposables.empty()); + to.assertValueSequenceOnly(Collections.emptyList()); + + to.onNext(5); + to.assertValueSequenceOnly(Collections.singletonList(5)); + + to.onNext(-1); + + try { + to.assertValueSequenceOnly(Collections.singletonList(5)); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSequenceOnlyThrowsWhenCompleted() { + TestObserver to = TestObserver.create(); + to.onSubscribe(Disposables.empty()); + + to.onComplete(); + + try { + to.assertValueSequenceOnly(Collections.emptyList()); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSequenceOnlyThrowsWhenErrored() { + TestObserver to = TestObserver.create(); + to.onSubscribe(Disposables.empty()); + + to.onError(new TestException()); + + try { + to.assertValueSequenceOnly(Collections.emptyList()); + throw new RuntimeException(); } catch (AssertionError ex) { // expected } diff --git a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java index 5e4082c399..98657d5883 100644 --- a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java @@ -624,7 +624,7 @@ public void testNoTerminalEventBut1Completed() { try { ts.assertNotTerminated(); - fail("Failed to report there were terminal event(s)!"); + throw new RuntimeException("Failed to report there were terminal event(s)!"); } catch (AssertionError ex) { // expected } @@ -638,7 +638,7 @@ public void testNoTerminalEventBut1Error() { try { ts.assertNotTerminated(); - fail("Failed to report there were terminal event(s)!"); + throw new RuntimeException("Failed to report there were terminal event(s)!"); } catch (AssertionError ex) { // expected } @@ -653,7 +653,7 @@ public void testNoTerminalEventBut1Error1Completed() { try { ts.assertNotTerminated(); - fail("Failed to report there were terminal event(s)!"); + throw new RuntimeException("Failed to report there were terminal event(s)!"); } catch (AssertionError ex) { // expected } @@ -669,7 +669,7 @@ public void testNoTerminalEventBut2Errors() { try { ts.assertNotTerminated(); - fail("Failed to report there were terminal event(s)!"); + throw new RuntimeException("Failed to report there were terminal event(s)!"); } catch (AssertionError ex) { // expected Throwable e = ex.getCause(); @@ -688,7 +688,7 @@ public void testNoValues() { try { ts.assertNoValues(); - fail("Failed to report there were values!"); + throw new RuntimeException("Failed to report there were values!"); } catch (AssertionError ex) { // expected } @@ -702,7 +702,7 @@ public void testValueCount() { try { ts.assertValueCount(3); - fail("Failed to report there were values!"); + throw new RuntimeException("Failed to report there were values!"); } catch (AssertionError ex) { // expected } @@ -1790,7 +1790,7 @@ public void withTag() { .assertResult(1) ; } - fail("Should have thrown!"); + throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { assertTrue(ex.toString(), ex.toString().contains("testing with item=2")); } @@ -1806,7 +1806,7 @@ public void timeoutIndicated() throws InterruptedException { try { ts.assertResult(1); - fail("Should have thrown!"); + throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { assertTrue(ex.toString(), ex.toString().contains("timeout!")); } @@ -1820,7 +1820,7 @@ public void timeoutIndicated2() throws InterruptedException { .awaitDone(1, TimeUnit.MILLISECONDS) .assertResult(1); - fail("Should have thrown!"); + throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { assertTrue(ex.toString(), ex.toString().contains("timeout!")); } @@ -1835,7 +1835,7 @@ public void timeoutIndicated3() throws InterruptedException { try { ts.assertResult(1); - fail("Should have thrown!"); + throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { assertTrue(ex.toString(), ex.toString().contains("timeout!")); } @@ -1848,7 +1848,7 @@ public void disposeIndicated() { try { ts.assertResult(1); - fail("Should have thrown!"); + throw new RuntimeException("Should have thrown!"); } catch (Throwable ex) { assertTrue(ex.toString(), ex.toString().contains("disposed!")); } @@ -1930,7 +1930,7 @@ public void assertTimeout2() { .test() .awaitCount(1, TestWaitStrategy.SLEEP_1MS, 50) .assertTimeout(); - fail("Should have thrown!"); + throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { assertTrue(ex.toString(), ex.getMessage().contains("No timeout?!")); } @@ -1951,7 +1951,7 @@ public void assertNoTimeout2() { .test() .awaitCount(1, TestWaitStrategy.SLEEP_1MS, 50) .assertNoTimeout(); - fail("Should have thrown!"); + throw new RuntimeException("Should have thrown!"); } catch (AssertionError ex) { assertTrue(ex.toString(), ex.getMessage().contains("Timeout?!")); } @@ -1968,7 +1968,7 @@ public boolean test(Integer t) throws Exception { throw new IllegalArgumentException(); } }); - fail("Should have thrown!"); + throw new RuntimeException("Should have thrown!"); } catch (IllegalArgumentException ex) { // expected } @@ -1985,7 +1985,7 @@ public boolean test(Integer t) throws Exception { throw new IllegalArgumentException(); } }); - fail("Should have thrown!"); + throw new RuntimeException("Should have thrown!"); } catch (IllegalArgumentException ex) { // expected } @@ -2024,7 +2024,7 @@ public void assertValuesOnlyThrowsOnUnexpectedValue() { try { ts.assertValuesOnly(5); - fail(); + throw new RuntimeException(); } catch (AssertionError ex) { // expected } @@ -2039,7 +2039,7 @@ public void assertValuesOnlyThrowsWhenCompleted() { try { ts.assertValuesOnly(); - fail(); + throw new RuntimeException(); } catch (AssertionError ex) { // expected } @@ -2054,7 +2054,131 @@ public void assertValuesOnlyThrowsWhenErrored() { try { ts.assertValuesOnly(); - fail(); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSetOnly() { + TestSubscriber ts = TestSubscriber.create(); + ts.onSubscribe(new BooleanSubscription()); + ts.assertValueSetOnly(Collections.emptySet()); + + ts.onNext(5); + ts.assertValueSetOnly(Collections.singleton(5)); + + ts.onNext(-1); + ts.assertValueSetOnly(new HashSet(Arrays.asList(5, -1))); + } + + @Test + public void assertValueSetOnlyThrowsOnUnexpectedValue() { + TestSubscriber ts = TestSubscriber.create(); + ts.onSubscribe(new BooleanSubscription()); + ts.assertValueSetOnly(Collections.emptySet()); + + ts.onNext(5); + ts.assertValueSetOnly(Collections.singleton(5)); + + ts.onNext(-1); + + try { + ts.assertValueSetOnly(Collections.singleton(5)); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSetOnlyThrowsWhenCompleted() { + TestSubscriber ts = TestSubscriber.create(); + ts.onSubscribe(new BooleanSubscription()); + + ts.onComplete(); + + try { + ts.assertValueSetOnly(Collections.emptySet()); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSetOnlyThrowsWhenErrored() { + TestSubscriber ts = TestSubscriber.create(); + ts.onSubscribe(new BooleanSubscription()); + + ts.onError(new TestException()); + + try { + ts.assertValueSetOnly(Collections.emptySet()); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSequenceOnly() { + TestSubscriber ts = TestSubscriber.create(); + ts.onSubscribe(new BooleanSubscription()); + ts.assertValueSequenceOnly(Collections.emptyList()); + + ts.onNext(5); + ts.assertValueSequenceOnly(Collections.singletonList(5)); + + ts.onNext(-1); + ts.assertValueSequenceOnly(Arrays.asList(5, -1)); + } + + @Test + public void assertValueSequenceOnlyThrowsOnUnexpectedValue() { + TestSubscriber ts = TestSubscriber.create(); + ts.onSubscribe(new BooleanSubscription()); + ts.assertValueSequenceOnly(Collections.emptyList()); + + ts.onNext(5); + ts.assertValueSequenceOnly(Collections.singletonList(5)); + + ts.onNext(-1); + + try { + ts.assertValueSequenceOnly(Collections.singletonList(5)); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSequenceOnlyThrowsWhenCompleted() { + TestSubscriber ts = TestSubscriber.create(); + ts.onSubscribe(new BooleanSubscription()); + + ts.onComplete(); + + try { + ts.assertValueSequenceOnly(Collections.emptyList()); + throw new RuntimeException(); + } catch (AssertionError ex) { + // expected + } + } + + @Test + public void assertValueSequenceOnlyThrowsWhenErrored() { + TestSubscriber ts = TestSubscriber.create(); + ts.onSubscribe(new BooleanSubscription()); + + ts.onError(new TestException()); + + try { + ts.assertValueSequenceOnly(Collections.emptyList()); + throw new RuntimeException(); } catch (AssertionError ex) { // expected } From 4af78a769a00ae70705deab12e6c88ccd9292b6e Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 23 May 2018 09:23:10 +0200 Subject: [PATCH 184/417] 2.x: Fix & prevent null checks on primitives (#6014) --- src/main/java/io/reactivex/Observable.java | 4 ---- .../reactivex/internal/functions/ObjectHelper.java | 13 +++++++++++++ .../internal/functions/ObjectHelperTest.java | 6 ++++++ .../operators/flowable/FlowableCreateTest.java | 1 + 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index e6438a46e5..c30ca995f1 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -1455,8 +1455,6 @@ public static Observable concatEager(ObservableSource Observable concatEager(ObservableSource> sources, int maxConcurrency, int prefetch) { - ObjectHelper.requireNonNull(maxConcurrency, "maxConcurrency is null"); - ObjectHelper.requireNonNull(prefetch, "prefetch is null"); return wrap(sources).concatMapEager((Function)Functions.identity(), maxConcurrency, prefetch); } @@ -1507,8 +1505,6 @@ public static Observable concatEager(Iterable Observable concatEager(Iterable> sources, int maxConcurrency, int prefetch) { - ObjectHelper.requireNonNull(maxConcurrency, "maxConcurrency is null"); - ObjectHelper.requireNonNull(prefetch, "prefetch is null"); return fromIterable(sources).concatMapEagerDelayError((Function)Functions.identity(), maxConcurrency, prefetch, false); } diff --git a/src/main/java/io/reactivex/internal/functions/ObjectHelper.java b/src/main/java/io/reactivex/internal/functions/ObjectHelper.java index f574f7f477..e77dd2ac0d 100644 --- a/src/main/java/io/reactivex/internal/functions/ObjectHelper.java +++ b/src/main/java/io/reactivex/internal/functions/ObjectHelper.java @@ -128,4 +128,17 @@ public boolean test(Object o1, Object o2) { return ObjectHelper.equals(o1, o2); } } + + /** + * Trap null-check attempts on primitives. + * @param value the value to check + * @param message the message to print + * @return the value + * @deprecated this method should not be used as there is no need + * to check primitives for nullness. + */ + @Deprecated + public static long requireNonNull(long value, String message) { + throw new InternalError("Null check on a primitive: " + message); + } } diff --git a/src/test/java/io/reactivex/internal/functions/ObjectHelperTest.java b/src/test/java/io/reactivex/internal/functions/ObjectHelperTest.java index ce5a2b340d..898900d34f 100644 --- a/src/test/java/io/reactivex/internal/functions/ObjectHelperTest.java +++ b/src/test/java/io/reactivex/internal/functions/ObjectHelperTest.java @@ -65,4 +65,10 @@ public void compareLong() { assertEquals(0, ObjectHelper.compare(0L, 0L)); assertEquals(1, ObjectHelper.compare(2L, 0L)); } + + @SuppressWarnings("deprecation") + @Test(expected = InternalError.class) + public void requireNonNullPrimitive() { + ObjectHelper.requireNonNull(0, "value"); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java index edc31e5b37..bbdff04d1c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java @@ -934,6 +934,7 @@ public void subscribe(FlowableEmitter e) throws Exception { } } + @SuppressWarnings("rawtypes") @Test public void emittersHasToString() { Map> emitterMap = From 9ff403e1a4cc6cbd209d5468583c4177d7e64d5e Mon Sep 17 00:00:00 2001 From: akarnokd Date: Wed, 23 May 2018 09:25:01 +0200 Subject: [PATCH 185/417] Release 2.1.14 --- CHANGES.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 57b1ce1056..0cfef94c45 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,42 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.14 - May 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.14%7C)) + +#### API changes + +- [Pull 5976](https://github.com/ReactiveX/RxJava/pull/5976): Add `Single.concatEager()`. +- [Pull 5986](https://github.com/ReactiveX/RxJava/pull/5986): Add `ConnectableObservable.refCount()` and `ConnectableFlowable.refCount()` with minimum consumer count & disconnect grace period. +- [Pull 5979](https://github.com/ReactiveX/RxJava/pull/5979): Add `Observable.throttleLatest` and `Flowable.throttleLatest()`. +- [Pull 6002](https://github.com/ReactiveX/RxJava/pull/6002): Add `MulticastProcessor`. +- [Pull 6010](https://github.com/ReactiveX/RxJava/pull/6010): Add `assertValueSetOnly` and `assertValueSequenceOnly` to `TestObserver`/`TestSubscriber`. + +#### Deprecations + +- [Pull 5982](https://github.com/ReactiveX/RxJava/pull/5982): Deprecate `getValues()` in `Subject`s/`FlowableProcessor`s to be removed in 3.x. + +#### Documentation changes + +- [Pull 5977](https://github.com/ReactiveX/RxJava/pull/5977): `Maybe`/`Single` JavaDocs; annotation cleanup. +- [Pull 5981](https://github.com/ReactiveX/RxJava/pull/5981): Improve JavaDocs of the `subscribeActual` methods. +- [Pull 5984](https://github.com/ReactiveX/RxJava/pull/5984): Add `blockingSubscribe` JavaDoc clarifications. +- [Pull 5987](https://github.com/ReactiveX/RxJava/pull/5987): Add marble diagrams to some `Single.doOnX` methods. +- [Pull 5992](https://github.com/ReactiveX/RxJava/pull/5992): `Observable` javadoc cleanup. + +#### Bugfixes + +- [Pull 5975](https://github.com/ReactiveX/RxJava/pull/5975): Fix `refCount()` connect/subscribe/cancel deadlock. +- [Pull 5978](https://github.com/ReactiveX/RxJava/pull/5978): `Flowable.take` to route post-cancel errors to plugin error handler. +- [Pull 5991](https://github.com/ReactiveX/RxJava/pull/5991): Fix `switchMap` to indicate boundary fusion. + +#### Other changes + +- [Pull 5985](https://github.com/ReactiveX/RxJava/pull/5985): Cleanup in the `Scheduler` class. +- [Pull 5996](https://github.com/ReactiveX/RxJava/pull/5996): Automatically publish the generated JavaDocs from CI. +- [Pull 5995](https://github.com/ReactiveX/RxJava/pull/5995): Implement `toString` method for some `Emitter`s. +- [Pull 6005](https://github.com/ReactiveX/RxJava/pull/6005): JavaDocs HTML formatting and whitespace cleanup. +- [Pull 6014](https://github.com/ReactiveX/RxJava/pull/6014): Fix & prevent `null` checks on primitives. + ### Version 2.1.13 - April 27, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.13%7C)) #### API changes From b9f5ef81237b16cb3d30d404740fb3ebf0511ed3 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 23 May 2018 20:35:39 +0200 Subject: [PATCH 186/417] 2.x: benchmark (0..1).flatMap and flattenAs performance (#6017) --- .../java/io/reactivex/BinaryFlatMapPerf.java | 275 ++++++++++++++++++ 1 file changed, 275 insertions(+) create mode 100644 src/jmh/java/io/reactivex/BinaryFlatMapPerf.java diff --git a/src/jmh/java/io/reactivex/BinaryFlatMapPerf.java b/src/jmh/java/io/reactivex/BinaryFlatMapPerf.java new file mode 100644 index 0000000000..45b4ee19ae --- /dev/null +++ b/src/jmh/java/io/reactivex/BinaryFlatMapPerf.java @@ -0,0 +1,275 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.reactivestreams.Publisher; + +import io.reactivex.Observable; +import io.reactivex.functions.Function; + +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(value = 1) +@State(Scope.Thread) +public class BinaryFlatMapPerf { + @Param({ "1", "1000", "1000000" }) + public int times; + + Flowable singleFlatMapPublisher; + + Flowable singleFlatMapHidePublisher; + + Flowable singleFlattenAsPublisher; + + Flowable maybeFlatMapPublisher; + + Flowable maybeFlatMapHidePublisher; + + Flowable maybeFlattenAsPublisher; + + Flowable completableFlatMapPublisher; + + Flowable completableFlattenAsPublisher; + + Observable singleFlatMapObservable; + + Observable singleFlatMapHideObservable; + + Observable singleFlattenAsObservable; + + Observable maybeFlatMapObservable; + + Observable maybeFlatMapHideObservable; + + Observable maybeFlattenAsObservable; + + Observable completableFlatMapObservable; + + Observable completableFlattenAsObservable; + + @Setup + public void setup() { + + // -------------------------------------------------------------------------- + + final Integer[] array = new Integer[times]; + Arrays.fill(array, 777); + + final List list = Arrays.asList(array); + + final Flowable arrayFlowable = Flowable.fromArray(array); + final Flowable arrayFlowableHide = Flowable.fromArray(array).hide(); + final Flowable listFlowable = Flowable.fromIterable(list); + + final Observable arrayObservable = Observable.fromArray(array); + final Observable arrayObservableHide = Observable.fromArray(array).hide(); + final Observable listObservable = Observable.fromIterable(list); + + // -------------------------------------------------------------------------- + + singleFlatMapPublisher = Single.just(1).flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return arrayFlowable; + } + }); + + singleFlatMapHidePublisher = Single.just(1).flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return arrayFlowableHide; + } + }); + + singleFlattenAsPublisher = Single.just(1).flattenAsFlowable(new Function>() { + @Override + public Iterable apply(Integer v) + throws Exception { + return list; + } + }); + + maybeFlatMapPublisher = Maybe.just(1).flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return arrayFlowable; + } + }); + + maybeFlatMapHidePublisher = Maybe.just(1).flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return arrayFlowableHide; + } + }); + + maybeFlattenAsPublisher = Maybe.just(1).flattenAsFlowable(new Function>() { + @Override + public Iterable apply(Integer v) + throws Exception { + return list; + } + }); + + completableFlatMapPublisher = Completable.complete().andThen(listFlowable); + + completableFlattenAsPublisher = Completable.complete().andThen(arrayFlowable); + + // -------------------------------------------------------------------------- + + singleFlatMapObservable = Single.just(1).flatMapObservable(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return arrayObservable; + } + }); + + singleFlatMapHideObservable = Single.just(1).flatMapObservable(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return arrayObservableHide; + } + }); + + singleFlattenAsObservable = Single.just(1).flattenAsObservable(new Function>() { + @Override + public Iterable apply(Integer v) + throws Exception { + return list; + } + }); + + maybeFlatMapObservable = Maybe.just(1).flatMapObservable(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return arrayObservable; + } + }); + + maybeFlatMapHideObservable = Maybe.just(1).flatMapObservable(new Function>() { + @Override + public Observable apply(Integer v) + throws Exception { + return arrayObservableHide; + } + }); + + maybeFlattenAsObservable = Maybe.just(1).flattenAsObservable(new Function>() { + @Override + public Iterable apply(Integer v) + throws Exception { + return list; + } + }); + + completableFlatMapObservable = Completable.complete().andThen(listObservable); + + completableFlattenAsObservable = Completable.complete().andThen(arrayObservable); + + } + + @Benchmark + public void singleFlatMapPublisher(Blackhole bh) { + singleFlatMapPublisher.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void singleFlatMapHidePublisher(Blackhole bh) { + singleFlatMapHidePublisher.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void singleFlattenAsPublisher(Blackhole bh) { + singleFlattenAsPublisher.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void maybeFlatMapPublisher(Blackhole bh) { + maybeFlatMapPublisher.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void maybeFlatMapHidePublisher(Blackhole bh) { + maybeFlatMapHidePublisher.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void maybeFlattenAsPublisher(Blackhole bh) { + maybeFlattenAsPublisher.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void completableFlatMapPublisher(Blackhole bh) { + completableFlatMapPublisher.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void completableFlattenAsPublisher(Blackhole bh) { + completableFlattenAsPublisher.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void singleFlatMapObservable(Blackhole bh) { + singleFlatMapObservable.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void singleFlatMapHideObservable(Blackhole bh) { + singleFlatMapHideObservable.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void singleFlattenAsObservable(Blackhole bh) { + singleFlattenAsObservable.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void maybeFlatMapObservable(Blackhole bh) { + maybeFlatMapObservable.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void maybeFlatMapHideObservable(Blackhole bh) { + maybeFlatMapHideObservable.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void maybeFlattenAsObservable(Blackhole bh) { + maybeFlattenAsObservable.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void completableFlatMapObservable(Blackhole bh) { + completableFlatMapObservable.subscribe(new PerfConsumer(bh)); + } + + @Benchmark + public void completableFlattenAsObservable(Blackhole bh) { + completableFlattenAsObservable.subscribe(new PerfConsumer(bh)); + } +} From 07e126f030a34d25b23c476fdb24384deb028c63 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Fri, 25 May 2018 12:35:34 +0200 Subject: [PATCH 187/417] 2.x: Fix Single.takeUntil, Maybe.takeUntil dispose behavior (#6019) --- .../maybe/MaybeTakeUntilPublisher.java | 1 + .../operators/single/SingleTakeUntil.java | 1 + .../completable/CompletableAmbTest.java | 74 +++++ .../flowable/FlowableTakeUntilTest.java | 130 ++++++++ .../operators/maybe/MaybeTakeUntilTest.java | 253 +++++++++++++++ .../observable/ObservableTakeUntilTest.java | 131 ++++++++ .../operators/single/SingleTakeUntilTest.java | 291 +++++++++++++++++- 7 files changed, 880 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java index 6db80da42f..793436526d 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java @@ -137,6 +137,7 @@ public void onSubscribe(Subscription s) { @Override public void onNext(Object value) { + SubscriptionHelper.cancel(this); parent.otherComplete(); } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java b/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java index 4eaa6f7620..2a4bb1b4b7 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java @@ -69,6 +69,7 @@ static final class TakeUntilMainObserver @Override public void dispose() { DisposableHelper.dispose(this); + other.dispose(); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java index 992acdc6e6..f6f3dc0337 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java @@ -186,4 +186,78 @@ public void ambRace() { RxJavaPlugins.reset(); } } + + + @Test + public void untilCompletableMainComplete() { + CompletableSubject main = CompletableSubject.create(); + CompletableSubject other = CompletableSubject.create(); + + TestObserver to = main.ambWith(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(); + } + + @Test + public void untilCompletableMainError() { + CompletableSubject main = CompletableSubject.create(); + CompletableSubject other = CompletableSubject.create(); + + TestObserver to = main.ambWith(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilCompletableOtherOnComplete() { + CompletableSubject main = CompletableSubject.create(); + CompletableSubject other = CompletableSubject.create(); + + TestObserver to = main.ambWith(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(); + } + + @Test + public void untilCompletableOtherError() { + CompletableSubject main = CompletableSubject.create(); + CompletableSubject other = CompletableSubject.create(); + + TestObserver to = main.ambWith(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(TestException.class); + } + } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java index ce7bd20179..be7bc1621b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java @@ -20,6 +20,7 @@ import org.reactivestreams.*; import io.reactivex.*; +import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; import io.reactivex.processors.PublishProcessor; import io.reactivex.subscribers.TestSubscriber; @@ -293,4 +294,133 @@ public Flowable apply(Flowable c) throws Exception { } }); } + + @Test + public void untilPublisherMainSuccess() { + PublishProcessor main = PublishProcessor.create(); + PublishProcessor other = PublishProcessor.create(); + + TestSubscriber ts = main.takeUntil(other).test(); + + assertTrue("Main no subscribers?", main.hasSubscribers()); + assertTrue("Other no subscribers?", other.hasSubscribers()); + + main.onNext(1); + main.onNext(2); + main.onComplete(); + + assertFalse("Main has subscribers?", main.hasSubscribers()); + assertFalse("Other has subscribers?", other.hasSubscribers()); + + ts.assertResult(1, 2); + } + + @Test + public void untilPublisherMainComplete() { + PublishProcessor main = PublishProcessor.create(); + PublishProcessor other = PublishProcessor.create(); + + TestSubscriber ts = main.takeUntil(other).test(); + + assertTrue("Main no subscribers?", main.hasSubscribers()); + assertTrue("Other no subscribers?", other.hasSubscribers()); + + main.onComplete(); + + assertFalse("Main has subscribers?", main.hasSubscribers()); + assertFalse("Other has subscribers?", other.hasSubscribers()); + + ts.assertResult(); + } + + @Test + public void untilPublisherMainError() { + PublishProcessor main = PublishProcessor.create(); + PublishProcessor other = PublishProcessor.create(); + + TestSubscriber ts = main.takeUntil(other).test(); + + assertTrue("Main no subscribers?", main.hasSubscribers()); + assertTrue("Other no subscribers?", other.hasSubscribers()); + + main.onError(new TestException()); + + assertFalse("Main has subscribers?", main.hasSubscribers()); + assertFalse("Other has subscribers?", other.hasSubscribers()); + + ts.assertFailure(TestException.class); + } + + @Test + public void untilPublisherOtherOnNext() { + PublishProcessor main = PublishProcessor.create(); + PublishProcessor other = PublishProcessor.create(); + + TestSubscriber ts = main.takeUntil(other).test(); + + assertTrue("Main no subscribers?", main.hasSubscribers()); + assertTrue("Other no subscribers?", other.hasSubscribers()); + + other.onNext(1); + + assertFalse("Main has subscribers?", main.hasSubscribers()); + assertFalse("Other has subscribers?", other.hasSubscribers()); + + ts.assertResult(); + } + + @Test + public void untilPublisherOtherOnComplete() { + PublishProcessor main = PublishProcessor.create(); + PublishProcessor other = PublishProcessor.create(); + + TestSubscriber ts = main.takeUntil(other).test(); + + assertTrue("Main no subscribers?", main.hasSubscribers()); + assertTrue("Other no subscribers?", other.hasSubscribers()); + + other.onComplete(); + + assertFalse("Main has subscribers?", main.hasSubscribers()); + assertFalse("Other has subscribers?", other.hasSubscribers()); + + ts.assertResult(); + } + + @Test + public void untilPublisherOtherError() { + PublishProcessor main = PublishProcessor.create(); + PublishProcessor other = PublishProcessor.create(); + + TestSubscriber ts = main.takeUntil(other).test(); + + assertTrue("Main no subscribers?", main.hasSubscribers()); + assertTrue("Other no subscribers?", other.hasSubscribers()); + + other.onError(new TestException()); + + assertFalse("Main has subscribers?", main.hasSubscribers()); + assertFalse("Other has subscribers?", other.hasSubscribers()); + + ts.assertFailure(TestException.class); + } + + @Test + public void untilPublisherDispose() { + PublishProcessor main = PublishProcessor.create(); + PublishProcessor other = PublishProcessor.create(); + + TestSubscriber ts = main.takeUntil(other).test(); + + assertTrue("Main no subscribers?", main.hasSubscribers()); + assertTrue("Other no subscribers?", other.hasSubscribers()); + + ts.dispose(); + + assertFalse("Main has subscribers?", main.hasSubscribers()); + assertFalse("Other has subscribers?", other.hasSubscribers()); + + ts.assertEmpty(); + } + } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilTest.java index 601c123d9e..8cd569869c 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilTest.java @@ -25,6 +25,7 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.MaybeSubject; public class MaybeTakeUntilTest { @@ -211,4 +212,256 @@ public void run() { to.assertResult(); } } + + @Test + public void untilMaybeMainSuccess() { + MaybeSubject main = MaybeSubject.create(); + MaybeSubject other = MaybeSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onSuccess(1); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(1); + } + + @Test + public void untilMaybeMainComplete() { + MaybeSubject main = MaybeSubject.create(); + MaybeSubject other = MaybeSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(); + } + + @Test + public void untilMaybeMainError() { + MaybeSubject main = MaybeSubject.create(); + MaybeSubject other = MaybeSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilMaybeOtherSuccess() { + MaybeSubject main = MaybeSubject.create(); + MaybeSubject other = MaybeSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onSuccess(1); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(); + } + + @Test + public void untilMaybeOtherComplete() { + MaybeSubject main = MaybeSubject.create(); + MaybeSubject other = MaybeSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(); + } + + @Test + public void untilMaybeOtherError() { + MaybeSubject main = MaybeSubject.create(); + MaybeSubject other = MaybeSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilMaybeDispose() { + MaybeSubject main = MaybeSubject.create(); + MaybeSubject other = MaybeSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + to.dispose(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertEmpty(); + } + + @Test + public void untilPublisherMainSuccess() { + MaybeSubject main = MaybeSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + main.onSuccess(1); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertResult(1); + } + + @Test + public void untilPublisherMainComplete() { + MaybeSubject main = MaybeSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + main.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertResult(); + } + + @Test + public void untilPublisherMainError() { + MaybeSubject main = MaybeSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + main.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilPublisherOtherOnNext() { + MaybeSubject main = MaybeSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + other.onNext(1); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertResult(); + } + + @Test + public void untilPublisherOtherOnComplete() { + MaybeSubject main = MaybeSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + other.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertResult(); + } + + @Test + public void untilPublisherOtherError() { + MaybeSubject main = MaybeSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + other.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilPublisherDispose() { + MaybeSubject main = MaybeSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + to.dispose(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertEmpty(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java index 7a2f139da9..d42e5df389 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java @@ -20,6 +20,7 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import io.reactivex.subjects.PublishSubject; @@ -271,4 +272,134 @@ public Observable apply(Observable o) throws Exception { } }); } + + + @Test + public void untilPublisherMainSuccess() { + PublishSubject main = PublishSubject.create(); + PublishSubject other = PublishSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onNext(1); + main.onNext(2); + main.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(1, 2); + } + + @Test + public void untilPublisherMainComplete() { + PublishSubject main = PublishSubject.create(); + PublishSubject other = PublishSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(); + } + + @Test + public void untilPublisherMainError() { + PublishSubject main = PublishSubject.create(); + PublishSubject other = PublishSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilPublisherOtherOnNext() { + PublishSubject main = PublishSubject.create(); + PublishSubject other = PublishSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onNext(1); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(); + } + + @Test + public void untilPublisherOtherOnComplete() { + PublishSubject main = PublishSubject.create(); + PublishSubject other = PublishSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(); + } + + @Test + public void untilPublisherOtherError() { + PublishSubject main = PublishSubject.create(); + PublishSubject other = PublishSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilPublisherDispose() { + PublishSubject main = PublishSubject.create(); + PublishSubject other = PublishSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + to.dispose(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertEmpty(); + } + } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java index 42633a9fcc..d646542a93 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java @@ -13,7 +13,7 @@ package io.reactivex.internal.operators.single; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.util.List; import java.util.concurrent.CancellationException; @@ -27,6 +27,7 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.*; public class SingleTakeUntilTest { @@ -291,4 +292,292 @@ protected void subscribeActual(Subscriber s) { .test() .assertFailure(CancellationException.class); } + + @Test + public void untilSingleMainSuccess() { + SingleSubject main = SingleSubject.create(); + SingleSubject other = SingleSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onSuccess(1); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(1); + } + + @Test + public void untilSingleMainError() { + SingleSubject main = SingleSubject.create(); + SingleSubject other = SingleSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilSingleOtherSuccess() { + SingleSubject main = SingleSubject.create(); + SingleSubject other = SingleSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onSuccess(1); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(CancellationException.class); + } + + @Test + public void untilSingleOtherError() { + SingleSubject main = SingleSubject.create(); + SingleSubject other = SingleSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilSingleDispose() { + SingleSubject main = SingleSubject.create(); + SingleSubject other = SingleSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + to.dispose(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertEmpty(); + } + + @Test + public void untilPublisherMainSuccess() { + SingleSubject main = SingleSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + main.onSuccess(1); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertResult(1); + } + + @Test + public void untilPublisherMainError() { + SingleSubject main = SingleSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + main.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilPublisherOtherOnNext() { + SingleSubject main = SingleSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + other.onNext(1); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertFailure(CancellationException.class); + } + + @Test + public void untilPublisherOtherOnComplete() { + SingleSubject main = SingleSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + other.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertFailure(CancellationException.class); + } + + @Test + public void untilPublisherOtherError() { + SingleSubject main = SingleSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + other.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilPublisherDispose() { + SingleSubject main = SingleSubject.create(); + PublishProcessor other = PublishProcessor.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasSubscribers()); + + to.dispose(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasSubscribers()); + + to.assertEmpty(); + } + + @Test + public void untilCompletableMainSuccess() { + SingleSubject main = SingleSubject.create(); + CompletableSubject other = CompletableSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onSuccess(1); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertResult(1); + } + + @Test + public void untilCompletableMainError() { + SingleSubject main = SingleSubject.create(); + CompletableSubject other = CompletableSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + main.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilCompletableOtherOnComplete() { + SingleSubject main = SingleSubject.create(); + CompletableSubject other = CompletableSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onComplete(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(CancellationException.class); + } + + @Test + public void untilCompletableOtherError() { + SingleSubject main = SingleSubject.create(); + CompletableSubject other = CompletableSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + other.onError(new TestException()); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void untilCompletableDispose() { + SingleSubject main = SingleSubject.create(); + CompletableSubject other = CompletableSubject.create(); + + TestObserver to = main.takeUntil(other).test(); + + assertTrue("Main no observers?", main.hasObservers()); + assertTrue("Other no observers?", other.hasObservers()); + + to.dispose(); + + assertFalse("Main has observers?", main.hasObservers()); + assertFalse("Other has observers?", other.hasObservers()); + + to.assertEmpty(); + } } From d24bfbd1e5e948de0e909304495aaea408b45117 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sat, 26 May 2018 18:41:22 +0200 Subject: [PATCH 188/417] 2.x: Add TCK for MulticastProcessor & {0..1}.flatMapPublisher (#6022) --- .../CompletableAndThenPublisherTckTest.java | 30 +++++++++ .../tck/MaybeFlatMapPublisherTckTest.java | 37 +++++++++++ .../MulticastProcessorAsPublisherTckTest.java | 63 ++++++++++++++++++ .../MulticastProcessorRefCountedTckTest.java | 65 +++++++++++++++++++ .../tck/MulticastProcessorTckTest.java | 65 +++++++++++++++++++ .../tck/SingleFlatMapFlowableTckTest.java | 37 +++++++++++ 6 files changed, 297 insertions(+) create mode 100644 src/test/java/io/reactivex/tck/CompletableAndThenPublisherTckTest.java create mode 100644 src/test/java/io/reactivex/tck/MaybeFlatMapPublisherTckTest.java create mode 100644 src/test/java/io/reactivex/tck/MulticastProcessorAsPublisherTckTest.java create mode 100644 src/test/java/io/reactivex/tck/MulticastProcessorRefCountedTckTest.java create mode 100644 src/test/java/io/reactivex/tck/MulticastProcessorTckTest.java create mode 100644 src/test/java/io/reactivex/tck/SingleFlatMapFlowableTckTest.java diff --git a/src/test/java/io/reactivex/tck/CompletableAndThenPublisherTckTest.java b/src/test/java/io/reactivex/tck/CompletableAndThenPublisherTckTest.java new file mode 100644 index 0000000000..5a4c5f450c --- /dev/null +++ b/src/test/java/io/reactivex/tck/CompletableAndThenPublisherTckTest.java @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; + +@Test +public class CompletableAndThenPublisherTckTest extends BaseTck { + + @Override + public Publisher createPublisher(final long elements) { + return + Completable.complete().hide().andThen(Flowable.range(0, (int)elements)) + ; + } +} diff --git a/src/test/java/io/reactivex/tck/MaybeFlatMapPublisherTckTest.java b/src/test/java/io/reactivex/tck/MaybeFlatMapPublisherTckTest.java new file mode 100644 index 0000000000..a05af6e197 --- /dev/null +++ b/src/test/java/io/reactivex/tck/MaybeFlatMapPublisherTckTest.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@Test +public class MaybeFlatMapPublisherTckTest extends BaseTck { + + @Override + public Publisher createPublisher(final long elements) { + return + Maybe.just(1).hide().flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.range(0, (int)elements); + } + }) + ; + } +} diff --git a/src/test/java/io/reactivex/tck/MulticastProcessorAsPublisherTckTest.java b/src/test/java/io/reactivex/tck/MulticastProcessorAsPublisherTckTest.java new file mode 100644 index 0000000000..01f4710c58 --- /dev/null +++ b/src/test/java/io/reactivex/tck/MulticastProcessorAsPublisherTckTest.java @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.processors.MulticastProcessor; +import io.reactivex.schedulers.Schedulers; + +@Test +public class MulticastProcessorAsPublisherTckTest extends BaseTck { + + public MulticastProcessorAsPublisherTckTest() { + super(100); + } + + @Override + public Publisher createPublisher(final long elements) { + final MulticastProcessor mp = MulticastProcessor.create(); + mp.start(); + + Schedulers.io().scheduleDirect(new Runnable() { + @Override + public void run() { + long start = System.currentTimeMillis(); + while (!mp.hasSubscribers()) { + try { + Thread.sleep(1); + } catch (InterruptedException ex) { + return; + } + + if (System.currentTimeMillis() - start > 200) { + return; + } + } + + for (int i = 0; i < elements; i++) { + while (!mp.offer(i)) { + Thread.yield(); + if (System.currentTimeMillis() - start > 1000) { + return; + } + } + } + mp.onComplete(); + } + }); + return mp; + } +} diff --git a/src/test/java/io/reactivex/tck/MulticastProcessorRefCountedTckTest.java b/src/test/java/io/reactivex/tck/MulticastProcessorRefCountedTckTest.java new file mode 100644 index 0000000000..24a3b8d09f --- /dev/null +++ b/src/test/java/io/reactivex/tck/MulticastProcessorRefCountedTckTest.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import java.util.concurrent.*; + +import org.reactivestreams.*; +import org.reactivestreams.tck.*; +import org.testng.annotations.Test; + +import io.reactivex.exceptions.TestException; +import io.reactivex.processors.*; + +@Test +public class MulticastProcessorRefCountedTckTest extends IdentityProcessorVerification { + + public MulticastProcessorRefCountedTckTest() { + super(new TestEnvironment(50)); + } + + @Override + public Processor createIdentityProcessor(int bufferSize) { + MulticastProcessor mp = MulticastProcessor.create(true); + return mp; + } + + @Override + public Publisher createFailedPublisher() { + MulticastProcessor mp = MulticastProcessor.create(); + mp.start(); + mp.onError(new TestException()); + return mp; + } + + @Override + public ExecutorService publisherExecutorService() { + return Executors.newCachedThreadPool(); + } + + @Override + public Integer createElement(int element) { + return element; + } + + @Override + public long maxSupportedSubscribers() { + return 1; + } + + @Override + public long maxElementsFromPublisher() { + return 1024; + } +} diff --git a/src/test/java/io/reactivex/tck/MulticastProcessorTckTest.java b/src/test/java/io/reactivex/tck/MulticastProcessorTckTest.java new file mode 100644 index 0000000000..53dd476e6f --- /dev/null +++ b/src/test/java/io/reactivex/tck/MulticastProcessorTckTest.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import java.util.concurrent.*; + +import org.reactivestreams.*; +import org.reactivestreams.tck.*; +import org.testng.annotations.Test; + +import io.reactivex.exceptions.TestException; +import io.reactivex.processors.*; + +@Test +public class MulticastProcessorTckTest extends IdentityProcessorVerification { + + public MulticastProcessorTckTest() { + super(new TestEnvironment(50)); + } + + @Override + public Processor createIdentityProcessor(int bufferSize) { + MulticastProcessor mp = MulticastProcessor.create(); + return new RefCountProcessor(mp); + } + + @Override + public Publisher createFailedPublisher() { + MulticastProcessor mp = MulticastProcessor.create(); + mp.start(); + mp.onError(new TestException()); + return mp; + } + + @Override + public ExecutorService publisherExecutorService() { + return Executors.newCachedThreadPool(); + } + + @Override + public Integer createElement(int element) { + return element; + } + + @Override + public long maxSupportedSubscribers() { + return 1; + } + + @Override + public long maxElementsFromPublisher() { + return 1024; + } +} diff --git a/src/test/java/io/reactivex/tck/SingleFlatMapFlowableTckTest.java b/src/test/java/io/reactivex/tck/SingleFlatMapFlowableTckTest.java new file mode 100644 index 0000000000..009bd5e50f --- /dev/null +++ b/src/test/java/io/reactivex/tck/SingleFlatMapFlowableTckTest.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.tck; + +import org.reactivestreams.Publisher; +import org.testng.annotations.Test; + +import io.reactivex.*; +import io.reactivex.functions.Function; + +@Test +public class SingleFlatMapFlowableTckTest extends BaseTck { + + @Override + public Publisher createPublisher(final long elements) { + return + Single.just(1).hide().flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) + throws Exception { + return Flowable.range(0, (int)elements); + } + }) + ; + } +} From 0ffb50f764329b206c027252354c94b8b467f180 Mon Sep 17 00:00:00 2001 From: Dave Moten Date: Sun, 27 May 2018 20:14:18 +1000 Subject: [PATCH 189/417] 2.x: add full implementation for Single.flatMapPublisher so doesn't batch requests (#6015) (#6021) --- src/main/java/io/reactivex/Single.java | 3 +- .../single/SingleFlatMapPublisher.java | 137 ++++++++++++++++++ .../operators/single/SingleFlatMapTest.java | 89 ++++++++++++ 3 files changed, 228 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/reactivex/internal/operators/single/SingleFlatMapPublisher.java diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 6ecdb5409c..8fa075b680 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2460,7 +2460,8 @@ public final Maybe flatMapMaybe(final Function Flowable flatMapPublisher(Function> mapper) { - return toFlowable().flatMap(mapper); + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new SingleFlatMapPublisher(this, mapper)); } /** diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapPublisher.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapPublisher.java new file mode 100644 index 0000000000..bdb7d166cd --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapPublisher.java @@ -0,0 +1,137 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.single; + +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; + +import io.reactivex.Flowable; +import io.reactivex.FlowableSubscriber; +import io.reactivex.Scheduler; +import io.reactivex.SingleObserver; +import io.reactivex.SingleSource; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.subscriptions.SubscriptionHelper; + +/** + * A Flowable that emits items based on applying a specified function to the item emitted by the + * source Single, where that function returns a Publisher. + *

                + * + *

                + *
                Backpressure:
                + *
                The returned {@code Flowable} honors the backpressure of the downstream consumer + * and the {@code Publisher} returned by the mapper function is expected to honor it as well.
                + *
                Scheduler:
                + *
                {@code flatMapPublisher} does not operate by default on a particular {@link Scheduler}.
                + *
                + * + * @param the source value type + * @param the result value type + * + * @see ReactiveX operators documentation: FlatMap + * @since 2.1.15 + */ +public final class SingleFlatMapPublisher extends Flowable { + + final SingleSource source; + final Function> mapper; + + public SingleFlatMapPublisher(SingleSource source, + Function> mapper) { + this.source = source; + this.mapper = mapper; + } + + @Override + protected void subscribeActual(Subscriber actual) { + source.subscribe(new SingleFlatMapPublisherObserver(actual, mapper)); + } + + static final class SingleFlatMapPublisherObserver extends AtomicLong + implements SingleObserver, FlowableSubscriber, Subscription { + + private static final long serialVersionUID = 7759721921468635667L; + + final Subscriber actual; + final Function> mapper; + final AtomicReference parent; + Disposable disposable; + + SingleFlatMapPublisherObserver(Subscriber actual, + Function> mapper) { + this.actual = actual; + this.mapper = mapper; + this.parent = new AtomicReference(); + } + + @Override + public void onSubscribe(Disposable d) { + this.disposable = d; + actual.onSubscribe(this); + } + + @Override + public void onSuccess(S value) { + Publisher f; + try { + f = ObjectHelper.requireNonNull(mapper.apply(value), "the mapper returned a null Publisher"); + } catch (Throwable e) { + Exceptions.throwIfFatal(e); + actual.onError(e); + return; + } + f.subscribe(this); + } + + @Override + public void onSubscribe(Subscription s) { + SubscriptionHelper.deferredSetOnce(parent, this, s); + } + + @Override + public void onNext(T t) { + actual.onNext(t); + } + + @Override + public void onComplete() { + actual.onComplete(); + } + + @Override + public void onError(Throwable e) { + actual.onError(e); + } + + @Override + public void request(long n) { + SubscriptionHelper.deferredRequest(parent, this, n); + } + + @Override + public void cancel() { + disposable.dispose(); + SubscriptionHelper.cancel(parent); + } + } + +} diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java index c2b1ecea91..9c0d81e28d 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java @@ -15,12 +15,15 @@ import static org.junit.Assert.*; +import java.util.concurrent.atomic.AtomicBoolean; + import org.junit.Test; import org.reactivestreams.Publisher; import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; +import io.reactivex.subscribers.TestSubscriber; public class SingleFlatMapTest { @@ -126,6 +129,92 @@ public Publisher apply(Integer v) throws Exception { .test() .assertResult(1, 2, 3, 4, 5); } + + @Test(expected = NullPointerException.class) + public void flatMapPublisherMapperNull() { + Single.just(1).flatMapPublisher(null); + } + + @Test + public void flatMapPublisherMapperThrows() { + final TestException ex = new TestException(); + Single.just(1) + .flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) throws Exception { + throw ex; + } + }) + .test() + .assertNoValues() + .assertError(ex); + } + + @Test + public void flatMapPublisherSingleError() { + final TestException ex = new TestException(); + Single.error(ex) + .flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) throws Exception { + return Flowable.just(1); + } + }) + .test() + .assertNoValues() + .assertError(ex); + } + + @Test + public void flatMapPublisherCancelDuringSingle() { + final AtomicBoolean disposed = new AtomicBoolean(); + TestSubscriber ts = Single.never() + .doOnDispose(new Action() { + @Override + public void run() throws Exception { + disposed.set(true); + } + }) + .flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) throws Exception { + return Flowable.range(v, 5); + } + }) + .test() + .assertNoValues() + .assertNotTerminated(); + assertFalse(disposed.get()); + ts.cancel(); + assertTrue(disposed.get()); + ts.assertNotTerminated(); + } + + @Test + public void flatMapPublisherCancelDuringFlowable() { + final AtomicBoolean disposed = new AtomicBoolean(); + TestSubscriber ts = + Single.just(1) + .flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) throws Exception { + return Flowable.never() + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + disposed.set(true); + } + }); + } + }) + .test() + .assertNoValues() + .assertNotTerminated(); + assertFalse(disposed.get()); + ts.cancel(); + assertTrue(disposed.get()); + ts.assertNotTerminated(); + } @Test(expected = NullPointerException.class) public void flatMapNull() { From 07586f4010ae935b5b1f7fd271fba0a587edbc1b Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 27 May 2018 14:09:51 +0200 Subject: [PATCH 190/417] 2.x: More time to BehaviorProcessor & Interval TCK tests (#6023) --- .../io/reactivex/tck/BehaviorProcessorAsPublisherTckTest.java | 4 ++++ src/test/java/io/reactivex/tck/IntervalTckTest.java | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/test/java/io/reactivex/tck/BehaviorProcessorAsPublisherTckTest.java b/src/test/java/io/reactivex/tck/BehaviorProcessorAsPublisherTckTest.java index cf1a47887e..4843f25ea7 100644 --- a/src/test/java/io/reactivex/tck/BehaviorProcessorAsPublisherTckTest.java +++ b/src/test/java/io/reactivex/tck/BehaviorProcessorAsPublisherTckTest.java @@ -22,6 +22,10 @@ @Test public class BehaviorProcessorAsPublisherTckTest extends BaseTck { + public BehaviorProcessorAsPublisherTckTest() { + super(50); + } + @Override public Publisher createPublisher(final long elements) { final BehaviorProcessor pp = BehaviorProcessor.create(); diff --git a/src/test/java/io/reactivex/tck/IntervalTckTest.java b/src/test/java/io/reactivex/tck/IntervalTckTest.java index cee8bf0415..6412a18a75 100644 --- a/src/test/java/io/reactivex/tck/IntervalTckTest.java +++ b/src/test/java/io/reactivex/tck/IntervalTckTest.java @@ -23,6 +23,10 @@ @Test public class IntervalTckTest extends BaseTck { + public IntervalTckTest() { + super(50); + } + @Override public Publisher createPublisher(long elements) { return From 43ceedf41839c7e2253c91f15204da8718b0c133 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 27 May 2018 23:06:39 +0200 Subject: [PATCH 191/417] 2.x: Dedicated {Single|Maybe}.flatMap{Publisher|Observable} & andThen(Observable|Publisher) implementations (#6024) * 2.x: Dedicated {0..1}.flatMap{Publisher|Obs} & andThen implementations * Fix local variable name. --- src/main/java/io/reactivex/Completable.java | 7 +- src/main/java/io/reactivex/Maybe.java | 7 +- src/main/java/io/reactivex/Single.java | 4 +- .../mixed/CompletableAndThenObservable.java | 101 ++++++++++++++ .../mixed/CompletableAndThenPublisher.java | 114 ++++++++++++++++ .../mixed/MaybeFlatMapObservable.java | 113 ++++++++++++++++ .../mixed/MaybeFlatMapPublisher.java | 127 ++++++++++++++++++ .../mixed/SingleFlatMapObservable.java | 113 ++++++++++++++++ .../completable/CompletableTest.java | 4 +- .../CompletableAndThenObservableTest.java | 115 ++++++++++++++++ .../CompletableAndThenPublisherTest.java | 77 +++++++++++ .../mixed/MaybeFlatMapObservableTest.java | 84 ++++++++++++ .../mixed/MaybeFlatMapPublisherTest.java | 91 +++++++++++++ .../mixed/SingleFlatMapObservableTest.java | 127 ++++++++++++++++++ .../operators/single/SingleFlatMapTest.java | 20 +-- 15 files changed, 1086 insertions(+), 18 deletions(-) create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenPublisher.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservable.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapPublisher.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservable.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservableTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenPublisherTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservableTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/MaybeFlatMapPublisherTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservableTest.java diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 8fca56c910..c07ba8ae6a 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -24,9 +24,8 @@ import io.reactivex.internal.fuseable.*; import io.reactivex.internal.observers.*; import io.reactivex.internal.operators.completable.*; -import io.reactivex.internal.operators.flowable.FlowableDelaySubscriptionOther; import io.reactivex.internal.operators.maybe.*; -import io.reactivex.internal.operators.observable.ObservableDelaySubscriptionOther; +import io.reactivex.internal.operators.mixed.*; import io.reactivex.internal.operators.single.SingleDelayWithCompletable; import io.reactivex.internal.util.ExceptionHelper; import io.reactivex.observers.TestObserver; @@ -872,7 +871,7 @@ public final Completable ambWith(CompletableSource other) { @SchedulerSupport(SchedulerSupport.NONE) public final Observable andThen(ObservableSource next) { ObjectHelper.requireNonNull(next, "next is null"); - return RxJavaPlugins.onAssembly(new ObservableDelaySubscriptionOther(next, toObservable())); + return RxJavaPlugins.onAssembly(new CompletableAndThenObservable(this, next)); } /** @@ -897,7 +896,7 @@ public final Observable andThen(ObservableSource next) { @SchedulerSupport(SchedulerSupport.NONE) public final Flowable andThen(Publisher next) { ObjectHelper.requireNonNull(next, "next is null"); - return RxJavaPlugins.onAssembly(new FlowableDelaySubscriptionOther(next, toFlowable())); + return RxJavaPlugins.onAssembly(new CompletableAndThenPublisher(this, next)); } /** diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index d965108efe..164ef91b3b 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -27,6 +27,7 @@ import io.reactivex.internal.observers.BlockingMultiObserver; import io.reactivex.internal.operators.flowable.*; import io.reactivex.internal.operators.maybe.*; +import io.reactivex.internal.operators.mixed.*; import io.reactivex.internal.util.*; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; @@ -2961,7 +2962,8 @@ public final Observable flattenAsObservable(final Function Observable flatMapObservable(Function> mapper) { - return toObservable().flatMap(mapper); + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new MaybeFlatMapObservable(this, mapper)); } /** @@ -2987,7 +2989,8 @@ public final Observable flatMapObservable(Function Flowable flatMapPublisher(Function> mapper) { - return toFlowable().flatMap(mapper); + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new MaybeFlatMapPublisher(this, mapper)); } /** diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 8fa075b680..89fe25c6f9 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -28,6 +28,7 @@ import io.reactivex.internal.operators.completable.*; import io.reactivex.internal.operators.flowable.*; import io.reactivex.internal.operators.maybe.*; +import io.reactivex.internal.operators.mixed.*; import io.reactivex.internal.operators.observable.*; import io.reactivex.internal.operators.single.*; import io.reactivex.internal.util.*; @@ -2535,7 +2536,8 @@ public final Observable flattenAsObservable(final Function Observable flatMapObservable(Function> mapper) { - return toObservable().flatMap(mapper); + ObjectHelper.requireNonNull(mapper, "mapper is null"); + return RxJavaPlugins.onAssembly(new SingleFlatMapObservable(this, mapper)); } /** diff --git a/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java b/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java new file mode 100644 index 0000000000..418f1ebbb8 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.AtomicReference; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; + +/** + * After Completable completes, it relays the signals + * of the ObservableSource to the downstream observer. + * + * @param the result type of the ObservableSource and this operator + * @since 2.1.15 + */ +public final class CompletableAndThenObservable extends Observable { + + final CompletableSource source; + + final ObservableSource other; + + public CompletableAndThenObservable(CompletableSource source, + ObservableSource other) { + this.source = source; + this.other = other; + } + + @Override + protected void subscribeActual(Observer s) { + AndThenObservableObserver parent = new AndThenObservableObserver(s, other); + s.onSubscribe(parent); + source.subscribe(parent); + } + + static final class AndThenObservableObserver + extends AtomicReference + implements Observer, CompletableObserver, Disposable { + + private static final long serialVersionUID = -8948264376121066672L; + + final Observer downstream; + + ObservableSource other; + + AndThenObservableObserver(Observer downstream, ObservableSource other) { + this.other = other; + this.downstream = downstream; + } + + @Override + public void onNext(R t) { + downstream.onNext(t); + } + + @Override + public void onError(Throwable t) { + downstream.onError(t); + } + + @Override + public void onComplete() { + ObservableSource o = other; + if (o == null) { + downstream.onComplete(); + } else { + other = null; + o.subscribe(this); + } + } + + + @Override + public void dispose() { + DisposableHelper.dispose(this); + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(get()); + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(this, d); + } + + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenPublisher.java b/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenPublisher.java new file mode 100644 index 0000000000..70c397402e --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenPublisher.java @@ -0,0 +1,114 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.subscriptions.SubscriptionHelper; + +/** + * After Completable completes, it relays the signals + * of the Publisher to the downstream subscriber. + * + * @param the result type of the Publisher and this operator + * @since 2.1.15 + */ +public final class CompletableAndThenPublisher extends Flowable { + + final CompletableSource source; + + final Publisher other; + + public CompletableAndThenPublisher(CompletableSource source, + Publisher other) { + this.source = source; + this.other = other; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new AndThenPublisherSubscriber(s, other)); + } + + static final class AndThenPublisherSubscriber + extends AtomicReference + implements FlowableSubscriber, CompletableObserver, Subscription { + + private static final long serialVersionUID = -8948264376121066672L; + + final Subscriber downstream; + + Publisher other; + + Disposable upstream; + + final AtomicLong requested; + + AndThenPublisherSubscriber(Subscriber downstream, Publisher other) { + this.downstream = downstream; + this.other = other; + this.requested = new AtomicLong(); + } + + @Override + public void onNext(R t) { + downstream.onNext(t); + } + + @Override + public void onError(Throwable t) { + downstream.onError(t); + } + + @Override + public void onComplete() { + Publisher p = other; + if (p == null) { + downstream.onComplete(); + } else { + other = null; + p.subscribe(this); + } + } + + @Override + public void request(long n) { + SubscriptionHelper.deferredRequest(this, requested, n); + } + + @Override + public void cancel() { + upstream.dispose(); + SubscriptionHelper.cancel(this); + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); + } + } + + @Override + public void onSubscribe(Subscription s) { + SubscriptionHelper.deferredSetOnce(this, requested, s); + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservable.java b/src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservable.java new file mode 100644 index 0000000000..a15c77cba8 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservable.java @@ -0,0 +1,113 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; + +/** + * Maps the success value of a Maybe onto an ObservableSource and + * relays its signals to the downstream observer. + * + * @param the success value type of the Maybe source + * @param the result type of the ObservableSource and this operator + * @since 2.1.15 + */ +public final class MaybeFlatMapObservable extends Observable { + + final MaybeSource source; + + final Function> mapper; + + public MaybeFlatMapObservable(MaybeSource source, + Function> mapper) { + this.source = source; + this.mapper = mapper; + } + + @Override + protected void subscribeActual(Observer s) { + FlatMapObserver parent = new FlatMapObserver(s, mapper); + s.onSubscribe(parent); + source.subscribe(parent); + } + + static final class FlatMapObserver + extends AtomicReference + implements Observer, MaybeObserver, Disposable { + + private static final long serialVersionUID = -8948264376121066672L; + + final Observer downstream; + + final Function> mapper; + + FlatMapObserver(Observer downstream, Function> mapper) { + this.downstream = downstream; + this.mapper = mapper; + } + + @Override + public void onNext(R t) { + downstream.onNext(t); + } + + @Override + public void onError(Throwable t) { + downstream.onError(t); + } + + @Override + public void onComplete() { + downstream.onComplete(); + } + + @Override + public void dispose() { + DisposableHelper.dispose(this); + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(get()); + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(this, d); + } + + @Override + public void onSuccess(T t) { + ObservableSource o; + + try { + o = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + downstream.onError(ex); + return; + } + + o.subscribe(this); + } + + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapPublisher.java b/src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapPublisher.java new file mode 100644 index 0000000000..2bd7b18f2e --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapPublisher.java @@ -0,0 +1,127 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; +import io.reactivex.internal.subscriptions.SubscriptionHelper; + +/** + * Maps the success value of a Maybe onto a Publisher and + * relays its signals to the downstream subscriber. + * + * @param the success value type of the Maybe source + * @param the result type of the Publisher and this operator + * @since 2.1.15 + */ +public final class MaybeFlatMapPublisher extends Flowable { + + final MaybeSource source; + + final Function> mapper; + + public MaybeFlatMapPublisher(MaybeSource source, + Function> mapper) { + this.source = source; + this.mapper = mapper; + } + + @Override + protected void subscribeActual(Subscriber s) { + source.subscribe(new FlatMapPublisherSubscriber(s, mapper)); + } + + static final class FlatMapPublisherSubscriber + extends AtomicReference + implements FlowableSubscriber, MaybeObserver, Subscription { + + private static final long serialVersionUID = -8948264376121066672L; + + final Subscriber downstream; + + final Function> mapper; + + Disposable upstream; + + final AtomicLong requested; + + FlatMapPublisherSubscriber(Subscriber downstream, Function> mapper) { + this.downstream = downstream; + this.mapper = mapper; + this.requested = new AtomicLong(); + } + + @Override + public void onNext(R t) { + downstream.onNext(t); + } + + @Override + public void onError(Throwable t) { + downstream.onError(t); + } + + @Override + public void onComplete() { + downstream.onComplete(); + } + + @Override + public void request(long n) { + SubscriptionHelper.deferredRequest(this, requested, n); + } + + @Override + public void cancel() { + upstream.dispose(); + SubscriptionHelper.cancel(this); + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); + } + } + + @Override + public void onSuccess(T t) { + Publisher p; + + try { + p = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + downstream.onError(ex); + return; + } + + p.subscribe(this); + } + + @Override + public void onSubscribe(Subscription s) { + SubscriptionHelper.deferredSetOnce(this, requested, s); + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservable.java b/src/main/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservable.java new file mode 100644 index 0000000000..590a726f89 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservable.java @@ -0,0 +1,113 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; + +/** + * Maps the success value of a Single onto an ObservableSource and + * relays its signals to the downstream observer. + * + * @param the success value type of the Single source + * @param the result type of the ObservableSource and this operator + * @since 2.1.15 + */ +public final class SingleFlatMapObservable extends Observable { + + final SingleSource source; + + final Function> mapper; + + public SingleFlatMapObservable(SingleSource source, + Function> mapper) { + this.source = source; + this.mapper = mapper; + } + + @Override + protected void subscribeActual(Observer s) { + FlatMapObserver parent = new FlatMapObserver(s, mapper); + s.onSubscribe(parent); + source.subscribe(parent); + } + + static final class FlatMapObserver + extends AtomicReference + implements Observer, SingleObserver, Disposable { + + private static final long serialVersionUID = -8948264376121066672L; + + final Observer downstream; + + final Function> mapper; + + FlatMapObserver(Observer downstream, Function> mapper) { + this.downstream = downstream; + this.mapper = mapper; + } + + @Override + public void onNext(R t) { + downstream.onNext(t); + } + + @Override + public void onError(Throwable t) { + downstream.onError(t); + } + + @Override + public void onComplete() { + downstream.onComplete(); + } + + @Override + public void dispose() { + DisposableHelper.dispose(this); + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(get()); + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(this, d); + } + + @Override + public void onSuccess(T t) { + ObservableSource o; + + try { + o = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + downstream.onError(ex); + return; + } + + o.subscribe(this); + } + + } +} diff --git a/src/test/java/io/reactivex/completable/CompletableTest.java b/src/test/java/io/reactivex/completable/CompletableTest.java index 010ba0c619..a595837f29 100644 --- a/src/test/java/io/reactivex/completable/CompletableTest.java +++ b/src/test/java/io/reactivex/completable/CompletableTest.java @@ -14,6 +14,7 @@ package io.reactivex.completable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; @@ -26,7 +27,7 @@ import io.reactivex.*; import io.reactivex.Observable; import io.reactivex.Observer; -import io.reactivex.disposables.Disposable; +import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.disposables.*; @@ -4428,6 +4429,7 @@ public void andThenError() { Completable.unsafeCreate(new CompletableSource() { @Override public void subscribe(CompletableObserver cs) { + cs.onSubscribe(Disposables.empty()); cs.onError(e); } }) diff --git a/src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservableTest.java new file mode 100644 index 0000000000..e75c8538ca --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservableTest.java @@ -0,0 +1,115 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.observers.TestObserver; +import io.reactivex.subjects.*; + +public class CompletableAndThenObservableTest { + + @Test + public void cancelMain() { + CompletableSubject cs = CompletableSubject.create(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = cs.andThen(ps) + .test(); + + assertTrue(cs.hasObservers()); + assertFalse(ps.hasObservers()); + + to.cancel(); + + assertFalse(cs.hasObservers()); + assertFalse(ps.hasObservers()); + } + + @Test + public void cancelOther() { + CompletableSubject cs = CompletableSubject.create(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = cs.andThen(ps) + .test(); + + assertTrue(cs.hasObservers()); + assertFalse(ps.hasObservers()); + + cs.onComplete(); + + assertFalse(cs.hasObservers()); + assertTrue(ps.hasObservers()); + + to.cancel(); + + assertFalse(cs.hasObservers()); + assertFalse(ps.hasObservers()); + } + + + @Test + public void errorMain() { + CompletableSubject cs = CompletableSubject.create(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = cs.andThen(ps) + .test(); + + assertTrue(cs.hasObservers()); + assertFalse(ps.hasObservers()); + + cs.onError(new TestException()); + + assertFalse(cs.hasObservers()); + assertFalse(ps.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void errorOther() { + CompletableSubject cs = CompletableSubject.create(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = cs.andThen(ps) + .test(); + + assertTrue(cs.hasObservers()); + assertFalse(ps.hasObservers()); + + cs.onComplete(); + + assertFalse(cs.hasObservers()); + assertTrue(ps.hasObservers()); + + ps.onError(new TestException()); + + assertFalse(cs.hasObservers()); + assertFalse(ps.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void isDisposed() { + TestHelper.checkDisposed(Completable.never().andThen(Observable.never())); + } + +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenPublisherTest.java b/src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenPublisherTest.java new file mode 100644 index 0000000000..5f27eeeecf --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenPublisherTest.java @@ -0,0 +1,77 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.functions.Function; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.CompletableSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class CompletableAndThenPublisherTest { + + @Test + public void cancelMain() { + CompletableSubject cs = CompletableSubject.create(); + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = cs.andThen(pp) + .test(); + + assertTrue(cs.hasObservers()); + assertFalse(pp.hasSubscribers()); + + ts.cancel(); + + assertFalse(cs.hasObservers()); + assertFalse(pp.hasSubscribers()); + } + + @Test + public void cancelOther() { + CompletableSubject cs = CompletableSubject.create(); + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = cs.andThen(pp) + .test(); + + assertTrue(cs.hasObservers()); + assertFalse(pp.hasSubscribers()); + + cs.onComplete(); + + assertFalse(cs.hasObservers()); + assertTrue(pp.hasSubscribers()); + + ts.cancel(); + + assertFalse(cs.hasObservers()); + assertFalse(pp.hasSubscribers()); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeCompletableToFlowable(new Function>() { + @Override + public Publisher apply(Completable m) throws Exception { + return m.andThen(Flowable.never()); + } + }); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservableTest.java new file mode 100644 index 0000000000..50ca4ffa01 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservableTest.java @@ -0,0 +1,84 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.internal.functions.Functions; +import io.reactivex.observers.TestObserver; +import io.reactivex.subjects.*; + +public class MaybeFlatMapObservableTest { + + @Test + public void cancelMain() { + MaybeSubject ms = MaybeSubject.create(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ms.flatMapObservable(Functions.justFunction(ps)) + .test(); + + assertTrue(ms.hasObservers()); + assertFalse(ps.hasObservers()); + + to.cancel(); + + assertFalse(ms.hasObservers()); + assertFalse(ps.hasObservers()); + } + + @Test + public void cancelOther() { + MaybeSubject ms = MaybeSubject.create(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ms.flatMapObservable(Functions.justFunction(ps)) + .test(); + + assertTrue(ms.hasObservers()); + assertFalse(ps.hasObservers()); + + ms.onSuccess(1); + + assertFalse(ms.hasObservers()); + assertTrue(ps.hasObservers()); + + to.cancel(); + + assertFalse(ms.hasObservers()); + assertFalse(ps.hasObservers()); + } + + @Test + public void mapperCrash() { + Maybe.just(1).flatMapObservable(new Function>() { + @Override + public ObservableSource apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void isDisposed() { + TestHelper.checkDisposed(Maybe.never().flatMapObservable(Functions.justFunction(Observable.never()))); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/MaybeFlatMapPublisherTest.java b/src/test/java/io/reactivex/internal/operators/mixed/MaybeFlatMapPublisherTest.java new file mode 100644 index 0000000000..d784a9e1fc --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/MaybeFlatMapPublisherTest.java @@ -0,0 +1,91 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.reactivestreams.Publisher; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.internal.functions.Functions; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.subjects.MaybeSubject; +import io.reactivex.subscribers.TestSubscriber; + +public class MaybeFlatMapPublisherTest { + + @Test + public void cancelMain() { + MaybeSubject ms = MaybeSubject.create(); + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = ms.flatMapPublisher(Functions.justFunction(pp)) + .test(); + + assertTrue(ms.hasObservers()); + assertFalse(pp.hasSubscribers()); + + ts.cancel(); + + assertFalse(ms.hasObservers()); + assertFalse(pp.hasSubscribers()); + } + + @Test + public void cancelOther() { + MaybeSubject ms = MaybeSubject.create(); + PublishProcessor pp = PublishProcessor.create(); + + TestSubscriber ts = ms.flatMapPublisher(Functions.justFunction(pp)) + .test(); + + assertTrue(ms.hasObservers()); + assertFalse(pp.hasSubscribers()); + + ms.onSuccess(1); + + assertFalse(ms.hasObservers()); + assertTrue(pp.hasSubscribers()); + + ts.cancel(); + + assertFalse(ms.hasObservers()); + assertFalse(pp.hasSubscribers()); + } + + @Test + public void mapperCrash() { + Maybe.just(1).flatMapPublisher(new Function>() { + @Override + public Publisher apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeMaybeToFlowable(new Function, Publisher>() { + @Override + public Publisher apply(Maybe m) throws Exception { + return m.flatMapPublisher(Functions.justFunction(Flowable.never())); + } + }); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservableTest.java new file mode 100644 index 0000000000..a6b0d80344 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservableTest.java @@ -0,0 +1,127 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.internal.functions.Functions; +import io.reactivex.observers.TestObserver; +import io.reactivex.subjects.*; + +public class SingleFlatMapObservableTest { + + @Test + public void cancelMain() { + SingleSubject ss = SingleSubject.create(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ss.flatMapObservable(Functions.justFunction(ps)) + .test(); + + assertTrue(ss.hasObservers()); + assertFalse(ps.hasObservers()); + + to.cancel(); + + assertFalse(ss.hasObservers()); + assertFalse(ps.hasObservers()); + } + + @Test + public void cancelOther() { + SingleSubject ss = SingleSubject.create(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ss.flatMapObservable(Functions.justFunction(ps)) + .test(); + + assertTrue(ss.hasObservers()); + assertFalse(ps.hasObservers()); + + ss.onSuccess(1); + + assertFalse(ss.hasObservers()); + assertTrue(ps.hasObservers()); + + to.cancel(); + + assertFalse(ss.hasObservers()); + assertFalse(ps.hasObservers()); + } + + @Test + public void errorMain() { + SingleSubject ss = SingleSubject.create(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ss.flatMapObservable(Functions.justFunction(ps)) + .test(); + + assertTrue(ss.hasObservers()); + assertFalse(ps.hasObservers()); + + ss.onError(new TestException()); + + assertFalse(ss.hasObservers()); + assertFalse(ps.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void errorOther() { + SingleSubject ss = SingleSubject.create(); + PublishSubject ps = PublishSubject.create(); + + TestObserver to = ss.flatMapObservable(Functions.justFunction(ps)) + .test(); + + assertTrue(ss.hasObservers()); + assertFalse(ps.hasObservers()); + + ss.onSuccess(1); + + assertFalse(ss.hasObservers()); + assertTrue(ps.hasObservers()); + + ps.onError(new TestException()); + + assertFalse(ss.hasObservers()); + assertFalse(ps.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void mapperCrash() { + Single.just(1).flatMapObservable(new Function>() { + @Override + public ObservableSource apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void isDisposed() { + TestHelper.checkDisposed(Single.never().flatMapObservable(Functions.justFunction(Observable.never()))); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java index 9c0d81e28d..ee1de82fb7 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java @@ -129,16 +129,16 @@ public Publisher apply(Integer v) throws Exception { .test() .assertResult(1, 2, 3, 4, 5); } - + @Test(expected = NullPointerException.class) public void flatMapPublisherMapperNull() { Single.just(1).flatMapPublisher(null); } - + @Test public void flatMapPublisherMapperThrows() { final TestException ex = new TestException(); - Single.just(1) + Single.just(1) .flatMapPublisher(new Function>() { @Override public Publisher apply(Integer v) throws Exception { @@ -149,11 +149,11 @@ public Publisher apply(Integer v) throws Exception { .assertNoValues() .assertError(ex); } - + @Test public void flatMapPublisherSingleError() { final TestException ex = new TestException(); - Single.error(ex) + Single.error(ex) .flatMapPublisher(new Function>() { @Override public Publisher apply(Integer v) throws Exception { @@ -164,7 +164,7 @@ public Publisher apply(Integer v) throws Exception { .assertNoValues() .assertError(ex); } - + @Test public void flatMapPublisherCancelDuringSingle() { final AtomicBoolean disposed = new AtomicBoolean(); @@ -182,18 +182,18 @@ public Publisher apply(Integer v) throws Exception { } }) .test() - .assertNoValues() + .assertNoValues() .assertNotTerminated(); assertFalse(disposed.get()); ts.cancel(); assertTrue(disposed.get()); ts.assertNotTerminated(); } - + @Test public void flatMapPublisherCancelDuringFlowable() { final AtomicBoolean disposed = new AtomicBoolean(); - TestSubscriber ts = + TestSubscriber ts = Single.just(1) .flatMapPublisher(new Function>() { @Override @@ -208,7 +208,7 @@ public void run() throws Exception { } }) .test() - .assertNoValues() + .assertNoValues() .assertNotTerminated(); assertFalse(disposed.get()); ts.cancel(); From 6fefdc6e6ca253f4fea2a576a0e6e93ee340491e Mon Sep 17 00:00:00 2001 From: Dave Moten Date: Tue, 29 May 2018 22:14:32 +1000 Subject: [PATCH 192/417] 2.x fix group-by eviction so that source is cancelled and reduce volatile reads (#5933) (#5947) --- .../operators/flowable/FlowableGroupBy.java | 35 +++-- .../flowable/FlowableGroupByTest.java | 122 ++++++++++++++++++ 2 files changed, 146 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java index dd0f362e00..568cd5141c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java @@ -104,7 +104,8 @@ public static final class GroupBySubscriber final AtomicInteger groupCount = new AtomicInteger(1); Throwable error; - volatile boolean done; + volatile boolean finished; + boolean done; boolean outputFused; @@ -178,12 +179,7 @@ public void onNext(T t) { group.onNext(v); - if (evictedGroups != null) { - GroupedUnicast evictedGroup; - while ((evictedGroup = evictedGroups.poll()) != null) { - evictedGroup.onComplete(); - } - } + completeEvictions(); if (newGroup) { q.offer(group); @@ -197,6 +193,7 @@ public void onError(Throwable t) { RxJavaPlugins.onError(t); return; } + done = true; for (GroupedUnicast g : groups.values()) { g.onError(t); } @@ -205,7 +202,7 @@ public void onError(Throwable t) { evictedGroups.clear(); } error = t; - done = true; + finished = true; drain(); } @@ -220,6 +217,7 @@ public void onComplete() { evictedGroups.clear(); } done = true; + finished = true; drain(); } } @@ -237,12 +235,27 @@ public void cancel() { // cancelling the main source means we don't want any more groups // but running groups still require new values if (cancelled.compareAndSet(false, true)) { + completeEvictions(); if (groupCount.decrementAndGet() == 0) { s.cancel(); } } } + private void completeEvictions() { + if (evictedGroups != null) { + int count = 0; + GroupedUnicast evictedGroup; + while ((evictedGroup = evictedGroups.poll()) != null) { + evictedGroup.onComplete(); + count++; + } + if (count != 0) { + groupCount.addAndGet(-count); + } + } + } + public void cancel(K key) { Object mapKey = key != null ? key : NULL_KEY; groups.remove(mapKey); @@ -279,7 +292,7 @@ void drainFused() { return; } - boolean d = done; + boolean d = finished; if (d && !delayError) { Throwable ex = error; @@ -321,7 +334,7 @@ void drainNormal() { long e = 0L; while (e != r) { - boolean d = done; + boolean d = finished; GroupedFlowable t = q.poll(); @@ -340,7 +353,7 @@ void drainNormal() { e++; } - if (e == r && checkTerminated(done, q.isEmpty(), a, q)) { + if (e == r && checkTerminated(finished, q.isEmpty(), a, q)) { return; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index 3e6dcca7ac..efd57f241f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -26,6 +26,7 @@ import org.mockito.Mockito; import org.reactivestreams.*; +import com.google.common.base.Ticker; import com.google.common.cache.*; import io.reactivex.*; @@ -1947,6 +1948,127 @@ public void run() throws Exception { } }; } + + private static final class TestTicker extends Ticker { + long tick = 0; + + @Override + public long read() { + return tick; + } + } + + @Test + public void testGroupByEvictionCancellationOfSource5933() { + PublishProcessor source = PublishProcessor.create(); + final TestTicker testTicker = new TestTicker(); + + Function, Map> mapFactory = new Function, Map>() { + @Override + public Map apply(final Consumer action) throws Exception { + return CacheBuilder.newBuilder() // + .expireAfterAccess(5, TimeUnit.SECONDS).removalListener(new RemovalListener() { + @Override + public void onRemoval(RemovalNotification notification) { + try { + action.accept(notification.getValue()); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + }).ticker(testTicker) // + .build().asMap(); + } + }; + + final List list = new CopyOnWriteArrayList(); + Flowable stream = source // + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + list.add("Source canceled"); + } + }) + .groupBy(Functions.identity(), Functions.identity(), false, + Flowable.bufferSize(), mapFactory) // + .flatMap(new Function, Publisher>() { + @Override + public Publisher apply(GroupedFlowable group) + throws Exception { + return group // + .doOnComplete(new Action() { + @Override + public void run() throws Exception { + list.add("Group completed"); + } + }).doOnCancel(new Action() { + @Override + public void run() throws Exception { + list.add("Group canceled"); + } + }); + } + }); + TestSubscriber ts = stream // + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + list.add("Outer group by canceled"); + } + }).test(); + + // Send 3 in the same group and wait for them to be seen + source.onNext(1); + source.onNext(1); + source.onNext(1); + ts.awaitCount(3); + + // Advance time far enough to evict the group. + // NOTE -- Comment this line out to make the test "pass". + testTicker.tick = TimeUnit.SECONDS.toNanos(6); + + // Send more data in the group (triggering eviction and recreation) + source.onNext(1); + + // Wait for the last 2 and then cancel the subscription + ts.awaitCount(4); + ts.cancel(); + + // Observe the result. Note that right now the result differs depending on whether eviction occurred or + // not. The observed sequence in that case is: Group completed, Outer group by canceled., Group canceled. + // The addition of the "Group completed" is actually fine, but the fact that the cancel doesn't reach the + // source seems like a bug. Commenting out the setting of "tick" above will produce the "expected" sequence. + System.out.println(list); + assertTrue(list.contains("Source canceled")); + assertEquals(Arrays.asList( + "Group completed", // this is here when eviction occurs + "Outer group by canceled", + "Group canceled", + "Source canceled" // This is *not* here when eviction occurs + ), list); + } + + @Test + public void testCancellationOfUpstreamWhenGroupedFlowableCompletes() { + final AtomicBoolean cancelled = new AtomicBoolean(); + Flowable.just(1).repeat().doOnCancel(new Action() { + @Override + public void run() throws Exception { + cancelled.set(true); + } + }) + .groupBy(Functions.identity(), Functions.identity()) // + .flatMap(new Function, Publisher>() { + @Override + public Publisher apply(GroupedFlowable g) throws Exception { + return g.first(0).toFlowable(); + } + }) + .take(4) // + .test() // + .assertComplete(); + assertTrue(cancelled.get()); + } //not thread safe private static final class SingleThreadEvictingHashMap implements Map { From 175f7de3ef6c9a3ed477b9bad1daf857686fc092 Mon Sep 17 00:00:00 2001 From: David Karnok Date: Wed, 30 May 2018 10:50:29 +0200 Subject: [PATCH 193/417] 2.x: Fix MulticastProcessor JavaDoc warnings (#6030) --- src/main/java/io/reactivex/processors/MulticastProcessor.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/processors/MulticastProcessor.java b/src/main/java/io/reactivex/processors/MulticastProcessor.java index fdc1652dc2..f72b145041 100644 --- a/src/main/java/io/reactivex/processors/MulticastProcessor.java +++ b/src/main/java/io/reactivex/processors/MulticastProcessor.java @@ -102,14 +102,14 @@ *

                * Example: *

                
                -    MulticastProcessor<Integer> mp = Flowable.range(1, 10)
                +    MulticastProcessor<Integer> mp = Flowable.range(1, 10)
                     .subscribeWith(MulticastProcessor.create());
                 
                     mp.test().assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
                 
                     // --------------------
                 
                -    MulticastProcessor<Integer> mp2 = MulticastProcessor.create(4);
                +    MulticastProcessor<Integer> mp2 = MulticastProcessor.create(4);
                     mp2.start();
                 
                     assertTrue(mp2.offer(1));
                
                From d506ddcc4c578f5372958dde86a7f17a9ee5cc59 Mon Sep 17 00:00:00 2001
                From: David Karnok 
                Date: Wed, 30 May 2018 11:16:02 +0200
                Subject: [PATCH 194/417] 2.x: Upgrade to Gradle 4.3.1, add TakeUntilPerf
                 (#6029)
                
                ---
                 build.gradle                                 |   3 +-
                 gradle/wrapper/gradle-wrapper.jar            | Bin 54708 -> 54712 bytes
                 gradle/wrapper/gradle-wrapper.properties     |   2 +-
                 src/jmh/java/io/reactivex/TakeUntilPerf.java |  95 +++++++++++++++++++
                 4 files changed, 98 insertions(+), 2 deletions(-)
                 create mode 100644 src/jmh/java/io/reactivex/TakeUntilPerf.java
                
                diff --git a/build.gradle b/build.gradle
                index d39826e76d..8b9203ee06 100644
                --- a/build.gradle
                +++ b/build.gradle
                @@ -9,7 +9,7 @@ buildscript {
                   dependencies {
                     classpath "ru.vyarus:gradle-animalsniffer-plugin:1.2.0"
                     classpath "gradle.plugin.nl.javadude.gradle.plugins:license-gradle-plugin:0.13.1"
                -    classpath "me.champeau.gradle:jmh-gradle-plugin:0.4.4"
                +    classpath "me.champeau.gradle:jmh-gradle-plugin:0.4.5"
                     classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3"
                     classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.5.2"
                   }
                @@ -201,6 +201,7 @@ jmh {
                     jmhVersion = jmhLibVersion
                     humanOutputFile = null
                     includeTests = false
                +    jvmArgs = ["-Djmh.ignoreLock=true"]
                     jvmArgsAppend = ["-Djmh.separateClasspathJAR=true"]
                 
                     if (project.hasProperty("jmh")) {
                diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
                index 736fb7d3f94c051b359fc7ae7212d351bc094bdd..ed88a042a287c140a32e1639edfc91b2a233da8c 100644
                GIT binary patch
                delta 795
                zcmYk4T}YEr7{}l9IOewecvrq|zRp&Pu)Rae%932Deb8trl2#f~U1)|>mXMGjAzer%
                z&iqrBDUui62!${~D9~`z+FbKvc2ief^yN(!L>FCjJZkP-{r}JJd7g95bB=#FVQe^|
                zd!KQ6Puiz4Ns><8FReCw%lO&6+{~nIb;N&j(mcOgCsleA4KI|~35Dlufje+)qXND_
                zm7$-C
                zNCU=IXTZy;owQ_Gcc$r5`e0pgFlB6mGbH1oT~6Y=uC2Rv0WW0hF>X)8$7ziUve!Zu
                zJc`J0<;CaQ^8~EOOGO87rsT&%W4?ez`K!=b7!R`w1w3AuEGqAL;^8fifX_WiXnL#B
                zW-qtdsPJ0F5gg_6ru73$lC39HMV@L=&=@*Oj#?q#gbtJLtdKe35;E7rRiBGHVU1mb
                zKkR0MSPq|K8Y*WlQS>sNw%G7~ri|*Z3i&r?M|DJ{V3V+&k-hZf2A4Vb5-FgL7A_Cq
                z^gE5RTDf%Kd}}hsxHY$lq>8poajRWXl}@&cP)~a=Cl~
                zP~a;;g!9j{Dl>u2)sgi94?593S4>K;kTtzYqOGnkepr7V3s~Hj&Nt9#zF)LW9We8L
                z8aW4rwJmt4VF>L*4siH;&A#wR+e7Y%>Eil69rB*$v$$2d$AZgkDa@W)gZKs0ud
                hdM7b5xg9l&a_0Yk%%8%#@f=)z#qC9x{!m~g_z#MO4vPQ)
                
                delta 660
                zcmYL{T}V@59LCT47dE4foi&v0Oi8Rvk1XB7GL2jmD_YuQ7Fk+BtkwsUjD&<;NJL%~
                zS`X4Uk+*h{U?KED<~+KuoNl|YtGX#o2nP|=Rc|jV&(-huJm-1g@SgFJg0Yc;!R>1n
                zmp#TNNs`)byW4cR?p!yM29?p5S0_y*`MmnVmEXU9Sa@%SJ91$4Z6M-j5AZeOWN%@c
                zs;4ChIjso6DV0i?z(Y(yRYJxYoowI-XEDn!f1^iB-ty%=4K;&UMm)&Dk;tR$O1=9B~P2sP;4JnvpZjr;>uHiU+(
                Z%l`i-;umRMy-ZGDa3fo-Yl{30{{Wl(01*HH
                
                diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
                index 74bb77845e..0e680f3759 100644
                --- a/gradle/wrapper/gradle-wrapper.properties
                +++ b/gradle/wrapper/gradle-wrapper.properties
                @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
                 distributionPath=wrapper/dists
                 zipStoreBase=GRADLE_USER_HOME
                 zipStorePath=wrapper/dists
                -distributionUrl=https\://services.gradle.org/distributions/gradle-4.2.1-bin.zip
                +distributionUrl=https\://services.gradle.org/distributions/gradle-4.3.1-bin.zip
                diff --git a/src/jmh/java/io/reactivex/TakeUntilPerf.java b/src/jmh/java/io/reactivex/TakeUntilPerf.java
                new file mode 100644
                index 0000000000..b27afa407e
                --- /dev/null
                +++ b/src/jmh/java/io/reactivex/TakeUntilPerf.java
                @@ -0,0 +1,95 @@
                +/**
                + * Copyright (c) 2016-present, RxJava Contributors.
                + *
                + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
                + * compliance with the License. You may obtain a copy of the License at
                + *
                + * http://www.apache.org/licenses/LICENSE-2.0
                + *
                + * Unless required by applicable law or agreed to in writing, software distributed under the License is
                + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
                + * the License for the specific language governing permissions and limitations under the License.
                + */
                +
                +package io.reactivex;
                +
                +import java.util.concurrent.*;
                +
                +import org.openjdk.jmh.annotations.*;
                +
                +import io.reactivex.functions.*;
                +import io.reactivex.internal.functions.Functions;
                +import io.reactivex.schedulers.Schedulers;
                +
                +@BenchmarkMode(Mode.Throughput)
                +@Warmup(iterations = 5)
                +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
                +@OutputTimeUnit(TimeUnit.SECONDS)
                +@Fork(value = 1)
                +@State(Scope.Thread)
                +@AuxCounters
                +public class TakeUntilPerf implements Consumer {
                +
                +    public volatile int items;
                +
                +    static final int count = 10000;
                +
                +    Flowable flowable;
                +
                +    Observable observable;
                +
                +    @Override
                +    public void accept(Integer t) throws Exception {
                +        items++;
                +    }
                +
                +    @Setup
                +    public void setup() {
                +
                +        flowable = Flowable.range(1, 1000 * 1000).takeUntil(Flowable.fromCallable(new Callable() {
                +            @Override
                +            public Object call() throws Exception {
                +                int c = count;
                +                while (items < c) { }
                +                return 1;
                +            }
                +        }).subscribeOn(Schedulers.single()));
                +
                +        observable = Observable.range(1, 1000 * 1000).takeUntil(Observable.fromCallable(new Callable() {
                +            @Override
                +            public Object call() throws Exception {
                +                int c = count;
                +                while (items < c) { }
                +                return 1;
                +            }
                +        }).subscribeOn(Schedulers.single()));
                +    }
                +
                +    @Benchmark
                +    public void flowable() {
                +        final CountDownLatch cdl = new CountDownLatch(1);
                +
                +        flowable.subscribe(this, Functions.emptyConsumer(), new Action() {
                +            @Override
                +            public void run() throws Exception {
                +                cdl.countDown();
                +            }
                +        });
                +
                +        while (cdl.getCount() != 0) { }
                +    }
                +
                +    @Benchmark
                +    public void observable() {
                +        final CountDownLatch cdl = new CountDownLatch(1);
                +
                +        observable.subscribe(this, Functions.emptyConsumer(), new Action() {
                +            @Override
                +            public void run() throws Exception {
                +                cdl.countDown();
                +            }
                +        });
                +
                +        while (cdl.getCount() != 0) { }
                +    }
                +}
                
                From 6038c02ad76613774958ba156d10ef82ad387b9f Mon Sep 17 00:00:00 2001
                From: David Karnok 
                Date: Wed, 30 May 2018 22:12:01 +0200
                Subject: [PATCH 195/417] 2.x: Improve Observable.takeUntil (#6028)
                
                ---
                 .../observable/ObservableTakeUntil.java       | 125 ++++++++++--------
                 .../observable/ObservableTakeUntilTest.java   |   8 +-
                 2 files changed, 75 insertions(+), 58 deletions(-)
                
                diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntil.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntil.java
                index 64639abc0a..35e04300e0 100644
                --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntil.java
                +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntil.java
                @@ -13,103 +13,120 @@
                 
                 package io.reactivex.internal.operators.observable;
                 
                -import java.util.concurrent.atomic.AtomicBoolean;
                +import java.util.concurrent.atomic.*;
                 
                 import io.reactivex.*;
                 import io.reactivex.disposables.Disposable;
                -import io.reactivex.internal.disposables.*;
                -import io.reactivex.observers.SerializedObserver;
                +import io.reactivex.internal.disposables.DisposableHelper;
                +import io.reactivex.internal.util.*;
                 
                 public final class ObservableTakeUntil extends AbstractObservableWithUpstream {
                +
                     final ObservableSource other;
                +
                     public ObservableTakeUntil(ObservableSource source, ObservableSource other) {
                         super(source);
                         this.other = other;
                     }
                     @Override
                     public void subscribeActual(Observer child) {
                -        final SerializedObserver serial = new SerializedObserver(child);
                +        TakeUntilMainObserver parent = new TakeUntilMainObserver(child);
                +        child.onSubscribe(parent);
                 
                -        final ArrayCompositeDisposable frc = new ArrayCompositeDisposable(2);
                +        other.subscribe(parent.otherObserver);
                +        source.subscribe(parent);
                +    }
                 
                -        final TakeUntilObserver tus = new TakeUntilObserver(serial, frc);
                +    static final class TakeUntilMainObserver extends AtomicInteger
                +    implements Observer, Disposable {
                 
                -        child.onSubscribe(frc);
                +        private static final long serialVersionUID = 1418547743690811973L;
                 
                -        other.subscribe(new TakeUntil(frc, serial));
                +        final Observer downstream;
                 
                -        source.subscribe(tus);
                -    }
                +        final AtomicReference upstream;
                 
                -    static final class TakeUntilObserver extends AtomicBoolean implements Observer {
                +        final OtherObserver otherObserver;
                 
                -        private static final long serialVersionUID = 3451719290311127173L;
                -        final Observer actual;
                -        final ArrayCompositeDisposable frc;
                +        final AtomicThrowable error;
                 
                -        Disposable s;
                -
                -        TakeUntilObserver(Observer actual, ArrayCompositeDisposable frc) {
                -            this.actual = actual;
                -            this.frc = frc;
                +        TakeUntilMainObserver(Observer downstream) {
                +            this.downstream = downstream;
                +            this.upstream = new AtomicReference();
                +            this.otherObserver = new OtherObserver();
                +            this.error = new AtomicThrowable();
                         }
                 
                         @Override
                -        public void onSubscribe(Disposable s) {
                -            if (DisposableHelper.validate(this.s, s)) {
                -                this.s = s;
                -                frc.setResource(0, s);
                -            }
                +        public void dispose() {
                +            DisposableHelper.dispose(upstream);
                +            DisposableHelper.dispose(otherObserver);
                         }
                 
                         @Override
                -        public void onNext(T t) {
                -            actual.onNext(t);
                +        public boolean isDisposed() {
                +            return DisposableHelper.isDisposed(upstream.get());
                         }
                 
                         @Override
                -        public void onError(Throwable t) {
                -            frc.dispose();
                -            actual.onError(t);
                +        public void onSubscribe(Disposable d) {
                +            DisposableHelper.setOnce(upstream, d);
                         }
                 
                         @Override
                -        public void onComplete() {
                -            frc.dispose();
                -            actual.onComplete();
                +        public void onNext(T t) {
                +            HalfSerializer.onNext(downstream, t, this, error);
                         }
                -    }
                -
                -    final class TakeUntil implements Observer {
                -        private final ArrayCompositeDisposable frc;
                -        private final SerializedObserver serial;
                 
                -        TakeUntil(ArrayCompositeDisposable frc, SerializedObserver serial) {
                -            this.frc = frc;
                -            this.serial = serial;
                +        @Override
                +        public void onError(Throwable e) {
                +            DisposableHelper.dispose(otherObserver);
                +            HalfSerializer.onError(downstream, e, this, error);
                         }
                 
                         @Override
                -        public void onSubscribe(Disposable s) {
                -            frc.setResource(1, s);
                +        public void onComplete() {
                +            DisposableHelper.dispose(otherObserver);
                +            HalfSerializer.onComplete(downstream, this, error);
                         }
                 
                -        @Override
                -        public void onNext(U t) {
                -            frc.dispose();
                -            serial.onComplete();
                +        void otherError(Throwable e) {
                +            DisposableHelper.dispose(upstream);
                +            HalfSerializer.onError(downstream, e, this, error);
                         }
                 
                -        @Override
                -        public void onError(Throwable t) {
                -            frc.dispose();
                -            serial.onError(t);
                +        void otherComplete() {
                +            DisposableHelper.dispose(upstream);
                +            HalfSerializer.onComplete(downstream, this, error);
                         }
                 
                -        @Override
                -        public void onComplete() {
                -            frc.dispose();
                -            serial.onComplete();
                +        final class OtherObserver extends AtomicReference
                +        implements Observer {
                +
                +            private static final long serialVersionUID = -8693423678067375039L;
                +
                +            @Override
                +            public void onSubscribe(Disposable d) {
                +                DisposableHelper.setOnce(this, d);
                +            }
                +
                +            @Override
                +            public void onNext(U t) {
                +                DisposableHelper.dispose(this);
                +                otherComplete();
                +            }
                +
                +            @Override
                +            public void onError(Throwable e) {
                +                otherError(e);
                +            }
                +
                +            @Override
                +            public void onComplete() {
                +                otherComplete();
                +            }
                +
                         }
                     }
                +
                 }
                diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java
                index d42e5df389..4251fcc108 100644
                --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java
                +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java
                @@ -70,7 +70,7 @@ public void testTakeUntilSourceCompleted() {
                 
                         verify(result, times(1)).onNext("one");
                         verify(result, times(1)).onNext("two");
                -        verify(sSource, times(1)).dispose();
                +        verify(sSource, never()).dispose(); // no longer disposing itself on terminal events
                         verify(sOther, times(1)).dispose();
                 
                     }
                @@ -95,7 +95,7 @@ public void testTakeUntilSourceError() {
                         verify(result, times(1)).onNext("two");
                         verify(result, times(0)).onNext("three");
                         verify(result, times(1)).onError(error);
                -        verify(sSource, times(1)).dispose();
                +        verify(sSource, never()).dispose(); // no longer disposing itself on terminal events
                         verify(sOther, times(1)).dispose();
                 
                     }
                @@ -122,7 +122,7 @@ public void testTakeUntilOtherError() {
                         verify(result, times(1)).onError(error);
                         verify(result, times(0)).onComplete();
                         verify(sSource, times(1)).dispose();
                -        verify(sOther, times(1)).dispose();
                +        verify(sOther, never()).dispose(); // no longer disposing itself on termination
                 
                     }
                 
                @@ -149,7 +149,7 @@ public void testTakeUntilOtherCompleted() {
                         verify(result, times(0)).onNext("three");
                         verify(result, times(1)).onComplete();
                         verify(sSource, times(1)).dispose();
                -        verify(sOther, times(1)).dispose(); // unsubscribed since SafeSubscriber unsubscribes after onComplete
                +        verify(sOther, never()).dispose(); // no longer disposing itself on terminal events
                 
                     }
                 
                
                From 09695b4ae069537d5a415865bb92ea6ddbc86393 Mon Sep 17 00:00:00 2001
                From: David Karnok 
                Date: Fri, 1 Jun 2018 10:11:59 +0200
                Subject: [PATCH 196/417] 2.x: Inline CompositeDisposable JavaDoc (#6031)
                
                ---
                 .../disposables/CompositeDisposable.java       | 18 ++++++++++++++++++
                 1 file changed, 18 insertions(+)
                
                diff --git a/src/main/java/io/reactivex/disposables/CompositeDisposable.java b/src/main/java/io/reactivex/disposables/CompositeDisposable.java
                index f9bf2d9e84..5bed43ec77 100644
                --- a/src/main/java/io/reactivex/disposables/CompositeDisposable.java
                +++ b/src/main/java/io/reactivex/disposables/CompositeDisposable.java
                @@ -85,6 +85,12 @@ public boolean isDisposed() {
                         return disposed;
                     }
                 
                +    /**
                +     * Adds a disposable to this container or disposes it if the
                +     * container has been disposed.
                +     * @param d the disposable to add, not null
                +     * @return true if successful, false if this container has been disposed
                +     */
                     @Override
                     public boolean add(@NonNull Disposable d) {
                         ObjectHelper.requireNonNull(d, "d is null");
                @@ -135,6 +141,12 @@ public boolean addAll(@NonNull Disposable... ds) {
                         return false;
                     }
                 
                +    /**
                +     * Removes and disposes the given disposable if it is part of this
                +     * container.
                +     * @param d the disposable to remove and dispose, not null
                +     * @return true if the operation was successful
                +     */
                     @Override
                     public boolean remove(@NonNull Disposable d) {
                         if (delete(d)) {
                @@ -144,6 +156,12 @@ public boolean remove(@NonNull Disposable d) {
                         return false;
                     }
                 
                +    /**
                +     * Removes (but does not dispose) the given disposable if it is part of this
                +     * container.
                +     * @param d the disposable to remove, not null
                +     * @return true if the operation was successful
                +     */
                     @Override
                     public boolean delete(@NonNull Disposable d) {
                         ObjectHelper.requireNonNull(d, "Disposable item is null");
                
                From e8156d500762e3c953c4a78ef337fa500654db21 Mon Sep 17 00:00:00 2001
                From: akarnokd 
                Date: Fri, 1 Jun 2018 10:43:20 +0200
                Subject: [PATCH 197/417] Remove whitespaces.
                
                ---
                 .../operators/flowable/FlowableGroupByTest.java    | 14 +++++++-------
                 1 file changed, 7 insertions(+), 7 deletions(-)
                
                diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java
                index efd57f241f..bc2473d93e 100644
                --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java
                +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java
                @@ -1948,16 +1948,16 @@ public void run() throws Exception {
                             }
                         };
                     }
                -    
                +
                     private static final class TestTicker extends Ticker {
                -        long tick = 0;
                +        long tick;
                 
                         @Override
                         public long read() {
                             return tick;
                         }
                     }
                -    
                +
                     @Test
                     public void testGroupByEvictionCancellationOfSource5933() {
                         PublishProcessor source = PublishProcessor.create();
                @@ -2022,11 +2022,11 @@ public void run() throws Exception {
                         source.onNext(1);
                         source.onNext(1);
                         ts.awaitCount(3);
                -        
                +
                         // Advance time far enough to evict the group.
                         // NOTE -- Comment this line out to make the test "pass".
                         testTicker.tick = TimeUnit.SECONDS.toNanos(6);
                -        
                +
                         // Send more data in the group (triggering eviction and recreation)
                         source.onNext(1);
                 
                @@ -2042,12 +2042,12 @@ public void run() throws Exception {
                         assertTrue(list.contains("Source canceled"));
                         assertEquals(Arrays.asList(
                                 "Group completed", // this is here when eviction occurs
                -                "Outer group by canceled", 
                +                "Outer group by canceled",
                                 "Group canceled",
                                 "Source canceled"  // This is *not* here when eviction occurs
                         ), list);
                     }
                -    
                +
                     @Test
                     public void testCancellationOfUpstreamWhenGroupedFlowableCompletes() {
                         final AtomicBoolean cancelled = new AtomicBoolean();
                
                From f3c88628440268c5cf8c0c880589d9ac411fd495 Mon Sep 17 00:00:00 2001
                From: francisc0j0shua 
                Date: Fri, 1 Jun 2018 20:17:02 +0200
                Subject: [PATCH 198/417] Update DESIGN.md (#6033)
                
                I've just read the DESIGN.md and noticed some things that I could do to improve the quality of the DESIGN.md. So as a result of my "proofreading" I mainly:
                - Added periods at the ending of some sentences.
                - Did case matching of certain types and terms. e.g. `OnSubscribe` -> `onSubscribe` OR flowable -> `Flowable`.
                
                Hope it helps! :smile:
                ---
                 DESIGN.md | 138 +++++++++++++++++++++++++++---------------------------
                 1 file changed, 69 insertions(+), 69 deletions(-)
                
                diff --git a/DESIGN.md b/DESIGN.md
                index 29d4d332f9..53f828186a 100644
                --- a/DESIGN.md
                +++ b/DESIGN.md
                @@ -38,12 +38,12 @@ Producer is in charge. Consumer has to do whatever it needs to keep up.
                 
                 Examples:
                 
                -- `Observable` (RxJS, Rx.Net, RxJava v1.x without backpressure, RxJava v2)
                -- Callbacks (the producer calls the function at its convenience)
                -- IRQ, mouse events, IO interrupts
                -- 2.x `Flowable` (with `request(n)` credit always granted faster or in larger quantity than producer)
                -- Reactive Streams `Publisher` (with `request(n)` credit always granted faster or in larger quantity than producer)
                -- Java 9 `Flow.Publisher` (with `request(n)` credit always granted faster than or in larger quantity producer)
                +- `Observable` (RxJS, Rx.Net, RxJava v1.x without backpressure, RxJava v2).
                +- Callbacks (the producer calls the function at its convenience).
                +- IRQ, mouse events, IO interrupts.
                +- 2.x `Flowable` (with `request(n)` credit always granted faster or in larger quantity than producer).
                +- Reactive Streams `Publisher` (with `request(n)` credit always granted faster or in larger quantity than producer).
                +- Java 9 `Flow.Publisher` (with `request(n)` credit always granted faster than or in larger quantity than producer).
                 
                 
                 ##### Synchronous Interactive/Pull
                @@ -52,11 +52,11 @@ Consumer is in charge. Producer has to do whatever it needs to keep up.
                 
                 Examples:
                 
                -- `Iterable`
                -- 2.x/1.x `Observable` (without concurrency, producer and consumer on the same thread)
                -- 2.x `Flowable` (without concurrency, producer and consumer on the same thread)
                -- Reactive Streams `Publisher` (without concurrency, producer and consumer on the same thread)
                -- Java 9 `Flow.Publisher` (without concurrency, producer and consumer on the same thread)
                +- `Iterable`.
                +- 2.x/1.x `Observable` (without concurrency, producer and consumer on the same thread).
                +- 2.x `Flowable` (without concurrency, producer and consumer on the same thread).
                +- Reactive Streams `Publisher` (without concurrency, producer and consumer on the same thread).
                +- Java 9 `Flow.Publisher` (without concurrency, producer and consumer on the same thread).
                 
                 
                 ##### Async Pull (Async Interactive)
                @@ -65,24 +65,24 @@ Consumer requests data when it wishes, and the data is then pushed when the prod
                 
                 Examples:
                 
                -- `Future` & `Promise`
                -- `Single` (lazy `Future`)
                -- 2.x `Flowable`
                -- Reactive Streams `Publisher`
                -- Java 9 `Flow.Publisher`
                -- 1.x `Observable` (with backpressure)
                -- `AsyncEnumerable`/`AsyncIterable`
                +- `Future` & `Promise`.
                +- `Single` (lazy `Future`).
                +- 2.x `Flowable`.
                +- Reactive Streams `Publisher`.
                +- Java 9 `Flow.Publisher`.
                +- 1.x `Observable` (with backpressure).
                +- `AsyncEnumerable`/`AsyncIterable`.
                 
                 There is an overhead (performance and mental) for achieving this, which is why we also have the 2.x `Observable` without backpressure.
                 
                 
                 ##### Flow Control
                 
                -Flow control is any mitigation strategies that a consumer applies to reduce the flow of data.
                +Flow control is any mitigation strategy that a consumer applies to reduce the flow of data.
                 
                 Examples:
                 
                -- Controlling the production of data, such as with `Iterator.next` or `Subscription.request(n)`
                +- Controlling the production of data, such as with `Iterator.next` or `Subscription.request(n)`.
                 - Preventing the delivery of data, such as buffer, drop, sample/throttle, and debounce.
                 
                 
                @@ -112,14 +112,14 @@ Stream that supports async and synchronous push. It does *not* support interacti
                 
                 Usable for:
                 
                -- sync or async
                -- push
                -- 0, 1, many or infinite items
                +- Sync or async.
                +- Push.
                +- 0, 1, many or infinite items.
                 
                 Flow control support:
                 
                -- buffering, sampling, throttling, windowing, dropping, etc
                -- temporal and count-based strategies
                +- Buffering, sampling, throttling, windowing, dropping, etc.
                +- Temporal and count-based strategies.
                 
                 *Type Signature*
                 
                @@ -147,23 +147,23 @@ Stream that supports async and synchronous push and pull. It supports interactiv
                 
                 Usable for:
                 
                -- pull sources
                -- push Observables with backpressure strategy (ie. `Observable.toFlowable(onBackpressureStrategy)`)
                -- sync or async
                -- 0, 1, many or infinite items
                +- Pull sources.
                +- Push Observables with backpressure strategy (i.e. `Observable.toFlowable(onBackpressureStrategy)`).
                +- Sync or async.
                +- 0, 1, many or infinite items.
                 
                 Flow control support:
                 
                -- buffering, sampling, throttling, windowing, dropping, etc
                -- temporal and count-based strategies
                -- `request(n)` consumer demand signal
                -	- for pull-based sources, this allows batched "async pull"
                -	- for push-based sources, this allows backpressure signals to conditionally apply strategies (i.e. drop, first, buffer, sample, fail, etc)
                +- Buffering, sampling, throttling, windowing, dropping, etc.
                +- Temporal and count-based strategies.
                +- `request(n)` consumer demand signal:
                +	- For pull-based sources, this allows batched "async pull".
                +	- For push-based sources, this allows backpressure signals to conditionally apply strategies (i.e. drop, first, buffer, sample, fail, etc.).
                 
                -You get a flowable from:
                +You get a `Flowable` from:
                 
                -- Converting a Observable with a backpressure strategy
                -- Create from sync/async OnSubscribe API (which participate in backpressure semantics)
                +- Converting a Observable with a backpressure strategy.
                +- Create from sync/async `onSubscribe` API (which participate in backpressure semantics).
                 
                 *Type Signature*
                 
                @@ -191,14 +191,14 @@ Lazy representation of a single response (lazy equivalent of `Future`/`Promise`)
                 
                 Usable for:
                 
                -- pull sources
                -- push sources being windowed or flow controlled (such as `window(1)` or `take(1)`)
                -- sync or async
                -- 1 item
                +- Pull sources.
                +- Push sources being windowed or flow controlled (such as `window(1)` or `take(1)`).
                +- Sync or async.
                +- 1 item.
                 
                 Flow control:
                 
                -- Not applicable (don't subscribe if the single response is not wanted)
                +- Not applicable (don't subscribe if the single response is not wanted).
                 
                 *Type Signature*
                 
                @@ -219,15 +219,15 @@ interface SingleSubscriber {
                 
                 ##### Completable
                 
                -Lazy representation of a unit of work that can complete or fail
                +Lazy representation of a unit of work that can complete or fail.
                 
                 - Semantic equivalent of `Observable.empty().doOnSubscribe()`.
                 - Alternative for scenarios often represented with types such as `Single` or `Observable`.
                 
                 Usable for:
                 
                -- sync or async
                -- 0 items
                +- Sync or async.
                +- 0 items.
                 
                 *Type Signature*
                 
                @@ -325,9 +325,9 @@ In the addition of the previous rules, an operator for `Flowable`:
                 
                 ### Creation
                 
                -Unlike RxJava 1.x, 2.x base classes are to be abstract, stateless and generally no longer wrap an `OnSubscribe` callback - this saves allocation in assembly time without limiting the expressiveness. Operator methods and standard factories still live as final on the base classes.
                +Unlike RxJava 1.x, 2.x base classes are to be abstract, stateless and generally no longer wrap an `onSubscribe` callback - this saves allocation in assembly time without limiting the expressiveness. Operator methods and standard factories still live as final on the base classes.
                 
                -Instead of the indirection of an `OnSubscribe` and `lift`, operators are to be implemented by extending the base classes. For example, the `map`
                +Instead of the indirection of an `onSubscribe` and `lift`, operators are to be implemented by extending the base classes. For example, the `map`
                 operator will look like this:
                 
                 ```java
                @@ -353,9 +353,9 @@ public final class FlowableMap extends Flowable {
                 }
                 ``` 
                 
                -Since Java still doesn't have extension methods, "adding" more operators can only happen through helper methods such as `lift(C -> C)` and `compose(R -> P)` where `C` is the default consumer type (i.e., `rs.Subscriber`), `R` is the base type (i.e., `Flowable`) and `P` is the base interface (i.e., `rs.Publisher`). As before, the library itself may gain or lose standard operators and/or overloads through the same community process.
                +Since Java still doesn't have extension methods, "adding" more operators can only happen through helper methods such as `lift(C -> C)` and `compose(R -> P)` where `C` is the default consumer type (i.e. `rs.Subscriber`), `R` is the base type (i.e. `Flowable`) and `P` is the base interface (i.e. `rs.Publisher`). As before, the library itself may gain or lose standard operators and/or overloads through the same community process.
                 
                -In concert, `create(OnSubscribe)` will not be available; standard operators extend the base types directly. The conversion of other RS-based libraries will happen through the `Flowable.wrap(Publisher)` static method. 
                +In concert, `create(onSubscribe)` will not be available; standard operators extend the base types directly. The conversion of other RS-based libraries will happen through the `Flowable.wrap(Publisher)` static method. 
                 
                 (*The unfortunate effect of `create` in 1.x was the ignorance of the Observable contract and beginner's first choice as an entry point. We can't eliminate this path since `rs.Publisher` is a single method functional interface that can be implemented just as badly.*)
                 
                @@ -363,26 +363,26 @@ Therefore, new standard factory methods will try to address the common entry poi
                 
                 The `Flowable` will contain the following `create` methods:
                 
                -   - `create(SyncGenerator)`: safe, synchronous generation of signals, one-by-one
                -   - `create(AsyncOnSubscribe)`: batch-create signals based on request patterns
                -   - `create(Consumer>)`: relay multiple values or error from multi-valued reactive-sources (i.e., button-clicks) while also give flow control options right there (buffer, drop, error, etc.).
                -   - `createSingle(Consumer>)`: relay a single value or error from other reactive sources (i.e., addListener callbacks)
                -   - `createEmpty(Consumer)`: signal a completion or error from valueless reactive sources
                +   - `create(SyncGenerator)`: safe, synchronous generation of signals, one-by-one.
                +   - `create(AsyncOnSubscribe)`: batch-create signals based on request patterns.
                +   - `create(Consumer>)`: relay multiple values or error from multi-valued reactive-sources (i.e. button-clicks) while also give flow control options right there (buffer, drop, error, etc.).
                +   - `createSingle(Consumer>)`: relay a single value or error from other reactive sources (i.e. addListener callbacks).
                +   - `createEmpty(Consumer)`: signal a completion or error from valueless reactive sources.
                    
                 The `Observable` will contain the following `create` methods:
                 
                -   - `create(SyncGenerator)`: safe, synchronous generation of signals, one-by-one
                -   - `create(Consumer>)`: relay multiple values or error from multi-valued reactive-sources (i.e., button-clicks) while also give flow control options right there (buffer, drop, error, etc.).
                -   - `createSingle(Consumer>)`: relay a single value or error from other reactive sources (i.e., addListener callbacks)
                -   - `createEmpty(Consumer)`: signal a completion or error from valueless reactive sources
                +   - `create(SyncGenerator)`: safe, synchronous generation of signals, one-by-one.
                +   - `create(Consumer>)`: relay multiple values or error from multi-valued reactive-sources (i.e. button-clicks) while also give flow control options right there (buffer, drop, error, etc.).
                +   - `createSingle(Consumer>)`: relay a single value or error from other reactive sources (i.e. addListener callbacks).
                +   - `createEmpty(Consumer)`: signal a completion or error from valueless reactive sources.
                 
                 The `Single` will contain the following `create` method:
                 
                -   - `create(Consumer>)`: relay a single value or error from other reactive sources (i.e., addListener callbacks)
                +   - `create(Consumer>)`: relay a single value or error from other reactive sources (i.e. addListener callbacks).
                    
                 The `Completable` will contain the following `create` method:
                 
                -   - `create(Consumer)`: signal a completion or error from valueless reactive sources
                +   - `create(Consumer)`: signal a completion or error from valueless reactive sources.
                 
                 
                 The first two `create` methods take an implementation of an interface which provides state and the generator methods:
                @@ -509,10 +509,10 @@ There are two main levels of operator fusion: *macro* and *micro*.
                 
                 Macro fusion deals with the higher level view of the operators, their identity and their combination (mostly in the form of subsequence). This is partially an internal affair of the operators, triggered by the downstream operator and may work with several cases. Given an operator application pair `a().b()` where `a` could be a source or an intermediate operator itself, when the application of `b` happens in assembly time, the following can happen:
                 
                -  - `b` identifies `a` and decides to not apply itself. Example: `empty().flatMap()` is functionally a no-op
                +  - `b` identifies `a` and decides to not apply itself. Example: `empty().flatMap()` is functionally a no-op.
                   - `b` identifies `a` and decides to apply a different, conventional operator. Example: `just().subscribeOn()` is turned into `just().observeOn()`.
                   - `b` decides to apply a new custom operator, combining and inlining existing behavior. Example: `just().subscribeOn()` internally goes to `ScalarScheduledPublisher`.
                -  - `a` is `b` and the two operator's parameter set can be combined into a single application. Example: `filter(p1).filter(p2)` combined into `filter(p1 && p2)`
                +  - `a` is `b` and the two operator's parameter set can be combined into a single application. Example: `filter(p1).filter(p2)` combined into `filter(p1 && p2)`.
                 
                 Participating in the macro-fusion externally is possible by implementing a marker interface when extending `Flowable`. Two kinds of interfaces are available: 
                 
                @@ -540,7 +540,7 @@ Currently, two main kinds of micro-fusion opportunities are available.
                 
                 ###### 1) Conditional Subscriber
                 
                -This extends the RS `Subscriber`interface with an extra method: `boolean tryOnNext(T value)` and can help avoiding small request amounts in case an operator didn't forward but dropped the value. The canonical use is for the `filter()` operator where if the predicate returns false, the operator has to request 1 from upstream (since the downstream doesn't know there was a value dropped and thus not request itself). Operators wanting to participate in this fusion have to implement and subscribe with an extended Subscriber interface:
                +This extends the RS `Subscriber`interface with an extra method: `boolean tryOnNext(T value)` and can help avoiding small request amounts in case an operator didn't forward but dropped the value. The canonical use is for the `filter()` operator where if the predicate returns false, the operator has to request 1 from upstream (since the downstream doesn't know there was a value dropped and thus not request itself). Operators wanting to participate in this fusion have to implement and subscribe with an extended `Subscriber` interface:
                 
                 ```java
                 interface ConditionalSubscriber {
                @@ -562,9 +562,9 @@ protected void subscribeActual(Subscriber s) {
                 
                 ###### 2) Queue-fusion
                 
                -The second category is when two (or more) operators share the same underlying queue and each append activity at the exit point (i.e., poll()) of the queue. This can work in two modes: synchronous and asynchronous.
                +The second category is when two (or more) operators share the same underlying queue and each append activity at the exit point (i.e. `poll()`) of the queue. This can work in two modes: synchronous and asynchronous.
                 
                -In synchronous mode, the elements of the sequence is already available (i.e., a fixed `range()` or `fromArray()`, or can be synchronously calculated in a pull fashion in `fromIterable`. In this mode, the requesting and regular onError-path is bypassed and is forbidden. Sources have to return null from `pull()` and false from `isEmpty()` if they have no more values and throw from these methods if they want to indicate an exceptional case.
                +In synchronous mode, the elements of the sequence is already available (i.e. a fixed `range()` or `fromArray()`, or can be synchronously calculated in a pull fashion in `fromIterable`. In this mode, the requesting and regular onError-path is bypassed and is forbidden. Sources have to return null from `pull()` and false from `isEmpty()` if they have no more values and throw from these methods if they want to indicate an exceptional case.
                 
                 In asynchronous mode, elements may become available at any time, therefore, `pull` returning null, as with regular queue-drain, is just the indication of temporary lack of source values. Completion and error still has to go through `onComplete` and `onError` as usual, requesting still happens as usual but when a value is available in the shared queue, it is indicated by an `onNext(null)` call. This can trigger a chain of `drain` calls without moving values in or out of different queues.
                 
                @@ -588,10 +588,10 @@ For performance, the mode is an integer bitflags setup, called early during subs
                 
                 Since RxJava 2.x is still JDK 6 compatible, the `QueueSubscription` can't itself default unnecessary methods and implementations are required to throw `UnsupportedOperationException` for `Queue` methods other than the following:
                 
                -  - `poll()`
                -  - `isEmpty()`
                -  - `clear()`
                -  - `size()`
                +  - `poll()`.
                +  - `isEmpty()`.
                +  - `clear()`.
                +  - `size()`.
                 
                 Even though other modern libraries also define this interface, they live in local packages and thus non-reusable without dragging in the whole library. Therefore, until externalized and standardized, cross-library micro-fusion won't happen.
                 
                
                From 5d8b0acec351199947fe15702946662c69bbd0f5 Mon Sep 17 00:00:00 2001
                From: Hans 
                Date: Sat, 9 Jun 2018 19:25:54 +0800
                Subject: [PATCH 199/417] 2.X: Fix disposed LambdaObserver onError to route to
                 global error handler (#6036)
                
                ---
                 .../internal/observers/LambdaObserver.java    |  2 ++
                 .../observers/LambdaObserverTest.java         | 29 +++++++++++++++++++
                 2 files changed, 31 insertions(+)
                
                diff --git a/src/main/java/io/reactivex/internal/observers/LambdaObserver.java b/src/main/java/io/reactivex/internal/observers/LambdaObserver.java
                index 041229a1ea..da3a2b85db 100644
                --- a/src/main/java/io/reactivex/internal/observers/LambdaObserver.java
                +++ b/src/main/java/io/reactivex/internal/observers/LambdaObserver.java
                @@ -79,6 +79,8 @@ public void onError(Throwable t) {
                                 Exceptions.throwIfFatal(e);
                                 RxJavaPlugins.onError(new CompositeException(t, e));
                             }
                +        } else {
                +            RxJavaPlugins.onError(t);
                         }
                     }
                 
                diff --git a/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java b/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java
                index d5d3f647d3..94fe4cb4c1 100644
                --- a/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java
                +++ b/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java
                @@ -15,6 +15,7 @@
                 
                 import static org.junit.Assert.*;
                 
                +import java.io.IOException;
                 import java.util.*;
                 
                 import io.reactivex.internal.functions.Functions;
                @@ -363,4 +364,32 @@ public void customOnErrorShouldReportCustomOnError() {
                 
                         assertTrue(o.hasCustomOnError());
                     }
                +
                +    @Test
                +    public void disposedObserverShouldReportErrorOnGlobalErrorHandler() {
                +        List errors = TestHelper.trackPluginErrors();
                +        try {
                +            final List observerErrors = Collections.synchronizedList(new ArrayList());
                +
                +            LambdaObserver o = new LambdaObserver(Functions.emptyConsumer(),
                +                    new Consumer() {
                +                        @Override
                +                        public void accept(Throwable t) {
                +                            observerErrors.add(t);
                +                        }
                +                    },
                +                    Functions.EMPTY_ACTION,
                +                    Functions.emptyConsumer());
                +
                +            o.dispose();
                +            o.onError(new IOException());
                +            o.onError(new IOException());
                +
                +            assertTrue(observerErrors.isEmpty());
                +            TestHelper.assertUndeliverable(errors, 0, IOException.class);
                +            TestHelper.assertUndeliverable(errors, 1, IOException.class);
                +        } finally {
                +            RxJavaPlugins.reset();
                +        }
                +    }
                 }
                
                From ba06bffaabf0bdf3fdd5298efcb42e2164434e18 Mon Sep 17 00:00:00 2001
                From: Sato Shun 
                Date: Thu, 14 Jun 2018 16:45:49 +0900
                Subject: [PATCH 200/417] fix MulticastProcessor javadoc comment (#6042)
                
                ---
                 src/main/java/io/reactivex/processors/MulticastProcessor.java | 4 ++--
                 1 file changed, 2 insertions(+), 2 deletions(-)
                
                diff --git a/src/main/java/io/reactivex/processors/MulticastProcessor.java b/src/main/java/io/reactivex/processors/MulticastProcessor.java
                index f72b145041..71d8a2dd8e 100644
                --- a/src/main/java/io/reactivex/processors/MulticastProcessor.java
                +++ b/src/main/java/io/reactivex/processors/MulticastProcessor.java
                @@ -43,7 +43,7 @@
                  *      the given prefetch amount and no reference counting behavior.
                  * 
              • {@link #create(boolean)}: create an empty {@code MulticastProcessor} with * {@link io.reactivex.Flowable#bufferSize() Flowable.bufferSize()} prefetch amount - * and no reference counting behavior.
              • + * and an optional reference counting behavior. *
              • {@link #create(int, boolean)}: create an empty {@code MulticastProcessor} with * the given prefetch amount and an optional reference counting behavior.
              • * @@ -174,7 +174,7 @@ public static MulticastProcessor create() { /** * Constructs a fresh instance with the default Flowable.bufferSize() prefetch - * amount and no refCount-behavior. + * amount and the optional refCount-behavior. * @param the input and output value type * @param refCount if true and if all Subscribers have canceled, the upstream * is cancelled From fc0ca6e151f12969ca077ad4eae6d24e464e857e Mon Sep 17 00:00:00 2001 From: Roman Wuattier Date: Thu, 14 Jun 2018 10:03:58 +0200 Subject: [PATCH 201/417] Fix Flowable.blockingSubscribe is unbounded and can lead to OOME (#6026) --- src/main/java/io/reactivex/Flowable.java | 85 ++++ .../internal/functions/Functions.java | 19 + .../flowable/FlowableBlockingSubscribe.java | 19 + .../subscribers/BoundedSubscriber.java | 140 +++++++ .../OnErrorNotImplementedExceptionTest.java | 6 + .../flowable/FlowableBlockingTest.java | 159 +++++++ .../subscribers/BoundedSubscriberTest.java | 388 ++++++++++++++++++ 7 files changed, 816 insertions(+) create mode 100644 src/main/java/io/reactivex/internal/subscribers/BoundedSubscriber.java create mode 100644 src/test/java/io/reactivex/internal/subscribers/BoundedSubscriberTest.java diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index b37e123bc8..387f36c5cd 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -5853,6 +5853,38 @@ public final void blockingSubscribe(Consumer onNext) { FlowableBlockingSubscribe.subscribe(this, onNext, Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION); } + /** + * Subscribes to the source and calls the given callbacks on the current thread. + *

                + * If the Flowable emits an error, it is wrapped into an + * {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} + * and routed to the RxJavaPlugins.onError handler. + * Using the overloads {@link #blockingSubscribe(Consumer, Consumer)} + * or {@link #blockingSubscribe(Consumer, Consumer, Action)} instead is recommended. + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. + *

                + *
                Backpressure:
                + *
                The operator consumes the source {@code Flowable} in an bounded manner (up to bufferSize + * outstanding request amount for items).
                + *
                Scheduler:
                + *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param onNext the callback action for each source value + * @param bufferSize the size of the buffer + * @since 2.1.15 - experimental + * @see #blockingSubscribe(Consumer, Consumer) + * @see #blockingSubscribe(Consumer, Consumer, Action) + */ + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final void blockingSubscribe(Consumer onNext, int bufferSize) { + FlowableBlockingSubscribe.subscribe(this, onNext, Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION, bufferSize); + } + /** * Subscribes to the source and calls the given callbacks on the current thread. *

                @@ -5877,6 +5909,32 @@ public final void blockingSubscribe(Consumer onNext, Consumeron the current thread. + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. + *

                + *
                Backpressure:
                + *
                The operator consumes the source {@code Flowable} in an bounded manner (up to bufferSize + * outstanding request amount for items).
                + *
                Scheduler:
                + *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param onNext the callback action for each source value + * @param onError the callback action for an error event + * @param bufferSize the size of the buffer + * @since 2.1.15 - experimental + * @see #blockingSubscribe(Consumer, Consumer, Action) + */ + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final void blockingSubscribe(Consumer onNext, Consumer onError, + int bufferSize) { + FlowableBlockingSubscribe.subscribe(this, onNext, onError, Functions.EMPTY_ACTION, bufferSize); + } /** * Subscribes to the source and calls the given callbacks on the current thread. @@ -5902,6 +5960,33 @@ public final void blockingSubscribe(Consumer onNext, Consumeron the current thread. + *

                + * Note that calling this method will block the caller thread until the upstream terminates + * normally or with an error. Therefore, calling this method from special threads such as the + * Android Main Thread or the Swing Event Dispatch Thread is not recommended. + *

                + *
                Backpressure:
                + *
                The operator consumes the source {@code Flowable} in an bounded manner (up to bufferSize + * outstanding request amount for items).
                + *
                Scheduler:
                + *
                {@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.
                + *
                + * @param onNext the callback action for each source value + * @param onError the callback action for an error event + * @param onComplete the callback action for the completion event. + * @param bufferSize the size of the buffer + * @since 2.1.15 - experimental + */ + @BackpressureSupport(BackpressureKind.FULL) + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final void blockingSubscribe(Consumer onNext, Consumer onError, Action onComplete, + int bufferSize) { + FlowableBlockingSubscribe.subscribe(this, onNext, onError, onComplete, bufferSize); + } + /** * Subscribes to the source and calls the {@link Subscriber} methods on the current thread. *

                diff --git a/src/main/java/io/reactivex/internal/functions/Functions.java b/src/main/java/io/reactivex/internal/functions/Functions.java index b54694844f..6aee33fea3 100644 --- a/src/main/java/io/reactivex/internal/functions/Functions.java +++ b/src/main/java/io/reactivex/internal/functions/Functions.java @@ -745,4 +745,23 @@ public void accept(Subscription t) throws Exception { t.request(Long.MAX_VALUE); } } + + @SuppressWarnings("unchecked") + public static Consumer boundedConsumer(int bufferSize) { + return (Consumer) new BoundedConsumer(bufferSize); + } + + public static class BoundedConsumer implements Consumer { + + final int bufferSize; + + BoundedConsumer(int bufferSize) { + this.bufferSize = bufferSize; + } + + @Override + public void accept(Subscription s) throws Exception { + s.request(bufferSize); + } + } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBlockingSubscribe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBlockingSubscribe.java index d79c6f3061..3d40aef2f9 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBlockingSubscribe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBlockingSubscribe.java @@ -108,4 +108,23 @@ public static void subscribe(Publisher o, final Consumer(onNext, onError, onComplete, Functions.REQUEST_MAX)); } + + /** + * Subscribes to the source and calls the given actions on the current thread. + * @param o the source publisher + * @param onNext the callback action for each source value + * @param onError the callback action for an error event + * @param onComplete the callback action for the completion event. + * @param bufferSize the number of elements to prefetch from the source Publisher + * @param the value type + */ + public static void subscribe(Publisher o, final Consumer onNext, + final Consumer onError, final Action onComplete, int bufferSize) { + ObjectHelper.requireNonNull(onNext, "onNext is null"); + ObjectHelper.requireNonNull(onError, "onError is null"); + ObjectHelper.requireNonNull(onComplete, "onComplete is null"); + ObjectHelper.verifyPositive(bufferSize, "number > 0 required"); + subscribe(o, new BoundedSubscriber(onNext, onError, onComplete, Functions.boundedConsumer(bufferSize), + bufferSize)); + } } diff --git a/src/main/java/io/reactivex/internal/subscribers/BoundedSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/BoundedSubscriber.java new file mode 100644 index 0000000000..5adbfeb207 --- /dev/null +++ b/src/main/java/io/reactivex/internal/subscribers/BoundedSubscriber.java @@ -0,0 +1,140 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.subscribers; + +import io.reactivex.FlowableSubscriber; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.CompositeException; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Action; +import io.reactivex.functions.Consumer; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.observers.LambdaConsumerIntrospection; +import io.reactivex.plugins.RxJavaPlugins; +import org.reactivestreams.Subscription; + +import java.util.concurrent.atomic.AtomicReference; + +public final class BoundedSubscriber extends AtomicReference + implements FlowableSubscriber, Subscription, Disposable, LambdaConsumerIntrospection { + + private static final long serialVersionUID = -7251123623727029452L; + final Consumer onNext; + final Consumer onError; + final Action onComplete; + final Consumer onSubscribe; + + final int bufferSize; + int consumed; + final int limit; + + public BoundedSubscriber(Consumer onNext, Consumer onError, + Action onComplete, Consumer onSubscribe, int bufferSize) { + super(); + this.onNext = onNext; + this.onError = onError; + this.onComplete = onComplete; + this.onSubscribe = onSubscribe; + this.bufferSize = bufferSize; + this.limit = bufferSize - (bufferSize >> 2); + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.setOnce(this, s)) { + try { + onSubscribe.accept(this); + } catch (Throwable e) { + Exceptions.throwIfFatal(e); + s.cancel(); + onError(e); + } + } + } + + @Override + public void onNext(T t) { + if (!isDisposed()) { + try { + onNext.accept(t); + + int c = consumed + 1; + if (c == limit) { + consumed = 0; + get().request(limit); + } else { + consumed = c; + } + } catch (Throwable e) { + Exceptions.throwIfFatal(e); + get().cancel(); + onError(e); + } + } + } + + @Override + public void onError(Throwable t) { + if (get() != SubscriptionHelper.CANCELLED) { + lazySet(SubscriptionHelper.CANCELLED); + try { + onError.accept(t); + } catch (Throwable e) { + Exceptions.throwIfFatal(e); + RxJavaPlugins.onError(new CompositeException(t, e)); + } + } else { + RxJavaPlugins.onError(t); + } + } + + @Override + public void onComplete() { + if (get() != SubscriptionHelper.CANCELLED) { + lazySet(SubscriptionHelper.CANCELLED); + try { + onComplete.run(); + } catch (Throwable e) { + Exceptions.throwIfFatal(e); + RxJavaPlugins.onError(e); + } + } + } + + @Override + public void dispose() { + cancel(); + } + + @Override + public boolean isDisposed() { + return get() == SubscriptionHelper.CANCELLED; + } + + @Override + public void request(long n) { + get().request(n); + } + + @Override + public void cancel() { + SubscriptionHelper.cancel(this); + } + + @Override + public boolean hasCustomOnError() { + return onError != Functions.ON_ERROR_MISSING; + } +} \ No newline at end of file diff --git a/src/test/java/io/reactivex/exceptions/OnErrorNotImplementedExceptionTest.java b/src/test/java/io/reactivex/exceptions/OnErrorNotImplementedExceptionTest.java index 1e6b97fc8c..d7b69ca107 100644 --- a/src/test/java/io/reactivex/exceptions/OnErrorNotImplementedExceptionTest.java +++ b/src/test/java/io/reactivex/exceptions/OnErrorNotImplementedExceptionTest.java @@ -66,6 +66,12 @@ public void flowableBlockingSubscribe1() { .blockingSubscribe(Functions.emptyConsumer()); } + @Test + public void flowableBoundedBlockingSubscribe1() { + Flowable.error(new TestException()) + .blockingSubscribe(Functions.emptyConsumer(), 128); + } + @Test public void observableSubscribe0() { Observable.error(new TestException()) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java index 09c246016a..88fa5e11cb 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java @@ -62,6 +62,38 @@ public void accept(Integer v) throws Exception { assertEquals(Arrays.asList(1, 2, 3, 4, 5), list); } + @Test + public void boundedBlockingSubscribeConsumer() { + final List list = new ArrayList(); + + Flowable.range(1, 5) + .subscribeOn(Schedulers.computation()) + .blockingSubscribe(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + list.add(v); + } + }, 128); + + assertEquals(Arrays.asList(1, 2, 3, 4, 5), list); + } + + @Test + public void boundedBlockingSubscribeConsumerBufferExceed() { + final List list = new ArrayList(); + + Flowable.range(1, 5) + .subscribeOn(Schedulers.computation()) + .blockingSubscribe(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + list.add(v); + } + }, 3); + + assertEquals(Arrays.asList(1, 2, 3, 4, 5), list); + } + @Test public void blockingSubscribeConsumerConsumer() { final List list = new ArrayList(); @@ -78,6 +110,38 @@ public void accept(Integer v) throws Exception { assertEquals(Arrays.asList(1, 2, 3, 4, 5), list); } + @Test + public void boundedBlockingSubscribeConsumerConsumer() { + final List list = new ArrayList(); + + Flowable.range(1, 5) + .subscribeOn(Schedulers.computation()) + .blockingSubscribe(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + list.add(v); + } + }, Functions.emptyConsumer(), 128); + + assertEquals(Arrays.asList(1, 2, 3, 4, 5), list); + } + + @Test + public void boundedBlockingSubscribeConsumerConsumerBufferExceed() { + final List list = new ArrayList(); + + Flowable.range(1, 5) + .subscribeOn(Schedulers.computation()) + .blockingSubscribe(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + list.add(v); + } + }, Functions.emptyConsumer(), 3); + + assertEquals(Arrays.asList(1, 2, 3, 4, 5), list); + } + @Test public void blockingSubscribeConsumerConsumerError() { final List list = new ArrayList(); @@ -98,6 +162,26 @@ public void accept(Object v) throws Exception { assertEquals(Arrays.asList(1, 2, 3, 4, 5, ex), list); } + @Test + public void boundedBlockingSubscribeConsumerConsumerError() { + final List list = new ArrayList(); + + TestException ex = new TestException(); + + Consumer cons = new Consumer() { + @Override + public void accept(Object v) throws Exception { + list.add(v); + } + }; + + Flowable.range(1, 5).concatWith(Flowable.error(ex)) + .subscribeOn(Schedulers.computation()) + .blockingSubscribe(cons, cons, 128); + + assertEquals(Arrays.asList(1, 2, 3, 4, 5, ex), list); + } + @Test public void blockingSubscribeConsumerConsumerAction() { final List list = new ArrayList(); @@ -121,6 +205,81 @@ public void run() throws Exception { assertEquals(Arrays.asList(1, 2, 3, 4, 5, 100), list); } + @Test + public void boundedBlockingSubscribeConsumerConsumerAction() { + final List list = new ArrayList(); + + Consumer cons = new Consumer() { + @Override + public void accept(Object v) throws Exception { + list.add(v); + } + }; + + Action action = new Action() { + @Override + public void run() throws Exception { + list.add(100); + } + }; + + Flowable.range(1, 5) + .subscribeOn(Schedulers.computation()) + .blockingSubscribe(cons, cons, action, 128); + + assertEquals(Arrays.asList(1, 2, 3, 4, 5, 100), list); + } + + @Test + public void boundedBlockingSubscribeConsumerConsumerActionBufferExceed() { + final List list = new ArrayList(); + + Consumer cons = new Consumer() { + @Override + public void accept(Object v) throws Exception { + list.add(v); + } + }; + + Action action = new Action() { + @Override + public void run() throws Exception { + list.add(100); + } + }; + + Flowable.range(1, 5) + .subscribeOn(Schedulers.computation()) + .blockingSubscribe(cons, cons, action, 3); + + assertEquals(Arrays.asList(1, 2, 3, 4, 5, 100), list); + } + + @Test + public void boundedBlockingSubscribeConsumerConsumerActionBufferExceedMillionItem() { + final List list = new ArrayList(); + + Consumer cons = new Consumer() { + @Override + public void accept(Object v) throws Exception { + list.add(v); + } + }; + + Action action = new Action() { + @Override + public void run() throws Exception { + list.add(1000001); + } + }; + + Flowable.range(1, 1000000) + .subscribeOn(Schedulers.computation()) + .blockingSubscribe(cons, cons, action, 128); + + assertEquals(1000000 + 1, list.size()); + } + @Test public void blockingSubscribeObserver() { final List list = new ArrayList(); diff --git a/src/test/java/io/reactivex/internal/subscribers/BoundedSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/BoundedSubscriberTest.java new file mode 100644 index 0000000000..0fed174be5 --- /dev/null +++ b/src/test/java/io/reactivex/internal/subscribers/BoundedSubscriberTest.java @@ -0,0 +1,388 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.subscribers; + +import io.reactivex.Flowable; +import io.reactivex.TestHelper; +import io.reactivex.exceptions.CompositeException; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.functions.Consumer; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import org.junit.Test; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class BoundedSubscriberTest { + + @Test + public void onSubscribeThrows() { + final List received = new ArrayList(); + + BoundedSubscriber o = new BoundedSubscriber(new Consumer() { + @Override + public void accept(Object o) throws Exception { + received.add(o); + } + }, new Consumer() { + @Override + public void accept(Throwable throwable) throws Exception { + received.add(throwable); + } + }, new Action() { + @Override + public void run() throws Exception { + received.add(1); + } + }, new Consumer() { + @Override + public void accept(Subscription subscription) throws Exception { + throw new TestException(); + } + }, 128); + + assertFalse(o.isDisposed()); + + Flowable.just(1).subscribe(o); + + assertTrue(received.toString(), received.get(0) instanceof TestException); + assertEquals(received.toString(), 1, received.size()); + + assertTrue(o.isDisposed()); + } + + @Test + public void onNextThrows() { + final List received = new ArrayList(); + + BoundedSubscriber o = new BoundedSubscriber(new Consumer() { + @Override + public void accept(Object o) throws Exception { + throw new TestException(); + } + }, new Consumer() { + @Override + public void accept(Throwable throwable) throws Exception { + received.add(throwable); + } + }, new Action() { + @Override + public void run() throws Exception { + received.add(1); + } + }, new Consumer() { + @Override + public void accept(Subscription subscription) throws Exception { + subscription.request(128); + } + }, 128); + + assertFalse(o.isDisposed()); + + Flowable.just(1).subscribe(o); + + assertTrue(received.toString(), received.get(0) instanceof TestException); + assertEquals(received.toString(), 1, received.size()); + + assertTrue(o.isDisposed()); + } + + @Test + public void onErrorThrows() { + List errors = TestHelper.trackPluginErrors(); + + try { + final List received = new ArrayList(); + + BoundedSubscriber o = new BoundedSubscriber(new Consumer() { + @Override + public void accept(Object o) throws Exception { + received.add(o); + } + }, new Consumer() { + @Override + public void accept(Throwable throwable) throws Exception { + throw new TestException("Inner"); + } + }, new Action() { + @Override + public void run() throws Exception { + received.add(1); + } + }, new Consumer() { + @Override + public void accept(Subscription subscription) throws Exception { + subscription.request(128); + } + }, 128); + + assertFalse(o.isDisposed()); + + Flowable.error(new TestException("Outer")).subscribe(o); + + assertTrue(received.toString(), received.isEmpty()); + + assertTrue(o.isDisposed()); + + TestHelper.assertError(errors, 0, CompositeException.class); + List ce = TestHelper.compositeList(errors.get(0)); + TestHelper.assertError(ce, 0, TestException.class, "Outer"); + TestHelper.assertError(ce, 1, TestException.class, "Inner"); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void onCompleteThrows() { + List errors = TestHelper.trackPluginErrors(); + + try { + final List received = new ArrayList(); + + BoundedSubscriber o = new BoundedSubscriber(new Consumer() { + @Override + public void accept(Object o) throws Exception { + received.add(o); + } + }, new Consumer() { + @Override + public void accept(Throwable throwable) throws Exception { + received.add(throwable); + } + }, new Action() { + @Override + public void run() throws Exception { + throw new TestException(); + } + }, new Consumer() { + @Override + public void accept(Subscription subscription) throws Exception { + subscription.request(128); + } + }, 128); + + assertFalse(o.isDisposed()); + + Flowable.empty().subscribe(o); + + assertTrue(received.toString(), received.isEmpty()); + + assertTrue(o.isDisposed()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void onNextThrowsCancelsUpstream() { + PublishProcessor pp = PublishProcessor.create(); + + final List errors = new ArrayList(); + + BoundedSubscriber s = new BoundedSubscriber(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + throw new TestException(); + } + }, new Consumer() { + @Override + public void accept(Throwable e) throws Exception { + errors.add(e); + } + }, new Action() { + @Override + public void run() throws Exception { + + } + }, new Consumer() { + @Override + public void accept(Subscription subscription) throws Exception { + subscription.request(128); + } + }, 128); + + pp.subscribe(s); + + assertTrue("No observers?!", pp.hasSubscribers()); + assertTrue("Has errors already?!", errors.isEmpty()); + + pp.onNext(1); + + assertFalse("Has observers?!", pp.hasSubscribers()); + assertFalse("No errors?!", errors.isEmpty()); + + assertTrue(errors.toString(), errors.get(0) instanceof TestException); + } + + @Test + public void onSubscribeThrowsCancelsUpstream() { + PublishProcessor pp = PublishProcessor.create(); + + final List errors = new ArrayList(); + + BoundedSubscriber s = new BoundedSubscriber(new Consumer() { + @Override + public void accept(Integer v) throws Exception { + } + }, new Consumer() { + @Override + public void accept(Throwable e) throws Exception { + errors.add(e); + } + }, new Action() { + @Override + public void run() throws Exception { + } + }, new Consumer() { + @Override + public void accept(Subscription s) throws Exception { + throw new TestException(); + } + }, 128); + + pp.subscribe(s); + + assertFalse("Has observers?!", pp.hasSubscribers()); + assertFalse("No errors?!", errors.isEmpty()); + + assertTrue(errors.toString(), errors.get(0) instanceof TestException); + } + + @Test + public void badSourceOnSubscribe() { + Flowable source = Flowable.fromPublisher(new Publisher() { + @Override + public void subscribe(Subscriber s) { + BooleanSubscription s1 = new BooleanSubscription(); + s.onSubscribe(s1); + BooleanSubscription s2 = new BooleanSubscription(); + s.onSubscribe(s2); + + assertFalse(s1.isCancelled()); + assertTrue(s2.isCancelled()); + + s.onNext(1); + s.onComplete(); + } + }); + + final List received = new ArrayList(); + + BoundedSubscriber o = new BoundedSubscriber(new Consumer() { + @Override + public void accept(Object v) throws Exception { + received.add(v); + } + }, new Consumer() { + @Override + public void accept(Throwable e) throws Exception { + received.add(e); + } + }, new Action() { + @Override + public void run() throws Exception { + received.add(100); + } + }, new Consumer() { + @Override + public void accept(Subscription s) throws Exception { + s.request(128); + } + }, 128); + + source.subscribe(o); + + assertEquals(Arrays.asList(1, 100), received); + } + + @Test + public void badSourceEmitAfterDone() { + Flowable source = Flowable.fromPublisher(new Publisher() { + @Override + public void subscribe(Subscriber s) { + BooleanSubscription s1 = new BooleanSubscription(); + s.onSubscribe(s1); + + s.onNext(1); + s.onComplete(); + s.onNext(2); + s.onError(new TestException()); + s.onComplete(); + } + }); + + final List received = new ArrayList(); + + BoundedSubscriber o = new BoundedSubscriber(new Consumer() { + @Override + public void accept(Object v) throws Exception { + received.add(v); + } + }, new Consumer() { + @Override + public void accept(Throwable e) throws Exception { + received.add(e); + } + }, new Action() { + @Override + public void run() throws Exception { + received.add(100); + } + }, new Consumer() { + @Override + public void accept(Subscription s) throws Exception { + s.request(128); + } + }, 128); + + source.subscribe(o); + + assertEquals(Arrays.asList(1, 100), received); + } + + @Test + public void onErrorMissingShouldReportNoCustomOnError() { + BoundedSubscriber o = new BoundedSubscriber(Functions.emptyConsumer(), + Functions.ON_ERROR_MISSING, + Functions.EMPTY_ACTION, + Functions.boundedConsumer(128), 128); + + assertFalse(o.hasCustomOnError()); + } + + @Test + public void customOnErrorShouldReportCustomOnError() { + BoundedSubscriber o = new BoundedSubscriber(Functions.emptyConsumer(), + Functions.emptyConsumer(), + Functions.EMPTY_ACTION, + Functions.boundedConsumer(128), 128); + + assertTrue(o.hasCustomOnError()); + } +} From 65c49561d90d2eb261bc91a512821ee57b076c16 Mon Sep 17 00:00:00 2001 From: Kiskae Date: Sat, 16 Jun 2018 15:18:49 +0200 Subject: [PATCH 202/417] Fix check that would always be false (#6045) Checking `BlockingSubscriber.TERMINATED` (`new Object()`) against `o` would always be false since `o` is a publisher. Since `v` comes from the queue this is presumably the variable that should be checked. However the check might even be redundant with this change since that variable can only appear in the queue after the subscriber has been cancelled. I am not familiar enough with the memory model to say whether the object appearing in the queue implies the cancelled subscriber is visible. --- .../internal/operators/flowable/FlowableBlockingSubscribe.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBlockingSubscribe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBlockingSubscribe.java index 3d40aef2f9..c5ac6884f6 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBlockingSubscribe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBlockingSubscribe.java @@ -63,7 +63,7 @@ public static void subscribe(Publisher o, Subscriber if (bs.isCancelled()) { break; } - if (o == BlockingSubscriber.TERMINATED + if (v == BlockingSubscriber.TERMINATED || NotificationLite.acceptFull(v, subscriber)) { break; } From 102700ce2fc0ee749eb7ce3a52b85397b638c07a Mon Sep 17 00:00:00 2001 From: David Karnok Date: Sun, 17 Jun 2018 15:31:04 +0200 Subject: [PATCH 203/417] 2.x: Add the wiki pages as docs (#6047) --- docs/Additional-Reading.md | 50 + ...phabetical-List-of-Observable-Operators.md | 250 +++ docs/Async-Operators.md | 11 + docs/Backpressure-(2.0).md | 503 +++++ docs/Backpressure.md | 175 ++ docs/Blocking-Observable-Operators.md | 49 + docs/Combining-Observables.md | 12 + docs/Conditional-and-Boolean-Operators.md | 21 + docs/Connectable-Observable-Operators.md | 75 + docs/Creating-Observables.md | 13 + docs/Error-Handling-Operators.md | 14 + docs/Error-Handling.md | 24 + docs/Filtering-Observables.md | 22 + docs/Getting-Started.md | 141 ++ docs/Home.md | 24 + docs/How-To-Use-RxJava.md | 400 ++++ docs/How-to-Contribute.md | 41 + docs/Implementing-Your-Own-Operators.md | 114 ++ docs/Implementing-custom-operators-(draft).md | 508 +++++ docs/Mathematical-and-Aggregate-Operators.md | 25 + docs/Observable-Utility-Operators.md | 28 + docs/Observable.md | 3 + docs/Parallel-flows.md | 33 + docs/Phantom-Operators.md | 166 ++ docs/Plugins.md | 171 ++ docs/Problem-Solving-Examples-in-RxJava.md | 80 + docs/README.md | 24 + docs/Reactive-Streams.md | 121 ++ docs/Scheduler.md | 3 + docs/String-Observables.md | 9 + docs/Subject.md | 12 + docs/The-RxJava-Android-Module.md | 110 ++ docs/Transforming-Observables.md | 10 + docs/What's-different-in-2.0.md | 972 +++++++++ docs/Writing-operators-for-2.0.md | 1746 +++++++++++++++++ docs/_Footer.md | 2 + docs/_Sidebar.md | 26 + docs/_Sidebar.md.md | 35 + 38 files changed, 6023 insertions(+) create mode 100644 docs/Additional-Reading.md create mode 100644 docs/Alphabetical-List-of-Observable-Operators.md create mode 100644 docs/Async-Operators.md create mode 100644 docs/Backpressure-(2.0).md create mode 100644 docs/Backpressure.md create mode 100644 docs/Blocking-Observable-Operators.md create mode 100644 docs/Combining-Observables.md create mode 100644 docs/Conditional-and-Boolean-Operators.md create mode 100644 docs/Connectable-Observable-Operators.md create mode 100644 docs/Creating-Observables.md create mode 100644 docs/Error-Handling-Operators.md create mode 100644 docs/Error-Handling.md create mode 100644 docs/Filtering-Observables.md create mode 100644 docs/Getting-Started.md create mode 100644 docs/Home.md create mode 100644 docs/How-To-Use-RxJava.md create mode 100644 docs/How-to-Contribute.md create mode 100644 docs/Implementing-Your-Own-Operators.md create mode 100644 docs/Implementing-custom-operators-(draft).md create mode 100644 docs/Mathematical-and-Aggregate-Operators.md create mode 100644 docs/Observable-Utility-Operators.md create mode 100644 docs/Observable.md create mode 100644 docs/Parallel-flows.md create mode 100644 docs/Phantom-Operators.md create mode 100644 docs/Plugins.md create mode 100644 docs/Problem-Solving-Examples-in-RxJava.md create mode 100644 docs/README.md create mode 100644 docs/Reactive-Streams.md create mode 100644 docs/Scheduler.md create mode 100644 docs/String-Observables.md create mode 100644 docs/Subject.md create mode 100644 docs/The-RxJava-Android-Module.md create mode 100644 docs/Transforming-Observables.md create mode 100644 docs/What's-different-in-2.0.md create mode 100644 docs/Writing-operators-for-2.0.md create mode 100644 docs/_Footer.md create mode 100644 docs/_Sidebar.md create mode 100644 docs/_Sidebar.md.md diff --git a/docs/Additional-Reading.md b/docs/Additional-Reading.md new file mode 100644 index 0000000000..8693b414c6 --- /dev/null +++ b/docs/Additional-Reading.md @@ -0,0 +1,50 @@ +(A more complete and up-to-date list of resources can be found at the reactivex.io site: [[http://reactivex.io/tutorials.html]]) + +# Introducing Reactive Programming +* [Introduction to Rx](http://www.introtorx.com/): a free, on-line book by Lee Campbell +* [The introduction to Reactive Programming you've been missing](https://gist.github.com/staltz/868e7e9bc2a7b8c1f754) by Andre Staltz +* [Mastering Observables](http://docs.couchbase.com/developer/java-2.0/observables.html) from the Couchbase documentation +* [Reactive Programming in Java 8 With RxJava](http://pluralsight.com/training/Courses/TableOfContents/reactive-programming-java-8-rxjava), a course designed by Russell Elledge +* [33rd Degree Reactive Java](http://www.slideshare.net/tkowalcz/33rd-degree-reactive-java) by Tomasz Kowalczewski +* [What Every Hipster Should Know About Functional Reactive Programming](http://www.infoq.com/presentations/game-functional-reactive-programming) - Bodil Stokke demos the creation of interactive game mechanics in RxJS +* [Your Mouse is a Database](http://queue.acm.org/detail.cfm?id=2169076) by Erik Meijer +* [A Playful Introduction to Rx](https://www.youtube.com/watch?v=WKore-AkisY) a video lecture by Erik Meijer +* Wikipedia: [Reactive Programming](http://en.wikipedia.org/wiki/Reactive_programming) and [Functional Reactive Programming](http://en.wikipedia.org/wiki/Functional_reactive_programming) +* [What is Reactive Programming?](http://blog.hackhands.com/overview-of-reactive-programming/) a video presentation by Jafar Husain. +* [2 minute introduction to Rx](https://medium.com/@andrestaltz/2-minute-introduction-to-rx-24c8ca793877) by André Staltz +* StackOverflow: [What is (functional) reactive programming?](http://stackoverflow.com/a/1030631/1946802) +* [The Reactive Manifesto](http://www.reactivemanifesto.org/) +* Grokking RxJava, [Part 1: The Basics](http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/), [Part 2: Operator, Operator](http://blog.danlew.net/2014/09/22/grokking-rxjava-part-2/), [Part 3: Reactive with Benefits](http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3/), [Part 4: Reactive Android](http://blog.danlew.net/2014/10/08/grokking-rxjava-part-4/) - published in Sep/Oct 2014 by Daniel Lew +* [FRP on Android](http://slides.com/yaroslavheriatovych/frponandroid#/) - publish in Jan 2014 by Yaroslav Heriatovych + +# How Netflix Is Using RxJava +* LambdaJam Chicago 2013: [Functional Reactive Programming in the Netflix API](https://speakerdeck.com/benjchristensen/functional-reactive-programming-in-the-netflix-api-lambdajam-2013) by Ben Christensen +* QCon London 2013 presentation: [Functional Reactive Programming in the Netflix API](http://www.infoq.com/presentations/netflix-functional-rx) and a related [interview](http://www.infoq.com/interviews/christensen-hystrix-rxjava) with Ben Christensen +* [Functional Reactive in the Netflix API with RxJava](http://techblog.netflix.com/2013/02/rxjava-netflix-api.html) by Ben Christensen and Jafar Husain +* [Optimizing the Netflix API](http://techblog.netflix.com/2013/01/optimizing-netflix-api.html) by Ben Christensen +* [Reactive Programming at Netflix](http://techblog.netflix.com/2013/01/reactive-programming-at-netflix.html) by Jafar Husain + +# RxScala +* [RxJava: Reactive Extensions in Scala](http://www.youtube.com/watch?v=tOMK_FYJREw&feature=youtu.be): video of Ben Christensen and Matt Jacobs presenting at SF Scala + +# Rx.NET +* [rx.codeplex.com](https://rx.codeplex.com) +* [Rx Design Guidelines (PDF)](http://go.microsoft.com/fwlink/?LinkID=205219) +* [Channel 9 MSDN videos on Reactive Extensions](http://channel9.msdn.com/Tags/reactive+extensions) +* [Beginner’s Guide to the Reactive Extensions](http://msdn.microsoft.com/en-us/data/gg577611) +* [Rx Is now Open Source](http://www.hanselman.com/blog/ReactiveExtensionsRxIsNowOpenSource.aspx) by Scott Hanselman +* [Rx Workshop: Observables vs. Events](http://channel9.msdn.com/Series/Rx-Workshop/Rx-Workshop-Observables-versus-Events) +* [Rx Workshop: Unified Programming Model](http://channel9.msdn.com/Series/Rx-Workshop/Rx-Workshop-Unified-Programming-Model) +* [MSDN Rx forum](http://social.msdn.microsoft.com/Forums/en-US/home?forum=rx) + +# RxJS +* [the RxJS github site](http://reactive-extensions.github.io/RxJS/) +* An interactive tutorial: [Functional Programming in Javascript](http://jhusain.github.io/learnrx/) and [an accompanying lecture (video)](http://www.youtube.com/watch?v=LB4lhFJBBq0) by Jafar Husain +* [Netflix JavaScript Talks - Async JavaScript with Reactive Extensions](https://www.youtube.com/watch?v=XRYN2xt11Ek) video of a talk by Jafar Husain about the Rx way of programming +* [RxJS](https://xgrommx.github.io/rx-book/), an on-line book by @xgrommx +* [Journey from procedural to reactive Javascript with stops](http://bahmutov.calepin.co/journey-from-procedural-to-reactive-javascript-with-stops.html) by Gleb Bahmutov + +# Miscellany +* [RxJava Observables and Akka Actors](http://onoffswitch.net/rxjava-observables-akka-actors/) by Anton Kropp +* [Vert.x and RxJava](http://slid.es/petermd/eclipsecon2014) by @petermd +* [RxJava in Different Flavours of Java](http://instil.co/2014/08/05/rxjava-in-different-flavours-of-java/): Java 7 and Java 8 implementations of the same code \ No newline at end of file diff --git a/docs/Alphabetical-List-of-Observable-Operators.md b/docs/Alphabetical-List-of-Observable-Operators.md new file mode 100644 index 0000000000..86495638c0 --- /dev/null +++ b/docs/Alphabetical-List-of-Observable-Operators.md @@ -0,0 +1,250 @@ +* **`aggregate( )`** — _see [**`reduce( )`**](Mathematical-and-Aggregate-Operators#reduce)_ +* [**`all( )`**](Conditional-and-Boolean-Operators#all) — determine whether all items emitted by an Observable meet some criteria +* [**`amb( )`**](Conditional-and-Boolean-Operators#amb) — given two or more source Observables, emits all of the items from the first of these Observables to emit an item +* **`ambWith( )`** — _instance version of [**`amb( )`**](Conditional-and-Boolean-Operators#amb)_ +* [**`and( )`**](Combining-Observables#and-then-and-when) — combine the emissions from two or more source Observables into a `Pattern` (`rxjava-joins`) +* **`apply( )`** (scala) — _see [**`create( )`**](Creating-Observables#create)_ +* **`asObservable( )`** (kotlin) — _see [**`from( )`**](Creating-Observables#from) (et al.)_ +* [**`asyncAction( )`**](Async-Operators#toasync-or-asyncaction-or-asyncfunc) — convert an Action into an Observable that executes the Action and emits its return value (`rxjava-async`) +* [**`asyncFunc( )`**](Async-Operators#toasync-or-asyncaction-or-asyncfunc) — convert a function into an Observable that executes the function and emits its return value (`rxjava-async`) +* [**`averageDouble( )`**](Mathematical-and-Aggregate-Operators#averageinteger-averagelong-averagefloat-and-averagedouble) — calculates the average of Doubles emitted by an Observable and emits this average (`rxjava-math`) +* [**`averageFloat( )`**](Mathematical-and-Aggregate-Operators#averageinteger-averagelong-averagefloat-and-averagedouble) — calculates the average of Floats emitted by an Observable and emits this average (`rxjava-math`) +* [**`averageInteger( )`**](Mathematical-and-Aggregate-Operators#averageinteger-averagelong-averagefloat-and-averagedouble) — calculates the average of Integers emitted by an Observable and emits this average (`rxjava-math`) +* [**`averageLong( )`**](Mathematical-and-Aggregate-Operators#averageinteger-averagelong-averagefloat-and-averagedouble) — calculates the average of Longs emitted by an Observable and emits this average (`rxjava-math`) +* **`blocking( )`** (clojure) — _see [**`toBlocking( )`**](Blocking-Observable-Operators)_ +* [**`buffer( )`**](Transforming-Observables#buffer) — periodically gather items from an Observable into bundles and emit these bundles rather than emitting the items one at a time +* [**`byLine( )`**](String-Observables#byline) (`StringObservable`) — converts an Observable of Strings into an Observable of Lines by treating the source sequence as a stream and splitting it on line-endings +* [**`cache( )`**](Observable-Utility-Operators#cache) — remember the sequence of items emitted by the Observable and emit the same sequence to future Subscribers +* [**`cast( )`**](Transforming-Observables#cast) — cast all items from the source Observable into a particular type before reemitting them +* **`catch( )`** (clojure) — _see [**`onErrorResumeNext( )`**](Error-Handling-Operators#onerrorresumenext)_ +* [**`chunkify( )`**](Phantom-Operators#chunkify) — returns an iterable that periodically returns a list of items emitted by the source Observable since the last list (⁇) +* [**`collect( )`**](Mathematical-and-Aggregate-Operators#collect) — collects items emitted by the source Observable into a single mutable data structure and returns an Observable that emits this structure +* [**`combineLatest( )`**](Combining-Observables#combinelatest) — when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function +* **`combineLatestWith( )`** (scala) — _instance version of [**`combineLatest( )`**](Combining-Observables#combinelatest)_ +* [**`concat( )`**](Mathematical-and-Aggregate-Operators#concat) — concatenate two or more Observables sequentially +* [**`concatMap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable) — transform the items emitted by an Observable into Observables, then flatten this into a single Observable, without interleaving +* **`concatWith( )`** — _instance version of [**`concat( )`**](Mathematical-and-Aggregate-Operators#concat)_ +* [**`connect( )`**](Connectable-Observable-Operators#connectableobservableconnect) — instructs a Connectable Observable to begin emitting items +* **`cons( )`** (clojure) — _see [**`concat( )`**](Mathematical-and-Aggregate-Operators#concat)_ +* [**`contains( )`**](Conditional-and-Boolean-Operators#contains) — determine whether an Observable emits a particular item or not +* [**`count( )`**](Mathematical-and-Aggregate-Operators#count-and-countlong) — counts the number of items emitted by an Observable and emits this count +* [**`countLong( )`**](Mathematical-and-Aggregate-Operators#count-and-countlong) — counts the number of items emitted by an Observable and emits this count +* [**`create( )`**](Creating-Observables#create) — create an Observable from scratch by means of a function +* **`cycle( )`** (clojure) — _see [**`repeat( )`**](Creating-Observables#repeat)_ +* [**`debounce( )`**](Filtering-Observables#throttlewithtimeout-or-debounce) — only emit an item from the source Observable after a particular timespan has passed without the Observable emitting any other items +* [**`decode( )`**](String-Observables#decode) (`StringObservable`) — convert a stream of multibyte characters into an Observable that emits byte arrays that respect character boundaries +* [**`defaultIfEmpty( )`**](Conditional-and-Boolean-Operators#defaultifempty) — emit items from the source Observable, or emit a default item if the source Observable completes after emitting no items +* [**`defer( )`**](Creating-Observables#defer) — do not create the Observable until a Subscriber subscribes; create a fresh Observable on each subscription +* [**`deferFuture( )`**](Async-Operators#deferfuture) — convert a Future that returns an Observable into an Observable, but do not attempt to get the Observable that the Future returns until a Subscriber subscribes (`rxjava-async`) +* [**`deferCancellableFuture( )`**](Phantom-Operators#fromcancellablefuture-startcancellablefuture-and-defercancellablefuture-) — convert a Future that returns an Observable into an Observable in a way that monitors the subscription status of the Observable to determine whether to halt work on the Future, but do not attempt to get the returned Observable until a Subscriber subscribes (⁇)(`rxjava-async`) +* [**`delay( )`**](Observable-Utility-Operators#delay) — shift the emissions from an Observable forward in time by a specified amount +* [**`dematerialize( )`**](Observable-Utility-Operators#dematerialize) — convert a materialized Observable back into its non-materialized form +* [**`distinct( )`**](Filtering-Observables#distinct) — suppress duplicate items emitted by the source Observable +* [**`distinctUntilChanged( )`**](Filtering-Observables#distinctuntilchanged) — suppress duplicate consecutive items emitted by the source Observable +* **`do( )`** (clojure) — _see [**`doOnEach( )`**](Observable-Utility-Operators#dooneach)_ +* [**`doOnCompleted( )`**](Observable-Utility-Operators#dooncompleted) — register an action to take when an Observable completes successfully +* [**`doOnEach( )`**](Observable-Utility-Operators#dooneach) — register an action to take whenever an Observable emits an item +* [**`doOnError( )`**](Observable-Utility-Operators#doonerror) — register an action to take when an Observable completes with an error +* **`doOnNext( )`** — _see [**`doOnEach( )`**](Observable-Utility-Operators#dooneach)_ +* **`doOnRequest( )`** — register an action to take when items are requested from an Observable via reactive-pull backpressure (⁇) +* [**`doOnSubscribe( )`**](Observable-Utility-Operators#doonsubscribe) — register an action to take when an observer subscribes to an Observable +* [**`doOnTerminate( )`**](Observable-Utility-Operators#doonterminate) — register an action to take when an Observable completes, either successfully or with an error +* [**`doOnUnsubscribe( )`**](Observable-Utility-Operators#doonunsubscribe) — register an action to take when an observer unsubscribes from an Observable +* [**`doWhile( )`**](Conditional-and-Boolean-Operators#dowhile) — emit the source Observable's sequence, and then repeat the sequence as long as a condition remains true (`contrib-computation-expressions`) +* **`drop( )`** (scala/clojure) — _see [**`skip( )`**](Filtering-Observables#skip)_ +* **`dropRight( )`** (scala) — _see [**`skipLast( )`**](Filtering-Observables#skiplast)_ +* **`dropUntil( )`** (scala) — _see [**`skipUntil( )`**](Conditional-and-Boolean-Operators#skipuntil)_ +* **`dropWhile( )`** (scala) — _see [**`skipWhile( )`**](Conditional-and-Boolean-Operators#skipwhile)_ +* **`drop-while( )`** (clojure) — _see [**`skipWhile( )`**](Conditional-and-Boolean-Operators#skipwhile)_ +* [**`elementAt( )`**](Filtering-Observables#elementat) — emit item _n_ emitted by the source Observable +* [**`elementAtOrDefault( )`**](Filtering-Observables#elementatordefault) — emit item _n_ emitted by the source Observable, or a default item if the source Observable emits fewer than _n_ items +* [**`empty( )`**](Creating-Observables#empty-error-and-never) — create an Observable that emits nothing and then completes +* [**`encode( )`**](String-Observables#encode) (`StringObservable`) — transform an Observable that emits strings into an Observable that emits byte arrays that respect character boundaries of multibyte characters in the original strings +* [**`error( )`**](Creating-Observables#empty-error-and-never) — create an Observable that emits nothing and then signals an error +* **`every( )`** (clojure) — _see [**`all( )`**](Conditional-and-Boolean-Operators#all)_ +* [**`exists( )`**](Conditional-and-Boolean-Operators#exists-and-isempty) — determine whether an Observable emits any items or not +* [**`filter( )`**](Filtering-Observables#filter) — filter items emitted by an Observable +* **`finally( )`** (clojure) — _see [**`finallyDo( )`**](Observable-Utility-Operators#finallydo)_ +* **`filterNot( )`** (scala) — _see [**`filter( )`**](Filtering-Observables#filter)_ +* [**`finallyDo( )`**](Observable-Utility-Operators#finallydo) — register an action to take when an Observable completes +* [**`first( )`**](Filtering-Observables#first-and-takefirst) (`Observable`) — emit only the first item emitted by an Observable, or the first item that meets some condition +* [**`first( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`) — emit only the first item emitted by an Observable, or the first item that meets some condition +* [**`firstOrDefault( )`**](Filtering-Observables#firstordefault) (`Observable`) — emit only the first item emitted by an Observable, or the first item that meets some condition, or a default value if the source Observable is empty +* [**`firstOrDefault( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`) — emit only the first item emitted by an Observable, or the first item that meets some condition, or a default value if the source Observable is empty +* **`firstOrElse( )`** (scala) — _see [**`firstOrDefault( )`**](Filtering-Observables#firstordefault) or [**`firstOrDefault( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`)_ +* [**`flatMap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable) — transform the items emitted by an Observable into Observables, then flatten this into a single Observable +* [**`flatMapIterable( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable) — create Iterables corresponding to each emission from a source Observable and merge the results into a single Observable +* **`flatMapIterableWith( )`** (scala) — _instance version of [**`flatMapIterable( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ +* **`flatMapWith( )`** (scala) — _instance version of [**`flatmap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ +* **`flatten( )`** (scala) — _see [**`merge( )`**](Combining-Observables#merge)_ +* **`flattenDelayError( )`** (scala) — _see [**`mergeDelayError( )`**](Combining-Observables#mergedelayerror)_ +* **`foldLeft( )`** (scala) — _see [**`reduce( )`**](Mathematical-and-Aggregate-Operators#reduce)_ +* **`forall( )`** (scala) — _see [**`all( )`**](Conditional-and-Boolean-Operators#all)_ +* **`forEach( )`** (`Observable`) — _see [**`subscribe( )`**](Observable#onnext-oncompleted-and-onerror)_ +* [**`forEach( )`**](Blocking-Observable-Operators#foreach) (`BlockingObservable`) — invoke a function on each item emitted by the Observable; block until the Observable completes +* [**`forEachFuture( )`**](Async-Operators#foreachfuture) (`Async`) — pass Subscriber methods to an Observable but also have it behave like a Future that blocks until it completes (`rxjava-async`) +* [**`forEachFuture( )`**](Phantom-Operators#foreachfuture) (`BlockingObservable`)— create a futureTask that will invoke a specified function on each item emitted by an Observable (⁇) +* [**`forIterable( )`**](Phantom-Operators#foriterable) — apply a function to the elements of an Iterable to create Observables which are then concatenated (⁇) +* [**`from( )`**](Creating-Observables#from) — convert an Iterable, a Future, or an Array into an Observable +* [**`from( )`**](String-Observables#from) (`StringObservable`) — convert a stream of characters or a Reader into an Observable that emits byte arrays or Strings +* [**`fromAction( )`**](Async-Operators#fromaction) — convert an Action into an Observable that invokes the action and emits its result when a Subscriber subscribes (`rxjava-async`) +* [**`fromCallable( )`**](Async-Operators#fromcallable) — convert a Callable into an Observable that invokes the callable and emits its result or exception when a Subscriber subscribes (`rxjava-async`) +* [**`fromCancellableFuture( )`**](Phantom-Operators#fromcancellablefuture-startcancellablefuture-and-defercancellablefuture-) — convert a Future into an Observable in a way that monitors the subscription status of the Observable to determine whether to halt work on the Future, but do not attempt to get the Future's value until a Subscriber subscribes (⁇)(`rxjava-async`) +* **`fromFunc0( )`** — _see [**`fromCallable( )`**](Async-Operators#fromcallable) (`rxjava-async`)_ +* [**`fromFuture( )`**](Phantom-Operators#fromfuture) — convert a Future into an Observable, but do not attempt to get the Future's value until a Subscriber subscribes (⁇) +* [**`fromRunnable( )`**](Async-Operators#fromrunnable) — convert a Runnable into an Observable that invokes the runable and emits its result when a Subscriber subscribes (`rxjava-async`) +* [**`generate( )`**](Phantom-Operators#generate-and-generateabsolutetime) — create an Observable that emits a sequence of items as generated by a function of your choosing (⁇) +* [**`generateAbsoluteTime( )`**](Phantom-Operators#generate-and-generateabsolutetime) — create an Observable that emits a sequence of items as generated by a function of your choosing, with each item emitted at an item-specific time (⁇) +* **`generator( )`** (clojure) — _see [**`generate( )`**](Phantom-Operators#generate-and-generateabsolutetime)_ +* [**`getIterator( )`**](Blocking-Observable-Operators#transformations-tofuture-toiterable-and-getiterator) — convert the sequence emitted by the Observable into an Iterator +* [**`groupBy( )`**](Transforming-Observables#groupby) — divide an Observable into a set of Observables that emit groups of items from the original Observable, organized by key +* **`group-by( )`** (clojure) — _see [**`groupBy( )`**](Transforming-Observables#groupby)_ +* [**`groupByUntil( )`**](Phantom-Operators#groupbyuntil) — a variant of the [`groupBy( )`](Transforming-Observables#groupby) operator that closes any open GroupedObservable upon a signal from another Observable (⁇) +* [**`groupJoin( )`**](Combining-Observables#join-and-groupjoin) — combine the items emitted by two Observables whenever one item from one Observable falls within a window of duration specified by an item emitted by the other Observable +* **`head( )`** (scala) — _see [**`first( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`)_ +* **`headOption( )`** (scala) — _see [**`firstOrDefault( )`**](Filtering-Observables#firstordefault) or [**`firstOrDefault( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`)_ +* **`headOrElse( )`** (scala) — _see [**`firstOrDefault( )`**](Filtering-Observables#firstordefault) or [**`firstOrDefault( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`)_ +* [**`ifThen( )`**](Conditional-and-Boolean-Operators#ifthen) — only emit the source Observable's sequence if a condition is true, otherwise emit an empty or default sequence (`contrib-computation-expressions`) +* [**`ignoreElements( )`**](Filtering-Observables#ignoreelements) — discard the items emitted by the source Observable and only pass through the error or completed notification +* [**`interval( )`**](Creating-Observables#interval) — create an Observable that emits a sequence of integers spaced by a given time interval +* **`into( )`** (clojure) — _see [**`reduce( )`**](Mathematical-and-Aggregate-Operators#reduce)_ +* [**`isEmpty( )`**](Conditional-and-Boolean-Operators#exists-and-isempty) — determine whether an Observable emits any items or not +* **`items( )`** (scala) — _see [**`just( )`**](Creating-Observables#just)_ +* [**`join( )`**](Combining-Observables#join-and-groupjoin) — combine the items emitted by two Observables whenever one item from one Observable falls within a window of duration specified by an item emitted by the other Observable +* [**`join( )`**](String-Observables#join) (`StringObservable`) — converts an Observable that emits a sequence of strings into an Observable that emits a single string that concatenates them all, separating them by a specified string +* [**`just( )`**](Creating-Observables#just) — convert an object into an Observable that emits that object +* [**`last( )`**](Blocking-Observable-Operators#last-and-lastordefault) (`BlockingObservable`) — block until the Observable completes, then return the last item emitted by the Observable +* [**`last( )`**](Filtering-Observables#last) (`Observable`) — emit only the last item emitted by the source Observable +* **`lastOption( )`** (scala) — _see [**`lastOrDefault( )`**](Filtering-Observables#lastOrDefault) or [**`lastOrDefault( )`**](Blocking-Observable-Operators#last-and-lastordefault) (`BlockingObservable`)_ +* [**`lastOrDefault( )`**](Blocking-Observable-Operators#last-and-lastordefault) (`BlockingObservable`) — block until the Observable completes, then return the last item emitted by the Observable or a default item if there is no last item +* [**`lastOrDefault( )`**](Filtering-Observables#lastOrDefault) (`Observable`) — emit only the last item emitted by an Observable, or a default value if the source Observable is empty +* **`lastOrElse( )`** (scala) — _see [**`lastOrDefault( )`**](Filtering-Observables#lastOrDefault) or [**`lastOrDefault( )`**](Blocking-Observable-Operators#last-and-lastordefault) (`BlockingObservable`)_ +* [**`latest( )`**](Blocking-Observable-Operators#latest) — returns an iterable that blocks until or unless the Observable emits an item that has not been returned by the iterable, then returns the latest such item +* **`length( )`** (scala) — _see [**`count( )`**](Mathematical-and-Aggregate-Operators#count-and-countlong)_ +* **`limit( )`** — _see [**`take( )`**](Filtering-Observables#take)_ +* **`longCount( )`** (scala) — _see [**`countLong( )`**](Mathematical-and-Aggregate-Operators#count-and-countlong)_ +* [**`map( )`**](Transforming-Observables#map) — transform the items emitted by an Observable by applying a function to each of them +* **`mapcat( )`** (clojure) — _see [**`concatMap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ +* **`mapMany( )`** — _see: [**`flatMap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ +* [**`materialize( )`**](Observable-Utility-Operators#materialize) — convert an Observable into a list of Notifications +* [**`max( )`**](Mathematical-and-Aggregate-Operators#max) — emits the maximum value emitted by a source Observable (`rxjava-math`) +* [**`maxBy( )`**](Mathematical-and-Aggregate-Operators#maxby) — emits the item emitted by the source Observable that has the maximum key value (`rxjava-math`) +* [**`merge( )`**](Combining-Observables#merge) — combine multiple Observables into one +* [**`mergeDelayError( )`**](Combining-Observables#mergedelayerror) — combine multiple Observables into one, allowing error-free Observables to continue before propagating errors +* **`merge-delay-error( )`** (clojure) — _see [**`mergeDelayError( )`**](Combining-Observables#mergedelayerror)_ +* **`mergeMap( )`** * — _see: [**`flatMap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ +* **`mergeMapIterable( )`** — _see: [**`flatMapIterable( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ +* **`mergeWith( )`** — _instance version of [**`merge( )`**](Combining-Observables#merge)_ +* [**`min( )`**](Mathematical-and-Aggregate-Operators#min) — emits the minimum value emitted by a source Observable (`rxjava-math`) +* [**`minBy( )`**](Mathematical-and-Aggregate-Operators#minby) — emits the item emitted by the source Observable that has the minimum key value (`rxjava-math`) +* [**`mostRecent( )`**](Blocking-Observable-Operators#mostrecent) — returns an iterable that always returns the item most recently emitted by the Observable +* [**`multicast( )`**](Phantom-Operators#multicast) — represents an Observable as a Connectable Observable +* [**`never( )`**](Creating-Observables#empty-error-and-never) — create an Observable that emits nothing at all +* [**`next( )`**](Blocking-Observable-Operators#next) — returns an iterable that blocks until the Observable emits another item, then returns that item +* **`nonEmpty( )`** (scala) — _see [**`isEmpty( )`**](Conditional-and-Boolean-Operators#exists-and-isempty)_ +* **`nth( )`** (clojure) — _see [**`elementAt( )`**](Filtering-Observables#elementat) and [**`elementAtOrDefault( )`**](Filtering-Observables#elementatordefault)_ +* [**`observeOn( )`**](Observable-Utility-Operators#observeon) — specify on which Scheduler a Subscriber should observe the Observable +* [**`ofType( )`**](Filtering-Observables#oftype) — emit only those items from the source Observable that are of a particular class +* [**`onBackpressureBlock( )`**](Backpressure) — block the Observable's thread until the Observer is ready to accept more items from the Observable (⁇) +* [**`onBackpressureBuffer( )`**](Backpressure) — maintain a buffer of all emissions from the source Observable and emit them to downstream Subscribers according to the requests they generate +* [**`onBackpressureDrop( )`**](Backpressure) — drop emissions from the source Observable unless there is a pending request from a downstream Subscriber, in which case emit enough items to fulfill the request +* [**`onErrorFlatMap( )`**](Phantom-Operators#onerrorflatmap) — instructs an Observable to emit a sequence of items whenever it encounters an error (⁇) +* [**`onErrorResumeNext( )`**](Error-Handling-Operators#onerrorresumenext) — instructs an Observable to emit a sequence of items if it encounters an error +* [**`onErrorReturn( )`**](Error-Handling-Operators#onerrorreturn) — instructs an Observable to emit a particular item when it encounters an error +* [**`onExceptionResumeNext( )`**](Error-Handling-Operators#onexceptionresumenext) — instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable) +* **`orElse( )`** (scala) — _see [**`defaultIfEmpty( )`**](Conditional-and-Boolean-Operators#defaultifempty)_ +* [**`parallel( )`**](Phantom-Operators#parallel) — split the work done on the emissions from an Observable into multiple Observables each operating on its own parallel thread (⁇) +* [**`parallelMerge( )`**](Phantom-Operators#parallelmerge) — combine multiple Observables into smaller number of Observables (⁇) +* [**`pivot( )`**](Phantom-Operators#pivot) — combine multiple sets of grouped observables so that they are arranged primarily by group rather than by set (⁇) +* [**`publish( )`**](Connectable-Observable-Operators#observablepublish) — represents an Observable as a Connectable Observable +* [**`publishLast( )`**](Phantom-Operators#publishlast) — represent an Observable as a Connectable Observable that emits only the last item emitted by the source Observable (⁇) +* [**`range( )`**](Creating-Observables#range) — create an Observable that emits a range of sequential integers +* [**`reduce( )`**](Mathematical-and-Aggregate-Operators#reduce) — apply a function to each emitted item, sequentially, and emit only the final accumulated value +* **`reductions( )`** (clojure) — _see [**`scan( )`**](Transforming-Observables#scan)_ +* [**`refCount( )`**](Connectable-Observable-Operators#connectableobservablerefcount) — makes a Connectable Observable behave like an ordinary Observable +* [**`repeat( )`**](Creating-Observables#repeat) — create an Observable that emits a particular item or sequence of items repeatedly +* [**`repeatWhen( )`**](Creating-Observables#repeatwhen) — create an Observable that emits a particular item or sequence of items repeatedly, depending on the emissions of a second Observable +* [**`replay( )`**](Connectable-Observable-Operators#observablereplay) — ensures that all Subscribers see the same sequence of emitted items, even if they subscribe after the Observable begins emitting the items +* **`rest( )`** (clojure) — _see [**`next( )`**](Blocking-Observable-Operators#next)_ +* **`return( )`** (clojure) — _see [**`just( )`**](Creating-Observables#just)_ +* [**`retry( )`**](Error-Handling-Operators#retry) — if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error +* [**`retrywhen( )`**](Error-Handling-Operators#retrywhen) — if a source Observable emits an error, pass that error to another Observable to determine whether to resubscribe to the source +* [**`runAsync( )`**](Async-Operators#runasync) — returns a `StoppableObservable` that emits multiple actions as generated by a specified Action on a Scheduler (`rxjava-async`) +* [**`sample( )`**](Filtering-Observables#sample-or-throttlelast) — emit the most recent items emitted by an Observable within periodic time intervals +* [**`scan( )`**](Transforming-Observables#scan) — apply a function to each item emitted by an Observable, sequentially, and emit each successive value +* **`seq( )`** (clojure) — _see [**`getIterator( )`**](Blocking-Observable-Operators#transformations-tofuture-toiterable-and-getiterator)_ +* [**`sequenceEqual( )`**](Conditional-and-Boolean-Operators#sequenceequal) — test the equality of sequences emitted by two Observables +* **`sequenceEqualWith( )`** (scala) — _instance version of [**`sequenceEqual( )`**](Conditional-and-Boolean-Operators#sequenceequal)_ +* [**`serialize( )`**](Observable-Utility-Operators#serialize) — force an Observable to make serialized calls and to be well-behaved +* **`share( )`** — _see [**`refCount( )`**](Connectable-Observable-Operators#connectableobservablerefcount)_ +* [**`single( )`**](Blocking-Observable-Operators#single-and-singleordefault) (`BlockingObservable`) — if the source Observable completes after emitting a single item, return that item, otherwise throw an exception +* [**`single( )`**](Observable-Utility-Operators#single-and-singleordefault) (`Observable`) — if the source Observable completes after emitting a single item, emit that item, otherwise notify of an exception +* **`singleOption( )`** (scala) — _see [**`singleOrDefault( )`**](Blocking-Observable-Operators#single-and-singleordefault) (`BlockingObservable`)_ +* [**`singleOrDefault( )`**](Blocking-Observable-Operators#single-and-singleordefault) (`BlockingObservable`) — if the source Observable completes after emitting a single item, return that item, otherwise return a default item +* [**`singleOrDefault( )`**](Observable-Utility-Operators#single-and-singleordefault) (`Observable`) — if the source Observable completes after emitting a single item, emit that item, otherwise emit a default item +* **`singleOrElse( )`** (scala) — _see [**`singleOrDefault( )`**](Observable-Utility-Operators#single-and-singleordefault)_ +* **`size( )`** (scala) — _see [**`count( )`**](Mathematical-and-Aggregate-Operators#count-and-countlong)_ +* [**`skip( )`**](Filtering-Observables#skip) — ignore the first _n_ items emitted by an Observable +* [**`skipLast( )`**](Filtering-Observables#skiplast) — ignore the last _n_ items emitted by an Observable +* [**`skipUntil( )`**](Conditional-and-Boolean-Operators#skipuntil) — discard items emitted by a source Observable until a second Observable emits an item, then emit the remainder of the source Observable's items +* [**`skipWhile( )`**](Conditional-and-Boolean-Operators#skipwhile) — discard items emitted by an Observable until a specified condition is false, then emit the remainder +* **`sliding( )`** (scala) — _see [**`window( )`**](Transforming-Observables#window)_ +* **`slidingBuffer( )`** (scala) — _see [**`buffer( )`**](Transforming-Observables#buffer)_ +* [**`split( )`**](String-Observables#split) (`StringObservable`) — converts an Observable of Strings into an Observable of Strings that treats the source sequence as a stream and splits it on a specified regex boundary +* [**`start( )`**](Async-Operators#start) — create an Observable that emits the return value of a function (`rxjava-async`) +* [**`startCancellableFuture( )`**](Phantom-Operators#fromcancellablefuture-startcancellablefuture-and-defercancellablefuture-) — convert a function that returns Future into an Observable that emits that Future's return value in a way that monitors the subscription status of the Observable to determine whether to halt work on the Future (⁇)(`rxjava-async`) +* [**`startFuture( )`**](Async-Operators#startfuture) — convert a function that returns Future into an Observable that emits that Future's return value (`rxjava-async`) +* [**`startWith( )`**](Combining-Observables#startwith) — emit a specified sequence of items before beginning to emit the items from the Observable +* [**`stringConcat( )`**](String-Observables#stringconcat) (`StringObservable`) — converts an Observable that emits a sequence of strings into an Observable that emits a single string that concatenates them all +* [**`subscribeOn( )`**](Observable-Utility-Operators#subscribeon) — specify which Scheduler an Observable should use when its subscription is invoked +* [**`sumDouble( )`**](Mathematical-and-Aggregate-Operators#suminteger-sumlong-sumfloat-and-sumdouble) — adds the Doubles emitted by an Observable and emits this sum (`rxjava-math`) +* [**`sumFloat( )`**](Mathematical-and-Aggregate-Operators#suminteger-sumlong-sumfloat-and-sumdouble) — adds the Floats emitted by an Observable and emits this sum (`rxjava-math`) +* [**`sumInteger( )`**](Mathematical-and-Aggregate-Operators#suminteger-sumlong-sumfloat-and-sumdouble) — adds the Integers emitted by an Observable and emits this sum (`rxjava-math`) +* [**`sumLong( )`**](Mathematical-and-Aggregate-Operators#suminteger-sumlong-sumfloat-and-sumdouble) — adds the Longs emitted by an Observable and emits this sum (`rxjava-math`) +* **`switch( )`** (scala) — _see [**`switchOnNext( )`**](Combining-Observables#switchonnext)_ +* [**`switchCase( )`**](Conditional-and-Boolean-Operators#switchcase) — emit the sequence from a particular Observable based on the results of an evaluation (`contrib-computation-expressions`) +* [**`switchMap( )`**](Transforming-Observables#switchmap) — transform the items emitted by an Observable into Observables, and mirror those items emitted by the most-recently transformed Observable +* [**`switchOnNext( )`**](Combining-Observables#switchonnext) — convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently emitted of those Observables +* **`synchronize( )`** — _see [**`serialize( )`**](Observable-Utility-Operators#serialize)_ +* [**`take( )`**](Filtering-Observables#take) — emit only the first _n_ items emitted by an Observable +* [**`takeFirst( )`**](Filtering-Observables#first-and-takefirst) — emit only the first item emitted by an Observable, or the first item that meets some condition +* [**`takeLast( )`**](Filtering-Observables#takelast) — only emit the last _n_ items emitted by an Observable +* [**`takeLastBuffer( )`**](Filtering-Observables#takelastbuffer) — emit the last _n_ items emitted by an Observable, as a single list item +* **`takeRight( )`** (scala) — _see [**`last( )`**](Filtering-Observables#last) (`Observable`) or [**`takeLast( )`**](Filtering-Observables#takelast)_ +* [**`takeUntil( )`**](Conditional-and-Boolean-Operators#takeuntil) — emits the items from the source Observable until a second Observable emits an item +* [**`takeWhile( )`**](Conditional-and-Boolean-Operators#takewhile) — emit items emitted by an Observable as long as a specified condition is true, then skip the remainder +* **`take-while( )`** (clojure) — _see [**`takeWhile( )`**](Conditional-and-Boolean-Operators#takewhile)_ +* [**`then( )`**](Combining-Observables#and-then-and-when) — transform a series of `Pattern` objects via a `Plan` template (`rxjava-joins`) +* [**`throttleFirst( )`**](Filtering-Observables#throttlefirst) — emit the first items emitted by an Observable within periodic time intervals +* [**`throttleLast( )`**](Filtering-Observables#sample-or-throttlelast) — emit the most recent items emitted by an Observable within periodic time intervals +* [**`throttleWithTimeout( )`**](Filtering-Observables#throttlewithtimeout-or-debounce) — only emit an item from the source Observable after a particular timespan has passed without the Observable emitting any other items +* **`throw( )`** (clojure) — _see [**`error( )`**](Creating-Observables#empty-error-and-never)_ +* [**`timeInterval( )`**](Observable-Utility-Operators#timeinterval) — emit the time lapsed between consecutive emissions of a source Observable +* [**`timeout( )`**](Filtering-Observables#timeout) — emit items from a source Observable, but issue an exception if no item is emitted in a specified timespan +* [**`timer( )`**](Creating-Observables#timer) — create an Observable that emits a single item after a given delay +* [**`timestamp( )`**](Observable-Utility-Operators#timestamp) — attach a timestamp to every item emitted by an Observable +* [**`toAsync( )`**](Async-Operators#toasync-or-asyncaction-or-asyncfunc) — convert a function or Action into an Observable that executes the function and emits its return value (`rxjava-async`) +* [**`toBlocking( )`**](Blocking-Observable-Operators) — transform an Observable into a BlockingObservable +* **`toBlockingObservable( )`** - _see [**`toBlocking( )`**](Blocking-Observable-Operators)_ +* [**`toFuture( )`**](Blocking-Observable-Operators#transformations-tofuture-toiterable-and-getiterator) — convert the Observable into a Future +* [**`toIterable( )`**](Blocking-Observable-Operators#transformations-tofuture-toiterable-and-getiterator) — convert the sequence emitted by the Observable into an Iterable +* **`toIterator( )`** — _see [**`getIterator( )`**](Blocking-Observable-Operators#transformations-tofuture-toiterable-and-getiterator)_ +* [**`toList( )`**](Mathematical-and-Aggregate-Operators#tolist) — collect all items from an Observable and emit them as a single List +* [**`toMap( )`**](Mathematical-and-Aggregate-Operators#tomap-and-tomultimap) — convert the sequence of items emitted by an Observable into a map keyed by a specified key function +* [**`toMultimap( )`**](Mathematical-and-Aggregate-Operators#tomap-and-tomultimap) — convert the sequence of items emitted by an Observable into an ArrayList that is also a map keyed by a specified key function +* **`toSeq( )`** (scala) — _see [**`toList( )`**](Mathematical-and-Aggregate-Operators#tolist)_ +* [**`toSortedList( )`**](Mathematical-and-Aggregate-Operators#tosortedlist) — collect all items from an Observable and emit them as a single, sorted List +* **`tumbling( )`** (scala) — _see [**`window( )`**](Transforming-Observables#window)_ +* **`tumblingBuffer( )`** (scala) — _see [**`buffer( )`**](Transforming-Observables#buffer)_ +* [**`using( )`**](Observable-Utility-Operators#using) — create a disposable resource that has the same lifespan as an Observable +* [**`when( )`**](Combining-Observables#and-then-and-when) — convert a series of `Plan` objects into an Observable (`rxjava-joins`) +* **`where( )`** — _see: [**`filter( )`**](Filtering-Observables#filter)_ +* [**`whileDo( )`**](Conditional-and-Boolean-Operators#whiledo) — if a condition is true, emit the source Observable's sequence and then repeat the sequence as long as the condition remains true (`contrib-computation-expressions`) +* [**`window( )`**](Transforming-Observables#window) — periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time +* [**`zip( )`**](Combining-Observables#zip) — combine sets of items emitted by two or more Observables together via a specified function and emit items based on the results of this function +* **`zipWith( )`** — _instance version of [**`zip( )`**](Combining-Observables#zip)_ +* **`zipWithIndex( )`** (scala) — _see [**`zip( )`**](Combining-Observables#zip)_ +* **`++`** (scala) — _see [**`concat( )`**](Mathematical-and-Aggregate-Operators#concat)_ +* **`+:`** (scala) — _see [**`startWith( )`**](Combining-Observables#startwith)_ + +(⁇) — this proposed operator is not part of RxJava 1.0 \ No newline at end of file diff --git a/docs/Async-Operators.md b/docs/Async-Operators.md new file mode 100644 index 0000000000..17e3bda561 --- /dev/null +++ b/docs/Async-Operators.md @@ -0,0 +1,11 @@ +The following operators are part of the distinct `rxjava-async` module. They are used to convert synchronous methods into Observables. + +* [**`start( )`**](http://reactivex.io/documentation/operators/start.html) — create an Observable that emits the return value of a function +* [**`toAsync( )` or `asyncAction( )` or `asyncFunc( )`**](http://reactivex.io/documentation/operators/start.html) — convert a function or Action into an Observable that executes the function and emits its return value +* [**`startFuture( )`**](http://reactivex.io/documentation/operators/start.html) — convert a function that returns Future into an Observable that emits that Future's return value +* [**`deferFuture( )`**](http://reactivex.io/documentation/operators/start.html) — convert a Future that returns an Observable into an Observable, but do not attempt to get the Observable that the Future returns until a Subscriber subscribes +* [**`forEachFuture( )`**](http://reactivex.io/documentation/operators/start.html) — pass Subscriber methods to an Observable but also have it behave like a Future that blocks until it completes +* [**`fromAction( )`**](http://reactivex.io/documentation/operators/start.html) — convert an Action into an Observable that invokes the action and emits its result when a Subscriber subscribes +* [**`fromCallable( )`**](http://reactivex.io/documentation/operators/start.html) — convert a Callable into an Observable that invokes the callable and emits its result or exception when a Subscriber subscribes +* [**`fromRunnable( )`**](http://reactivex.io/documentation/operators/start.html) — convert a Runnable into an Observable that invokes the runable and emits its result when a Subscriber subscribes +* [**`runAsync( )`**](http://reactivex.io/documentation/operators/start.html) — returns a `StoppableObservable` that emits multiple actions as generated by a specified Action on a Scheduler \ No newline at end of file diff --git a/docs/Backpressure-(2.0).md b/docs/Backpressure-(2.0).md new file mode 100644 index 0000000000..61361d21c4 --- /dev/null +++ b/docs/Backpressure-(2.0).md @@ -0,0 +1,503 @@ +*Originally contributed to [StackOverflow Documentation](https://stackoverflow.com/documentation/rx-java/2341/backpressure) (going [defunct](https://meta.stackoverflow.com/questions/354217/sunsetting-documentation/)) by [@akarnokd](https://github.com/akarnokd), revised for version 2.x.* + +# Introduction + +**Backpressure** is when in an `Flowable` processing pipeline, some asynchronous stages can't process the values fast enough and need a way to tell the upstream producer to slow down. + +The classic case of the need for backpressure is when the producer is a hot source: + +```java + PublishProcessor source = PublishProcessor.create(); + + source + .observeOn(Schedulers.computation()) + .subscribe(v -> compute(v), Throwable::printStackTrace); + + for (int i = 0; i < 1_000_000; i++) { + source.onNext(i); + } + + Thread.sleep(10_000); +``` + +In this example, the main thread will produce 1 million items to an end consumer which is processing it on a background thread. It is likely the `compute(int)` method takes some time but the overhead of the `Flowable` operator chain may also add to the time it takes to process items. However, the producing thread with the for loop can't know this and keeps `onNext`ing. + +Internally, asynchronous operators have buffers to hold such elements until they can be processed. In the classical Rx.NET and early RxJava, these buffers were unbounded, meaning that they would likely hold nearly all 1 million elements from the example. The problem starts when there are, for example, 1 billion elements or the same 1 million sequence appears 1000 times in a program, leading to `OutOfMemoryError` and generally slowdowns due to excessive GC overhead. + +Similar to how error-handling became a first-class citizen and received operators to deal with it (via `onErrorXXX` operators), backpressure is another property of dataflows that the programmer has to think about and handle (via `onBackpressureXXX` operators). + +Beyond the `PublishProcessor`above, there are other operators that don't support backpressure, mostly due to functional reasons. For example, the operator `interval` emits values periodically, backpressuring it would lead to shifting in the period relative to a wall clock. + +In modern RxJava, most asynchronous operators now have a bounded internal buffer, like `observeOn` above and any attempt to overflow this buffer will terminate the whole sequence with `MissingBackpressureException`. The documentation of each operator has a description about its backpressure behavior. + +However, backpressure is present more subtly in regular cold sequences (which don't and shouldn't yield `MissingBackpressureException`). If the first example is rewritten: + + Flowable.range(1, 1_000_000) + .observeOn(Schedulers.computation()) + .subscribe(v -> compute(v), Throwable::printStackTrace); + + Thread.sleep(10_000); + +There is no error and everything runs smoothly with small memory usage. The reason for this is that many source operators can "generate" values on demand and thus the operator `observeOn` can tell the `range` generate at most so many values the `observeOn` buffer can hold at once without overflow. + +This negotiation is based on the computer science concept of co-routines (I call you, you call me). The operator `range` sends a callback, in the form of an implementation of the `org.reactivestreams.Subscription` interface, to the `observeOn` by calling its (inner `Subscriber`'s) `onSubscribe`. In return, the `observeOn` calls `Subscription.request(n)` with a value to tell the `range` it is allowed to produce (i.e., `onNext` it) that many **additional** elements. It is then the `observeOn`'s responsibility to call the `request` method in the right time and with the right value to keep the data flowing but not overflowing. + +Expressing backpressure in end-consumers is rarely necessary (because they are synchronous in respect to their immediate upstream and backpressure naturally happens due to call-stack blocking), but it may be easier to understand the workings of it: + +```java + Flowable.range(1, 1_000_000) + .subscribe(new DisposableSubscriber() { + @Override + public void onStart() { + request(1); + } + + public void onNext(Integer v) { + compute(v); + + request(1); + } + + @Override + public void onError(Throwable ex) { + ex.printStackTrace(); + } + + @Override + public void onComplete() { + System.out.println("Done!"); + } + }); +``` + +Here the `onStart` implementation indicates `range` to produce its first value, which is then received in `onNext`. Once the `compute(int)` finishes, the another value is then requested from `range`. In a naive implementation of `range`, such call would recursively call `onNext`, leading to `StackOverflowError` which is of course undesirable. + +To prevent this, operators use so-called trampolining logic that prevents such reentrant calls. In `range`'s terms, it will remember that there was a `request(1)` call while it called `onNext()` and once `onNext()` returns, it will make another round and call `onNext()` with the next integer value. Therefore, if the two are swapped, the example still works the same: + +```java + @Override + public void onNext(Integer v) { + request(1); + + compute(v); + } +``` + +However, this is not true for `onStart`. Although the `Flowable` infrastructure guarantees it will be called at most once on each `Subscriber`, the call to `request(1)` may trigger the emission of an element right away. If one has initialization logic after the call to `request(1)` which is needed by `onNext`, you may end up with exceptions: + +```java + Flowable.range(1, 1_000_000) + .subscribe(new DisposableSubscriber() { + + String name; + + @Override + public void onStart() { + request(1); + + name = "RangeExample"; + } + + @Override + public void onNext(Integer v) { + compute(name.length + v); + + request(1); + } + + // ... rest is the same + }); +``` + +In this synchronous case, a `NullPointerException` will be thrown immediately while still executing `onStart`. A more subtle bug happens if the call to `request(1)` triggers an asynchronous call to `onNext` on some other thread and reading `name` in `onNext` races writing it in `onStart` post `request`. + +Therefore, one should do all field initialization in `onStart` or even before that and call `request()` last. Implementations of `request()` in operators ensure proper happens-before relation (or in other terms, memory release or full fence) when necessary. + +# The onBackpressureXXX operators + +Most developers encounter backpressure when their application fails with `MissingBackpressureException` and the exception usually points to the `observeOn` operator. The actual cause is usually the non-backpressured use of `PublishProcessor`, `timer()` or `interval()` or custom operators created via `create()`. + +There are several ways of dealing with such situations. + +## Increasing the buffer sizes + +Sometimes such overflows happen due to bursty sources. Suddenly, the user taps the screen too quickly and `observeOn`'s default 16-element internal buffer on Android overflows. + +Most backpressure-sensitive operators in the recent versions of RxJava now allow programmers to specify the size of their internal buffers. The relevant parameters are usually called `bufferSize`, `prefetch` or `capacityHint`. Given the overflowing example in the introduction, we can just increase the buffer size of `observeOn` to have enough room for all values. + +```java + PublishProcessor source = PublishProcessor.create(); + + source.observeOn(Schedulers.computation(), 1024 * 1024) + .subscribe(e -> { }, Throwable::printStackTrace); + + for (int i = 0; i < 1_000_000; i++) { + source.onNext(i); + } +``` + +Note however that generally, this may be only a temporary fix as the overflow can still happen if the source overproduces the predicted buffer size. In this case, one can use one of the following operators. + +## Batching/skipping values with standard operators + +In case the source data can be processed more efficiently in batch, one can reduce the likelihood of `MissingBackpressureException` by using one of the standard batching operators (by size and/or by time). + +``` + PublishProcessor source = PublishProcessor.create(); + + source + .buffer(1024) + .observeOn(Schedulers.computation(), 1024) + .subscribe(list -> { + list.parallelStream().map(e -> e * e).first(); + }, Throwable::printStackTrace); + + for (int i = 0; i < 1_000_000; i++) { + source.onNext(i); + } +``` + +If some of the values can be safely ignored, one can use the sampling (with time or another `Flowable`) and throttling operators (`throttleFirst`, `throttleLast`, `throttleWithTimeout`). + +```java + PublishProcessor source = PublishProcessor.create(); + + source + .sample(1, TimeUnit.MILLISECONDS) + .observeOn(Schedulers.computation(), 1024) + .subscribe(v -> compute(v), Throwable::printStackTrace); + + for (int i = 0; i < 1_000_000; i++) { + source.onNext(i); + } +``` + +Note hovewer that these operators only reduce the rate of value reception by the downstream and thus they may still lead to `MissingBackpressureException`. + +## onBackpressureBuffer() + +This operator in its parameterless form reintroduces an unbounded buffer between the upstream source and the downstream operator. Being unbounded means as long as the JVM doesn't run out of memory, it can handle almost any amount coming from a bursty source. + +```java + Flowable.range(1, 1_000_000) + .onBackpressureBuffer() + .observeOn(Schedulers.computation(), 8) + .subscribe(e -> { }, Throwable::printStackTrace); +``` + +In this example, the `observeOn` goes with a very low buffer size yet there is no `MissingBackpressureException` as `onBackpressureBuffer` soaks up all the 1 million values and hands over small batches of it to `observeOn`. + +Note however that `onBackpressureBuffer` consumes its source in an unbounded manner, that is, without applying any backpressure to it. This has the consequence that even a backpressure-supporting source such as `range` will be completely realized. + +There are 4 additional overloads of `onBackpressureBuffer` + +### onBackpressureBuffer(int capacity) + +This is a bounded version that signals `BufferOverflowError`in case its buffer reaches the given capacity. + +```java + Flowable.range(1, 1_000_000) + .onBackpressureBuffer(16) + .observeOn(Schedulers.computation()) + .subscribe(e -> { }, Throwable::printStackTrace); +``` + +The relevance of this operator is decreasing as more and more operators now allow setting their buffer sizes. For the rest, this gives an opportunity to "extend their internal buffer" by having a larger number with `onBackpressureBuffer` than their default. + +### onBackpressureBuffer(int capacity, Action onOverflow) + +This overload calls a (shared) action in case an overflow happens. Its usefulness is rather limited as there is no other information provided about the overflow than the current call stack. + +### onBackpressureBuffer(int capacity, Action onOverflow, BackpressureOverflowStrategy strategy) + +This overload is actually more useful as it let's one define what to do in case the capacity has been reached. The `BackpressureOverflow.Strategy` is an interface actually but the class `BackpressureOverflow` offers 4 static fields with implementations of it representing typical actions: + + - `ON_OVERFLOW_ERROR`: this is the default behavior of the previous two overloads, signalling a `BufferOverflowException` + - `ON_OVERFLOW_DEFAULT`: currently it is the same as `ON_OVERFLOW_ERROR` + - `ON_OVERFLOW_DROP_LATEST` : if an overflow would happen, the current value will be simply ignored and only the old values will be delivered once the downstream requests. + - `ON_OVERFLOW_DROP_OLDEST` : drops the oldest element in the buffer and adds the current value to it. + +```java + Flowable.range(1, 1_000_000) + .onBackpressureBuffer(16, () -> { }, + BufferOverflowStrategy.ON_OVERFLOW_DROP_OLDEST) + .observeOn(Schedulers.computation()) + .subscribe(e -> { }, Throwable::printStackTrace); +``` + +Note that the last two strategies cause discontinuity in the stream as they drop out elements. In addition, they won't signal `BufferOverflowException`. + +## onBackpressureDrop() + +Whenever the downstream is not ready to receive values, this operator will drop that elemenet from the sequence. One can think of it as a 0 capacity `onBackpressureBuffer` with strategy `ON_OVERFLOW_DROP_LATEST`. + +This operator is useful when one can safely ignore values from a source (such as mouse moves or current GPS location signals) as there will be more up-to-date values later on. + +```java + component.mouseMoves() + .onBackpressureDrop() + .observeOn(Schedulers.computation(), 1) + .subscribe(event -> compute(event.x, event.y)); +``` + +It may be useful in conjunction with the source operator `interval()`. For example, if one wants to perform some periodic background task but each iteration may last longer than the period, it is safe to drop the excess interval notification as there will be more later on: + +```java + Flowable.interval(1, TimeUnit.MINUTES) + .onBackpressureDrop() + .observeOn(Schedulers.io()) + .doOnNext(e -> networkCall.doStuff()) + .subscribe(v -> { }, Throwable::printStackTrace); +``` + +There exist one overload of this operator: `onBackpressureDrop(Consumer onDrop)` where the (shared) action is called with the value being dropped. This variant allows cleaning up the values themselves (e.g., releasing associated resources). + +## onBackpressureLatest() + +The final operator keeps only the latest value and practically overwrites older, undelivered values. One can think of this as a variant of the `onBackpressureBuffer` with a capacity of 1 and strategy of `ON_OVERFLOW_DROP_OLDEST`. + +Unlike `onBackpressureDrop` there is always a value available for consumption if the downstream happened to be lagging behind. This can be useful in some telemetry-like situations where the data may come in some bursty pattern but only the very latest is interesting for processing. + +For example, if the user clicks a lot on the screen, we'd still want to react to its latest input. + +```java + component.mouseClicks() + .onBackpressureLatest() + .observeOn(Schedulers.computation()) + .subscribe(event -> compute(event.x, event.y), Throwable::printStackTrace); +``` + +The use of `onBackpressureDrop` in this case would lead to a situation where the very last click gets dropped and leaves the user wondering why the business logic wasn't executed. + +# Creating backpressured datasources + +Creating backpressured data sources is the relatively easier task when dealing with backpressure in general because the library already offers static methods on `Flowable` that handle backpressure for the developer. We can distinguish two kinds of factory methods: cold "generators" that either return and generate elements based on downstream demand and hot "pushers" that usually bridge non-reactive and/or non-backpressurable data sources and layer some backpressure handling on top of them. + +## just + +The most basic backpressure aware source is created via `just`: + +```java + Flowable.just(1).subscribe(new DisposableSubscriber() { + @Override + public void onStart() { + request(0); + } + + @Override + public void onNext(Integer v) { + System.out.println(v); + } + + // the rest is omitted for brevity + } +``` + +Since we explicitly don't request in `onStart`, this will not print anything. `just` is great when there is a constant value we'd like to jump-start a sequence. + +Unfortunately, `just` is often mistaken for a way to compute something dynamically to be consumed by `Subscriber`s: + +```java + int counter; + + int computeValue() { + return ++counter; + } + + Flowable o = Flowable.just(computeValue()); + + o.subscribe(System.out:println); + o.subscribe(System.out:println); +``` + +Surprising to some, this prints 1 twice instead of printing 1 and 2 respectively. If the call is rewritten, it becomes obvious why it works so: + +```java + int temp = computeValue(); + + Flowable o = Flowable.just(temp); +``` + +The `computeValue` is called as part of the main routine and not in response to the subscribers subscribing. + +## fromCallable + +What people actually need is the method `fromCallable`: + +```java + Flowable o = Flowable.fromCallable(() -> computeValue()); +``` + +Here the `computeValue` is executed only when a subscriber subscribes and for each of them, printing the expected 1 and 2. Naturally, `fromCallable` also properly supports backpressure and won't emit the computed value unless requested. Note however that the computation does happen anyway. In case the computation itself should be delayed until the downstream actually requests, we can use `just` with `map`: + +```java + Flowable.just("This doesn't matter").map(ignored -> computeValue())... +``` + +`just` won't emit its constant value until requested when it is mapped to the result of the `computeValue`, still called for each subscriber individually. + +## fromArray + +If the data is already available as an array of objects, a list of objects or any `Iterable` source, the respective `from` overloads will handle the backpressure and emission of such sources: + +```java + Flowable.fromArray(1, 2, 3, 4, 5).subscribe(System.out::println); +``` + +For convenience (and avoiding warnings about generic array creation) there are 2 to 10 argument overloads to `just` that internally delegate to `from`. + +The `fromIterable` also gives an interesting opportunity. Many value generation can be expressed in a form of a state-machine. Each requested element triggers a state transition and computation of the returned value. + +Writing such state machines as `Iterable`s is somewhat complicated (but still easier than writing an `Flowable` for consuming it) and unlike C#, Java doesn't have any support from the compiler to build such state machines by simply writing classically looking code (with `yield return` and `yield break`). Some libraries offer some help, such as Google Guava's `AbstractIterable` and IxJava's `Ix.generate()` and `Ix.forloop()`. These are by themselves worthy of a full series so let's see some very basic `Iterable` source that repeats some constant value indefinitely: + +```java + Iterable iterable = () -> new Iterator() { + @Override + public boolean hasNext() { + return true; + } + + @Override + public Integer next() { + return 1; + } + }; + + Flowable.fromIterable(iterable).take(5).subscribe(System.out::println); +``` + +If we'd consume the `iterator` via classic for-loop, that would result in an infinite loop. Since we build an `Flowable` out of it, we can express our will to consume only the first 5 of it and then stop requesting anything. This is the true power of lazily evaluating and computing inside `Flowable`s. + +## generate() + +Sometimes, the data source to be converted into the reactive world itself is synchronous (blocking) and pull-like, that is, we have to call some `get` or `read` method to get the next piece of data. One could, of course, turn that into an `Iterable` but when such sources are associated with resources, we may leak those resources if the downstream unsubscribes the sequence before it would end. + +To handle such cases, RxJava has the `generate` factory method family. + +```java + Flowable o = Flowable.generate( + () -> new FileInputStream("data.bin"), + (inputstream, output) -> { + try { + int abyte = inputstream.read(); + if (abyte < 0) { + output.onComplete(); + } else { + output.onNext(abyte); + } + } catch (IOException ex) { + output.onError(ex); + } + return inputstream; + }, + inputstream -> { + try { + inputstream.close(); + } catch (IOException ex) { + RxJavaPlugins.onError(ex); + } + } + ); +``` + +Generally, `generate` uses 3 callbacks. + +The first callbacks allows one to create a per-subscriber state, such as the `FileInputStream` in the example; the file will be opened independently to each individual subscriber. + +The second callback takes this state object and provides an output `Observer` whose `onXXX` methods can be called to emit values. This callback is executed as many times as the downstream requested. At each invocation, it has to call `onNext` at most once optionally followed by either `onError` or `onComplete`. In the example we call `onComplete()` if the read byte is negative, indicating and end of file, and call `onError` in case the read throws an `IOException`. + +The final callback gets invoked when the downstream unsubscribes (closing the inputstream) or when the previous callback called the terminal methods; it allows freeing up resources. Since not all sources need all these features, the static methods of `Flowable.generate` let's one create instances without them. + +Unfortunately, many method calls across the JVM and other libraries throw checked exceptions and need to be wrapped into `try-catch`es as the functional interfaces used by this class don't allow throwing checked exceptions. + +Of course, we can imitate other typical sources, such as an unbounded range with it: + +```java + Flowable.generate( + () -> 0, + (current, output) -> { + output.onNext(current); + return current + 1; + }, + e -> { } + ); +``` + +In this setup, the `current` starts out with `0` and next time the lambda is invoked, the parameter `current` now holds `1`. + +*(Remark: the 1.x classes `SyncOnSubscribe` and `AsyncOnSubscribe` are no longer available.)* + +## create(emitter) + +Sometimes, the source to be wrapped into an `Flowable` is already hot (such as mouse moves) or cold but not backpressurable in its API (such as an asynchronous network callback). + +To handle such cases, a recent version of RxJava introduced the `create(emitter)` factory method. It takes two parameters: + + - a callback that will be called with an instance of the `Emitter` interface for each incoming subscriber, + - a `BackpressureStrategy` enumeration that mandates the developer to specify the backpressure behavior to be applied. It has the usual modes, similar to `onBackpressureXXX` in addition to signalling a `MissingBackpressureException` or simply ignoring such overflow inside it altogether. + +Note that it currently doesn't support additional parameters to those backpressure modes. If one needs those customization, using `NONE` as the backpressure mode and applying the relevant `onBackpressureXXX` on the resulting `Flowable` is the way to go. + +The first typical case for its use when one wants to interact with a push-based source, such as GUI events. Those APIs feature some form of `addListener`/`removeListener` calls that one can utilize: + +```java + Flowable.create(emitter -> { + ActionListener al = e -> { + emitter.onNext(e); + }; + + button.addActionListener(al); + + emitter.setCancellation(() -> + button.removeListener(al)); + + }, BackpressureStrategy.BUFFER); +``` + +The `Emitter` is relatively straightforward to use; one can call `onNext`, `onError` and `onComplete` on it and the operator handles backpressure and unsubscription management on its own. In addition, if the wrapped API supports cancellation (such as the listener removal in the example), one can use the `setCancellation` (or `setSubscription` for `Subscription`-like resources) to register a cancellation callback that gets invoked when the downstream unsubscribes or the `onError`/`onComplete` is called on the provided `Emitter`instance. + +These methods allow only a single resource to be associated with the emitter at a time and setting a new one unsubscribes the old one automatically. If one has to handle multiple resources, create a `CompositeSubscription`, associate it with the emitter and then add further resources to the `CompositeSubscription` itself: + +```java + Flowable.create(emitter -> { + CompositeSubscription cs = new CompositeSubscription(); + + Worker worker = Schedulers.computation().createWorker(); + + ActionListener al = e -> { + emitter.onNext(e); + }; + + button.addActionListener(al); + + cs.add(worker); + cs.add(Subscriptions.create(() -> + button.removeActionListener(al)); + + emitter.setSubscription(cs); + + }, BackpressureMode.BUFFER); +``` + +The second scenario usually involves some asynchronous, callback-based API that has to be converted into an `Flowable`. + +```java + Flowable.create(emitter -> { + + someAPI.remoteCall(new Callback() { + @Override + public void onSuccess(Data data) { + emitter.onNext(data); + emitter.onComplete(); + } + + @Override + public void onFailure(Exception error) { + emitter.onError(error); + } + }); + + }, BackpressureMode.LATEST); +``` + +In this case, the delegation works the same way. Unfortunately, usually, these classical callback-style APIs don't support cancellation, but if they do, one can setup their cancellation just like in the previoius examples (with perhaps a more involved way though). Note the use of the `LATEST` backpressure mode; if we know there will be only a single value, we don't need the `BUFFER` strategy as it allocates a default 128 element long buffer (that grows as necessary) that is never going to be fully utilized. \ No newline at end of file diff --git a/docs/Backpressure.md b/docs/Backpressure.md new file mode 100644 index 0000000000..d9e7bfa65a --- /dev/null +++ b/docs/Backpressure.md @@ -0,0 +1,175 @@ +# Introduction + +In RxJava it is not difficult to get into a situation in which an Observable is emitting items more rapidly than an operator or subscriber can consume them. This presents the problem of what to do with such a growing backlog of unconsumed items. + +For example, imagine using the [`zip`](http://reactivex.io/documentation/operators/zip.html) operator to zip together two infinite Observables, one of which emits items twice as frequently as the other. A naive implementation of the `zip` operator would have to maintain an ever-expanding buffer of items emitted by the faster Observable to eventually combine with items emitted by the slower one. This could cause RxJava to seize an unwieldy amount of system resources. + +There are a variety of strategies with which you can exercise flow control and backpressure in RxJava in order to alleviate the problems caused when a quickly-producing Observable meets a slow-consuming observer. This page explains some of these strategies, and also shows you how you can design your own Observables and Observable operators to respect requests for flow control. + +## Hot and cold Observables, and multicasted Observables + +A _cold_ Observable emits a particular sequence of items, but can begin emitting this sequence when its Observer finds it to be convenient, and at whatever rate the Observer desires, without disrupting the integrity of the sequence. For example if you convert a static Iterable into an Observable, that Observable will emit the same sequence of items no matter when it is later subscribed to or how frequently those items are observed. Examples of items emitted by a cold Observable might include the results of a database query, file retrieval, or web request. + +A _hot_ Observable begins generating items to emit immediately when it is created. Subscribers typically begin observing the sequence of items emitted by a hot Observable from somewhere in the middle of the sequence, beginning with the first item emitted by the Observable subsequent to the establishment of the subscription. Such an Observable emits items at its own pace, and it is up to its observers to keep up. Examples of items emitted by a hot Observable might include mouse & keyboard events, system events, or stock prices. + +When a cold Observable is _multicast_ (when it is converted into a `ConnectableObservable` and its [`connect()`](http://reactivex.io/documentation/operators/connect.html) method is called), it effectively becomes _hot_ and for the purposes of backpressure and flow-control it should be treated as a hot Observable. + +Cold Observables are ideal for the reactive pull model of backpressure described below. Hot Observables typically do not cope well with a reactive pull model, and are better candidates for some of the other flow control strategies discussed on this page, such as the use of [the `onBackpressureBuffer` or `onBackpressureDrop` operators](http://reactivex.io/documentation/operators/backpressure.html), throttling, buffers, or windows. + +# Useful operators that avoid the need for backpressure + +Your first line of defense against the problems of over-producing Observables is to use some of the ordinary set of Observable operators to reduce the number of emitted items to a more manageable number. The examples in this section will show how you might use such operators to handle a bursty Observable like the one illustrated in the following marble diagram: + +​ + +By fine-tuning the parameters to these operators you can ensure that a slow-consuming observer is not overwhelmed by a fast-producing Observable. + +## Throttling + +Operators like [`sample( )` or `throttleLast( )`](http://reactivex.io/documentation/operators/sample.html), [`throttleFirst( )`](http://reactivex.io/documentation/operators/sample.html), and [`throttleWithTimeout( )` or `debounce( )`](http://reactivex.io/documentation/operators/debounce.html) allow you to regulate the rate at which an Observable emits items. + +The following diagrams show how you could use each of these operators on the bursty Observable shown above. + +### sample (or throttleLast) +The `sample` operator periodically "dips" into the sequence and emits only the most recently emitted item during each dip: + +​ +````groovy +Observable burstySampled = bursty.sample(500, TimeUnit.MILLISECONDS); +```` + +### throttleFirst +The `throttleFirst` operator is similar, but emits not the most recently emitted item, but the first item that was emitted after the previous "dip": + +​ +````groovy +Observable burstyThrottled = bursty.throttleFirst(500, TimeUnit.MILLISECONDS); +```` + +### debounce (or throttleWithTimeout) +The `debounce` operator emits only those items from the source Observable that are not followed by another item within a specified duration: + +​ +````groovy +Observable burstyDebounced = bursty.debounce(10, TimeUnit.MILLISECONDS); +```` + +## Buffers and windows + +You can also use an operator like [`buffer( )`](http://reactivex.io/documentation/operators/buffer.html) or [`window( )`](http://reactivex.io/documentation/operators/window.html) to collect items from the over-producing Observable and then emit them, less-frequently, as collections (or Observables) of items. The slow consumer can then decide whether to process only one particular item from each collection, to process some combination of those items, or to schedule work to be done on each item in the collection, as appropriate. + +The following diagrams show how you could use each of these operators on the bursty Observable shown above. + +### buffer + +You could, for example, close and emit a buffer of items from the bursty Observable periodically, at a regular interval of time: + +​ +````groovy +Observable> burstyBuffered = bursty.buffer(500, TimeUnit.MILLISECONDS); +```` + +Or you could get fancy, and collect items in buffers during the bursty periods and emit them at the end of each burst, by using the `debounce` operator to emit a buffer closing indicator to the `buffer` operator: + +​ +````groovy +// we have to multicast the original bursty Observable so we can use it +// both as our source and as the source for our buffer closing selector: +Observable burstyMulticast = bursty.publish().refCount(); +// burstyDebounced will be our buffer closing selector: +Observable burstyDebounced = burstMulticast.debounce(10, TimeUnit.MILLISECONDS); +// and this, finally, is the Observable of buffers we're interested in: +Observable> burstyBuffered = burstyMulticast.buffer(burstyDebounced); +```` + +### window + +`window` is similar to `buffer`. One variant of `window` allows you to periodically emit Observable windows of items at a regular interval of time: + +​ +````groovy +Observable> burstyWindowed = bursty.window(500, TimeUnit.MILLISECONDS); +```` + +You could also choose to emit a new window each time you have collected a particular number of items from the source Observable: + +​ +````groovy +Observable> burstyWindowed = bursty.window(5); +```` + +# Callstack blocking as a flow-control alternative to backpressure + +Another way of handling an overproductive Observable is to block the callstack (parking the thread that governs the overproductive Observable). This has the disadvantage of going against the “reactive” and non-blocking model of Rx. However this can be a viable option if the problematic Observable is on a thread that can be blocked safely. Currently RxJava does not expose any operators to facilitate this. + +If the Observable, all of the operators that operate on it, and the observer that is subscribed to it, are all operating in the same thread, this effectively establishes a form of backpressure by means of callstack blocking. But be aware that many Observable operators do operate in distinct threads by default (the javadocs for those operators will indicate this). + +# How a subscriber establishes “reactive pull” backpressure + +When you subscribe to an `Observable` with a `Subscriber`, you can request reactive pull backpressure by calling `Subscriber.request(n)` in the `Subscriber`’s `onStart()` method (where _n_ is the maximum number of items you want the `Observable` to emit before the next `request()` call). + +Then, after handling this item (or these items) in `onNext()`, you can call `request()` again to instruct the `Observable` to emit another item (or items). Here is an example of a `Subscriber` that requests one item at a time from `someObservable`: + +````java +someObservable.subscribe(new Subscriber() { + @Override + public void onStart() { + request(1); + } + + @Override + public void onCompleted() { + // gracefully handle sequence-complete + } + + @Override + public void onError(Throwable e) { + // gracefully handle error + } + + @Override + public void onNext(t n) { + // do something with the emitted item "n" + // request another item: + request(1); + } +}); +```` + +You can pass a magic number to `request`, `request(Long.MAX_VALUE)`, to disable reactive pull backpressure and to ask the Observable to emit items at its own pace. `request(0)` is a legal call, but has no effect. Passing values less than zero to `request` will cause an exception to be thrown. + +## Reactive pull backpressure isn’t magic + +Backpressure doesn’t make the problem of an overproducing Observable or an underconsuming Subscriber go away. It just moves the problem up the chain of operators to a point where it can be handled better. + +Let’s take a closer look at the problem of the uneven [`zip`](http://reactivex.io/documentation/operators/zip.html). + +You have two Observables, _A_ and _B_, where _B_ is inclined to emit items more frequently than _A_. When you try to `zip` these two Observables together, the `zip` operator combines item _n_ from _A_ and item _n_ from _B_, but meanwhile _B_ has also emitted items _n_+1 to _n_+_m_. The `zip` operator has to hold on to these items so it can combine them with items _n_+1 to _n_+_m_ from _A_ as they are emitted, but meanwhile _m_ keeps growing and so the size of the buffer needed to hold on to these items keeps increasing. + +You could attach a throttling operator to _B_, but this would mean ignoring some of the items _B_ emits, which might not be appropriate. What you’d really like to do is to signal to _B_ that it needs to slow down and then let _B_ decide how to do this in a way that maintains the integrity of its emissions. + +The reactive pull backpressure model lets you do this. It creates a sort of active pull from the Subscriber in contrast to the normal passive push Observable behavior. + +The `zip` operator as implemented in RxJava uses this technique. It maintains a small buffer of items for each source Observable, and it requests no more items from each source Observable than would fill its buffer. Each time `zip` emits an item, it removes the corresponding items from its buffers and requests exactly one more item from each of its source Observables. + +(Many RxJava operators exercise reactive pull backpressure. Some operators do not need to use this variety of backpressure, as they operate in the same thread as the Observable they operate on, and so they exert a form of blocking backpressure simply by not giving the Observable the opportunity to emit another item until they have finished processing the previous one. For other operators, backpressure is inappropriate as they have been explicitly designed to deal with flow control in other ways. The RxJava javadocs for those operators that are methods of the Observable class indicate which ones do not use reactive pull backpressure and why.) + +For this to work, though, Observables _A_ and _B_ must respond correctly to the `request()`. If an Observable has not been written to support reactive pull backpressure (such support is not a requirement for Observables), you can apply one of the following operators to it, each of which forces a simple form of backpressure behavior: + +
                +
                onBackpressureBuffer
                +
                maintains a buffer of all emissions from the source Observable and emits them to downstream Subscribers according to the requests they generate

                an experimental version of this operator (not available in RxJava 1.0) allows you to set the capacity of the buffer; applying this operator will cause the resulting Observable to terminate with an error if this buffer is overrun​
                +
                onBackpressureDrop
                +
                drops emissions from the source Observable unless there is a pending request from a downstream Subscriber, in which case it will emit enough items to fulfill the request
                +
                onBackpressureBlock (experimental, not in RxJava 1.0)
                +
                blocks the thread on which the source Observable is operating until such time as a Subscriber issues a request for items, and then unblocks the thread only so long as there are pending requests
                +
                + +If you do not apply any of these operators to an Observable that does not support backpressure, _and_ if either you as the Subscriber or some operator between you and the Observable attempts to apply reactive pull backpressure, you will encounter a `MissingBackpressureException` which you will be notified of via your `onError()` callback. + +# Further reading + +If the standard operators are providing the expected behavior, [one can write custom operators in RxJava](https://github.com/ReactiveX/RxJava/wiki/Implementing-custom-operators-(draft)). + +# See also +* [RxJava 0.20.0-RC1 release notes](https://github.com/ReactiveX/RxJava/releases/tag/0.20.0-RC1) \ No newline at end of file diff --git a/docs/Blocking-Observable-Operators.md b/docs/Blocking-Observable-Operators.md new file mode 100644 index 0000000000..64d6e1b40a --- /dev/null +++ b/docs/Blocking-Observable-Operators.md @@ -0,0 +1,49 @@ +This section explains the [`BlockingObservable`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html) subclass. A Blocking Observable extends the ordinary Observable class by providing a set of operators on the items emitted by the Observable that block. + +To transform an `Observable` into a `BlockingObservable`, use the [`Observable.toBlocking( )`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toBlocking()) method or the [`BlockingObservable.from( )`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#from(rx.Observable)) method. + +* [**`forEach( )`**](http://reactivex.io/documentation/operators/subscribe.html) — invoke a function on each item emitted by the Observable; block until the Observable completes +* [**`first( )`**](http://reactivex.io/documentation/operators/first.html) — block until the Observable emits an item, then return the first item emitted by the Observable +* [**`firstOrDefault( )`**](http://reactivex.io/documentation/operators/first.html) — block until the Observable emits an item or completes, then return the first item emitted by the Observable or a default item if the Observable did not emit an item +* [**`last( )`**](http://reactivex.io/documentation/operators/last.html) — block until the Observable completes, then return the last item emitted by the Observable +* [**`lastOrDefault( )`**](http://reactivex.io/documentation/operators/last.html) — block until the Observable completes, then return the last item emitted by the Observable or a default item if there is no last item +* [**`mostRecent( )`**](http://reactivex.io/documentation/operators/first.html) — returns an iterable that always returns the item most recently emitted by the Observable +* [**`next( )`**](http://reactivex.io/documentation/operators/takelast.html) — returns an iterable that blocks until the Observable emits another item, then returns that item +* [**`latest( )`**](http://reactivex.io/documentation/operators/first.html) — returns an iterable that blocks until or unless the Observable emits an item that has not been returned by the iterable, then returns that item +* [**`single( )`**](http://reactivex.io/documentation/operators/first.html) — if the Observable completes after emitting a single item, return that item, otherwise throw an exception +* [**`singleOrDefault( )`**](http://reactivex.io/documentation/operators/first.html) — if the Observable completes after emitting a single item, return that item, otherwise return a default item +* [**`toFuture( )`**](http://reactivex.io/documentation/operators/to.html) — convert the Observable into a Future +* [**`toIterable( )`**](http://reactivex.io/documentation/operators/to.html) — convert the sequence emitted by the Observable into an Iterable +* [**`getIterator( )`**](http://reactivex.io/documentation/operators/to.html) — convert the sequence emitted by the Observable into an Iterator + +> This documentation accompanies its explanations with a modified form of "marble diagrams." Here is how these marble diagrams represent Blocking Observables: + + + +#### see also: +* javadoc: `BlockingObservable` +* javadoc: `toBlocking()` +* javadoc: `BlockingObservable.from()` + +## Appendix: similar blocking and non-blocking operators + + + + + + + + + + + + + + + + + + + + +
                operatorresult when it acts onequivalent in Rx.NET
                Observable that emits multiple itemsObservable that emits one itemObservable that emits no items
                Observable.firstthe first itemthe single itemNoSuchElementfirstAsync
                BlockingObservable.firstthe first itemthe single itemNoSuchElementfirst
                Observable.firstOrDefaultthe first itemthe single itemthe default itemfirstOrDefaultAsync
                BlockingObservable.firstOrDefaultthe first itemthe single itemthe default itemfirstOrDefault
                Observable.lastthe last itemthe single itemNoSuchElementlastAsync
                BlockingObservable.lastthe last itemthe single itemNoSuchElementlast
                Observable.lastOrDefaultthe last itemthe single itemthe default itemlastOrDefaultAsync
                BlockingObservable.lastOrDefaultthe last itemthe single itemthe default itemlastOrDefault
                Observable.singleIllegal Argumentthe single itemNoSuchElementsingleAsync
                BlockingObservable.singleIllegal Argumentthe single itemNoSuchElementsingle
                Observable.singleOrDefaultIllegal Argumentthe single itemthe default itemsingleOrDefaultAsync
                BlockingObservable.singleOrDefaultIllegal Argumentthe single itemthe default itemsingleOrDefault
                \ No newline at end of file diff --git a/docs/Combining-Observables.md b/docs/Combining-Observables.md new file mode 100644 index 0000000000..2a60e64bd2 --- /dev/null +++ b/docs/Combining-Observables.md @@ -0,0 +1,12 @@ +This section explains operators you can use to combine multiple Observables. + +* [**`startWith( )`**](http://reactivex.io/documentation/operators/startwith.html) — emit a specified sequence of items before beginning to emit the items from the Observable +* [**`merge( )`**](http://reactivex.io/documentation/operators/merge.html) — combine multiple Observables into one +* [**`mergeDelayError( )`**](http://reactivex.io/documentation/operators/merge.html) — combine multiple Observables into one, allowing error-free Observables to continue before propagating errors +* [**`zip( )`**](http://reactivex.io/documentation/operators/zip.html) — combine sets of items emitted by two or more Observables together via a specified function and emit items based on the results of this function +* (`rxjava-joins`) [**`and( )`, `then( )`, and `when( )`**](http://reactivex.io/documentation/operators/and-then-when.html) — combine sets of items emitted by two or more Observables by means of `Pattern` and `Plan` intermediaries +* [**`combineLatest( )`**](http://reactivex.io/documentation/operators/combinelatest.html) — when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function +* [**`join( )` and `groupJoin( )`**](http://reactivex.io/documentation/operators/join.html) — combine the items emitted by two Observables whenever one item from one Observable falls within a window of duration specified by an item emitted by the other Observable +* [**`switchOnNext( )`**](http://reactivex.io/documentation/operators/switch.html) — convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently emitted of those Observables + +> (`rxjava-joins`) — indicates that this operator is currently part of the optional `rxjava-joins` package under `rxjava-contrib` and is not included with the standard RxJava set of operators diff --git a/docs/Conditional-and-Boolean-Operators.md b/docs/Conditional-and-Boolean-Operators.md new file mode 100644 index 0000000000..f7ed64ce34 --- /dev/null +++ b/docs/Conditional-and-Boolean-Operators.md @@ -0,0 +1,21 @@ +This section explains operators with which you conditionally emit or transform Observables, or can do boolean evaluations of them: + +### Conditional Operators +* [**`amb( )`**](http://reactivex.io/documentation/operators/amb.html) — given two or more source Observables, emits all of the items from the first of these Observables to emit an item +* [**`defaultIfEmpty( )`**](http://reactivex.io/documentation/operators/defaultifempty.html) — emit items from the source Observable, or emit a default item if the source Observable completes after emitting no items +* (`rxjava-computation-expressions`) [**`doWhile( )`**](http://reactivex.io/documentation/operators/repeat.html) — emit the source Observable's sequence, and then repeat the sequence as long as a condition remains true +* (`rxjava-computation-expressions`) [**`ifThen( )`**](http://reactivex.io/documentation/operators/defer.html) — only emit the source Observable's sequence if a condition is true, otherwise emit an empty or default sequence +* [**`skipUntil( )`**](http://reactivex.io/documentation/operators/skipuntil.html) — discard items emitted by a source Observable until a second Observable emits an item, then emit the remainder of the source Observable's items +* [**`skipWhile( )`**](http://reactivex.io/documentation/operators/skipwhile.html) — discard items emitted by an Observable until a specified condition is false, then emit the remainder +* (`rxjava-computation-expressions`) [**`switchCase( )`**](http://reactivex.io/documentation/operators/defer.html) — emit the sequence from a particular Observable based on the results of an evaluation +* [**`takeUntil( )`**](http://reactivex.io/documentation/operators/takeuntil.html) — emits the items from the source Observable until a second Observable emits an item or issues a notification +* [**`takeWhile( )` and `takeWhileWithIndex( )`**](http://reactivex.io/documentation/operators/takewhile.html) — emit items emitted by an Observable as long as a specified condition is true, then skip the remainder +* (`rxjava-computation-expressions`) [**`whileDo( )`**](http://reactivex.io/documentation/operators/repeat.html) — if a condition is true, emit the source Observable's sequence and then repeat the sequence as long as the condition remains true + +> (`rxjava-computation-expressions`) — indicates that this operator is currently part of the optional `rxjava-computation-expressions` package under `rxjava-contrib` and is not included with the standard RxJava set of operators + +### Boolean Operators +* [**`all( )`**](http://reactivex.io/documentation/operators/all.html) — determine whether all items emitted by an Observable meet some criteria +* [**`contains( )`**](http://reactivex.io/documentation/operators/contains.html) — determine whether an Observable emits a particular item or not +* [**`exists( )` and `isEmpty( )`**](http://reactivex.io/documentation/operators/contains.html) — determine whether an Observable emits any items or not +* [**`sequenceEqual( )`**](http://reactivex.io/documentation/operators/sequenceequal.html) — test the equality of the sequences emitted by two Observables diff --git a/docs/Connectable-Observable-Operators.md b/docs/Connectable-Observable-Operators.md new file mode 100644 index 0000000000..a048547529 --- /dev/null +++ b/docs/Connectable-Observable-Operators.md @@ -0,0 +1,75 @@ +This section explains the [`ConnectableObservable`](http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html) subclass and its operators: + +* [**`ConnectableObservable.connect( )`**](http://reactivex.io/documentation/operators/connect.html) — instructs a Connectable Observable to begin emitting items +* [**`Observable.publish( )`**](http://reactivex.io/documentation/operators/publish.html) — represents an Observable as a Connectable Observable +* [**`Observable.replay( )`**](http://reactivex.io/documentation/operators/replay.html) — ensures that all Subscribers see the same sequence of emitted items, even if they subscribe after the Observable begins emitting the items +* [**`ConnectableObservable.refCount( )`**](http://reactivex.io/documentation/operators/refcount.html) — makes a Connectable Observable behave like an ordinary Observable + +A Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only when its `connect()` method is called. In this way you can wait for all intended Subscribers to subscribe to the Observable before the Observable begins emitting items. + + + +The following example code shows two Subscribers subscribing to the same Observable. In the first case, they subscribe to an ordinary Observable; in the second case, they subscribe to a Connectable Observable that only connects after both Subscribers subscribe. Note the difference in the output: + +**Example #1:** +```groovy +def firstMillion = Observable.range( 1, 1000000 ).sample(7, java.util.concurrent.TimeUnit.MILLISECONDS); + +firstMillion.subscribe( + { println("Subscriber #1:" + it); }, // onNext + { println("Error: " + it.getMessage()); }, // onError + { println("Sequence #1 complete"); } // onCompleted +); + +firstMillion.subscribe( + { println("Subscriber #2:" + it); }, // onNext + { println("Error: " + it.getMessage()); }, // onError + { println("Sequence #2 complete"); } // onCompleted +); +``` +``` +Subscriber #1:211128 +Subscriber #1:411633 +Subscriber #1:629605 +Subscriber #1:841903 +Sequence #1 complete +Subscriber #2:244776 +Subscriber #2:431416 +Subscriber #2:621647 +Subscriber #2:826996 +Sequence #2 complete +``` +**Example #2:** +```groovy +def firstMillion = Observable.range( 1, 1000000 ).sample(7, java.util.concurrent.TimeUnit.MILLISECONDS).publish(); + +firstMillion.subscribe( + { println("Subscriber #1:" + it); }, // onNext + { println("Error: " + it.getMessage()); }, // onError + { println("Sequence #1 complete"); } // onCompleted +); + +firstMillion.subscribe( + { println("Subscriber #2:" + it); }, // onNext + { println("Error: " + it.getMessage()); }, // onError + { println("Sequence #2 complete"); } // onCompleted +); + +firstMillion.connect(); +``` +``` +Subscriber #2:208683 +Subscriber #1:208683 +Subscriber #2:432509 +Subscriber #1:432509 +Subscriber #2:644270 +Subscriber #1:644270 +Subscriber #2:887885 +Subscriber #1:887885 +Sequence #2 complete +Sequence #1 complete +``` + +#### see also: +* javadoc: `ConnectableObservable` +* Introduction to Rx: Publish and Connect \ No newline at end of file diff --git a/docs/Creating-Observables.md b/docs/Creating-Observables.md new file mode 100644 index 0000000000..25b215f982 --- /dev/null +++ b/docs/Creating-Observables.md @@ -0,0 +1,13 @@ +This page shows methods that create Observables. + +* [**`just( )`**](http://reactivex.io/documentation/operators/just.html) — convert an object or several objects into an Observable that emits that object or those objects +* [**`from( )`**](http://reactivex.io/documentation/operators/from.html) — convert an Iterable, a Future, or an Array into an Observable +* [**`create( )`**](http://reactivex.io/documentation/operators/create.html) — **advanced use only!** create an Observable from scratch by means of a function, consider `fromEmitter` instead +* [**`fromEmitter()`**](http://reactivex.io/RxJava/javadoc/rx/Observable.html#fromEmitter(rx.functions.Action1,%20rx.AsyncEmitter.BackpressureMode)) — create safe, backpressure-enabled, unsubscription-supporting Observable via a function and push events. +* [**`defer( )`**](http://reactivex.io/documentation/operators/defer.html) — do not create the Observable until a Subscriber subscribes; create a fresh Observable on each subscription +* [**`range( )`**](http://reactivex.io/documentation/operators/range.html) — create an Observable that emits a range of sequential integers +* [**`interval( )`**](http://reactivex.io/documentation/operators/interval.html) — create an Observable that emits a sequence of integers spaced by a given time interval +* [**`timer( )`**](http://reactivex.io/documentation/operators/timer.html) — create an Observable that emits a single item after a given delay +* [**`empty( )`**](http://reactivex.io/documentation/operators/empty-never-throw.html) — create an Observable that emits nothing and then completes +* [**`error( )`**](http://reactivex.io/documentation/operators/empty-never-throw.html) — create an Observable that emits nothing and then signals an error +* [**`never( )`**](http://reactivex.io/documentation/operators/empty-never-throw.html) — create an Observable that emits nothing at all diff --git a/docs/Error-Handling-Operators.md b/docs/Error-Handling-Operators.md new file mode 100644 index 0000000000..8acae59787 --- /dev/null +++ b/docs/Error-Handling-Operators.md @@ -0,0 +1,14 @@ +There are a variety of operators that you can use to react to or recover from `onError` notifications from Observables. For example, you might: + +1. swallow the error and switch over to a backup Observable to continue the sequence +1. swallow the error and emit a default item +1. swallow the error and immediately try to restart the failed Observable +1. swallow the error and try to restart the failed Observable after some back-off interval + +The following pages explain these operators. + +* [**`onErrorResumeNext( )`**](http://reactivex.io/documentation/operators/catch.html) — instructs an Observable to emit a sequence of items if it encounters an error +* [**`onErrorReturn( )`**](http://reactivex.io/documentation/operators/catch.html) — instructs an Observable to emit a particular item when it encounters an error +* [**`onExceptionResumeNext( )`**](http://reactivex.io/documentation/operators/catch.html) — instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable) +* [**`retry( )`**](http://reactivex.io/documentation/operators/retry.html) — if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error +* [**`retryWhen( )`**](http://reactivex.io/documentation/operators/retry.html) — if a source Observable emits an error, pass that error to another Observable to determine whether to resubscribe to the source \ No newline at end of file diff --git a/docs/Error-Handling.md b/docs/Error-Handling.md new file mode 100644 index 0000000000..3de9c396d9 --- /dev/null +++ b/docs/Error-Handling.md @@ -0,0 +1,24 @@ +An Observable typically does not _throw_ exceptions. Instead it notifies any observers that an unrecoverable error has occurred by terminating the Observable sequence with an `onError` notification. + +There are some exceptions to this. For example, if the `onError()` call _itself_ fails, the Observable will not attempt to notify the observer of this by again calling `onError` but will throw a `RuntimeException`, an `OnErrorFailedException`, or an `OnErrorNotImplementedException`. + +# Techniques for recovering from onError notifications + +So rather than _catch_ exceptions, your observer or operator should more typically respond to `onError` notifications of exceptions. There are also a variety of Observable operators that you can use to react to or recover from `onError` notifications from Observables. For example, you might use an operator to: + +1. swallow the error and switch over to a backup Observable to continue the sequence +1. swallow the error and emit a default item +1. swallow the error and immediately try to restart the failed Observable +1. swallow the error and try to restart the failed Observable after some back-off interval + +You can use the operators described in [[Error Handling Operators]] to implement these strategies. + +# RxJava-specific exceptions and what to do about them + +
                +
                CompositeException
                This indicates that more than one exception occurred. You can use the exception’s getExceptions() method to retrieve the individual exceptions that make up the composite.
                +
                MissingBackpressureException
                This indicates that a Subscriber or operator attempted to apply reactive pull backpressure to an Observable that does not implement it. See [[Backpressure]] for work-arounds for Observables that do not implement reactive pull backpressure.
                +
                OnErrorFailedException
                This indicates that an Observable tried to call its observer’s onError() method, but that method itself threw an exception.
                +
                OnErrorNotImplementedException
                This indicates that an Observable tried to call its observer’s onError() method, but that no such method existed. You can eliminate this by either fixing the Observable so that it no longer reaches an error condition, by implementing an onError handler in the observer, or by intercepting the onError notification before it reaches the observer by using one of the operators described elsewhere on this page.
                +
                OnErrorThrowable
                Observers pass throwables of this sort into their observers’ onError() handlers. A Throwable of this variety contains more information about the error and about the Observable-specific state of the system at the time of the error than does a standard Throwable.
                +
                \ No newline at end of file diff --git a/docs/Filtering-Observables.md b/docs/Filtering-Observables.md new file mode 100644 index 0000000000..7e12d91094 --- /dev/null +++ b/docs/Filtering-Observables.md @@ -0,0 +1,22 @@ +This page shows operators you can use to filter and select items emitted by Observables. + +* [**`filter( )`**](http://reactivex.io/documentation/operators/filter.html) — filter items emitted by an Observable +* [**`takeLast( )`**](http://reactivex.io/documentation/operators/takelast.html) — only emit the last _n_ items emitted by an Observable +* [**`last( )`**](http://reactivex.io/documentation/operators/last.html) — emit only the last item emitted by an Observable +* [**`lastOrDefault( )`**](http://reactivex.io/documentation/operators/last.html) — emit only the last item emitted by an Observable, or a default value if the source Observable is empty +* [**`takeLastBuffer( )`**](http://reactivex.io/documentation/operators/takelast.html) — emit the last _n_ items emitted by an Observable, as a single list item +* [**`skip( )`**](http://reactivex.io/documentation/operators/skip.html) — ignore the first _n_ items emitted by an Observable +* [**`skipLast( )`**](http://reactivex.io/documentation/operators/skiplast.html) — ignore the last _n_ items emitted by an Observable +* [**`take( )`**](http://reactivex.io/documentation/operators/take.html) — emit only the first _n_ items emitted by an Observable +* [**`first( )` and `takeFirst( )`**](http://reactivex.io/documentation/operators/first.html) — emit only the first item emitted by an Observable, or the first item that meets some condition +* [**`firstOrDefault( )`**](http://reactivex.io/documentation/operators/first.html) — emit only the first item emitted by an Observable, or the first item that meets some condition, or a default value if the source Observable is empty +* [**`elementAt( )`**](http://reactivex.io/documentation/operators/elementat.html) — emit item _n_ emitted by the source Observable +* [**`elementAtOrDefault( )`**](http://reactivex.io/documentation/operators/elementat.html) — emit item _n_ emitted by the source Observable, or a default item if the source Observable emits fewer than _n_ items +* [**`sample( )` or `throttleLast( )`**](http://reactivex.io/documentation/operators/sample.html) — emit the most recent items emitted by an Observable within periodic time intervals +* [**`throttleFirst( )`**](http://reactivex.io/documentation/operators/sample.html) — emit the first items emitted by an Observable within periodic time intervals +* [**`throttleWithTimeout( )` or `debounce( )`**](http://reactivex.io/documentation/operators/debounce.html) — only emit an item from the source Observable after a particular timespan has passed without the Observable emitting any other items +* [**`timeout( )`**](http://reactivex.io/documentation/operators/timeout.html) — emit items from a source Observable, but issue an exception if no item is emitted in a specified timespan +* [**`distinct( )`**](http://reactivex.io/documentation/operators/distinct.html) — suppress duplicate items emitted by the source Observable +* [**`distinctUntilChanged( )`**](http://reactivex.io/documentation/operators/distinct.html) — suppress duplicate consecutive items emitted by the source Observable +* [**`ofType( )`**](http://reactivex.io/documentation/operators/filter.html) — emit only those items from the source Observable that are of a particular class +* [**`ignoreElements( )`**](http://reactivex.io/documentation/operators/ignoreelements.html) — discard the items emitted by the source Observable and only pass through the error or completed notification diff --git a/docs/Getting-Started.md b/docs/Getting-Started.md new file mode 100644 index 0000000000..1a95121c4e --- /dev/null +++ b/docs/Getting-Started.md @@ -0,0 +1,141 @@ +## Getting Binaries + +You can find binaries and dependency information for Maven, Ivy, Gradle, SBT, and others at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22io.reactivex%22%20AND%20a%3A%22rxjava%22). + +Example for Maven: + +```xml + + io.reactivex + rxjava + 1.3.4 + +``` +and for Ivy: + +```xml + +``` + +and for SBT: + +```scala +libraryDependencies += "io.reactivex" %% "rxscala" % "0.26.5" + +libraryDependencies += "io.reactivex" % "rxjava" % "1.3.4" +``` + +and for Gradle: +```groovy +compile 'io.reactivex:rxjava:1.3.4' +``` + +If you need to download the jars instead of using a build system, create a Maven `pom` file like this with the desired version: + +```xml + + + 4.0.0 + com.netflix.rxjava.download + rxjava-download + 1.0-SNAPSHOT + Simple POM to download rxjava and dependencies + http://github.com/ReactiveX/RxJava + + + io.reactivex + rxjava + 1.3.4 + + + + +``` + +Then execute: + +``` +$ mvn -f download-rxjava-pom.xml dependency:copy-dependencies +``` + +That command downloads `rxjava-*.jar` and its dependencies into `./target/dependency/`. + +You need Java 6 or later. + +### Snapshots + +Snapshots are available via [JFrog](https://oss.jfrog.org/webapp/search/artifact/?5&q=rxjava): + +```groovy +repositories { + maven { url 'https://oss.jfrog.org/libs-snapshot' } +} + +dependencies { + compile 'io.reactivex:rxjava:1.3.y-SNAPSHOT' +} +``` + +## Building + +To check out and build the RxJava source, issue the following commands: + +``` +$ git clone git@github.com:ReactiveX/RxJava.git +$ cd RxJava/ +$ ./gradlew build +``` + +To do a clean build, issue the following command: + +``` +$ ./gradlew clean build +``` + +A build should look similar to this: + +``` +$ ./gradlew build +:rxjava:compileJava +:rxjava:processResources UP-TO-DATE +:rxjava:classes +:rxjava:jar +:rxjava:sourcesJar +:rxjava:signArchives SKIPPED +:rxjava:assemble +:rxjava:licenseMain UP-TO-DATE +:rxjava:licenseTest UP-TO-DATE +:rxjava:compileTestJava +:rxjava:processTestResources UP-TO-DATE +:rxjava:testClasses +:rxjava:test +:rxjava:check +:rxjava:build + +BUILD SUCCESSFUL + +Total time: 30.758 secs +``` + +On a clean build you will see the unit tests run. They will look something like this: + +``` +> Building > :rxjava:test > 91 tests completed +``` + +#### Troubleshooting + +One developer reported getting the following error: + +> Could not resolve all dependencies for configuration ':language-adaptors:rxjava-scala:provided' + +He was able to resolve the problem by removing old versions of `scala-library` from `.gradle/caches` and `.m2/repository/org/scala-lang/` and then doing a clean build. (See this page for details.) + +You may get the following error during building RxJava: + +> Failed to apply plugin [id 'java'] +> Could not generate a proxy class for class nebula.core.NamedContainerProperOrder. + +It's a JVM issue, see [GROOVY-6951](https://jira.codehaus.org/browse/GROOVY-6951) for details. If so, you can run `export GRADLE_OPTS=-noverify` before building RxJava, or update your JDK. diff --git a/docs/Home.md b/docs/Home.md new file mode 100644 index 0000000000..474c8edc77 --- /dev/null +++ b/docs/Home.md @@ -0,0 +1,24 @@ +RxJava is a Java VM implementation of [ReactiveX (Reactive Extensions)](https://reactivex.io): a library for composing asynchronous and event-based programs by using observable sequences. + +For more information about ReactiveX, see the [Introduction to ReactiveX](http://reactivex.io/intro.html) page. + +### RxJava is Lightweight + +RxJava tries to be very lightweight. It is implemented as a single JAR that is focused on just the Observable abstraction and related higher-order functions. + +### RxJava is a Polyglot Implementation + +RxJava supports Java 6 or higher and JVM-based languages such as [Groovy](https://github.com/ReactiveX/RxGroovy), [Clojure](https://github.com/ReactiveX/RxClojure), [JRuby](https://github.com/ReactiveX/RxJRuby), [Kotlin](https://github.com/ReactiveX/RxKotlin) and [Scala](https://github.com/ReactiveX/RxScala). + +RxJava is meant for a more polyglot environment than just Java/Scala, and it is being designed to respect the idioms of each JVM-based language. (This is something we’re still working on.) + +### RxJava Libraries + +The following external libraries can work with RxJava: + +* [Hystrix](https://github.com/Netflix/Hystrix/wiki/How-To-Use#wiki-Reactive-Execution) latency and fault tolerance bulkheading library. +* [Camel RX](http://camel.apache.org/rx.html) provides an easy way to reuse any of the [Apache Camel components, protocols, transports and data formats](http://camel.apache.org/components.html) with the RxJava API +* [rxjava-http-tail](https://github.com/myfreeweb/rxjava-http-tail) allows you to follow logs over HTTP, like `tail -f` +* [mod-rxvertx - Extension for VertX](https://github.com/vert-x/mod-rxvertx) that provides support for Reactive Extensions (RX) using the RxJava library +* [rxjava-jdbc](https://github.com/davidmoten/rxjava-jdbc) - use RxJava with jdbc connections to stream ResultSets and do functional composition of statements +* [rtree](https://github.com/davidmoten/rtree) - immutable in-memory R-tree and R*-tree with RxJava api including backpressure \ No newline at end of file diff --git a/docs/How-To-Use-RxJava.md b/docs/How-To-Use-RxJava.md new file mode 100644 index 0000000000..d10274d959 --- /dev/null +++ b/docs/How-To-Use-RxJava.md @@ -0,0 +1,400 @@ +# Hello World! + +The following sample implementations of “Hello World” in Java, Groovy, Clojure, and Scala create an Observable from a list of Strings, and then subscribe to this Observable with a method that prints “Hello _String_!” for each string emitted by the Observable. + +You can find additional code examples in the `/src/examples` folders of each [language adaptor](https://github.com/ReactiveX/): + +* [RxGroovy examples](https://github.com/ReactiveX/RxGroovy/tree/1.x/src/examples/groovy/rx/lang/groovy/examples) +* [RxClojure examples](https://github.com/ReactiveX/RxClojure/tree/0.x/src/examples/clojure/rx/lang/clojure/examples) +* [RxScala examples](https://github.com/ReactiveX/RxScala/tree/0.x/examples/src/main/scala) + +### Java + +```java +public static void hello(String... names) { + Observable.from(names).subscribe(new Action1() { + + @Override + public void call(String s) { + System.out.println("Hello " + s + "!"); + } + + }); +} +``` + +```java +hello("Ben", "George"); +Hello Ben! +Hello George! +``` + +### Groovy + +```groovy +def hello(String[] names) { + Observable.from(names).subscribe { println "Hello ${it}!" } +} +``` + +```groovy +hello("Ben", "George") +Hello Ben! +Hello George! +``` + +### Clojure + +```clojure +(defn hello + [&rest] + (-> (Observable/from &rest) + (.subscribe #(println (str "Hello " % "!"))))) +``` + +``` +(hello ["Ben" "George"]) +Hello Ben! +Hello George! +``` +### Scala + +```scala +import rx.lang.scala.Observable + +def hello(names: String*) { + Observable.from(names) subscribe { n => + println(s"Hello $n!") + } +} +``` + +```scala +hello("Ben", "George") +Hello Ben! +Hello George! +``` + +# How to Design Using RxJava + +To use RxJava you create Observables (which emit data items), transform those Observables in various ways to get the precise data items that interest you (by using Observable operators), and then observe and react to these sequences of interesting items (by implementing Observers or Subscribers and then subscribing them to the resulting transformed Observables). + +## Creating Observables + +To create an Observable, you can either implement the Observable's behavior manually by passing a function to [`create( )`](http://reactivex.io/documentation/operators/create.html) that exhibits Observable behavior, or you can convert an existing data structure into an Observable by using [some of the Observable operators that are designed for this purpose](Creating-Observables). + +### Creating an Observable from an Existing Data Structure + +You use the Observable [`just( )`](http://reactivex.io/documentation/operators/just.html) and [`from( )`](http://reactivex.io/documentation/operators/from.html) methods to convert objects, lists, or arrays of objects into Observables that emit those objects: + +```groovy +Observable o = Observable.from("a", "b", "c"); + +def list = [5, 6, 7, 8] +Observable o = Observable.from(list); + +Observable o = Observable.just("one object"); +``` + +These converted Observables will synchronously invoke the [`onNext( )`](Observable#onnext-oncompleted-and-onerror) method of any subscriber that subscribes to them, for each item to be emitted by the Observable, and will then invoke the subscriber’s [`onCompleted( )`](Observable#onnext-oncompleted-and-onerror) method. + +### Creating an Observable via the `create( )` method + +You can implement asynchronous i/o, computational operations, or even “infinite” streams of data by designing your own Observable and implementing it with the [`create( )`](http://reactivex.io/documentation/operators/create.html) method. + +#### Synchronous Observable Example + +```groovy +/** + * This example shows a custom Observable that blocks + * when subscribed to (does not spawn an extra thread). + */ +def customObservableBlocking() { + return Observable.create { aSubscriber -> + 50.times { i -> + if (!aSubscriber.unsubscribed) { + aSubscriber.onNext("value_${i}") + } + } + // after sending all values we complete the sequence + if (!aSubscriber.unsubscribed) { + aSubscriber.onCompleted() + } + } +} + +// To see output: +customObservableBlocking().subscribe { println(it) } +``` + +#### Asynchronous Observable Example + +The following example uses Groovy to create an Observable that emits 75 strings. + +It is written verbosely, with static typing and implementation of the `Func1` anonymous inner class, to make the example more clear: + +```groovy +/** + * This example shows a custom Observable that does not block + * when subscribed to as it spawns a separate thread. + */ +def customObservableNonBlocking() { + return Observable.create({ subscriber -> + Thread.start { + for (i in 0..<75) { + if (subscriber.unsubscribed) { + return + } + subscriber.onNext("value_${i}") + } + // after sending all values we complete the sequence + if (!subscriber.unsubscribed) { + subscriber.onCompleted() + } + } + } as Observable.OnSubscribe) +} + +// To see output: +customObservableNonBlocking().subscribe { println(it) } +``` + +Here is the same code in Clojure that uses a Future (instead of raw thread) and is implemented more consisely: + +```clojure +(defn customObservableNonBlocking [] + "This example shows a custom Observable that does not block + when subscribed to as it spawns a separate thread. + + returns Observable" + (Observable/create + (fn [subscriber] + (let [f (future + (doseq [x (range 50)] (-> subscriber (.onNext (str "value_" x)))) + ; after sending all values we complete the sequence + (-> subscriber .onCompleted)) + )) + )) +``` + +```clojure +; To see output +(.subscribe (customObservableNonBlocking) #(println %)) +``` + +Here is an example that fetches articles from Wikipedia and invokes onNext with each one: + +```clojure +(defn fetchWikipediaArticleAsynchronously [wikipediaArticleNames] + "Fetch a list of Wikipedia articles asynchronously. + + return Observable of HTML" + (Observable/create + (fn [subscriber] + (let [f (future + (doseq [articleName wikipediaArticleNames] + (-> subscriber (.onNext (http/get (str "http://en.wikipedia.org/wiki/" articleName))))) + ; after sending response to onnext we complete the sequence + (-> subscriber .onCompleted)) + )))) +``` + +```clojure +(-> (fetchWikipediaArticleAsynchronously ["Tiger" "Elephant"]) + (.subscribe #(println "--- Article ---\n" (subs (:body %) 0 125) "..."))) +``` + +Back to Groovy, the same Wikipedia functionality but using closures instead of anonymous inner classes: + +```groovy +/* + * Fetch a list of Wikipedia articles asynchronously. + */ +def fetchWikipediaArticleAsynchronously(String... wikipediaArticleNames) { + return Observable.create { subscriber -> + Thread.start { + for (articleName in wikipediaArticleNames) { + if (subscriber.unsubscribed) { + return + } + subscriber.onNext(new URL("http://en.wikipedia.org/wiki/$%7BarticleName%7D").text) + } + if (!subscriber.unsubscribed) { + subscriber.onCompleted() + } + } + return subscriber + } +} + +fetchWikipediaArticleAsynchronously("Tiger", "Elephant") + .subscribe { println "--- Article ---\n${it.substring(0, 125)}" } +``` + +Results: + +```text +--- Article --- + + + +Tiger - Wikipedia, the free encyclopedia ... +--- Article --- + + + +Elephant - Wikipedia, the free encyclopedia</tit ... +``` + +Note that all of the above examples ignore error handling, for brevity. See below for examples that include error handling. + +More information can be found on the [[Observable]] and [[Creating Observables|Creating-Observables]] pages. + +## Transforming Observables with Operators + +RxJava allows you to chain _operators_ together to transform and compose Observables. + +The following example, in Groovy, uses a previously defined, asynchronous Observable that emits 75 items, skips over the first 10 of these ([`skip(10)`](http://reactivex.io/documentation/operators/skip.html)), then takes the next 5 ([`take(5)`](http://reactivex.io/documentation/operators/take.html)), and transforms them ([`map(...)`](http://reactivex.io/documentation/operators/map.html)) before subscribing and printing the items: + +```groovy +/** + * Asynchronously calls 'customObservableNonBlocking' and defines + * a chain of operators to apply to the callback sequence. + */ +def simpleComposition() { + customObservableNonBlocking().skip(10).take(5) + .map({ stringValue -> return stringValue + "_xform"}) + .subscribe({ println "onNext => " + it}) +} +``` + +This results in: + +```text +onNext => value_10_xform +onNext => value_11_xform +onNext => value_12_xform +onNext => value_13_xform +onNext => value_14_xform +``` + +Here is a marble diagram that illustrates this transformation: + +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/Composition.1.png" width="640" height="536" /> + +This next example, in Clojure, consumes three asynchronous Observables, including a dependency from one to another, and emits a single response item by combining the items emitted by each of the three Observables with the [`zip`](http://reactivex.io/documentation/operators/zip.html) operator and then transforming the result with [`map`](http://reactivex.io/documentation/operators/map.html): + +```clojure +(defn getVideoForUser [userId videoId] + "Get video metadata for a given userId + - video metadata + - video bookmark position + - user data + return Observable<Map>" + (let [user-observable (-> (getUser userId) + (.map (fn [user] {:user-name (:name user) :language (:preferred-language user)}))) + bookmark-observable (-> (getVideoBookmark userId videoId) + (.map (fn [bookmark] {:viewed-position (:position bookmark)}))) + ; getVideoMetadata requires :language from user-observable so nest inside map function + video-metadata-observable (-> user-observable + (.mapMany + ; fetch metadata after a response from user-observable is received + (fn [user-map] + (getVideoMetadata videoId (:language user-map)))))] + ; now combine 3 observables using zip + (-> (Observable/zip bookmark-observable video-metadata-observable user-observable + (fn [bookmark-map metadata-map user-map] + {:bookmark-map bookmark-map + :metadata-map metadata-map + :user-map user-map})) + ; and transform into a single response object + (.map (fn [data] + {:video-id videoId + :video-metadata (:metadata-map data) + :user-id userId + :language (:language (:user-map data)) + :bookmark (:viewed-position (:bookmark-map data)) + }))))) +``` + +The response looks like this: + +```clojure +{:video-id 78965, + :video-metadata {:video-id 78965, :title House of Cards: Episode 1, + :director David Fincher, :duration 3365}, + :user-id 12345, :language es-us, :bookmark 0} +``` + +And here is a marble diagram that illustrates how that code produces that response: + +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/Composition.2.png" width="640" height="742" /> + +The following example, in Groovy, comes from [Ben Christensen’s QCon presentation on the evolution of the Netflix API](https://speakerdeck.com/benjchristensen/evolution-of-the-netflix-api-qcon-sf-2013). It combines two Observables with the [`merge`](http://reactivex.io/documentation/operators/merge.html) operator, then uses the [`reduce`](http://reactivex.io/documentation/operators/reduce.html) operator to construct a single item out of the resulting sequence, then transforms that item with [`map`](http://reactivex.io/documentation/operators/map.html) before emitting it: + +```groovy +public Observable getVideoSummary(APIVideo video) { + def seed = [id:video.id, title:video.getTitle()]; + def bookmarkObservable = getBookmark(video); + def artworkObservable = getArtworkImageUrl(video); + return( Observable.merge(bookmarkObservable, artworkObservable) + .reduce(seed, { aggregate, current -> aggregate << current }) + .map({ [(video.id.toString() : it] })) +} +``` + +And here is a marble diagram that illustrates how that code uses the [`reduce`](http://reactivex.io/documentation/operators/reduce.html) operator to bring the results from multiple Observables together in one structure: + +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/Composition.3.png" width="640" height="640" /> + +## Error Handling + +Here is a version of the Wikipedia example from above revised to include error handling: + +```groovy +/* + * Fetch a list of Wikipedia articles asynchronously, with error handling. + */ +def fetchWikipediaArticleAsynchronouslyWithErrorHandling(String... wikipediaArticleNames) { + return Observable.create({ subscriber -> + Thread.start { + try { + for (articleName in wikipediaArticleNames) { + if (true == subscriber.isUnsubscribed()) { + return; + } + subscriber.onNext(new URL("http://en.wikipedia.org/wiki/"+articleName).getText()); + } + if (false == subscriber.isUnsubscribed()) { + subscriber.onCompleted(); + } + } catch(Throwable t) { + if (false == subscriber.isUnsubscribed()) { + subscriber.onError(t); + } + } + return (subscriber); + } + }); +} +``` + +Notice how it now invokes [`onError(Throwable t)`](Observable#onnext-oncompleted-and-onerror) if an error occurs and note that the following code passes [`subscribe()`](http://reactivex.io/documentation/operators/subscribe.html) a second method that handles `onError`: + +```groovy +fetchWikipediaArticleAsynchronouslyWithErrorHandling("Tiger", "NonExistentTitle", "Elephant") + .subscribe( + { println "--- Article ---\n" + it.substring(0, 125) }, + { println "--- Error ---\n" + it.getMessage() }) +``` + +See the [Error-Handling-Operators](Error-Handling-Operators) page for more information on specialized error handling techniques in RxJava, including methods like [`onErrorResumeNext()`](http://reactivex.io/documentation/operators/catch.html) and [`onErrorReturn()`](http://reactivex.io/documentation/operators/catch.html) that allow Observables to continue with fallbacks in the event that they encounter errors. + +Here is an example of how you can use such a method to pass along custom information about any exceptions you encounter. Imagine you have an Observable or cascade of Observables — `myObservable` — and you want to intercept any exceptions that would normally pass through to an Subscriber’s `onError` method, replacing these with a customized Throwable of your own design. You could do this by modifying `myObservable` with the [`onErrorResumeNext()`](http://reactivex.io/documentation/operators/catch.html) method, and passing into that method an Observable that calls `onError` with your customized Throwable (a utility method called [`error()`](http://reactivex.io/documentation/operators/empty-never-throw.html) will generate such an Observable for you): + +```groovy +myModifiedObservable = myObservable.onErrorResumeNext({ t -> + Throwable myThrowable = myCustomizedThrowableCreator(t); + return (Observable.error(myThrowable)); +}); +``` \ No newline at end of file diff --git a/docs/How-to-Contribute.md b/docs/How-to-Contribute.md new file mode 100644 index 0000000000..1b63812764 --- /dev/null +++ b/docs/How-to-Contribute.md @@ -0,0 +1,41 @@ +RxJava is still a work in progress and has a long list of work documented in the [[Issues|https://github.com/ReactiveX/RxJava/issues]]. + + +If you wish to contribute we would ask that you: +- read [[Rx Design Guidelines|http://blogs.msdn.com/b/rxteam/archive/2010/10/28/rx-design-guidelines.aspx]] +- review existing code and comply with existing patterns and idioms +- include unit tests +- stick to Rx contracts as defined by the Rx.Net implementation when porting operators (each issue attempts to reference the correct documentation from MSDN) + +Information about licensing can be found at: [[CONTRIBUTING|https://github.com/ReactiveX/RxJava/blob/1.x/CONTRIBUTING.md]]. + +## How to import the project into Eclipse +Two options below: + +###Import as Eclipse project + + ./gradlew eclipse + +In Eclipse +* choose File - Import - General - Existing Projects into Workspace +* Browse to RxJava folder +* click Finish. +* Right click on the project in Package Explorer, select Properties - Java Compiler - Errors/Warnings - click Enable project specific settings. +* Still in Errors/Warnings, go to Deprecated and restricted API and set Forbidden reference (access-rules) to Warning. + +###Import as Gradle project + +You need the Gradle plugin for Eclipse installed. + +In Eclipse +* choose File - Import - Gradle - Gradle Project. +* Browse to RxJava folder +* click Build Model +* select the project +* click Finish + + + + + + diff --git a/docs/Implementing-Your-Own-Operators.md b/docs/Implementing-Your-Own-Operators.md new file mode 100644 index 0000000000..9e4a165f8b --- /dev/null +++ b/docs/Implementing-Your-Own-Operators.md @@ -0,0 +1,114 @@ +You can implement your own Observable operators. This page shows you how. + +If your operator is designed to *originate* an Observable, rather than to transform or react to a source Observable, use the [`create( )`](http://reactivex.io/documentation/operators/create.html) method rather than trying to implement `Observable` manually. Otherwise, you can create a custom operator by following the instructions on this page. + +If your operator is designed to act on the individual items emitted by a source Observable, follow the instructions under [_Sequence Operators_](Implementing-Your-Own-Operators#sequence-operators) below. If your operator is designed to transform the source Observable as a whole (for instance, by applying a particular set of existing RxJava operators to it) follow the instructions under [_Transformational Operators_](Implementing-Your-Own-Operators#transformational-operators) below. + +(**Note:** in Xtend, a Groovy-like language, you can implement your operators as _extension methods_ and can thereby chain them directly without using the methods described on this page. See [RxJava and Xtend](http://mnmlst-dvlpr.blogspot.de/2014/07/rxjava-and-xtend.html) for details.) + +# Sequence Operators + +The following example shows how you can use the `lift( )` operator to chain your custom operator (in this example: `myOperator`) alongside standard RxJava operators like `ofType` and `map`: +```groovy +fooObservable = barObservable.ofType(Integer).map({it*2}).lift(new myOperator<T>()).map({"transformed by myOperator: " + it}); +``` +The following section shows how you form the scaffolding of your operator so that it will work correctly with `lift( )`. + +## Implementing Your Operator + +Define your operator as a public class that implements the [`Operator`](http://reactivex.io/RxJava/javadoc/rx/Observable.Operator.html) interface, like so: +```java +public class myOperator<T> implements Operator<T> { + public myOperator( /* any necessary params here */ ) { + /* any necessary initialization here */ + } + + @Override + public Subscriber<? super T> call(final Subscriber<? super T> s) { + return new Subscriber<t>(s) { + @Override + public void onCompleted() { + /* add your own onCompleted behavior here, or just pass the completed notification through: */ + if(!s.isUnsubscribed()) { + s.onCompleted(); + } + } + + @Override + public void onError(Throwable t) { + /* add your own onError behavior here, or just pass the error notification through: */ + if(!s.isUnsubscribed()) { + s.onError(t); + } + } + + @Override + public void onNext(T item) { + /* this example performs some sort of operation on each incoming item and emits the results */ + if(!s.isUnsubscribed()) { + transformedItem = myOperatorTransformOperation(item); + s.onNext(transformedItem); + } + } + }; + } +} +``` + +# Transformational Operators + +The following example shows how you can use the `compose( )` operator to chain your custom operator (in this example, an operator called `myTransformer` that transforms an Observable that emits Integers into one that emits Strings) alongside standard RxJava operators like `ofType` and `map`: +```groovy +fooObservable = barObservable.ofType(Integer).map({it*2}).compose(new myTransformer<Integer,String>()).map({"transformed by myOperator: " + it}); +``` +The following section shows how you form the scaffolding of your operator so that it will work correctly with `compose( )`. + +## Implementing Your Transformer + +Define your transforming function as a public class that implements the [`Transformer`](http://reactivex.io/RxJava/javadoc/rx/Observable.Transformer.html) interface, like so: + +````java +public class myTransformer<Integer,String> implements Transformer<Integer,String> { + public myTransformer( /* any necessary params here */ ) { + /* any necessary initialization here */ + } + + @Override + public Observable<String> call(Observable<Integer> source) { + /* + * this simple example Transformer applies map() to the source Observable + * in order to transform the "source" observable from one that emits + * integers to one that emits string representations of those integers. + */ + return source.map( new Func1<Integer,String>() { + @Override + public String call(Integer t1) { + return String.valueOf(t1); + } + } ); + } +} +```` + +## See also + +* [“Don’t break the chain: use RxJava’s compose() operator”](http://blog.danlew.net/2015/03/02/dont-break-the-chain/) by Dan Lew + +# Other Considerations + +* Your sequence operator may want to check [its Subscriber’s `isUnsubscribed( )` status](Observable#unsubscribing) before it emits any item to (or sends any notification to) the Subscriber. There’s no need to waste time generating items that no Subscriber is interested in seeing. +* Take care that your sequence operator obeys the core tenets of the Observable contract: + * It may call a Subscriber’s [`onNext( )`](Observable#onnext-oncompleted-and-onerror) method any number of times, but these calls must be non-overlapping. + * It may call either a Subscriber’s [`onCompleted( )`](Observable#onnext-oncompleted-and-onerror) or [`onError( )`](Observable#onnext-oncompleted-and-onerror) method, but not both, exactly once, and it may not subsequently call a Subscriber’s [`onNext( )`](Observable#onnext-oncompleted-and-onerror) method. + * If you are unable to guarantee that your operator conforms to the above two tenets, you can add the [`serialize( )`](Observable-Utility-Operators#serialize) operator to it, which will force the correct behavior. +* Keep an eye on [Issue #1962](https://github.com/ReactiveX/RxJava/issues/1962) — there are plans to create a test scaffold that you can use to write tests which verify that your new operator conforms to the Observable contract. +* Do not block within your operator. +* When possible, you should compose new operators by combining existing operators, rather than implementing them with new code. RxJava itself does this with some of its standard operators, for example: + * [`first( )`](http://reactivex.io/documentation/operators/first.html) is defined as <tt>[take(1)](http://reactivex.io/documentation/operators/take.html).[single( )](http://reactivex.io/documentation/operators/first.html)</tt> + * [`ignoreElements( )`](http://reactivex.io/documentation/operators/ignoreelements.html) is defined as <tt>[filter(alwaysFalse( ))](http://reactivex.io/documentation/operators/filter.html)</tt> + * [`reduce(a)`](http://reactivex.io/documentation/operators/reduce.html) is defined as <tt>[scan(a)](http://reactivex.io/documentation/operators/scan.html).[last( )](http://reactivex.io/documentation/operators/last.html)</tt> +* If your operator uses functions or lambdas that are passed in as parameters (predicates, for instance), note that these may be sources of exceptions, and be prepared to catch these and notify subscribers via `onError( )` calls. + * Some exceptions are considered “fatal” and for them there’s no point in trying to call `onError( )` because that will either be futile or will just compound the problem. You can use the `Exceptions.throwIfFatal(throwable)` method to filter out such fatal exceptions and rethrow them rather than try to notify about them. +* In general, notify subscribers of error conditions immediately, rather than making an effort to emit more items first. +* Be aware that “<code>null</code>” is a valid item that may be emitted by an Observable. A frequent source of bugs is to test some variable meant to hold an emitted item against <code>null</code> as a substitute for testing whether or not an item was emitted. An emission of “<code>null</code>” is still an emission and is not the same as not emitting anything. +* It can be tricky to make your operator behave well in *backpressure* scenarios. See [Advanced RxJava](http://akarnokd.blogspot.hu/), a blog from Dávid Karnok, for a good discussion of the factors at play and how to deal with them. \ No newline at end of file diff --git a/docs/Implementing-custom-operators-(draft).md b/docs/Implementing-custom-operators-(draft).md new file mode 100644 index 0000000000..a95b6968f0 --- /dev/null +++ b/docs/Implementing-custom-operators-(draft).md @@ -0,0 +1,508 @@ +# Introduction + +RxJava features over 100 operators to support the most common reactive dataflow patterns. Generally, there exist a combination of operators, typically `flatMap`, `defer` and `publish`, that allow composing less common patterns with standard guarantees. When you have an uncommon pattern and you can't seem to find the right operators, try asking about it on our issue list (or Stackoverflow) first. + +If none of this applies to your use case, you may want to implement a custom operator. Be warned that **writing operators is hard**: when one writes an operator, the `Observable` **protocol**, **unsubscription**, **backpressure** and **concurrency** have to be taken into account and adhered to the letter. + +*Note that this page uses Java 8 syntax for brevity.* + +# Considerations + +## Observable protocol + +The `Observable` protocol states that you have to call the `Observer` methods, `onNext`, `onError` and `onCompleted` in a sequential manner. In other words, these can't be called concurrently and have to be **serialized**. The `SerializedObserver` and `SerializedSubscriber` wrappers help you with these. Note that there are cases where this serialization has to happen. + +In addition, there is an expected pattern of method calls on `Observer`: + +``` +onNext* (onError | onCompleted)? +``` + +A custom operator has to honor this pattern on its push side as well. For example, if your operator turns an `onNext` into an `onError`, the upstream has to be stopped and no further methods can be called on the dowstream. + +## Unsubscription + +The basic `Observer` method has no direct means to signal to the upstream source to stop emitting events. One either has to get the `Subscription` that the `Observable.subscribe(Observer<T>)` returns **and** be asynchronous itself. + +This shortcoming was resolved by introducing the `Subscriber` class that implements the `Subscription` interface. The interface allows detecting if a `Subscriber` is no longer interested in the events. + +```java +interface Subscription { + boolean isUnsubscribed(); + + void unsubscribe(); +} +``` + +In an operator, this allows active checking of the `Subscriber` state before emitting an event. + +In some cases, one needs to react to the child unsubscribing immediately and not just before an emission. To support this case, the `Subscriber` class has an `add(Subscription)` method that let's the operator register `Subscription`s of its own which get unsubscribed when the downstream calls `Subscriber.unsubscribe()`. + +```java +InputStream in = ... + +child.add(Subscriptions.create(() -> { + try { + in.close(); + } catch (IOException ex) { + RxJavaHooks.onError(ex); + } +})); +``` + +## Backpressure + +The name of this feature is often misinterpreted. It is about telling the upstream how many `onNext` events the downstream is ready to receive. For example, if the downstream requests 5, the upstream can only call `onNext` 5 times. If the upstream can't produce 5 elements but 3, it should deliver that 3 element followed by an `onError` or `onCompleted` (depending on the operator's purpose). The requests are cumulative in the sense that if the downstream requests 5 and then 2, there is going to be 7 requests outstanding. + +Backpressure handling adds a great deal of complexity to most operators: one has to track how many elements the downstream requested, how many have been delivered (by usually subtracting from the request amount) and sometimes how many elements are still available (but can't be delivered without requests). In addition, the downstream can request from any thread and is not required to happen on the common thread where otherwise the `onXXX` methods are called. + +The backpressure 'channel' is established between the upstream and downstream via the `Producer` interface: + +```java +interface Producer { + void request(long n); +} +``` + +When an upstream supports backpressure, it will call the `Subscriber.setProducer(Producer)` method on its downstream `Subscriber` with the implementation of this interface. The downstream then can respond with `Long.MAX_VALUE` to start an unbounded streaming (effectively no backpressure between the immediate upstream and downstream) or any other positive value. A request amount of zero should be ignored. + +Protocol-vise, there is no strict time when a producer can be set and it may never appear. Operators have to be ready to deal with this situation and assume the upstream runs in unbounded mode (as if `Long.MAX_VALUE` was requested). + +Often, operators may implement `Producer` and `Subscription` in a single class to handle both requests and unsubscriptions from the downstream: + +```java +final class MyEmitter implements Producer, Subscription { + final Subscriber<Integer> subscriber; + + public MyEmitter(Subscriber<Integer> subscriber) { + this.subscriber = subscriber; + } + + @Override + public void request(long n) { + if (n > 0) { + subscriber.onCompleted(); + } + } + + @Override + public void unsubscribe() { + System.out.println("Unsubscribed"); + } + + @Override + public boolean isUnsubscribed() { + return true; + } +} + +MyEmitter emitter = new MyEmitter(child); + +child.add(emitter); +child.setProducer(emitter); +``` + +Unfortunately, you can't implement `Producer` on a `Subscriber` because of an API oversight: `Subscriber` has a protected final `request(long n)` method to perform **deferred requesting** (store and accumulate the local request amounts until `setProducer` is called). + +## Concurrency + +When writing operators, we mostly have to deal with concurrency via the standard Java concurrency primitives: `AtomicXXX` classes, volatile variables, `Queue`s, mutual exclusion, Executors, etc. + +### RxJava tools + +RxJava has a few support classes and utilities that let's one deal with concurrency inside operators. + +The first one, `BackpressureUtils` deals with managing the cumulative requested and produced element counts for an operator. Its `getAndAddRequested()` method takes an `AtomicLong`, accumulates request amounts atomically and makes sure they don't overflow `Long.MAX_VALUE`. Its pair `produced()` subtracts the amount operators have produced, thus when both are in play, the given `AtomicLong` holds the current outstanding request amount for the downstream. + +Operators sometimes have to switch between multiple sources. If a previous source didn't fulfill all its requested amount, the new source has to start with that unfulfilled amount. Otherwise as the downstream didn't receive the requested amount (and no terminal event either), it can't know when to request more. If this switch happens at an `Observable` boundary (think `concat`), the `ProducerArbiter` helps managing the change. + +If there is only one item to emit eventually, the `SingleProducer` and `SingleDelayedProducer` help work out the backpressure handling: + +```java +child.setProducer(new SingleProducer<>(child, 1)); + +// or + +SingleDelayedProducer<Integer> p = new SingleDelayedProducer<>(child); + +child.add(p); +child.setProducer(p); + +p.setValue(2); +``` + +### The queue-drain approach + +Usually, one has to serialize calls to the `onXXX` methods so only one thread at a time is in any of them. The first thought, namely using `synchronized` blocks, is forbidden. It may cause deadlocks and unnecessary thread blocking. + +Most operators, however, can use a non-blocking approach called queue-drain. It works by posting the element to be emitted (or work to be performed) onto a **queue** then atomically increments a counter. If the value before the increment was zero, it means the current thread won the right to emit the contents of the queue. Once the queue is **drained**, the counter is decremented until zero and the thread continues with other activities. + +In code: + +```java +final AtomicInteger counter = new AtomicInteger(); +final Queue<T> queue = new ConcurrentLinkedQueue<>(); + +public void onNext(T t) { + queue.offer(t); + drain(); +} + +void drain() { + if (counter.getAndIncrement() == 0) { + do { + t = queue.poll(); + child.onNext(t); + } while (counter.decrementAndGet() != 0); + } +} +``` + +Often, the when the downstream requests some amount, that should also trigger a similar drain() call: + +```java + +final AtomicLong requested = new AtomicLong(); + +@Override +public void request(long n) { + if (n > 0) { + BackpressureUtils.getAndAddRequested(requested, n); + drain(); + } +} +``` + +Many operators do more than just draining the queue and emitting its content: they have to coordinate with the downstream to emit as many items from the queue as the downstream requested. + +For example, if one writes an operator that is unbounded-in but honors the requests of the downstream, the following `drain` pattern will do the job: + +```java +// downstream's consumer +final Subscriber<? super T> child; +// temporary storage for values +final Queue<T> queue; +// mutual exclusion +final AtomicInteger counter = new AtomicInteger(); +// tracks the downstream request amount +final AtomicLong requested = new AtomicLong(); + +// no more values expected from upstream +volatile boolean done; +// the upstream error if any +Throwable error; + +void drain() { + if (counter.getAndIncrement() != 0) { + return; + } + + int missed = 1; + Subscriber<? super T> child = this.child; + Queue<T> queue = this.queue; + + for (;;) { + long requests = requested.get(); + long emission = 0L; + + while (emission != requests) { // don't emit more than requested + if (child.isUnsubscribed()) { + return; + } + + boolean stop = done; // order matters here! + T t = queue.poll(); + boolean empty = t == null; + + // if no more values, emit an error or completion event + if (stop && empty) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + } else { + child.onCompleted(); + } + return; + } + // the upstream hasn't stopped yet but we don't have a value available + if (empty) { + break; + } + + child.onNext(t); + emission++; + } + + // if we are at a request boundary, a terminal event can be still emitted without requests + if (emission == requests) { + if (child.isUnsubscribed()) { + return; + } + + boolean stop = done; // order matters here! + boolean empty = queue.isEmpty(); + + // if no more values, emit an error or completion event + if (stop && empty) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + } else { + child.onCompleted(); + } + return; + } + } + + // decrement the current request amount by the emission count + if (emission != 0L && requests != Long.MAX_VALUE) { + BackpressureUtils.produced(requested, emission); + } + + // indicate that we have performed the outstanding amount of work + missed = counter.addAndGet(-missed); + if (missed == 0) { + return; + } + // if a concurrent getAndIncrement() happened, we loop back and continue + } +} +``` + +# Creating source operators + +One creates a source operator by implementing the `OnSubscribe` interface and then calls `Observable.create` with it: + +```java +OnSubscribe<T> onSubscribe = (Subscriber<? super T> child) -> { + // logic here +}; + +Observable<T> observable = Observable.create(onSubscribe); +``` + +*Note: a common mistake when writing an operator is that one simply calls `onNext` disregarding backpressure; one should use `fromCallable` instead for synchronously (blockingly) generating a single value.* + +The `logic here` could be arbitrary complex logic. Usually, one creates a class implementing `Subscription` and `Producer`, sets it on the `child` and works out the emission pattern: + +```java +OnSubscribe<T> onSubscribe = (Subscriber<? super T> child) -> { + MySubscription mys = new MySubscription(child, otherParams); + child.add(mys); + child.setProducer(mys); + + mys.runBusinessLogic(); +}; +``` + +## Converting a callback-API to reactive + +One of the reasons custom sources are created is when one converts a classical, callback-based 'reactive' API to RxJava. In this case, one has to setup the callback on the non-RxJava source and wire up unsubscription if possible: + +```java +OnSubscribe<Data> onSubscribe = (Subscriber<? super Data> child) -> { + Callback cb = event -> { + if (event.isSuccess()) { + child.setProducer(new SingleProducer<Data>(child, event.getData())); + } else { + child.onError(event.getError()); + } + }; + + Closeable c = api.query("someinput", cb); + + child.add(Subscriptions.create(() -> Closeables.closeQuietly(c))); +}; +``` + +In this example, the `api` takes a callback and returns a `Closeable`. Our handler signals the data by setting a `SingleProducer` of it to deal with downstream backpressure. If the downstream wants to cancel a running API call, the wrap to `Subscription` will close the query. + +However, in case the callback is called more than once, one has to deal with backpressure a different way. At this level, perhaps the most easiest way is to apply `onBackpressureBuffer` or `onBackpressureDrop` on the created `Observable`: + +```java +OnSubscribe<Data> onSubscribe = (Subscriber<? super Data> child) -> { + Callback cb = event -> { + if (event.isSuccess()) { + child.onNext(event.getData()); + } else { + child.onError(event.getError()); + } + }; + + Closeable c = api.query("someinput", cb); + + child.add(Subscriptions.create(() -> Closeables.closeQuietly(c))); +}; + +Observable<T> observable = Observable.create(onSubscribe).onBackpressureBuffer(); +``` + +# Creating intermediate operators + +Writing an intermediate operator is more difficult because one may need to coordinate request amount between the upstream and downstream. + +Intermediate operators are nothing but `Subscriber`s themselves, wrapping the downstream `Subscriber` themselves, modulating the calls to `onXXX`methods and they get subscribed to the upstream's `Observable`: + +```java +Func1<T, R> mapper = ... + +Observable<T> source = ... + +OnSubscribe<R> onSubscribe = (Subscriber<? super R> child) -> { + + source.subscribe(new MapSubscriber<T, R>(child) { + @Override + public void onNext(T t) { + child.onNext(function.call(t)); + } + + // ... etc + }); + +} +``` + +Depending on whether the safety-net of the `Observable.subscribe` method is too much of an overhead, one can call `Observable.unsafeSubscribe` but then the operator has to manage and unsubscribe its own resources manually. + +This approach has a common pattern that can be factored out - at the expense of more allocation and indirection - and became the `lift` operator. + +The `lift` operator takes an `Observable.Operator<R, T>` interface implementor where `R` is the output type towards the downstream and `T` is the input type from the upstream. In our example, we can rewrite the operator as follows: + +```java + +Operator<R, T> op = child -> + return new MapSubscriber<T, R>(child) { + @Override + public void onNext(T t) { + child.onNext(function.call(t)); + } + + // ... etc + }; +} + +source.lift(op)... +``` + +The constructor of `Subscriber(Subscriber<?>)` has some caveats: it shares the underlying resource management between `child` and `MapSubscriber`. This has the unfortunate effect that when the business logic calls `MapSubscriber.unsubscribe`, it may inadvertently unsubscribe the `child`'s resources prematurely. In addition, it sets up the `Subscriber` in a way that calls to `setProducer` are forwarded to the `child` as well. + +Sometimes it is acceptable, but generally one should avoid this coupling by implementing these custom `Subscriber`s among the following pattern: + +```java +public final class MapSubscriber<T, R> extends Subscriber<T> { + final Subscriber<? super R> child; + + final Function<T, R> mapper; + + public MapSubscriber(Subscriber<? super R> child, Func1<T, R> mapper) { + // no call to super(child) ! + this.child = child; + this.mapper = mapper; + + // prevent premature requesting + this.request(0); + } + + // setup the unsubscription and request links to downstream + void init() { + child.add(this); + child.setProducer(n -> requestMore(n)); + } + + @Override + public void onNext(T t) { + try { + child.onNext(mapper.call(t)); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + // if something crashed non-fatally, unsubscribe from upstream and signal the error + unsubscribe(); + onError(ex); + } + } + + @Override + public void onError(Throwable e) { + child.onError(e); + } + + @Override + public void onCompleted() { + child.onCompleted(); + } + + void requestMore(long n) { + // deal with the downstream requests + this.request(n); + } +} + +Operator<R, T> op = child -> { + MapSubscriber<T, R> parent = new MapSubscriber<T, R>(child, mapper); + parent.init(); + return parent; +} +``` + +Some operators may not emit the received value to the `child` subscriber (such as filter). In this case, one has to call `request(1)` to ask for a replenishment because the downstream doesn't know about the dropped value and won't request itself: + +```java +// ... + + @Override + public void onNext(T t) { + try { + if (predicate.call(t)) { + child.onNext(t); + } else { + request(1); + } + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + unsubscribe(); + onError(ex); + } + } + +// ... +``` + +When an operator maps an `onNext` emission to a terminal event then before calling the terminal event it should unsubscribe the subscriber to upstream (usually called the parent). In addition, because upstream may (legally) do something like this: + +```java +child.onNext(blah); +// no check for unsubscribed here +child.onCompleted(); +``` + +we should ensure that the operator complies with the `Observable` contract and only emits one terminal event so we use a defensive done flag: + +```java +boolean done; // = false; + +@Override +public void onError(Throwable e) { + if (done) { + return; + } + done = true; + ... +} + +@Override +public void onCompleted(Throwable e) { + if (done) { + return; + } + done = true; + ... +} +``` + +An example of this pattern is seen in `OnSubscribeMap`. + +# Further reading + +Writing operators that consume multiple source `Observable`s or produce to multiple `Subscriber`s are the most difficult one to implement. + +For inspiration, see the [blog posts](http://akarnokd.blogspot.hu/) of @akarnokd about the RxJava internals. The reader is advised to read from the very first post on and keep reading in sequence. \ No newline at end of file diff --git a/docs/Mathematical-and-Aggregate-Operators.md b/docs/Mathematical-and-Aggregate-Operators.md new file mode 100644 index 0000000000..f4a976f9d3 --- /dev/null +++ b/docs/Mathematical-and-Aggregate-Operators.md @@ -0,0 +1,25 @@ +This page shows operators that perform mathematical or other operations over an entire sequence of items emitted by an Observable. Because these operations must wait for the source Observable to complete emitting items before they can construct their own emissions (and must usually buffer these items), these operators are dangerous to use on Observables that may have very long or infinite sequences. + +#### Operators in the `rxjava-math` module +* [**`averageInteger( )`**](http://reactivex.io/documentation/operators/average.html) — calculates the average of Integers emitted by an Observable and emits this average +* [**`averageLong( )`**](http://reactivex.io/documentation/operators/average.html) — calculates the average of Longs emitted by an Observable and emits this average +* [**`averageFloat( )`**](http://reactivex.io/documentation/operators/average.html) — calculates the average of Floats emitted by an Observable and emits this average +* [**`averageDouble( )`**](http://reactivex.io/documentation/operators/average.html) — calculates the average of Doubles emitted by an Observable and emits this average +* [**`max( )`**](http://reactivex.io/documentation/operators/max.html) — emits the maximum value emitted by a source Observable +* [**`maxBy( )`**](http://reactivex.io/documentation/operators/max.html) — emits the item emitted by the source Observable that has the maximum key value +* [**`min( )`**](http://reactivex.io/documentation/operators/min.html) — emits the minimum value emitted by a source Observable +* [**`minBy( )`**](http://reactivex.io/documentation/operators/min.html) — emits the item emitted by the source Observable that has the minimum key value +* [**`sumInteger( )`**](http://reactivex.io/documentation/operators/sum.html) — adds the Integers emitted by an Observable and emits this sum +* [**`sumLong( )`**](http://reactivex.io/documentation/operators/sum.html) — adds the Longs emitted by an Observable and emits this sum +* [**`sumFloat( )`**](http://reactivex.io/documentation/operators/sum.html) — adds the Floats emitted by an Observable and emits this sum +* [**`sumDouble( )`**](http://reactivex.io/documentation/operators/sum.html) — adds the Doubles emitted by an Observable and emits this sum + +#### Other Aggregate Operators +* [**`concat( )`**](http://reactivex.io/documentation/operators/concat.html) — concatenate two or more Observables sequentially +* [**`count( )` and `countLong( )`**](http://reactivex.io/documentation/operators/count.html) — counts the number of items emitted by an Observable and emits this count +* [**`reduce( )`**](http://reactivex.io/documentation/operators/reduce.html) — apply a function to each emitted item, sequentially, and emit only the final accumulated value +* [**`collect( )`**](http://reactivex.io/documentation/operators/reduce.html) — collect items emitted by the source Observable into a single mutable data structure and return an Observable that emits this structure +* [**`toList( )`**](http://reactivex.io/documentation/operators/to.html) — collect all items from an Observable and emit them as a single List +* [**`toSortedList( )`**](http://reactivex.io/documentation/operators/to.html) — collect all items from an Observable and emit them as a single, sorted List +* [**`toMap( )`**](http://reactivex.io/documentation/operators/to.html) — convert the sequence of items emitted by an Observable into a map keyed by a specified key function +* [**`toMultiMap( )`**](http://reactivex.io/documentation/operators/to.html) — convert the sequence of items emitted by an Observable into an ArrayList that is also a map keyed by a specified key function \ No newline at end of file diff --git a/docs/Observable-Utility-Operators.md b/docs/Observable-Utility-Operators.md new file mode 100644 index 0000000000..b23c871894 --- /dev/null +++ b/docs/Observable-Utility-Operators.md @@ -0,0 +1,28 @@ +This page lists various utility operators for working with Observables. + +* [**`materialize( )`**](http://reactivex.io/documentation/operators/materialize-dematerialize.html) — convert an Observable into a list of Notifications +* [**`dematerialize( )`**](http://reactivex.io/documentation/operators/materialize-dematerialize.html) — convert a materialized Observable back into its non-materialized form +* [**`timestamp( )`**](http://reactivex.io/documentation/operators/timestamp.html) — attach a timestamp to every item emitted by an Observable +* [**`serialize( )`**](http://reactivex.io/documentation/operators/serialize.html) — force an Observable to make serialized calls and to be well-behaved +* [**`cache( )`**](http://reactivex.io/documentation/operators/replay.html) — remember the sequence of items emitted by the Observable and emit the same sequence to future Subscribers +* [**`observeOn( )`**](http://reactivex.io/documentation/operators/observeon.html) — specify on which Scheduler a Subscriber should observe the Observable +* [**`subscribeOn( )`**](http://reactivex.io/documentation/operators/subscribeon.html) — specify which Scheduler an Observable should use when its subscription is invoked +* [**`doOnEach( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to take whenever an Observable emits an item +* [**`doOnNext( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to call just before the Observable passes an `onNext` event along to its downstream +* [**`doAfterNext( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to call after the Observable has passed an `onNext` event along to its downstream +* [**`doOnCompleted( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to take when an Observable completes successfully +* [**`doOnError( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to take when an Observable completes with an error +* [**`doOnTerminate( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to call just before an Observable terminates, either successfully or with an error +* [**`doAfterTerminate( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to call just after an Observable terminated, either successfully or with an error +* [**`doOnSubscribe( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to take when an observer subscribes to an Observable +* *1.x* [**`doOnUnsubscribe( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to take when an observer unsubscribes from an Observable +* [**`finallyDo( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to take when an Observable completes +* [**`doFinally( )`**](http://reactivex.io/documentation/operators/do.html) — register an action to call when an Observable terminates or it gets disposed +* [**`delay( )`**](http://reactivex.io/documentation/operators/delay.html) — shift the emissions from an Observable forward in time by a specified amount +* [**`delaySubscription( )`**](http://reactivex.io/documentation/operators/delay.html) — hold an Subscriber's subscription request for a specified amount of time before passing it on to the source Observable +* [**`timeInterval( )`**](http://reactivex.io/documentation/operators/timeinterval.html) — emit the time lapsed between consecutive emissions of a source Observable +* [**`using( )`**](http://reactivex.io/documentation/operators/using.html) — create a disposable resource that has the same lifespan as an Observable +* [**`single( )`**](http://reactivex.io/documentation/operators/first.html) — if the Observable completes after emitting a single item, return that item, otherwise throw an exception +* [**`singleOrDefault( )`**](http://reactivex.io/documentation/operators/first.html) — if the Observable completes after emitting a single item, return that item, otherwise return a default item +* [**`repeat( )`**](http://reactivex.io/documentation/operators/repeat.html) — create an Observable that emits a particular item or sequence of items repeatedly +* [**`repeatWhen( )`**](http://reactivex.io/documentation/operators/repeat.html) — create an Observable that emits a particular item or sequence of items repeatedly, depending on the emissions of a second Observable \ No newline at end of file diff --git a/docs/Observable.md b/docs/Observable.md new file mode 100644 index 0000000000..fec5467908 --- /dev/null +++ b/docs/Observable.md @@ -0,0 +1,3 @@ +In RxJava an object that implements the _Observer_ interface _subscribes_ to an object of the _Observable_ class. Then that subscriber reacts to whatever item or sequence of items the Observable object _emits_. This pattern facilitates concurrent operations because it does not need to block while waiting for the Observable to emit objects, but instead it creates a sentry in the form of a subscriber that stands ready to react appropriately at whatever future time the Observable does so. + +For information about the Observable class, see [the Observable documentation page at ReactiveX.io](http://reactivex.io/documentation/observable.html). \ No newline at end of file diff --git a/docs/Parallel-flows.md b/docs/Parallel-flows.md new file mode 100644 index 0000000000..8cd0e9a8c9 --- /dev/null +++ b/docs/Parallel-flows.md @@ -0,0 +1,33 @@ +# Introduction + +Version 2.0.5 introduced the `ParallelFlowable` API that allows parallel execution of a few select operators such as `map`, `filter`, `concatMap`, `flatMap`, `collect`, `reduce` and so on. Note that is a **parallel mode** for `Flowable` (a sub-domain specific language) instead of a new reactive base type. + +Consequently, several typical operators such as `take`, `skip` and many others are not available and there is no `ParallelObservable` because **backpressure** is essential in not flooding the internal queues of the parallel operators as by expectation, we want to go parallel because the processing of the data is slow on one thread. + +The easiest way of entering the parallel world is by using `Flowable.parallel`: + +```java +ParallelFlowable<Integer> source = Flowable.range(1, 1000).parallel(); +``` + +By default, the parallelism level is set to the number of available CPUs (`Runtime.getRuntime().availableProcessors()`) and the prefetch amount from the sequential source is set to `Flowable.bufferSize()` (128). Both can be specified via overloads of `parallel()`. + +`ParallelFlowable` follows the same principles of parametric asynchrony as `Flowable` does, therefore, `parallel()` on itself doesn't introduce the asynchronous consumption of the sequential source but only prepares the parallel flow; the asynchrony is defined via the `runOn(Scheduler)` operator. + +```java +ParallelFlowable<Integer> psource = source.runOn(Schedulers.io()); +``` + +The parallelism level (`ParallelFlowable.parallelism()`) doesn't have to match the parallelism level of the `Scheduler`. The `runOn` operator will use as many `Scheduler.Worker` instances as defined by the parallelized source. This allows `ParallelFlowable` to work for CPU intensive tasks via `Schedulers.computation()`, blocking/IO bound tasks through `Schedulers.io()` and unit testing via `TestScheduler`. You can specify the prefetch amount on `runOn` as well. + +Once the necessary parallel operations have been applied, you can return to the sequential `Flowable` via the `ParallelFlowable.sequential()` operator. + +```java +Flowable<Integer> result = psource.filter(v -> v % 3 == 0).map(v -> v * v).sequential(); +``` + +Note that `sequential` doesn't guarantee any ordering between values flowing through the parallel operators. + +# Parallel operators + +TBD \ No newline at end of file diff --git a/docs/Phantom-Operators.md b/docs/Phantom-Operators.md new file mode 100644 index 0000000000..60da4a1a40 --- /dev/null +++ b/docs/Phantom-Operators.md @@ -0,0 +1,166 @@ +These operators have been proposed but are not part of the 1.0 release of RxJava. + +* [**`chunkify( )`**](Phantom-Operators#chunkify) — returns an iterable that periodically returns a list of items emitted by the source Observable since the last list +* [**`fromFuture( )`**](Phantom-Operators#fromfuture) — convert a Future into an Observable, but do not attempt to get the Future's value until a Subscriber subscribes +* [**`forEachFuture( )`**](Phantom-Operators#foreachfuture) — create a futureTask that will invoke a specified function on each item emitted by an Observable +* [**`forIterable( )`**](Phantom-Operators#foriterable) — apply a function to the elements of an Iterable to create Observables which are then concatenated +* [**`fromCancellableFuture( )`, `startCancellableFuture( )`, and `deferCancellableFuture( )`**](Phantom-Operators#fromcancellablefuture-startcancellablefuture-and-defercancellablefuture-) — versions of Future-to-Observable converters that monitor the subscription status of the Observable to determine whether to halt work on the Future +* [**`generate( )` and `generateAbsoluteTime( )`**](Phantom-Operators#generate-and-generateabsolutetime) — create an Observable that emits a sequence of items as generated by a function of your choosing +* [**`groupByUntil( )`**](Phantom-Operators#groupbyuntil) — a variant of the `groupBy` operator that closes any open `GroupedObservable` upon a signal from another Observable +* [**`multicast( )`**](Phantom-Operators#multicast) — represents an Observable as a Connectable Observable +* [**`onErrorFlatMap( )`**](Phantom-Operators#onerrorflatmap) — instructs an Observable to emit a sequence of items whenever it encounters an error +* [**`parallel( )`**](Phantom-Operators#parallel) — split the work done on the emissions from an Observable into multiple Observables each operating on its own parallel thread +* [**`parallelMerge( )`**](Phantom-Operators#parallelmerge) — combine multiple Observables into a smaller number of Observables, to facilitate parallelism +* [**`pivot( )`**](Phantom-Operators#pivot) — combine multiple sets of grouped observables so that they are arranged primarily by group rather than by set +* [**`publishLast( )`**](Phantom-Operators#publishlast) — represent an Observable as a Connectable Observable that emits only the last item emitted by the source Observable + + +*** + +## chunkify( ) +#### returns an iterable that periodically returns a list of items emitted by the source Observable since the last list +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/B.chunkify.png" width="640" height="490" /> + +The `chunkify( )` operator represents a blocking observable as an Iterable, that, each time you iterate over it, returns a list of items emitted by the source Observable since the previous iteration. These lists may be empty if there have been no such items emitted. + +*** + +## fromFuture( ) +#### convert a Future into an Observable, but do not attempt to get the Future's value until a Subscriber subscribes +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/fromFuture.png" width="640" height="335" /> + +The `fromFuture( )` method also converts a Future into an Observable, but it obtains this Future indirectly, by means of a function you provide. It creates the Observable immediately, but waits to call the function and to obtain the Future until a Subscriber subscribes to it. + +*** + +## forEachFuture( ) +#### create a futureTask that will invoke a specified function on each item emitted by an Observable +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/B.forEachFuture.png" width="640" height="375" /> + +The `forEachFuture( )` returns a `FutureTask` for each item emitted by the source Observable (or each item and each notification) that, when executed, will apply a function you specify to each such item (or item and notification). + +*** + +## forIterable( ) +#### apply a function to the elements of an Iterable to create Observables which are then concatenated +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/forIterable.png" width="640" height="310" /> + +`forIterable( )` is similar to `from(Iterable )` but instead of the resulting Observable emitting the elements of the Iterable as its own emitted items, it applies a specified function to each of these elements to generate one Observable per element, and then concatenates the emissions of these Observables to be its own sequence of emitted items. + +*** + +## fromCancellableFuture( ), startCancellableFuture( ), and deferCancellableFuture( ) +#### versions of Future-to-Observable converters that monitor the subscription status of the Observable to determine whether to halt work on the Future + +If the a subscriber to the Observable that results when a Future is converted to an Observable later unsubscribes from that Observable, it can be useful to have the ability to stop attempting to retrieve items from the Future. The "cancellable" Future enables you do do this. These three methods will return Observables that, when unsubscribed to, will also "unsubscribe" from the underlying Futures. + +*** + +## generate( ) and generateAbsoluteTime( ) +#### create an Observable that emits a sequence of items as generated by a function of your choosing +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/generate.png" width="640" height="315" /> + +The basic form of `generate( )` takes four parameters. These are `initialState` and three functions: `iterate( )`, `condition( )`, and `resultSelector( )`. `generate( )` uses these four parameters to generate an Observable sequence, which is its return value. It does so in the following way. + +`generate( )` creates each emission from the sequence by applying the `resultSelector( )` function to the current _state_ and emitting the resulting item. The first state, which determines the first emitted item, is `initialState`. `generate( )` determines each subsequent state by applying `iterate( )` to the current state. Before emitting an item, `generate( )` tests the result of `condition( )` applied to the current state. If the result of this test is `false`, instead of calling `resultSelector( )` and emitting the resulting value, `generate( )` terminates the sequence and stops iterating the state. + +There are also versions of `generate( )` that allow you to do the work of generating the sequence on a particular `Scheduler` and that allow you to set the time interval between emissions by applying a function to the current state. The `generateAbsoluteTime( )` allows you to control the time at which an item is emitted by applying a function to the state to get an absolute system clock time (rather than an interval from the previous emission). + +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/generateAbsoluteTime.png" width="640" height="330" /> + +#### see also: +* <a href="http://www.introtorx.com/Content/v1.0.10621.0/04_CreatingObservableSequences.html#ObservableGenerate">Introduction to Rx: Generate</a> +* Linq: <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.generate.aspx">`Generate`</a> +* RxJS: <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md#rxobservablegenerateinitialstate-condition-iterate-resultselector-scheduler">`generate`</a>, <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md#rxobservablegeneratewithabsolutetimeinitialstate-condition-iterate-resultselector-timeselector-scheduler">`generateWithAbsoluteTime`</a>, and <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md#rxobservablegeneratewithrelativetimeinitialstate-condition-iterate-resultselector-timeselector-scheduler">`generateWithRelativeTime`</a> + +*** +## groupByUntil( ) +#### a variant of the `groupBy` operator that closes any open `GroupedObservable` upon a signal from another Observable + +This version of `groupBy` adds another parameter: an Observable that emits duration markers. When a duration marker is emitted by this Observable, any grouped Observables that have been opened are closed, and `groupByUntil( )` will create new grouped Observables for any subsequent emissions by the source Observable. + +<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/groupByUntil.png" width="640" height="375" />​ + +Another variety of `groupByUntil( )` limits the number of groups that can be active at any particular time. If an item is emitted by the source Observable that would cause the number of groups to exceed this maximum, before the new group is emitted, one of the existing groups is closed (that is, the Observable it represents terminates by calling its Subscribers' `onCompleted` methods and then expires). + +*** + +## multicast( ) +#### represents an Observable as a Connectable Observable +To represent an Observable as a Connectable Observable, use the `multicast( )` method. + +#### see also: +* javadoc: <a href="http://reactivex.io/RxJava/javadoc/rx/Observable.html#multicast(rx.functions.Func0)">`multicast(subjectFactory)`</a> +* javadoc: <a href="http://reactivex.io/RxJava/javadoc/rx/Observable.html#multicast(rx.functions.Func0,%20rx.functions.Func1)">`multicast(subjectFactory, selector)`</a> +* RxJS: <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md#rxobservableprototypemulticastsubject--subjectselector-selector">`multicast`</a> +* Linq: <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.multicast.aspx">`Multicast`</a> +* <a href="http://www.introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html#PublishAndConnect">Introduction to Rx: Publish and Connect</a> +* <a href="http://www.introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html#Multicast">Introduction to Rx: Multicast</a> + +*** + +## onErrorFlatMap( ) +#### instructs an Observable to emit a sequence of items whenever it encounters an error +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/onErrorFlatMap.png" width="640" height="310" />​ + +The `onErrorFlatMap( )` method is similar to `onErrorResumeNext( )` except that it does not assume the source Observable will correctly terminate when it issues an error. Because of this, after emitting its backup sequence of items, `onErrorFlatMap( )` relinquishes control of the emitted sequence back to the source Observable. If that Observable again issues an error, `onErrorFlatMap( )` will again emit its backup sequence. + +The backup sequence is an Observable that is returned from a function that you pass to `onErrorFlatMap( )`. This function takes the Throwable issued by the source Observable as its argument, and so you can customize the sequence based on the nature of the Throwable. + +Because `onErrorFlatMap( )` is designed to work with pathological source Observables that do not terminate after issuing an error, it is mostly useful in debugging/testing scenarios. + +Note that you should apply `onErrorFlatMap( )` directly to the pathological source Observable, and not to that Observable after it has been modified by additional operators, as such operators may effectively renormalize the source Observable by unsubscribing from it immediately after it issues an error. Below, for example, is an illustration showing how `onErrorFlatMap( )` will respond to two error-generating Observables that have been merged by the `merge( )` operator. Note that it will *not* react to both errors generated by both Observables, but only to the single error passed along by `merge( )`: + +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/onErrorFlatMap.withMerge.png" width="640" height="630" />​ + +*** + +## parallel( ) +#### split the work done on the emissions from an Observable into multiple Observables each operating on its own parallel thread +<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/parallel.png" width="640" height="475" />​ + +The `parallel( )` method splits an Observable into as many Observables as there are available processors, and does work in parallel on each of these Observables. `parallel( )` then merges the results of these parallel computations back into a single, well-behaved Observable sequence. + +For the simple “run things in parallel” use case, you can instead use something like this: +```java +streamOfItems.flatMap(item -> { + itemToObservable(item).subscribeOn(Schedulers.io()); +}); +``` +Kick off your work for each item inside [`flatMap`](Transforming-Observables#flatmap-concatmap-and-flatmapiterable) using [`subscribeOn`](Observable-Utility-Operators#subscribeon) to make it asynchronous, or by using a function that already makes asychronous calls. + +#### see also: +* <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a> by Graham Lea + +*** + +## parallelMerge( ) +#### combine multiple Observables into a smaller number of Observables, to facilitate parallelism +<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/parallelMerge.png" width="640" height="535" />​ + +Use the `parallelMerge( )` method to take an Observable that emits a large number of Observables and to reduce it to an Observable that emits a particular, smaller number of Observables that emit the same set of items as the original larger set of Observables: for instance a number of Observables that matches the number of parallel processes that you want to use when processing the emissions from the complete set of Observables. + +*** + +## pivot( ) +#### combine multiple sets of grouped observables so that they are arranged primarily by group rather than by set +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/pivot.png" width="640" height="580" />​ + +If you combine multiple sets of grouped observables, such as those created by [`groupBy( )` and `groupByUntil( )`](Transforming-Observables#wiki-groupby-and-groupbyuntil), then even if those grouped observables have been grouped by a similar differentiation function, the resulting grouping will be primarily based on which set the observable came from, not on which group the observable belonged to. + +An example may make this clearer. Imagine you use `groupBy( )` to group the emissions of an Observable (Observable1) that emits integers into two grouped observables, one emitting the even integers and the other emitting the odd integers. You then repeat this process on a second Observable (Observable2) that emits another set of integers. You hope then to combine the sets of grouped observables emitted by each of these into a single grouped Observable by means of a operator like `from(Observable1, Observable2)`. + +The result will be a grouped observable that emits two groups: the grouped observable resulting from transforming Observable1, and the grouped observable resulting from transforming Observable2. Each of those grouped observables emit observables that in turn emit the odds and evens from the source observables. You can use `pivot( )` to change this around: by applying `pivot( )` to this grouped observable it will transform into one that emits two different groups: the odds group and the evens group, with each of these groups emitting a separate observable corresponding to which source observable its set of integers came from. Here is an illustration: + +<img src="http://github.com/Netflix/RxJava/wiki/images/rx-operators/pivot.ex.png" width="640" height="1140" />​ + +*** + +## publishLast( ) +#### represent an Observable as a Connectable Observable that emits only the last item emitted by the source Observable +<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/publishLast.png" width="640" height="310" /> + +#### see also: +* RxJS: <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md#rxobservableprototypepublishlatestselector">`publishLast`</a> +* Linq: <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.publishlast.aspx">`PublishLast`</a> +* <a href="http://www.introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html#PublishLast">Introduction to Rx: PublishLast</a> \ No newline at end of file diff --git a/docs/Plugins.md b/docs/Plugins.md new file mode 100644 index 0000000000..38dfcafd12 --- /dev/null +++ b/docs/Plugins.md @@ -0,0 +1,171 @@ +Plugins allow you to modify the default behavior of RxJava in several respects: + +* by changing the set of default computation, i/o, and new thread Schedulers +* by registering a handler for extraordinary errors that RxJava may encounter +* by registering functions that can take note of the occurrence of several regular RxJava activities + +As of 1.1.7 the regular `RxJavaPlugins` and the other hook classes have been deprecated in favor of `RxJavaHooks`. + +# RxJavaHooks + +The new `RxJavaHooks` allows you to hook into the lifecycle of the `Observable`, `Single` and `Completable` types, the `Scheduler`s returned by `Schedulers` and offers a catch-all for undeliverable errors. + +You can now change these hooks at runtime and there is no need to prepare hooks via system parameters anymore. Since users may still rely on the old hooking system, RxJavaHooks delegates to those old hooks by default. + +The `RxJavaHooks` has setters and getters of the various hook types: + +| Hook | Description | +|------|-------------| +| onError : `Action1<Throwable>` | Sets the catch-all callback | +| onObservableCreate : `Func1<Observable.OnSubscribe, Observable.OnSubscribe>` | Called when operators and sources are instantiated on `Observable` | +| onObservableStart : `Func2<Observable, Observable.OnSubscribe, Observable.OnSubscribe>` | Called before subscribing to an `Observable` actually happens | +| onObservableSubscribeError : `Func1<Throwable, Throwable>` | Called when subscribing to an `Observable` fails | +| onObservableReturn : `Func1<Subscription, Subscription>` | Called when the subscribing to an `Observable` succeeds and before returning the `Subscription` handler for it | +| onObservableLift : `Func1<Observable.Operator, Observable.Operator>` | Called when the operator `lift` is used with `Observable` | +| onSingleCreate : `Func1<Single.OnSubscribe, Single.OnSubscribe>` | Called when operators and sources are instantiated on `Single` | +| onSingleStart : `Func2<Single, Observable.OnSubscribe, Observable.OnSubscribe>` | Called before subscribing to a `Single` actually happens | +| onSingleSubscribeError : `Func1<Throwable, Throwable>` | Called when subscribing to a `Single` fails | +| onSingleReturn : `Func1<Subscription, Subscription>` | Called when the subscribing to a `Single` succeeds and before returning the `Subscription` handler for it | +| onSingleLift : `Func1<Observable.Operator, Observable.Operator>` | Called when the operator `lift` is used (note: `Observable.Operator` is deliberate here) | +| onCompletableCreate : `Func1<Completable.OnSubscribe, Completable.OnSubscribe>` | Called when operators and sources are instantiated on `Completable` | +| onCompletableStart : `Func2<Completable, Completable.OnSubscribe, Completable.OnSubscribe>` | Called before subscribing to a `Completable` actually happens | +| onCompletableSubscribeError : `Func1<Throwable, Throwable>` | Called when subscribing to a `Completable` fails | +| onCompletableLift : `Func1<Completable.Operator, Completable.Operator>` | Called when the operator `lift` is used with `Completable` | +| onComputationScheduler : `Func1<Scheduler, Scheduler>` | Called when using `Schedulers.computation()` | +| onIOScheduler : `Func1<Scheduler, Scheduler>` | Called when using `Schedulers.io()` | +| onNewThreadScheduler : `Func1<Scheduler, Scheduler>` | Called when using `Schedulers.newThread()` | +| onScheduleAction : `Func1<Action0, Action0>` | Called when a task gets scheduled in any of the `Scheduler`s | +| onGenericScheduledExecutorService : `Func0<ScheduledExecutorService>` | that should return single-threaded executors to support background timed tasks of RxJava itself | + +Reading and changing these hooks is thread-safe. + +You can also clear all hooks via `clear()` or reset to the default behavior (of delegating to the old RxJavaPlugins system) via `reset()`. + +Example: + +```java +RxJavaHooks.setOnObservableCreate(o -> { + System.out.println("Creating " + o.getClass()); + return o; +}); +try { + Observable.range(1, 10) + .map(v -> v * 2) + .filter(v -> v % 4 == 0) + .subscribe(System.out::println); +} finally { + RxJavaHooks.reset(); +} +``` + +In addition, the `RxJavaHooks` offers the so-called assembly tracking feature. This shims a custom `Observable`, `Single` and `Completable` into their chains which captures the current stacktrace when those operators were instantiated (assembly-time). Whenever an error is signalled via onError, these middle components attach this assembly-time stacktraces as last causes of that exception. This may help locating the problematic sequence in a codebase where there are too many similar flows and the plain exception itself doesn't tell which one failed in your codebase. + +Example: + +```java +RxJavaHooks.enableAssemblyTracking(); +try { + Observable.empty().single() + .subscribe(System.out::println, Throwable::printStackTrace); +} finally { + RxJavaHooks.resetAssemblyTracking(); +} +``` + +This will print something like this: + +``` +java.lang.NoSuchElementException +at rx.internal.operators.OnSubscribeSingle(OnSubscribeSingle.java:57) +... +Assembly trace: +at com.example.TrackingExample(TrackingExample:10) +``` + +The stacktrace string is also available in a field to support debugging and discovering the status of various operators in a running chain. + +The stacktrace is filtered by removing irrelevant entries such as Thread entry points, unit test runners and the entries of the tracking system itself to reduce noise. + +# RxJavaSchedulersHook + +**Deprecated** + +This plugin allows you to override the default computation, i/o, and new thread Schedulers with Schedulers of your choosing. To do this, extend the class `RxJavaSchedulersHook` and override these methods: + +* `Scheduler getComputationScheduler( )` +* `Scheduler getIOScheduler( )` +* `Scheduler getNewThreadScheduler( )` +* `Action0 onSchedule(action)` + +Then follow these steps: + +1. Create an object of the new `RxJavaDefaultSchedulers` subclass you have implemented. +1. Obtain the global `RxJavaPlugins` instance via `RxJavaPlugins.getInstance( )`. +1. Pass your default schedulers object to the `registerSchedulersHook( )` method of that instance. + +When you do this, RxJava will begin to use the Schedulers returned by your methods rather than its built-in defaults. + +# RxJavaErrorHandler + +**Deprecated** + +This plugin allows you to register a function that will handle errors that are passed to `SafeSubscriber.onError(Throwable)`. (`SafeSubscriber` is used for wrapping the incoming `Subscriber` when one calls `subscribe()`). To do this, extend the class `RxJavaErrorHandler` and override this method: + +* `void handleError(Throwable e)` + +Then follow these steps: + +1. Create an object of the new `RxJavaErrorHandler` subclass you have implemented. +1. Obtain the global `RxJavaPlugins` instance via `RxJavaPlugins.getInstance( )`. +1. Pass your error handler object to the `registerErrorHandler( )` method of that instance. + +When you do this, RxJava will begin to use your error handler to field errors that are passed to `SafeSubscriber.onError(Throwable)`. + +For example, this will call the hook: + +```java +RxJavaPlugins.getInstance().reset(); + +RxJavaPlugins.getInstance().registerErrorHandler(new RxJavaErrorHandler() { + @Override + public void handleError(Throwable e) { + e.printStackTrace(); + } +}); + +Observable.error(new IOException()) +.subscribe(System.out::println, e -> { }); +``` + +however, this call and chained operators in general won't trigger it in each stage: + +```java +Observable.error(new IOException()) +.map(v -> "" + v) +.unsafeSubscribe(System.out::println, e -> { }); +``` + +# RxJavaObservableExecutionHook + +**Deprecated** + +This plugin allows you to register functions that RxJava will call upon certain regular RxJava activities, for instance for logging or metrics-collection purposes. To do this, extend the class `RxJavaObservableExecutionHook` and override any or all of these methods: + +<table><thead> + <tr><th>method</th><th>when invoked</th></tr> + </thead><tbody> + <tr><td><tt>onCreate( )</tt></td><td>during <tt>Observable.create( )</tt></td></tr> + <tr><td><tt>onSubscribeStart( )</tt></td><td>immediately before <tt>Observable.subscribe( )</tt></td></tr> + <tr><td><tt>onSubscribeReturn( )</tt></td><td>immediately after <tt>Observable.subscribe( )</tt></td></tr> + <tr><td><tt>onSubscribeError( )</tt></td><td>upon a failed execution of <tt>Observable.subscribe( )</tt></td></tr> + <tr><td><tt>onLift( )</tt></td><td>during <tt>Observable.lift( )</tt></td></tr> + </tbody> +</table> + +Then follow these steps: + +1. Create an object of the new `RxJavaObservableExecutionHook` subclass you have implemented. +1. Obtain the global `RxJavaPlugins` instance via `RxJavaPlugins.getInstance( )`. +1. Pass your execution hooks object to the `registerObservableExecutionHook( )` method of that instance. + +When you do this, RxJava will begin to call your functions when it encounters the specific conditions they were designed to take note of. \ No newline at end of file diff --git a/docs/Problem-Solving-Examples-in-RxJava.md b/docs/Problem-Solving-Examples-in-RxJava.md new file mode 100644 index 0000000000..1b41c2a122 --- /dev/null +++ b/docs/Problem-Solving-Examples-in-RxJava.md @@ -0,0 +1,80 @@ +This page will present some elementary RxJava puzzles and walk through some solutions (using the Groovy language implementation of RxJava) as a way of introducing you to some of the RxJava operators. + +# Project Euler problem #1 + +There used to be a site called "Project Euler" that presented a series of mathematical computing conundrums (some fairly easy, others quite baffling) and challenged people to solve them. The first one was a sort of warm-up exercise: + +> If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. + +There are several ways we could go about this with RxJava. We might, for instance, begin by going through all of the natural numbers below 1000 with [`range`](Creating-Observables#range) and then [`filter`](Filtering-Observables#filter) out those that are not a multiple either of 3 or of 5: +````groovy +def threesAndFives = Observable.range(1,999).filter({ !((it % 3) && (it % 5)) }); +```` +Or, we could generate two Observable sequences, one containing the multiples of three and the other containing the multiples of five (by [`map`](https://github.com/Netflix/RxJava/wiki/Transforming-Observables#map)ping each value onto its appropriate multiple), making sure to only generating new multiples while they are less than 1000 (the [`takeWhile`](Conditional-and-Boolean-Operators#takewhile-and-takewhilewithindex) operator will help here), and then [`merge`](Combining-Observables#merge) these sets: +````groovy +def threes = Observable.range(1,999).map({it*3}).takeWhile({it<1000}); +def fives = Observable.range(1,999).map({it*5}).takeWhile({it<1000}); +def threesAndFives = Observable.merge(threes, fives).distinct(); +```` +Don't forget the [`distinct`](Filtering-Observables#distinct) operator here, otherwise merge will duplicate numbers like 15 that are multiples of both 5 and 3. + +Next, we want to sum up the numbers in the resulting sequence. If you have installed the optional `rxjava-math` module, this is elementary: just use an operator like [`sumInteger` or `sumLong`](Mathematical-and-Aggregate-Operators#suminteger-sumlong-sumfloat-and-sumdouble) on the `threesAndFives` Observable. But what if you don't have this module? How could you use standard RxJava operators to sum up a sequence and emit that sum? + +There are a number of operators that reduce a sequence emitted by a source Observable to a single value emitted by the resulting Observable. Most of the ones that are not in the `rxjava-math` module emit boolean evaluations of the sequence; we want something that can emit a number. The [`reduce`](Mathematical-and-Aggregate-Operators#reduce) operator will do the job: +````groovy +def summer = threesAndFives.reduce(0, { a, b -> a+b }); +```` +Here is how `reduce` gets the job done. It starts with 0 as a seed. Then, with each item that `threesAndFives` emits, it calls the closure `{ a, b -> a+b }`, passing it the current seed value as `a` and the emission as `b`. The closure adds these together and returns that sum, and `reduce` uses this returned value to overwrite its seed. When `threesAndFives` completes, `reduce` emits the final value returned from the closure as its sole emission: +<table> + <thead> + <tr><th>iteration</th><th>seed</th><th>emission</th><th>reduce</th></tr> + </thead> + <tbody> + <tr><td>1</td><td>0</td><td>3</td><td>3</td></tr> + <tr><td>2</td><td>3</td><td>5</td><td>8</td></tr> + <tr><td>3</td><td>8</td><td>6</td><td>14</td></tr> + <tr><td colspan="4"><center>…</center></td></tr> + <tr><td>466</td><td>232169</td><td>999</td><td>233168</td></tr> + </tbody> +</table> +Finally, we want to see the result. This means we must [subscribe](Observable#onnext-oncompleted-and-onerror) to the Observable we have constructed: +````groovy +summer.subscribe({println(it);}); +```` + +# Generate the Fibonacci Sequence + +How could you create an Observable that emits [the Fibonacci sequence](http://en.wikipedia.org/wiki/Fibonacci_number)? + +The most direct way would be to use the [`create`](Creating-Observables#wiki-create) operator to make an Observable "from scratch," and then use a traditional loop within the closure you pass to that operator to generate the sequence. Something like this: +````groovy +def fibonacci = Observable.create({ observer -> + def f1=0; f2=1, f=1; + while(!observer.isUnsubscribed() { + observer.onNext(f); + f = f1+f2; + f1 = f2; + f2 = f; + }; +}); +```` +But this is a little too much like ordinary linear programming. Is there some way we can instead create this sequence by composing together existing Observable operators? + +Here's an option that does this: +```` +def fibonacci = Observable.from(0).repeat().scan([0,1], { a,b -> [a[1], a[0]+a[1]] }).map({it[1]}); +```` +It's a little [janky](http://www.urbandictionary.com/define.php?term=janky). Let's walk through it: + +The `Observable.from(0).repeat()` creates an Observable that just emits a series of zeroes. This just serves as grist for the mill to keep [`scan`](Transforming-Observables#scan) operating. The way `scan` usually behaves is that it operates on the emissions from an Observable, one at a time, accumulating the result of operations on each emission in some sort of register, which it emits as its own emissions. The way we're using it here, it ignores the emissions from the source Observable entirely, and simply uses these emissions as an excuse to transform and emit its register. That register gets `[0,1]` as a seed, and with each iteration changes the register from `[a,b]` to `[b,a+b]` and then emits this register. + +This has the effect of emitting the following sequence of items: `[0,1], [1,1], [1,2], [2,3], [3,5], [5,8]...` + +The second item in this array describes the Fibonacci sequence. We can use `map` to reduce the sequence to just that item. + +To print out a portion of this sequence (using either method), you would use code like the following: +````groovy +fibonnaci.take(15).subscribe({println(it)})]; +```` + +Is there a less-janky way to do this? The [`generate`](https://github.com/Netflix/RxJava/wiki/Phantom-Operators#generate-and-generateabsolutetime) operator would avoid the silliness of creating an Observable that does nothing but turn the crank of `seed`, but this operator is not yet part of RxJava. Perhaps you can think of a more elegant solution? \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000000..474c8edc77 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,24 @@ +RxJava is a Java VM implementation of [ReactiveX (Reactive Extensions)](https://reactivex.io): a library for composing asynchronous and event-based programs by using observable sequences. + +For more information about ReactiveX, see the [Introduction to ReactiveX](http://reactivex.io/intro.html) page. + +### RxJava is Lightweight + +RxJava tries to be very lightweight. It is implemented as a single JAR that is focused on just the Observable abstraction and related higher-order functions. + +### RxJava is a Polyglot Implementation + +RxJava supports Java 6 or higher and JVM-based languages such as [Groovy](https://github.com/ReactiveX/RxGroovy), [Clojure](https://github.com/ReactiveX/RxClojure), [JRuby](https://github.com/ReactiveX/RxJRuby), [Kotlin](https://github.com/ReactiveX/RxKotlin) and [Scala](https://github.com/ReactiveX/RxScala). + +RxJava is meant for a more polyglot environment than just Java/Scala, and it is being designed to respect the idioms of each JVM-based language. (<a href="https://github.com/Netflix/RxJava/pull/304">This is something we’re still working on.</a>) + +### RxJava Libraries + +The following external libraries can work with RxJava: + +* [Hystrix](https://github.com/Netflix/Hystrix/wiki/How-To-Use#wiki-Reactive-Execution) latency and fault tolerance bulkheading library. +* [Camel RX](http://camel.apache.org/rx.html) provides an easy way to reuse any of the [Apache Camel components, protocols, transports and data formats](http://camel.apache.org/components.html) with the RxJava API +* [rxjava-http-tail](https://github.com/myfreeweb/rxjava-http-tail) allows you to follow logs over HTTP, like `tail -f` +* [mod-rxvertx - Extension for VertX](https://github.com/vert-x/mod-rxvertx) that provides support for Reactive Extensions (RX) using the RxJava library +* [rxjava-jdbc](https://github.com/davidmoten/rxjava-jdbc) - use RxJava with jdbc connections to stream ResultSets and do functional composition of statements +* [rtree](https://github.com/davidmoten/rtree) - immutable in-memory R-tree and R*-tree with RxJava api including backpressure \ No newline at end of file diff --git a/docs/Reactive-Streams.md b/docs/Reactive-Streams.md new file mode 100644 index 0000000000..c3a65b883a --- /dev/null +++ b/docs/Reactive-Streams.md @@ -0,0 +1,121 @@ +# Reactive Streams + RxJava + +[Reactive Streams](https://github.com/reactive-streams/reactive-streams-jvm/) has been a [collaborative effort](https://medium.com/@viktorklang/reactive-streams-1-0-0-interview-faaca2c00bec) to standardize the protocol for asynchronous streams on the JVM. The RxJava team was [part of the effort](https://github.com/reactive-streams/reactive-streams-jvm/graphs/contributors) from the beginning and supports the use of Reactive Streams APIs and eventually the [Java 9 Flow APIs](http://cs.oswego.edu/pipermail/concurrency-interest/2015-January/013641.html) which are [resulting from the success of the Reactive Stream effort](https://github.com/reactive-streams/reactive-streams-jvm/issues/195). + +## How does this relate to RxJava itself? + +#### RxJava 1.x + +Currently RxJava 1.x does not directly implement the Reactive Streams APIs. This is due to RxJava 1.x already existing and not being able to break public APIs. It does however comply semantically with the non-blocking "reactive pull" approach to backpressure and flow control and thus can use a bridge between types. The [RxJavaReactiveStreams module](https://github.com/ReactiveX/RxJavaReactiveStreams) bridges between the RxJava 1.x types and Reactive Streams types for interop between Reactive Streams implementations and passes the Reactive Streams [TCK compliance tests](https://github.com/ReactiveX/RxJavaReactiveStreams/blob/0.x/rxjava-reactive-streams/build.gradle#L8). + +Its API looks like this: + +```java +package rx; + +import org.reactivestreams.Publisher; + +public abstract class RxReactiveStreams { + + public static <T> Publisher<T> toPublisher(Observable<T> observable) { … } + + public static <T> Observable<T> toObservable(Publisher<T> publisher) { … } + +} +``` + +#### RxJava 2.x + +[RxJava 2.x](https://github.com/ReactiveX/RxJava/issues/2450) will target Reactive Streams APIs directly for Java 8+. The plan is to also support Java 9 `j.u.c.Flow` types by leveraging new Java multi-versioned jars to support this when using RxJava 2.x in Java 9 while still working on Java 8. + +RxJava 2 will truly be "Reactive Extensions" now that there is an interface to extend. RxJava 1 didn't have a base interface or contract to extend so had to define it from scratch. RxJava 2 intends on being a high performing, battle-tested, lightweight (single dependency on Reactive Streams), non-opinionated implementation of Reactive Streams and `j.u.c.Flow` that provides a library of higher-order functions with parameterized concurrency. + +## Public APIs of Libraries + +A strong area of value for Reactive Streams is public APIs exposed in libraries. Following is some guidance and recommendation on how to use both Reactive Streams and RxJava in creating reactive libraries while decoupling the concrete implementations. + +### Pros of Exposing Reactive Stream APIs instead of RxJava + +* Lightweight: Very lightweight dependency on interfaces without any concrete implementations. This keeps dependency graphs and bytesize small. +* Future Proof: Since the Reactive Stream API is so simple, was collaboratively defined and is [becoming part](https://github.com/reactive-streams/reactive-streams-jvm/issues/195) of [JDK 9](http://cs.oswego.edu/pipermail/concurrency-interest/2015-January/013641.html) it is a future proof API for exposing async access to data. The [`j.u.c.Flow` APIs](http://gee.cs.oswego.edu/dl/jsr166/dist/docs/java/util/concurrent/Flow.html) of JDK 9 match the APIs of Reactive Streams so any types that implement the Reactive Streams `Publisher` will also be able to implement the `Flow.Publisher` type. +* Interop: An API exposed with Reactive Streams types can easily be consumed by any implementation such as RxJava, Akka Streams and Reactor. + +### Cons of Exposing Reactive Stream APIs instead of RxJava + +* A Reactive Stream `Publisher` is not very useful by itself. Without higher-order functions like `flatMap` it is just a better callback. This means that consumption of a `Publisher` will almost always need to be converted or wrapped into a Reactive Stream implementation. This can be verbose and awkward to always be wrapping `Publisher` APIs into a concrete implementation. If the JVM supported extension methods this would be elegant, but since it doesn't it is explicit and verbose. + + Specifically the Reactive Streams and Flow `Publisher` interfaces do not provide any implementations of operators like `flatMap`, `merge`, `filter`, `take`, `zip` and the many others used to compose and transform async streams. A `Publisher` can only be subscribed to. A concrete implementation such as RxJava is needed to provide composition. +* The Reactive Streams specification and binary artifacts do not provide a concrete implementation of `Publisher`. Generally a library will need or want capabilities provides by RxJava, Akka Streams, etc for its internal use or just to produce a valid `Publisher` that supports backpressure semantics (which are non-trivial to implement correctly). + +### Recommended Approach + +Now that Reactive Streams has achieved 1.0 we recommend using it for core APIs that are intended for interop. This will allow embracing asynchronous stream semantics without a hard dependency on any single implementation. This means a consumer of the API can then choose RxJava 1.x, RxJava 2.x, Akka Streams, Reactor or other stream composition libraries as suits them best. It also provides better future proofing, for example as RxJava moves from 1.x to 2.x. + +However, to limit the cons listed above, we also recommend making it easy for consumption without developers needing to explicitly wrap the APIs with their composition library of choice. For this reason we recommend providing wrapper modules for popular Reactive Stream implementations on top of the core API, otherwise your customers will each need to do this themselves. + +Note that if Java offered extension methods this approach wouldn't be needed, but until Java offers that (not anytime soon if ever) the following is an approach to achieve the pros and address the cons. + +For example, a database driver may have modules such as this: + + +// core library exposing Reactive Stream Publisher APIs +* async-database-driver + +// integration jars wrapped with concrete implementations +* async-database-driver-rxjava1 +* async-database-driver-rxjava2 +* async-database-driver-akka-stream + +The "core" may expose an API like this: + +```java +package com.database.driver; + +public class Database { + public org.reactivestreams.Publisher getValue(String key); +} +``` + +The RxJava 1.x wrapper could then be a separate module that provides RxJava specific APIs like this: + +```java +package com.database.driver.rxjava1; + +public class Database { + public rx.Observable getValue(String key); +} +``` + +The core `Publisher` API can be wrapped as simply as this: + +```java +public rx.Observable getValue(String key) { + return RxReactiveStreams.toObservable(coreDatabase.getValue(key)); +} +``` + +The RxJava 2.x wrapper would differ like this (once 2.x is available): + +```java +package com.database.driver.rxjava2; + +public class Database { + public io.reactivex.Observable getValue(String key); +} +``` + +The Akka Streams wrapper would in turn look like this: + +```java +package com.database.driver.akkastream; + +public class Database { + public akka.stream.javadsl.Source getValue(String key); +} +``` + +A developer could then choose to depend directly on the `async-database-driver` APIs but most will use one of the wrappers that supports the composition library they have chosen. + +---- + +If something could be clarified further, please help improve this page via discussion at https://github.com/ReactiveX/RxJava/issues/2917 \ No newline at end of file diff --git a/docs/Scheduler.md b/docs/Scheduler.md new file mode 100644 index 0000000000..95657cc488 --- /dev/null +++ b/docs/Scheduler.md @@ -0,0 +1,3 @@ +If you want to introduce multithreading into your cascade of Observable operators, you can do so by instructing those operators (or particular Observables) to operate on particular Schedulers. + +For more information about Schedulers, see [the ReactiveX `Scheduler` documentation page](http://reactivex.io/documentation/scheduler.html). \ No newline at end of file diff --git a/docs/String-Observables.md b/docs/String-Observables.md new file mode 100644 index 0000000000..3dc3038b94 --- /dev/null +++ b/docs/String-Observables.md @@ -0,0 +1,9 @@ +The `StringObservable` class contains methods that represent operators particular to Observables that deal in string-based sequences and streams. These include: + +* [**`byLine( )`**](http://reactivex.io/documentation/operators/map.html) — converts an Observable of Strings into an Observable of Lines by treating the source sequence as a stream and splitting it on line-endings +* [**`decode( )`**](http://reactivex.io/documentation/operators/from.html) — convert a stream of multibyte characters into an Observable that emits byte arrays that respect character boundaries +* [**`encode( )`**](http://reactivex.io/documentation/operators/map.html) — transform an Observable that emits strings into an Observable that emits byte arrays that respect character boundaries of multibyte characters in the original strings +* [**`from( )`**](http://reactivex.io/documentation/operators/from.html) — convert a stream of characters or a Reader into an Observable that emits byte arrays or Strings +* [**`join( )`**](http://reactivex.io/documentation/operators/sum.html) — converts an Observable that emits a sequence of strings into an Observable that emits a single string that concatenates them all, separating them by a specified string +* [**`split( )`**](http://reactivex.io/documentation/operators/flatmap.html) — converts an Observable of Strings into an Observable of Strings that treats the source sequence as a stream and splits it on a specified regex boundary +* [**`stringConcat( )`**](http://reactivex.io/documentation/operators/sum.html) — converts an Observable that emits a sequence of strings into an Observable that emits a single string that concatenates them all \ No newline at end of file diff --git a/docs/Subject.md b/docs/Subject.md new file mode 100644 index 0000000000..ffb7feeb51 --- /dev/null +++ b/docs/Subject.md @@ -0,0 +1,12 @@ +A <a href="http://reactivex.io/RxJava/javadoc/rx/subjects/Subject.html">`Subject`</a> is a sort of bridge or proxy that acts both as an `Subscriber` and as an `Observable`. Because it is a Subscriber, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items. + +For more information about the varieties of Subject and how to use them, see [the ReactiveX `Subject` documentation](http://reactivex.io/documentation/subject.html). + +#### Serializing +When you use a Subject as a Subscriber, take care not to call its `onNext( )` method (or its other `on` methods) from multiple threads, as this could lead to non-serialized calls, which violates the Observable contract and creates an ambiguity in the resulting Subject. + +To protect a Subject from this danger, you can convert it into a [`SerializedSubject`](http://reactivex.io/RxJava/javadoc/rx/subjects/SerializedSubject.html) with code like the following: + +```java +mySafeSubject = new SerializedSubject( myUnsafeSubject ); +``` diff --git a/docs/The-RxJava-Android-Module.md b/docs/The-RxJava-Android-Module.md new file mode 100644 index 0000000000..108febec04 --- /dev/null +++ b/docs/The-RxJava-Android-Module.md @@ -0,0 +1,110 @@ +**Note:** This page is out-of-date. See [the RxAndroid wiki](https://github.com/ReactiveX/RxAndroid/wiki) for more up-to-date instructions. + +*** + +The `rxjava-android` module contains Android-specific bindings for RxJava. It adds a number of classes to RxJava to assist in writing reactive components in Android applications. + +- It provides a `Scheduler` that schedules an `Observable` on a given Android `Handler` thread, particularly the main UI thread. +- It provides operators that make it easier to deal with `Fragment` and `Activity` life-cycle callbacks. +- It provides wrappers for various Android messaging and notification components so that they can be lifted into an Rx call chain +- It provides reusable, self-contained, reactive components for common Android use cases and UI concerns. _(coming soon)_ + +# Binaries + +You can find binaries and dependency information for Maven, Ivy, Gradle and others at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22rxandroid%22). + +Here is an example for [Maven](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22rxandroid%22): + +```xml +<dependency> + <groupId>io.reactivex</groupId> + <artifactId>rxandroid</artifactId> + <version>0.23.0</version> +</dependency> +``` + +…and for Ivy: + +```xml +<dependency org="io.reactivex" name="rxandroid" rev="0.23.0" /> +``` + +The currently supported `minSdkVersion` is `10` (Android 2.3/Gingerbread) + +# Examples + +## Observing on the UI thread + +You commonly deal with asynchronous tasks on Android by observing the task’s result or outcome on the main UI thread. Using vanilla Android, you would typically accomplish this with an `AsyncTask`. With RxJava you would instead declare your `Observable` to be observed on the main thread by using the `observeOn` operator: + +```java +public class ReactiveFragment extends Fragment { + +@Override +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Observable.from("one", "two", "three", "four", "five") + .subscribeOn(Schedulers.newThread()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(/* an Observer */); +} +``` + +This executes the Observable on a new thread, which emits results through `onNext` on the main UI thread. + +## Observing on arbitrary threads +The previous example is a specialization of a more general concept: binding asynchronous communication to an Android message loop by using the `Handler` class. In order to observe an `Observable` on an arbitrary thread, create a `Handler` bound to that thread and use the `AndroidSchedulers.handlerThread` scheduler: + +```java +new Thread(new Runnable() { + @Override + public void run() { + final Handler handler = new Handler(); // bound to this thread + Observable.from("one", "two", "three", "four", "five") + .subscribeOn(Schedulers.newThread()) + .observeOn(AndroidSchedulers.handlerThread(handler)) + .subscribe(/* an Observer */) + + // perform work, ... + } +}, "custom-thread-1").start(); +``` + +This executes the Observable on a new thread and emits results through `onNext` on `custom-thread-1`. (This example is contrived since you could as well call `observeOn(Schedulers.currentThread())` but it illustrates the idea.) + +## Fragment and Activity life-cycle + +On Android it is tricky for asynchronous actions to access framework objects in their callbacks. That’s because Android may decide to destroy an `Activity`, for instance, while a background thread is still running. The thread will attempt to access views on the now dead `Activity`, which results in a crash. (This will also create a memory leak, since your background thread holds on to the `Activity` even though it’s not visible anymore.) + +This is still a concern when using RxJava on Android, but you can deal with the problem in a more elegant way by using `Subscription`s and a number of Observable operators. In general, when you run an `Observable` inside an `Activity` that subscribes to the result (either directly or through an inner class), you must unsubscribe from the sequence in `onDestroy`, as shown in the following example: + +```java +// MyActivity +private Subscription subscription; + +protected void onCreate(Bundle savedInstanceState) { + this.subscription = observable.subscribe(this); +} + +... + +protected void onDestroy() { + this.subscription.unsubscribe(); + super.onDestroy(); +} +``` + +This ensures that all references to the subscriber (the `Activity`) will be released as soon as possible, and no more notifications will arrive at the subscriber through `onNext`. + +One problem with this is that if the `Activity` is destroyed because of a change in screen orientation, the Observable will fire again in `onCreate`. You can prevent this by using the `cache` or `replay` Observable operators, while making sure the Observable somehow survives the `Activity` life-cycle (for instance, by storing it in a global cache, in a Fragment, etc.) You can use either operator to ensure that when the subscriber subscribes to an Observable that’s already “running,” items emitted by the Observable during the span when it was detached from the `Activity` will be “played back,” and any in-flight notifications from the Observable will be delivered as usual. + +# See also +* [How the New York Times is building its Android app with Groovy/RxJava](http://open.blogs.nytimes.com/2014/08/18/getting-groovy-with-reactive-android/?_php=true&_type=blogs&_php=true&_type=blogs&_r=1&) by Mohit Pandey +* [Functional Reactive Programming on Android With RxJava](http://mttkay.github.io/blog/2013/08/25/functional-reactive-programming-on-android-with-rxjava/) and [Conquering concurrency - bringing the Reactive Extensions to the Android platform](https://speakerdeck.com/mttkay/conquering-concurrency-bringing-the-reactive-extensions-to-the-android-platform) by Matthias Käppler +* [Learning RxJava for Android by example](https://github.com/kaushikgopal/Android-RxJava) by Kaushik Gopal +* [Top 7 Tips for RxJava on Android](http://blog.futurice.com/top-7-tips-for-rxjava-on-android) and [Rx Architectures in Android](http://www.slideshare.net/TimoTuominen1/rxjava-architectures-on-android-8-android-livecode-32531688) by Timo Tuominen +* [FRP on Android](http://slid.es/yaroslavheriatovych/frponandroid) by Yaroslav Heriatovych +* [Rx for .NET and RxJava for Android](http://blog.futurice.com/tech-pick-of-the-week-rx-for-net-and-rxjava-for-android) by Olli Salonen +* [RxJava in Xtend for Android](http://blog.futurice.com/android-development-has-its-own-swift) by Andre Medeiros +* [RxJava and Xtend](http://mnmlst-dvlpr.blogspot.de/2014/07/rxjava-and-xtend.html) by Stefan Oehme +* Grokking RxJava, [Part 1: The Basics](http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/), [Part 2: Operator, Operator](http://blog.danlew.net/2014/09/22/grokking-rxjava-part-2/), [Part 3: Reactive with Benefits](http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3/), [Part 4: Reactive Android](http://blog.danlew.net/2014/10/08/grokking-rxjava-part-4/) - published in Sep/Oct 2014 by Daniel Lew \ No newline at end of file diff --git a/docs/Transforming-Observables.md b/docs/Transforming-Observables.md new file mode 100644 index 0000000000..aa7b53e89f --- /dev/null +++ b/docs/Transforming-Observables.md @@ -0,0 +1,10 @@ +This page shows operators with which you can transform items that are emitted by an Observable. + +* [**`map( )`**](http://reactivex.io/documentation/operators/map.html) — transform the items emitted by an Observable by applying a function to each of them +* [**`flatMap( )`, `concatMap( )`, and `flatMapIterable( )`**](http://reactivex.io/documentation/operators/flatmap.html) — transform the items emitted by an Observable into Observables (or Iterables), then flatten this into a single Observable +* [**`switchMap( )`**](http://reactivex.io/documentation/operators/flatmap.html) — transform the items emitted by an Observable into Observables, and mirror those items emitted by the most-recently transformed Observable +* [**`scan( )`**](http://reactivex.io/documentation/operators/scan.html) — apply a function to each item emitted by an Observable, sequentially, and emit each successive value +* [**`groupBy( )`**](http://reactivex.io/documentation/operators/groupby.html) — divide an Observable into a set of Observables that emit groups of items from the original Observable, organized by key +* [**`buffer( )`**](http://reactivex.io/documentation/operators/buffer.html) — periodically gather items from an Observable into bundles and emit these bundles rather than emitting the items one at a time +* [**`window( )`**](http://reactivex.io/documentation/operators/window.html) — periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time +* [**`cast( )`**](http://reactivex.io/documentation/operators/map.html) — cast all items from the source Observable into a particular type before reemitting them \ No newline at end of file diff --git a/docs/What's-different-in-2.0.md b/docs/What's-different-in-2.0.md new file mode 100644 index 0000000000..4dbaea04b1 --- /dev/null +++ b/docs/What's-different-in-2.0.md @@ -0,0 +1,972 @@ +RxJava 2.0 has been completely rewritten from scratch on top of the Reactive-Streams specification. The specification itself has evolved out of RxJava 1.x and provides a common baseline for reactive systems and libraries. + +Because Reactive-Streams has a different architecture, it mandates changes to some well known RxJava types. This wiki page attempts to summarize what has changed and describes how to rewrite 1.x code into 2.x code. + +For technical details on how to write operators for 2.x, please visit the [Writing Operators](https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0) wiki page. + +# Contents + + - [Maven address and base package](#maven-address-and-base-package) + - [Javadoc](#javadoc) + - [Nulls](#nulls) + - [Observable and Flowable](#observable-and-flowable) + - [Single](#single) + - [Completable](#completable) + - [Maybe](#maybe) + - [Base reactive interfaces](#base-reactive-interfaces) + - [Subjects and Processors](#subjects-and-processors) + - [Other classes](#other-classes) + - [Functional interfaces](#functional-interfaces) + - [Subscriber](#subscriber) + - [Subscription](#subscription) + - [Backpressure](#backpressure) + - [Reactive-Streams compliance](#reactive-streams-compliance) + - [Runtime hooks](#runtime-hooks) + - [Error handling](#error-handling) + - [Scheduler](#schedulers) + - [Entering the reactive world](#entering-the-reactive-world) + - [Leaving the reactive world](#leaving-the-reactive-world) + - [Testing](#testing) + - [Operator differences](#operator-differences) + - [Miscellaneous changes](#miscellaneous-changes) + + +# Maven address and base package + +To allow having RxJava 1.x and RxJava 2.x side-by-side, RxJava 2.x is under the maven coordinates `io.reactivex.rxjava2:rxjava:2.x.y` and classes are accessible below `io.reactivex`. + +Users switching from 1.x to 2.x have to re-organize their imports, but carefully. + +# Javadoc + +The official Javadoc pages for 2.x is hosted at http://reactivex.io/RxJava/2.x/javadoc/ + +# Nulls + +RxJava 2.x no longer accepts `null` values and the following will yield `NullPointerException` immediately or as a signal to downstream: + +```java +Observable.just(null); + +Single.just(null); + +Observable.fromCallable(() -> null) + .subscribe(System.out::println, Throwable::printStackTrace); + +Observable.just(1).map(v -> null) + .subscribe(System.out::println, Throwable::printStackTrace); +``` + +This means that `Observable<Void>` can no longer emit any values but only terminate normally or with an exception. API designers may instead choose to define `Observable<Object>` with no guarantee on what `Object` will be (which should be irrelevant anyway). For example, if one needs a signaller-like source, a shared enum can be defined and its solo instance `onNext`'d: + +```java +enum Irrelevant { INSTANCE; } + +Observable<Object> source = Observable.create((ObservableEmitter<Object> emitter) -> { + System.out.println("Side-effect 1"); + emitter.onNext(Irrelevant.INSTANCE); + + System.out.println("Side-effect 2"); + emitter.onNext(Irrelevant.INSTANCE); + + System.out.println("Side-effect 3"); + emitter.onNext(Irrelevant.INSTANCE); +}); + +source.subscribe(e -> { /* Ignored. */ }, Throwable::printStackTrace); +``` + +# Observable and Flowable + +A small regret about introducing backpressure in RxJava 0.x is that instead of having a separate base reactive class, the `Observable` itself was retrofitted. The main issue with backpressure is that many hot sources, such as UI events, can't be reasonably backpressured and cause unexpected `MissingBackpressureException` (i.e., beginners don't expect them). + +We try to remedy this situation in 2.x by having `io.reactivex.Observable` non-backpressured and the new `io.reactivex.Flowable` be the backpressure-enabled base reactive class. + +The good news is that operator names remain (mostly) the same. The bad news is that one should be careful when performing 'organize imports' as it may select the non-backpressured `io.reactivex.Observable` unintended. + +## Which type to use? + +When architecting dataflows (as an end-consumer of RxJava) or deciding upon what type your 2.x compatible library should take and return, you can consider a few factors that should help you avoid problems down the line such as `MissingBackpressureException` or `OutOfMemoryError`. + +### When to use Observable + + - You have a flow of no more than 1000 elements at its longest: i.e., you have so few elements over time that there is practically no chance for OOME in your application. + - You deal with GUI events such as mouse moves or touch events: these can rarely be backpressured reasonably and aren't that frequent. You may be able to handle an element frequency of 1000 Hz or less with Observable but consider using sampling/debouncing anyway. + - Your flow is essentially synchronous but your platform doesn't support Java Streams or you miss features from it. Using `Observable` has lower overhead in general than `Flowable`. *(You could also consider IxJava which is optimized for Iterable flows supporting Java 6+)*. + +### When to use Flowable + + - Dealing with 10k+ of elements that are generated in some fashion somewhere and thus the chain can tell the source to limit the amount it generates. + - Reading (parsing) files from disk is inherently blocking and pull-based which works well with backpressure as you control, for example, how many lines you read from this for a specified request amount). + - Reading from a database through JDBC is also blocking and pull-based and is controlled by you by calling `ResultSet.next()` for likely each downstream request. + - Network (Streaming) IO where either the network helps or the protocol used supports requesting some logical amount. + - Many blocking and/or pull-based data sources which may eventually get a non-blocking reactive API/driver in the future. + + +# Single + +The 2.x `Single` reactive base type, which can emit a single `onSuccess` or `onError` has been redesigned from scratch. Its architecture now derives from the Reactive-Streams design. Its consumer type (`rx.Single.SingleSubscriber<T>`) has been changed from being a class that accepts `rx.Subscription` resources to be an interface `io.reactivex.SingleObserver<T>` that has only 3 methods: + +```java +interface SingleObserver<T> { + void onSubscribe(Disposable d); + void onSuccess(T value); + void onError(Throwable error); +} +``` + +and follows the protocol `onSubscribe (onSuccess | onError)?`. + +# Completable + +The `Completable` type remains largely the same. It was already designed along the Reactive-Streams style for 1.x so no user-level changes there. + +Similar to the naming changes, `rx.Completable.CompletableSubscriber` has become `io.reactivex.CompletableObserver` with `onSubscribe(Disposable)`: + +```java +interface CompletableObserver<T> { + void onSubscribe(Disposable d); + void onComplete(); + void onError(Throwable error); +} +``` + +and still follows the protocol `onSubscribe (onComplete | onError)?`. + +# Maybe + +RxJava 2.0.0-RC2 introduced a new base reactive type called `Maybe`. Conceptually, it is a union of `Single` and `Completable` providing the means to capture an emission pattern where there could be 0 or 1 item or an error signalled by some reactive source. + +The `Maybe` class is accompanied by `MaybeSource` as its base interface type, `MaybeObserver<T>` as its signal-receiving interface and follows the protocol `onSubscribe (onSuccess | onError | onComplete)?`. Because there could be at most 1 element emitted, the `Maybe` type has no notion of backpressure (because there is no buffer bloat possible as with unknown length `Flowable`s or `Observable`s. + +This means that an invocation of `onSubscribe(Disposable)` is potentially followed by one of the other `onXXX` methods. Unlike `Flowable`, if there is only a single value to be signalled, only `onSuccess` is called and `onComplete` is not. + +Working with this new base reactive type is practically the same as the others as it offers a modest subset of the `Flowable` operators that make sense with a 0 or 1 item sequence. + +```java +Maybe.just(1) +.map(v -> v + 1) +.filter(v -> v == 1) +.defaultIfEmpty(2) +.test() +.assertResult(2); +``` + +# Base reactive interfaces + +Following the style of extending the Reactive-Streams `Publisher<T>` in `Flowable`, the other base reactive classes now extend similar base interfaces (in package `io.reactivex`): + +```java +interface ObservableSource<T> { + void subscribe(Observer<? super T> observer); +} + +interface SingleSource<T> { + void subscribe(SingleObserver<? super T> observer); +} + +interface CompletableSource { + void subscribe(CompletableObserver observer); +} + +interface MaybeSource<T> { + void subscribe(MaybeObserver<? super T> observer); +} +``` + +Therefore, many operators that required some reactive base type from the user now accept `Publisher` and `XSource`: + +```java +Flowable<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapper); + +Observable<R> flatMap(Function<? super T, ? extends ObservableSource<? extends R>> mapper); +``` + +By having `Publisher` as input this way, you can compose with other Reactive-Streams compliant libraries without the need to wrap them or convert them into `Flowable` first. + +If an operator has to offer a reactive base type, however, the user will receive the full reactive class (as giving out an `XSource` is practically useless as it doesn't have operators on it): + +```java +Flowable<Flowable<Integer>> windows = source.window(5); + +source.compose((Flowable<T> flowable) -> + flowable + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread())); +``` + +# Subjects and Processors + +In the Reactive-Streams specification, the `Subject`-like behavior, namely being a consumer and supplier of events at the same time, is done by the `org.reactivestreams.Processor` interface. As with the `Observable`/`Flowable` split, the backpressure-aware, Reactive-Streams compliant implementations are based on the `FlowableProcessor<T>` class (which extends `Flowable` to give a rich set of instance operators). An important change regarding `Subject`s (and by extension, `FlowableProcessor`) that they no longer support `T -> R` like conversion (that is, input is of type `T` and the output is of type `R`). (We never had a use for it in 1.x and the original `Subject<T, R>` came from .NET where there is a `Subject<T>` overload because .NET allows the same class name with a different number of type arguments.) + +The `io.reactivex.subjects.AsyncSubject`, `io.reactivex.subjects.BehaviorSubject`, `io.reactivex.subjects.PublishSubject`, `io.reactivex.subjects.ReplaySubject` and `io.reactivex.subjects.UnicastSubject` in 2.x don't support backpressure (as part of the 2.x `Observable` family). + +The `io.reactivex.processors.AsyncProcessor`, `io.reactivex.processors.BehaviorProcessor`, `io.reactivex.processors.PublishProcessor`, `io.reactivex.processors.ReplayProcessor` and `io.reactivex.processors.UnicastProcessor` are backpressure-aware. The `BehaviorProcessor` and `PublishProcessor` don't coordinate requests (use `Flowable.publish()` for that) of their downstream subscribers and will signal them `MissingBackpressureException` if the downstream can't keep up. The other `XProcessor` types honor backpressure of their downstream subscribers but otherwise, when subscribed to a source (optional), they consume it in an unbounded manner (requesting `Long.MAX_VALUE`). + +## TestSubject + +The 1.x `TestSubject` has been dropped. Its functionality can be achieved via `TestScheduler`, `PublishProcessor`/`PublishSubject` and `observeOn(testScheduler)`/scheduler parameter. + +```java +TestScheduler scheduler = new TestScheduler(); +PublishSubject<Integer> ps = PublishSubject.create(); + +TestObserver<Integer> ts = ps.delay(1000, TimeUnit.MILLISECONDS, scheduler) +.test(); + +ts.assertEmpty(); + +ps.onNext(1); + +scheduler.advanceTimeBy(999, TimeUnit.MILLISECONDS); + +ts.assertEmpty(); + +scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); + +ts.assertValue(1); +``` + +## SerializedSubject + +The `SerializedSubject` is no longer a public class. You have to use `Subject.toSerialized()` and `FlowableProcessor.toSerialized()` instead. + +# Other classes + +The `rx.observables.ConnectableObservable` is now `io.reactivex.observables.ConnectableObservable<T>` and `io.reactivex.flowables.ConnectableFlowable<T>`. + +## GroupedObservable + +The `rx.observables.GroupedObservable` is now `io.reactivex.observables.GroupedObservable<T>` and `io.reactivex.flowables.GroupedFlowable<T>`. + +In 1.x, you could create an instance with `GroupedObservable.from()` which was used internally by 1.x. In 2.x, all use cases now extend `GroupedObservable` directly thus the factory methods are no longer available; the whole class is now abstract. + +You can extend the class and add your own custom `subscribeActual` behavior to achieve something similar to the 1.x features: + +```java +class MyGroup<K, V> extends GroupedObservable<K, V> { + final K key; + + final Subject<V> subject; + + public MyGroup(K key) { + this.key = key; + this.subject = PublishSubject.create(); + } + + @Override + public T getKey() { + return key; + } + + @Override + protected void subscribeActual(Observer<? super T> observer) { + subject.subscribe(observer); + } +} +``` + +(The same approach works with `GroupedFlowable` as well.) + +# Functional interfaces + +Because both 1.x and 2.x is aimed at Java 6+, we can't use the Java 8 functional interfaces such as `java.util.function.Function`. Instead, we defined our own functional interfaces in 1.x and 2.x follows this tradition. + +One notable difference is that all our functional interfaces now define `throws Exception`. This is a large convenience for consumers and mappers that otherwise throw and would need `try-catch` to transform or suppress a checked exception. + +```java +Flowable.just("file.txt") +.map(name -> Files.readLines(name)) +.subscribe(lines -> System.out.println(lines.size()), Throwable::printStackTrace); +``` + +If the file doesn't exist or can't be read properly, the end consumer will print out `IOException` directly. Note also the `Files.readLines(name)` invoked without try-catch. + +## Actions + +As the opportunity to reduce component count, 2.x doesn't define `Action3`-`Action9` and `ActionN` (these were unused within RxJava itself anyway). + +The remaining action interfaces were named according to the Java 8 functional types. The no argument `Action0` is replaced by the `io.reactivex.functions.Action` for the operators and `java.lang.Runnable` for the `Scheduler` methods. `Action1` has been renamed to `Consumer` and `Action2` is called `BiConsumer`. `ActionN` is replaced by the `Consumer<Object[]>` type declaration. + +## Functions + +We followed the naming convention of Java 8 by defining `io.reactivex.functions.Function` and `io.reactivex.functions.BiFunction`, plus renaming `Func3` - `Func9` into `Function3` - `Function9` respectively. The `FuncN` is replaced by the `Function<Object[], R>` type declaration. + +In addition, operators requiring a predicate no longer use `Func1<T, Boolean>` but have a separate, primitive-returning type of `Predicate<T>` (allows better inlining due to no autoboxing). + +The `io.reactivex.functions.Functions` utility class offers common function sources and conversions to `Function<Object[], R>`. + +# Subscriber + +The Reactive-Streams specification has its own Subscriber as an interface. This interface is lightweight and combines request management with cancellation into a single interface `org.reactivestreams.Subscription` instead of having `rx.Producer` and `rx.Subscription` separately. This allows creating stream consumers with less internal state than the quite heavy `rx.Subscriber` of 1.x. + +```java +Flowable.range(1, 10).subscribe(new Subscriber<Integer>() { + @Override + public void onSubscribe(Subscription s) { + s.request(Long.MAX_VALUE); + } + + @Override + public void onNext(Integer t) { + System.out.println(t); + } + + @Override + public void onError(Throwable t) { + t.printStackTrace(); + } + + @Override + public void onComplete() { + System.out.println("Done"); + } +}); +``` + +Due to the name conflict, replacing the package from `rx` to `org.reactivestreams` is not enough. In addition, `org.reactivestreams.Subscriber` has no notion of adding resources to it, cancelling it or requesting from the outside. + +To bridge the gap we defined abstract classes `DefaultSubscriber`, `ResourceSubscriber` and `DisposableSubscriber` (plus their `XObserver` variants) for `Flowable` (and `Observable`) respectively that offers resource tracking support (of `Disposable`s) just like `rx.Subscriber` and can be cancelled/disposed externally via `dispose()`: + +```java +ResourceSubscriber<Integer> subscriber = new ResourceSubscriber<Integer>() { + @Override + public void onStart() { + request(Long.MAX_VALUE); + } + + @Override + public void onNext(Integer t) { + System.out.println(t); + } + + @Override + public void onError(Throwable t) { + t.printStackTrace(); + } + + @Override + public void onComplete() { + System.out.println("Done"); + } +}; + +Flowable.range(1, 10).delay(1, TimeUnit.SECONDS).subscribe(subscriber); + +subscriber.dispose(); +``` + +Note also that due to Reactive-Streams compatibility, the method `onCompleted` has been renamed to `onComplete` without the trailing `d`. + +Since 1.x `Observable.subscribe(Subscriber)` returned `Subscription`, users often added the `Subscription` to a `CompositeSubscription` for example: + +```java +CompositeSubscription composite = new CompositeSubscription(); + +composite.add(Observable.range(1, 5).subscribe(new TestSubscriber<Integer>())); +``` + +Due to the Reactive-Streams specification, `Publisher.subscribe` returns void and the pattern by itself no longer works in 2.0. To remedy this, the method `E subscribeWith(E subscriber)` has been added to each base reactive class which returns its input subscriber/observer as is. With the two examples before, the 2.x code can now look like this since `ResourceSubscriber` implements `Disposable` directly: + +```java +CompositeDisposable composite2 = new CompositeDisposable(); + +composite2.add(Flowable.range(1, 5).subscribeWith(subscriber)); +``` + +### Calling request from onSubscribe/onStart + +Note that due to how request management works, calling `request(n)` from `Subscriber.onSubscribe` or `ResourceSubscriber.onStart` may trigger calls to `onNext` immediately before the `request()` call itself returns to the `onSubscribe`/`onStart` method of yours: + +```java +Flowable.range(1, 3).subscribe(new Subscriber<Integer>() { + + @Override + public void onSubscribe(Subscription s) { + System.out.println("OnSubscribe start"); + s.request(Long.MAX_VALUE); + System.out.println("OnSubscribe end"); + } + + @Override + public void onNext(Integer v) { + System.out.println(v); + } + + @Override + public void onError(Throwable e) { + e.printStackTrace(); + } + + @Override + public void onComplete() { + System.out.println("Done"); + } +}); +``` + +This will print: + +``` +OnSubscribe start +1 +2 +3 +Done +OnSubscribe end +``` + +The problem comes when one does some initialization in `onSubscribe`/`onStart` after calling `request` there and `onNext` may or may not see the effects of the initialization. To avoid this situation, make sure you call `request` **after** all initialization have been done in `onSubscribe`/`onStart`. + +This behavior differs from 1.x where a `request` call went through a deferred logic that accumulated requests until an upstream `Producer` arrived at some time (This nature adds overhead to all operators and consumers in 1.x.) In 2.x, there is always a `Subscription` coming down first and 90% of the time there is no need to defer requesting. + +# Subscription + +In RxJava 1.x, the interface `rx.Subscription` was responsible for stream and resource lifecycle management, namely unsubscribing a sequence and releasing general resources such as scheduled tasks. The Reactive-Streams specification took this name for specifying an interaction point between a source and a consumer: `org.reactivestreams.Subscription` allows requesting a positive amount from the upstream and allows cancelling the sequence. + +To avoid the name clash, the 1.x `rx.Subscription` has been renamed into `io.reactivex.Disposable` (somewhat resembling .NET's own IDisposable). + +Because Reactive-Streams base interface, `org.reactivestreams.Publisher` defines the `subscribe()` method as `void`, `Flowable.subscribe(Subscriber)` no longer returns any `Subscription` (or `Disposable`). The other base reactive types also follow this signature with their respective subscriber types. + +The other overloads of `subscribe` now return `Disposable` in 2.x. + +The original `Subscription` container types have been renamed and updated + + - `CompositeSubscription` to `CompositeDisposable` + - `SerialSubscription` and `MultipleAssignmentSubscription` have been merged into `SerialDisposable`. The `set()` method disposes the old value and `replace()` method does not. + - `RefCountSubscription` has been removed. + +# Backpressure + +The Reactive-Streams specification mandates operators supporting backpressure, specifically via the guarantee that they don't overflow their consumers when those don't request. Operators of the new `Flowable` base reactive type now consider downstream request amounts properly, however, this doesn't mean `MissingBackpressureException` is gone. The exception is still there but this time, the operator that can't signal more `onNext` will signal this exception instead (allowing better identification of who is not properly backpressured). + +As an alternative, the 2.x `Observable` doesn't do backpressure at all and is available as a choice to switch over. + +# Reactive-Streams compliance + +**updated in 2.0.7** + +**The `Flowable`-based sources and operators are, as of 2.0.7, fully Reactive-Streams version 1.0.0 specification compliant.** + +Before 2.0.7, the operator `strict()` had to be applied in order to achieve the same level of compliance. In 2.0.7, the operator `strict()` returns `this`, is deprecated and will be removed completely in 2.1.0. + +As one of the primary goals of RxJava 2, the design focuses on performance and in order enable it, RxJava 2.0.7 adds a custom `io.reactivex.FlowableSubscriber` interface (extends `org.reactivestreams.Subscriber`) but adds no new methods to it. The new interface is **constrained to RxJava 2** and represents a consumer to `Flowable` that is able to work in a mode that relaxes the Reactive-Streams version 1.0.0 specification in rules §1.3, §2.3, §2.12 and §3.9: + + - §1.3 relaxation: `onSubscribe` may run concurrently with `onNext` in case the `FlowableSubscriber` calls `request()` from inside `onSubscribe` and it is the resposibility of `FlowableSubscriber` to ensure thread-safety between the remaining instructions in `onSubscribe` and `onNext`. + - §2.3 relaxation: calling `Subscription.cancel` and `Subscription.request` from `FlowableSubscriber.onComplete()` or `FlowableSubscriber.onError()` is considered a no-operation. + - §2.12 relaxation: if the same `FlowableSubscriber` instance is subscribed to multiple sources, it must ensure its `onXXX` methods remain thread safe. + - §3.9 relaxation: issuing a non-positive `request()` will not stop the current stream but signal an error via `RxJavaPlugins.onError`. + +From a user's perspective, if one was using the the `subscribe` methods other than `Flowable.subscribe(Subscriber<? super T>)`, there is no need to do anything regarding this change and there is no extra penalty for it. + +If one was using `Flowable.subscribe(Subscriber<? super T>)` with the built-in RxJava `Subscriber` implementations such as `DisposableSubscriber`, `TestSubscriber` and `ResourceSubscriber`, there is a small runtime overhead (one `instanceof` check) associated when the code is not recompiled against 2.0.7. + +If a custom class implementing `Subscriber` was employed before, subscribing it to a `Flowable` adds an internal wrapper that ensures observing the Flowable is 100% compliant with the specification at the cost of some per-item overhead. + +In order to help lift these extra overheads, a new method `Flowable.subscribe(FlowableSubscriber<? super T>)` has been added which exposes the original behavior from before 2.0.7. It is recommended that new custom consumer implementations extend `FlowableSubscriber` instead of just `Subscriber`. + +# Runtime hooks + +The 2.x redesigned the `RxJavaPlugins` class which now supports changing the hooks at runtime. Tests that want to override the schedulers and the lifecycle of the base reactive types can do it on a case-by-case basis through callback functions. + +The class-based `RxJavaObservableHook` and friends are now gone and `RxJavaHooks` functionality is incorporated into `RxJavaPlugins`. + +# Error handling + +One important design requirement for 2.x is that no `Throwable` errors should be swallowed. This means errors that can't be emitted because the downstream's lifecycle already reached its terminal state or the downstream cancelled a sequence which was about to emit an error. + +Such errors are routed to the `RxJavaPlugins.onError` handler. This handler can be overridden with the method `RxJavaPlugins.setErrorHandler(Consumer<Throwable>)`. Without a specific handler, RxJava defaults to printing the `Throwable`'s stacktrace to the console and calls the current thread's uncaught exception handler. + +On desktop Java, this latter handler does nothing on an `ExecutorService` backed `Scheduler` and the application can keep running. However, Android is more strict and terminates the application in such uncaught exception cases. + +If this behavior is desirable can be debated, but in any case, if you want to avoid such calls to the uncaught exception handler, the **final application** that uses RxJava 2 (directly or transitively) should set a no-op handler: + +```java +// If Java 8 lambdas are supported +RxJavaPlugins.setErrorHandler(e -> { }); + +// If no Retrolambda or Jack +RxJavaPlugins.setErrorHandler(Functions.<Throwable>emptyConsumer()); +``` +It is not advised intermediate libraries change the error handler outside their own testing environment. + +Unfortunately, RxJava can't tell which of these out-of-lifecycle, undeliverable exceptions should or shouldn't crash your app. Identifying the source and reason for these exceptions can be tiresome, especially if they originate from a source and get routed to `RxJavaPlugins.onError` somewhere lower the chain. + +Therefore, 2.0.6 introduces specific exception wrappers to help distinguish and track down what was happening the time of the error: +- `OnErrorNotImplementedException`: reintroduced to detect when the user forgot to add error handling to `subscribe()`. +- `ProtocolViolationException`: indicates a bug in an operator +- `UndeliverableException`: wraps the original exception that can't be delivered due to lifecycle restrictions on a `Subscriber`/`Observer`. It is automatically applied by `RxJavaPlugins.onError` with intact stacktrace that may help find which exact operator rerouted the original error. + +If an undeliverable exception is an instance/descendant of `NullPointerException`, `IllegalStateException` (`UndeliverableException` and `ProtocolViolationException` extend this), `IllegalArgumentException`, `CompositeException`, `MissingBackpressureException` or `OnErrorNotImplementedException`, the `UndeliverableException` wrapping doesn't happen. + +In addition, some 3rd party libraries/code throw when they get interrupted by a cancel/dispose call which leads to an undeliverable exception most of the time. Internal changes in 2.0.6 now consistently cancel or dispose a `Subscription`/`Disposable` before cancelling/disposing a task or worker (which causes the interrupt on the target thread). + +``` java +// in some library +try { + doSomethingBlockingly() +} catch (InterruptedException ex) { + // check if the interrupt is due to cancellation + // if so, no need to signal the InterruptedException + if (!disposable.isDisposed()) { + observer.onError(ex); + } +} +``` + +If the library/code already did this, the undeliverable `InterruptedException`s should stop now. If this pattern was not employed before, we encourage updating the code/library in question. + +If one decides to add a non-empty global error consumer, here is an example that manages the typical undeliverable exceptions based on whether they represent a likely bug or an ignorable application/network state: + +```java +RxJavaPlugins.setErrorHandler(e -> { + if (e instanceof UndeliverableException) { + e = e.getCause(); + } + if ((e instanceof IOException) || (e instanceof SocketException)) { + // fine, irrelevant network problem or API that throws on cancellation + return; + } + if (e instanceof InterruptedException) { + // fine, some blocking code was interrupted by a dispose call + return; + } + if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { + // that's likely a bug in the application + Thread.currentThread().getUncaughtExceptionHandler() + .handleException(Thread.currentThread(), e); + return; + } + if (e instanceof IllegalStateException) { + // that's a bug in RxJava or in a custom operator + Thread.currentThread().getUncaughtExceptionHandler() + .handleException(Thread.currentThread(), e); + return; + } + Log.warning("Undeliverable exception received, not sure what to do", e); +}); +``` + +# Schedulers + +The 2.x API still supports the main default scheduler types: `computation`, `io`, `newThread` and `trampoline`, accessible through `io.reactivex.schedulers.Schedulers` utility class. + +The `immediate` scheduler is not present in 2.x. It was frequently misused and didn't implement the `Scheduler` specification correctly anyway; it contained blocking sleep for delayed action and didn't support recursive scheduling at all. Use `Schedulers.trampoline()` instead. + +The `Schedulers.test()` has been removed as well to avoid the conceptional difference with the rest of the default schedulers. Those return a "global" scheduler instance whereas `test()` returned always a new instance of the `TestScheduler`. Test developers are now encouraged to simply `new TestScheduler()` in their code. + +The `io.reactivex.Scheduler` abstract base class now supports scheduling tasks directly without the need to create and then destroy a `Worker` (which is often forgotten): + +```java +public abstract class Scheduler { + + public Disposable scheduleDirect(Runnable task) { ... } + + public Disposable scheduleDirect(Runnable task, long delay, TimeUnit unit) { ... } + + public Disposable scheduleDirectPeriodically(Runnable task, long initialDelay, + long period, TimeUnit unit) { ... } + + public long now(TimeUnit unit) { ... } + + // ... rest is the same: lifecycle methods, worker creation +} +``` + +The main purpose is to avoid the tracking overhead of the `Worker`s for typically one-shot tasks. The methods have a default implementation that reuses `createWorker` properly but can be overridden with more efficient implementations if necessary. + +The method that returns the scheduler's own notion of current time, `now()` has been changed to accept a `TimeUnit` to indicate the unit of measure. + +# Entering the reactive world + +One of the design flaws of RxJava 1.x was the exposure of the `rx.Observable.create()` method that while powerful, not the typical operator you want to use to enter the reactive world. Unfortunately, so many depend on it that we couldn't remove or rename it. + +Since 2.x is a fresh start, we won't make that mistake again. Each reactive base type `Flowable`, `Observable`, `Single`, `Maybe` and `Completable` feature a safe `create` operator that does the right thing regarding backpressure (for `Flowable`) and cancellation (all): + +```java +Flowable.create((FlowableEmitter<Integer> emitter) -> { + emitter.onNext(1); + emitter.onNext(2); + emitter.onComplete(); +}, BackpressureStrategy.BUFFER); +``` + +Practically, the 1.x `fromEmitter` (formerly `fromAsync`) has been renamed to `Flowable.create`. The other base reactive types have similar `create` methods (minus the backpressure strategy). + +# Leaving the reactive world + +Apart from subscribing to the base types with their respective consumers (`Subscriber`, `Observer`, `SingleObserver`, `MaybeObserver` and `CompletableObserver`) and functional-interface based consumers (such as `subscribe(Consumer<T>, Consumer<Throwable>, Action)`), the formerly separate 1.x `BlockingObservable` (and similar classes for the others) has been integrated with the main reactive type. Now you can directly block for some results by invoking a `blockingX` operation directly: + +```java +List<Integer> list = Flowable.range(1, 100).toList().blockingGet(); // toList() returns Single + +Integer i = Flowable.range(100, 100).blockingLast(); +``` + +(The reason for this is twofold: performance and ease of use of the library as a synchronous Java 8 Streams-like processor.) + +Another significant difference between `rx.Subscriber` (and co) and `org.reactivestreams.Subscriber` (and co) is that in 2.x, your `Subscriber`s and `Observer`s are not allowed to throw anything but fatal exceptions (see `Exceptions.throwIfFatal()`). (The Reactive-Streams specification allows throwing `NullPointerException` if the `onSubscribe`, `onNext` or `onError` receives a `null` value, but RxJava doesn't let `null`s in any way.) This means the following code is no longer legal: + +```java +Subscriber<Integer> subscriber = new Subscriber<Integer>() { + @Override + public void onSubscribe(Subscription s) { + s.request(Long.MAX_VALUE); + } + + public void onNext(Integer t) { + if (t == 1) { + throw new IllegalArgumentException(); + } + } + + public void onError(Throwable e) { + if (e instanceof IllegalArgumentException) { + throw new UnsupportedOperationException(); + } + } + + public void onComplete() { + throw new NoSuchElementException(); + } +}; + +Flowable.just(1).subscribe(subscriber); +``` + +The same applies to `Observer`, `SingleObserver`, `MaybeObserver` and `CompletableObserver`. + +Since many of the existing code targeting 1.x do such things, the method `safeSubscribe` has been introduced that does handle these non-conforming consumers. + +Alternatively, you can use the `subscribe(Consumer<T>, Consumer<Throwable>, Action)` (and similar) methods to provide a callback/lambda that can throw: + +```java +Flowable.just(1) +.subscribe( + subscriber::onNext, + subscriber::onError, + subscriber::onComplete, + subscriber::onSubscribe +); +``` + +# Testing + +Testing RxJava 2.x works the same way as it does in 1.x. `Flowable` can be tested with `io.reactivex.subscribers.TestSubscriber` whereas the non-backpressured `Observable`, `Single`, `Maybe` and `Completable` can be tested with `io.reactivex.observers.TestObserver`. + +## test() "operator" + +To support our internal testing, all base reactive types now feature `test()` methods (which is a huge convenience for us) returning `TestSubscriber` or `TestObserver`: + +```java +TestSubscriber<Integer> ts = Flowable.range(1, 5).test(); + +TestObserver<Integer> to = Observable.range(1, 5).test(); + +TestObserver<Integer> tso = Single.just(1).test(); + +TestObserver<Integer> tmo = Maybe.just(1).test(); + +TestObserver<Integer> tco = Completable.complete().test(); +``` + +The second convenience is that most `TestSubscriber`/`TestObserver` methods return the instance itself allowing chaining the various `assertX` methods. The third convenience is that you can now fluently test your sources without the need to create or introduce `TestSubscriber`/`TestObserver` instance in your code: + +```java +Flowable.range(1, 5) +.test() +.assertResult(1, 2, 3, 4, 5) +; +``` + +### Notable new assert methods + + - `assertResult(T... items)`: asserts if subscribed, received exactly the given items in the given order followed by `onComplete` and no errors + - `assertFailure(Class<? extends Throwable> clazz, T... items)`: asserts if subscribed, received exactly the given items in the given order followed by a `Throwable` error of wich `clazz.isInstance()` returns true. + - `assertFailureAndMessage(Class<? extends Throwable> clazz, String message, T... items)`: same as `assertFailure` plus validates the `getMessage()` contains the specified message + - `awaitDone(long time, TimeUnit unit)` awaits a terminal event (blockingly) and cancels the sequence if the timeout elapsed. + - `assertOf(Consumer<TestSubscriber<T>> consumer)` compose some assertions into the fluent chain (used internally for fusion test as operator fusion is not part of the public API right now). + +One of the benefits is that changing `Flowable` to `Observable` here the test code part doesn't have to change at all due to the implicit type change of the `TestSubscriber` to `TestObserver`. + +## cancel and request upfront + +The `test()` method on `TestObserver` has a `test(boolean cancel)` overload which cancels/disposes the `TestSubscriber`/`TestObserver` before it even gets subscribed: + +```java +PublishSubject<Integer> pp = PublishSubject.create(); + +// nobody subscribed yet +assertFalse(pp.hasSubscribers()); + +pp.test(true); + +// nobody remained subscribed +assertFalse(pp.hasSubscribers()); +``` + +`TestSubscriber` has the `test(long initialRequest)` and `test(long initialRequest, boolean cancel)` overloads to specify the initial request amount and whether the `TestSubscriber` should be also immediately cancelled. If the `initialRequest` is given, the `TestSubscriber` offers the `requestMore(long)` method to keep requesting in a fluent manner: + +```java +Flowable.range(1, 5) +.test(0) +.assertValues() +.requestMore(1) +.assertValues(1) +.requestMore(2) +.assertValues(1, 2, 3) +.requestMore(2) +.assertResult(1, 2, 3, 4, 5); +``` + +or alternatively the `TestSubscriber` instance has to be captured to gain access to its `request()` method: + +```java +PublishProcessor<Integer> pp = PublishProcessor.create(); + +TestSubscriber<Integer> ts = pp.test(0L); + +ts.request(1); + +pp.onNext(1); +pp.onNext(2); + +ts.assertFailure(MissingBackpressureException.class, 1); +``` + +## Testing an async source + +Given an asynchronous source, fluent blocking for a terminal event is now possible: + +```java +Flowable.just(1) +.subscribeOn(Schedulers.single()) +.test() +.awaitDone(5, TimeUnit.SECONDS) +.assertResult(1); +``` + +## Mockito & TestSubscriber + +Those who are using Mockito and mocked `Observer` in 1.x has to mock the `Subscriber.onSubscribe` method to issue an initial request, otherwise, the sequence will hang or fail with hot sources: + +```java +@SuppressWarnings("unchecked") +public static <T> Subscriber<T> mockSubscriber() { + Subscriber<T> w = mock(Subscriber.class); + + Mockito.doAnswer(new Answer<Object>() { + @Override + public Object answer(InvocationOnMock a) throws Throwable { + Subscription s = a.getArgumentAt(0, Subscription.class); + s.request(Long.MAX_VALUE); + return null; + } + }).when(w).onSubscribe((Subscription)any()); + + return w; +} +``` + +# Operator differences + +Most operators are still there in 2.x and practically all of them have the same behavior as they had in 1.x. The following subsections list each base reactive type and the difference between 1.x and 2.x. + +Generally, many operators gained overloads that now allow specifying the internal buffer size or prefetch amount they should run their upstream (or inner sources). + +Some operator overloads have been renamed with a postfix, such as `fromArray`, `fromIterable` etc. The reason for this is that when the library is compiled with Java 8, the javac often can't disambiguate between functional interface types. + +Operators marked as `@Beta` or `@Experimental` in 1.x are promoted to standard. + +## 1.x Observable to 2.x Flowable + +### Factory methods: + +| 1.x | 2.x | +|----------|-----------| +| `amb` | added `amb(ObservableSource...)` overload, 2-9 argument versions dropped | +| RxRingBuffer.SIZE | `bufferSize()` | +| `combineLatest` | added varargs overload, added overloads with `bufferSize` argument, `combineLatest(List)` dropped | +| `concat` | added overload with `prefetch` argument, 5-9 source overloads dropped, use `concatArray` instead | +| N/A | added `concatArray` and `concatArrayDelayError` | +| N/A | added `concatArrayEager` and `concatArrayEagerDelayError` | +| `concatDelayError` | added overloads with option to delay till the current ends or till the very end | +| `concatEagerDelayError` | added overloads with option to delay till the current ends or till the very end | +| `create(SyncOnSubscribe)` | replaced with `generate` + overloads (distinct interfaces, you can implement them all at once) | +| `create(AsnycOnSubscribe)` | not present | +| `create(OnSubscribe)` | repurposed with safe `create(FlowableOnSubscribe, BackpressureStrategy)`, raw support via `unsafeCreate()` | +| `from` | disambiguated into `fromArray`, `fromIterable`, `fromFuture` | +| N/A | added `fromPublisher` | +| `fromAsync` | renamed to `create()` | +| N/A | added `intervalRange()` | +| `limit` | dropped, use `take` | +| `merge` | added overloads with `prefetch` | +| `mergeDelayError` | added overloads with `prefetch` | +| `sequenceEqual` | added overload with `bufferSize` | +| `switchOnNext` | added overload with `prefetch` | +| `switchOnNextDelayError` | added overload with `prefetch` | +| `timer` | deprecated overloads dropped | +| `zip` | added overloads with `bufferSize` and `delayErrors` capabilities, disambiguated to `zipArray` and `zipIterable` | + +### Instance methods: + +| 1.x | 2.x | +|----------|----------| +| `all` | **RC3** returns `Single<Boolean>` now | +| `any` | **RC3** returns `Single<Boolean>` now | +| `asObservable` | renamed to `hide()`, hides all identities now | +| `buffer` | overloads with custom `Collection` supplier | +| `cache(int)` | deprecated and dropped | +| `collect` | **RC3** returns `Single<U>` | +| `collect(U, Action2<U, T>)` | disambiguated to `collectInto` and **RC3** returns `Single<U>` | +| `concatMap` | added overloads with `prefetch` | +| `concatMapDelayError` | added overloads with `prefetch`, option to delay till the current ends or till the very end | +| `concatMapEager` | added overloads with `prefetch` | +| `concatMapEagerDelayError` | added overloads with `prefetch`, option to delay till the current ends or till the very end | `contains` | **RC3** returns `Single<Boolean> now | +| `count` | **RC3** returns `Single<Long>` now | +| `countLong` | dropped, use `count` | +| `distinct` | overload with custom `Collection` supplier. | +| `doOnCompleted` | renamed to `doOnComplete`, note the missing `d`! | +| `doOnUnsubscribe` | renamed to `Flowable.doOnCancel` and `doOnDispose` for the others, [additional info](https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#dooncanceldoondisposeunsubscribeon) | +| N/A | added `doOnLifecylce` to handle `onSubscribe`, `request` and `cancel` peeking | +| `elementAt(int)` | **RC3** no longer signals NoSuchElementException if the source is shorter than the index | +| `elementAt(Func1, int)` | dropped, use `filter(predicate).elementAt(int)` | +| `elementAtOrDefault(int, T)` | renamed to `elementAt(int, T)` and **RC3** returns `Single<T>` | +| `elementAtOrDefault(Func1, int, T)` | dropped, use `filter(predicate).elementAt(int, T)` | +| `first()` | **RC3** renamed to `firstElement` and returns `Maybe<T>` | +| `first(Func1)` | dropped, use `filter(predicate).first()` | +| `firstOrDefault(T)` | renamed to `first(T)` and **RC3** returns `Single<T>` | +| `firstOrDefault(Func1, T)` | dropped, use `filter(predicate).first(T)` | +| `flatMap` | added overloads with `prefetch` | +| N/A | added `forEachWhile(Predicate<T>, [Consumer<Throwable>, [Action]])` for conditionally stopping consumption | +| `groupBy` | added overload with `bufferSize` and `delayError` option, *the custom internal map version didn't make it into RC1* | +| `ignoreElements` | **RC3** returns `Completable` | +| `isEmpty` | **RC3** returns `Single<Boolean>` | +| `last()` | **RC3** renamed to `lastElement` and returns `Maybe<T>` | +| `last(Func1)` | dropped, use `filter(predicate).last()` | +| `lastOrDefault(T)` | renamed to `last(T)` and **RC3** returns `Single<T>` | +| `lastOrDefault(Func1, T)` | dropped, use `filter(predicate).last(T)` | +| `nest` | dropped, use manual `just` | +| `publish(Func1)` | added overload with `prefetch` | +| `reduce(Func2)` | **RC3** returns `Maybe<T>` | +| N/A | added `reduceWith(Callable, BiFunction)` to reduce in a Subscriber-individual manner, returns `Single<T>` | +| N/A | added `repeatUntil(BooleanSupplier)` | +| `repeatWhen(Func1, Scheduler)` | dropped the overload, use `subscribeOn(Scheduler).repeatWhen(Function)` instead | +| `retry` | added `retry(Predicate)`, `retry(int, Predicate)` | +| N/A | added `retryUntil(BooleanSupplier)` | +| `retryWhen(Func1, Scheduler)` | dropped the overload, use `subscribeOn(Scheduler).retryWhen(Function)` instead | +| `sample` | doesn't emit the very last item if the upstream completes within the period, added overloads with `emitLast` parameter | +| N/A | added `scanWith(Callable, BiFunction)` to scan in a Subscriber-individual manner | +| `single()` | **RC3** renamed to `singleElement` and returns `Maybe<T>` | +| `single(Func1)` | dropped, use `filter(predicate).single()` | +| `singleOrDefault(T)` | renamed to `single(T)` and **RC3** returns `Single<T>` | +| `singleOrDefault(Func1, T)` | dropped, use `filter(predicate).single(T)` | +| `skipLast` | added overloads with `bufferSize` and `delayError` options | +| `startWith` | 2-9 argument version dropped, use `startWithArray` instead | +| N/A | added `startWithArray` to disambiguate | +| `subscribe` | No longer wraps all consumer types (i.e., `Observer`) with a safety wrapper, (just like the 1.x `unsafeSubscribe` no longer available). Use `safeSubscribe` to get an explicit safety wrapper around a consumer type. | +| N/A | added `subscribeWith` that returns its input after subscription | +| `switchMap` | added overload with `prefetch` argument | +| `switchMapDelayError` | added overload with `prefetch` argument | +| `takeLastBuffer` | dropped | +| N/A | added `test()` (returns TestSubscriber subscribed to this) with overloads to fluently test | +| `throttleLast` | doesn't emit the very last item if the upstream completes within the period, use `sample` with the `emitLast` parameter | +| `timeout(Func0<Observable>, ...)` | signature changed to `timeout(Publisher, ...)` and dropped the function, use `defer(Callable<Publisher>>)` if necessary | +| `toBlocking().y` | inlined as `blockingY()` operators, except `toFuture` | +| `toCompletable` | **RC3** dropped, use `ignoreElements` | +| `toList` | **RC3** returns `Single<List<T>>` | +| `toMap` | **RC3** returns `Single<Map<K, V>>` | +| `toMultimap` | **RC3** returns `Single<Map<K, Collection<V>>>` | +| N/A | added `toFuture` | +| N/A | added `toObservable` | +| `toSingle` | **RC3** dropped, use `single(T)` | +| `toSortedList` | **RC3** returns `Single<List<T>>` | +| `unsafeSubscribe` | Removed as the Reactive Streams specification mandates the `onXXX` methods don't crash and therefore the default is to not have a safety net in `subscribe`. The new `safeSubscribe` method was introduced to explicitly add the safety wrapper around a consumer type. | +| `withLatestFrom` | 5-9 source overloads dropped | +| `zipWith` | added overloads with `prefetch` and `delayErrors` options | + +### Different return types + +Some operators that produced exactly one value or an error now return `Single` in 2.x (or `Maybe` if an empty source is allowed). + +*(Remark: this is "experimental" in RC2 and RC3 to see how it feels to program with such mixed-type sequences and whether or not there has to be too much `toObservable`/`toFlowable` back-conversion.)* + +| Operator | Old return type | New return type | Remark | +|----------|-----------------|-----------------|--------| +| `all(Predicate)` | `Observable<Boolean>` | `Single<Boolean>` | Emits true if all elements match the predicate | +| `any(Predicate)` | `Observable<Boolean>` | `Single<Boolean>` | Emits true if any elements match the predicate | +| `count()` | `Observable<Long>` | `Single<Long>` | Counts the number of elements in the sequence | +| `elementAt(int)` | `Observable<T>` | `Maybe<T>` | Emits the element at the given index or completes | +| `elementAt(int, T)` | `Observable<T>` | `Single<T>` | Emits the element at the given index or the default | +| `elementAtOrError(int)` | `Observable<T>` | `Single<T>` | Emits the indexth element or a `NoSuchElementException` | +| `first(T)` | `Observable<T>` | `Single<T>` | Emits the very first element or `NoSuchElementException` | +| `firstElement()` | `Observable<T>` | `Maybe<T>` | Emits the very first element or completes | +| `firstOrError()` | `Observable<T>` | `Single<T>` | Emits the first element or a `NoSuchElementException` if the source is empty | +| `ignoreElements()` | `Observable<T>` | `Completable` | Ignore all but the terminal events | +| `isEmpty()` | `Observable<Boolean>` | `Single<Boolean>` | Emits true if the source is empty | +| `last(T)` | `Observable<T>` | `Single<T>` | Emits the very last element or the default item | +| `lastElement()` | `Observable<T>` | `Maybe<T>` | Emits the very last element or completes | +| `lastOrError()` | `Observable<T>` | `Single<T>` | Emits the lastelement or a `NoSuchElementException` if the source is empty | +| `reduce(BiFunction)` | `Observable<T>` | `Maybe<T>` | Emits the reduced value or completes | +| `reduce(Callable, BiFunction)` | `Observable<U>` | `Single<U>` | Emits the reduced value (or the initial value) | +| `reduceWith(U, BiFunction)` | `Observable<U>` | `Single<U>` | Emits the reduced value (or the initial value) | +| `single(T)` | `Observable<T>` | `Single<T>` | Emits the only element or the default item | +| `singleElement()` | `Observable<T>` | `Maybe<T>` | Emits the only element or completes | +| `singleOrError()` | `Observable<T>` | `Single<T>` | Emits the one and only element, IndexOutOfBoundsException if the source is longer than 1 item or a `NoSuchElementException` if the source is empty | +| `toList()` | `Observable<List<T>>` | `Single<List<T>>` | collects all elements into a `List` | +| `toMap()` | `Observable<Map<K, V>>` | `Single<Map<K, V>>` | collects all elements into a `Map` | +| `toMultimap()` | `Observable<Map<K, Collection<V>>>` | `Single<Map<K, Collection<V>>>` | collects all elements into a `Map` with collection | +| `toSortedList()` | `Observable<List<T>>` | `Single<List<T>>` | collects all elements into a `List` and sorts it | + +### Removals + +To make sure the final API of 2.0 is clean as possible, we remove methods and other components between release candidates without deprecating them. + +| Removed in version | Component | Remark | +|---------|-----------|--------| +| RC3 | `Flowable.toCompletable()` | use `Flowable.ignoreElements()` | +| RC3 | `Flowable.toSingle()` | use `Flowable.single(T)` | +| RC3 | `Flowable.toMaybe()` | use `Flowable.singleElement()` | +| RC3 | `Observable.toCompletable()` | use `Observable.ignoreElements()` | +| RC3 | `Observable.toSingle()` | use `Observable.single(T)` | +| RC3 | `Observable.toMaybe()` | use `Observable.singleElement()` | + +# Miscellaneous changes + +## doOnCancel/doOnDispose/unsubscribeOn + +In 1.x, the `doOnUnsubscribe` was always executed on a terminal event because 1.x' `SafeSubscriber` called `unsubscribe` on itself. This was practically unnecessary and the Reactive-Streams specification states that when a terminal event arrives at a `Subscriber`, the upstream `Subscription` should be considered cancelled and thus calling `cancel()` is a no-op. + +For the same reason, `unsubscribeOn` is not called on the regular termination path but only when there is an actual `cancel` (or `dispose`) call on the chain. + +Therefore, the following sequence won't call `doOnCancel`: + +```java +Flowable.just(1, 2, 3) +.doOnCancel(() -> System.out.println("Cancelled!")) +.subscribe(System.out::println); +``` + +However, the following will call since the `take` operator cancels after the set amount of `onNext` events have been delivered: + +```java +Flowable.just(1, 2, 3) +.doOnCancel(() -> System.out.println("Cancelled!")) +.take(2) +.subscribe(System.out::println); +``` + +If you need to perform cleanup on both regular termination or cancellation, consider the operator `using` instead. + +Alternatively, the `doFinally` operator (introduced in 2.0.1 and standardized in 2.1) calls a developer specified `Action` that gets executed after a source completed, failed with an error or got cancelled/disposed: + +```java +Flowable.just(1, 2, 3) +.doFinally(() -> System.out.println("Finally")) +.subscribe(System.out::println); + +Flowable.just(1, 2, 3) +.doFinally(() -> System.out.println("Finally")) +.take(2) // cancels the above after 2 elements +.subscribe(System.out::println); +``` \ No newline at end of file diff --git a/docs/Writing-operators-for-2.0.md b/docs/Writing-operators-for-2.0.md new file mode 100644 index 0000000000..7b6e57666e --- /dev/null +++ b/docs/Writing-operators-for-2.0.md @@ -0,0 +1,1746 @@ +##### Table of contents + + - [Introduction](#introduction) + - [Warning on internal components](warning-on-internal-components) + - [Atomics, serialization, deferred actions](#atomics-serialization-deferred-actions) + - [Field updaters and Android](#field-updaters-and-android) + - [Request accounting](#request-accounting) + - [Once](#once) + - [Serialization](#serialization) + - [Queues](#queues) + - [Deferred actions](#deferred-actions) + - [Deferred cancellation](#deferred-cancellation) + - [Deferred requesting](#deferred-requesting) + - [Atomic error management](#atomic-error-management) + - [Half-serialization](#half-serialization) + - [Fast-path queue-drain](#fast-path-queue-drain) + - [FlowableSubscriber](#flowablesubscriber) + - [Backpressure and cancellation](#backpressure-and-cancellation) + - [Replenishing](#replenishing) + - [Stable prefetching](#stable-prefetching) + - [Single-valued results](#single-valued-results) + - [Single-element post-complete](#single-element-post-complete) + - [Multi-element post-complete](#multi-element-post-complete) + - [Creating operator classes](#creating-operator-classes) + - [Operator by extending a base reactive class](#operator-by-extending-a-base-reactive-class) + - [Operator targeting lift()](#operator-targeting-lift) + - [Operator fusion](#operator-fusion) + - [Generations](#generations) + - [Components](#components) + - [Callable and ScalarCallable](#callable-and-scalarcallable) + - [ConditionalSubscriber](#conditionalsubscriber) + - [QueueSubscription and QueueDisposable](#queuesubscription-and-queuedisposable) + - [Example implementations](#example-implementations) + - [Map-filter hybrid](https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0#map--filter-hybrid) + - [Ordered merge](#ordered-merge) + +# Introduction + +Writing operators, source-like (`fromEmitter`) or intermediate-like (`flatMap`) **has always been a hard task to do in RxJava**. There are many rules to obey, many cases to consider but at the same time, many (legal) shortcuts to take to build a well performing code. Now writing an operator specifically for 2.x is 10 times harder than for 1.x. If you want to exploit all the advanced, 4th generation features, that's even 2-3 times harder on top (so 30 times harder in total). + +*(If you have been following [my blog](http://akarnokd.blogspot.hu/) about RxJava internals, writing operators is maybe only 2 times harder than 1.x; some things have moved around, some tools popped up while others have been dropped but there is a relatively straight mapping from 1.x concepts and approaches to 2.x concepts and approaches.)* + +In this article, I'll describe the how-to's from the perspective of a developer who skipped the 1.x knowledge base and basically wants to write operators that conforms the Reactive-Streams specification as well as RxJava 2.x's own extensions and additional expectations/requirements. + +Since **Reactor 3** has the same architecture as **RxJava 2** (no accident, I architected and contributed 80% of **Reactor 3** as well) the same principles outlined in this page applies to writing operators for **Reactor 3**. Note however that they chose different naming and locations for their utility and support classes so you may have to search for the equivalent components. + +## Warning on internal components + +RxJava has several hundred public classes implementing various operators and helper facilities. Since there is no way to hide these in Java 6-8, the general contract is that anything below `io.reactivex.internal` is considered private and subject to change without warnings. It is not recommended to reference these in your code (unless you contribute to RxJava itself) and must be prepared that even a patch change may shuffle/rename things around in them. That being said, they usually contain valuable tools for operator builders and as such are quite attractive to use them in your custom code. + +# Atomics, serialization, deferred actions + +As RxJava itself has building blocks for creating reactive dataflows, its components have building blocks as well in the form of concurrency primitives and algorithms. Many refer to the book [Concurrency in Practice](https://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601) for learning the fundamentals needed. Unfortunately, other than some explanation of the Java Memory Model, the book lacks the techniques required for developing operators for RxJava 1.x and 2.x. + +## Field updaters and Android + +If you looked at the source code of RxJava and then at **Reactor 3**, you might have noticed that RxJava doesn't use the +`AtomicXFieldUpdater` classes. The reason for this is that on certain Android devices, the runtime "messes up" the field +names and the reflection logic behind the field updaters fails to locate those fields in the operators. To avoid this we decided to only use the full `AtomicX` classes (as fields or extending them). + +If you target the RxJava library with your custom operator (or Android), you are encouraged to do the same. If you plan have operators running on desktop Java, feel free to use the field updaters instead. + +## Request accounting + +When dealing with backpressure in `Flowable` operators, one needs a way to account the downstream requests and emissions in response to those requests. For this we use a single `AtomicLong`. Accounting must be atomic because requesting more and emitting items to fulfill an earlier request may happen at the same time. + +The naive approach for accounting would be to simply call `AtomicLong.getAndAdd()` with new requests and `AtomicLong.addAndGet()` for decrementing based on how many elements were emitted. + +The problem with this is that the Reactive-Streams specification declares `Long.MAX_VALUE` as the upper bound for outstanding requests (interprets it as the unbounded mode) but adding two large longs may overflow the `long` into a negative value. In addition, if for some reason, there are more values emitted than were requested, the subtraction may yield a negative current request value, causing crashes or hangs. + +Therefore, both addition and subtraction have to be capped at `Long.MAX_VALUE` and `0` respectively. Since there is no dedicated `AtomicLong` method for it, we have to use a Compare-And-Set loop. (Usually, requesting happens relatively rarely compared to emission amounts thus the lack of dedicated machine code instruction is not a performance bottleneck.) + +```java +public static long add(AtomicLong requested, long n) { + for (;;) { + long current = requested.get(); + if (current == Long.MAX_VALUE) { + return Long.MAX_VALUE; + } + long update = current + n; + if (update < 0L) { + update = Long.MAX_VALUE; + } + if (requested.compareAndSet(current, update)) { + return current; + } + } +} + +public static long produced(AtomicLong requested, long n) { +for (;;) { + long current = requested.get(); + if (current == Long.MAX_VALUE) { + return Long.MAX_VALUE; + } + long update = current - n; + if (update < 0L) { + update = 0; + } + if (requested.compareAndSet(current, update)) { + return update; + } + } +} +``` + +In fact, these are so common in RxJava's operators that these algorithms are available as utility methods on the **internal** `BackpressureHelper` class under the same name. + +Sometimes, instead of having a separate `AtomicLong` field, your operator can extend `AtomicLong` saving on the indirection and class size. The practice in RxJava 2.x operators is that unless there is another atomic counter needed by the operator, (such as work-in-progress counter, see the later subsection) and otherwise doesn't need a base class, they extend `AtomicLong` directly. + +The `BackpressureHelper` class features special versions of `add` and `produced` which treat `Long.MIN_VALUE` as a cancellation indication and won't change the `AtomicLong`s value if they see it. + +## Once + +RxJava 2 expanded the single-event reactive types to include `Maybe` (called as the reactive `Optional` by some). The common property of `Single`, `Completable` and `Maybe` is that they can only call one of the 3 kinds of methods on their consumers: `(onSuccess | onError | onComplete)`. Since they also participate in concurrent scenarios, an operator needs a way to ensure that only one of them is called even though the input sources may call multiple of them at once. + +To ensure this, operators may use the `AtomicBoolean.compareAndSet` to atomically chose the event to relay (and thus the other events to drop). + +```java +final AtomicBoolean once = new AtomicBoolean(); + +final MaybeObserver<? super T> child = ...; + +void emitSuccess(T value) { + if (once.compareAndSet(false, true)) { + child.onSuccess(value); + } +} + +void emitFailure(Throwable e) { + if (once.compareAndSet(false, true)) { + child.onError(e); + } else { + RxJavaPlugins.onError(e); + } +} +``` + +Note that the same sequential requirement applies to these 0-1 reactive sources as to `Flowable`/`Observable`, therefore, if your operator doesn't have to deal with events from multiple sources (and pick one of them), you don't need this construct. + +## Serialization + +With more complicated sources, it may happen that multiple things happen that may trigger emission towards the downstream, such as upstream becoming available while the downstream requests for more data while the sequence gets cancelled by a timeout. + +Instead of working out the often very complicated state transitions via atomics, perhaps the easiest way is to serialize the events, actions or tasks and have one thread perform the necessary steps after that. This is what I call **queue-drain** approach (or trampolining by some). + +(The other approach, **emitter-loop** is no longer recommended with 2.x due to its potential blocking `synchronized` constructs that looks performant in single-threaded case but destroys it in true concurrent case.) + + +The concept is relatively simple: have a concurrent queue and a work-in-progress atomic counter, enqueue the item, increment the counter and if the counter transitioned from 0 to 1, keep draining the queue, work with the element and decrement the counter until it reaches zero again: + +```java +final ConcurrentLinkedQueue<Runnable> queue = ...; +final AtomicInteger wip = ...; + +void execute(Runnable r) { + queue.offer(r); + if (wip.getAndIncrement() == 0) { + do { + queue.poll().run(); + } while (wip.decrementAndGet() != 0); + } +} +``` + +The same pattern applies when one has to emit onNext values to a downstream consumer: + +```java +final ConcurrentLinkedQueue<T> queue = ...; +final AtomicInteger wip = ...; +final Subscriber<? super T> child = ...; + +void emit(T r) { + queue.offer(r); + if (wip.getAndIncrement() == 0) { + do { + child.onNext(queue.poll()); + } while (wip.decrementAndGet() != 0); + } +} +``` + +### Queues + +Using `ConcurrentLinkedQueue` is a reliable although mostly an overkill for such situations because it allocates on each call to `offer()` and is unbounded. It can be replaced with more optimized queues (see [JCTools](https://github.com/JCTools/JCTools/)) and RxJava itself also has some customized queues available (internal!): + + - `SpscArrayQueue` used when the queue is known to be fed by a single thread but the serialization has to look at other things (request, cancellation, termination) that can be read from other fields. Example: `observeOn` has a fixed request pattern which fits into this type of queue and extra fields for passing an error, completion or downstream requests into the drain logic. + - `SpscLinkedArrayQueue` used when the queue is known to be fed by a single thread but there is no bound on the element count. Example: `UnicastProcessor`, almost all buffering `Observable` operator. Some operators use it with multiple event sources by synchronizing on the `offer` side - a tradeoff between allocation and potential blocking: + +```java +SpscLinkedArrayQueue<T> q = ... +synchronized(q) { + q.offer(value); +} +``` + + - `MpscLinkedQueue` where there could be many feeders and unknown number of elements. Example: `buffer` with reactive boundary. + +The RxJava 2.x implementations of these types of queues have different class hierarchy than the JDK/JCTools versions. Our classes don't implement the `java.util.Queue` interface but rather a custom, simplified interface: + +```java +interface SimpleQueue<T> { + boolean offer(T t); + + boolean offer(T t1, T t2); + + T poll() throws Exception; + + boolean isEmpty(); + + void clear(); +} + +interface SimplePlainQueue<T> extends SimpleQueue<T> { + @Override + T poll(); +} + +public final class SpscArrayQueue<T> implements SimplePlainQueue<T> { + // ... +} +``` + +This simplified queue API gets rid of the unused parts (iterator, collections API remnants) and adds a bi-offer method (only implemented atomically in `SpscLinkedArrayQueue` currently). The second interface, `SimplePlainQueue` is defined to suppress the `throws Exception` on poll on queue types that won't throw that exception and there is no need for try-catch around them. + +## Deferred actions + +The Reactive-Streams has a strict requirement that calling `onSubscribe()` must happen before any calls to the rest of the `onXXX` methods and by nature, any calls to `Subscription.request()` and `Subscription.cancel()`. The same logic applies to the design of `Observable`, `Single`, `Completable` and `Maybe` with their connection type of `Disposable`. + +Often though, such call to `onSubscribe` may happen later than the respective `cancel()` needs to happen. For example, the user may want to call `cancel()` before the respective `Subscription` actually becomes available in `subscribeOn`. Other operators may need to call `onSubscribe` before they connect to other sources but at that time, there is no direct way for relaying a `cancel` call to an unavailable upstream `Subscription`. + +The solution is **deferred cancellation** and **deferred requesting** in general. + +### Deferred cancellation + +This approach affects all 5 reactive types and works the same way for everyone. First, have an `AtomicReference` that will hold the respective connection type (or any other type whose method call has to happen later). Two methods are needed handling the `AtomicReference` class, one that sets the actual instance and one that calls the `cancel`/`dispose` method on it. + +```java +static final Disposable DISPOSED; +static { + DISPOSED = Disposables.empty(); + DISPOSED.dispose(); +} + +static boolean set(AtomicReference<Disposable> target, Disposable value) { + for (;;) { + Disposable current = target.get(); + if (current == DISPOSED) { + if (value != null) { + value.dispose(); + } + return false; + } + if (target.compareAndSet(current, value)) { + if (current != null) { + current.dispose(); + } + return true; + } + } +} + +static boolean dispose(AtomicReference<Disposable> target) { + Disposable current = target.getAndSet(DISPOSED); + if (current != DISPOSED) { + if (current != null) { + current.dispose(); + } + return true; + } + return false; +} +``` + +The approach uses an unique sentinel value `DISPOSED` - that should not appear elsewhere in your code - to indicate once a late actual `Disposable` arrives, it should be disposed immediately. Both methods return true if the operation succeeded or false if the target was already disposed. + +Sometimes, only one call to `set` is permitted (i.e., `setOnce`) and other times, the previous non-null value needs no call to `dispose` because it is known to be disposed already (i.e., `replace`). + +As with the request management, there are utility classes and methods for these operations: + + - (internal) `SequentialDisposable` that uses `update`, `replace` and `dispose` but leaks the API of `AtomicReference` + - `SerialDisposable` that has safe API with `set`, `replace` and `dispose` among other things + - (internal) `DisposableHelper` that features the methods shown above and the global disposed sentinel used by RxJava. It may come handy when one uses `AtomicReference<Disposable>` as a base class. + +The same pattern applies to `Subscription` with its `cancel()` method and with helper (internal) class `SubscriptionHelper` (but no `SequentialSubscription` or `SerialSubscription`, see next subsection). + +### Deferred requesting + +With `Flowable`s (and Reactive-Streams `Publisher`s) the `request()` calls need to be deferred as well. In one form (the simpler one), the respective late `Subscription` will eventually arrive and we need to relay all previous and all subsequent request amount to its `request()` method. + +In 1.x, this behavior was implicitly provided by `rx.Subscriber` but at a high cost that had to be payed by all instances whether or not they needed this feature. + +The solution works by having the `AtomicReference` for the `Subscription` and an `AtomicLong` to store and accumulate the requests until the actual `Subscription` arrives, then atomically request all deferred value once. + +```java +static boolean deferredSetOnce(AtomicReference<Subscription> subscription, + AtomicLong requested, Subscription newSubscription) { + if (subscription.compareAndSet(null, newSubscription) { + long r = requested.getAndSet(0L); + if (r != 0) { + newSubscription.request(r); + } + return true; + } + newSubscription.cancel(); + if (subscription.get() != SubscriptionHelper.CANCELLED) { + RxJavaPlugins.onError(new IllegalStateException("Subscription already set!")); + } + return false; +} + +static void deferredRequest(AtomicReference<Subscription> subscription, + AtomicLong requested, long n) { + Subscription current = subscription.get(); + if (current != null) { + current.request(n); + } else { + BackpressureHelper.add(requested, n); + current = subscription.get(); + if (current != null) { + long r = requested.getAndSet(0L); + if (r != 0L) { + current.request(r); + } + } + } +} +``` + +In `deferredSetOnce`, if the CAS from null to the `newSubscription` succeeds, we atomically exchange the request amount to 0L and if the original value was nonzero, we request from `newSubscription`. In `deferredRequest`, if there is a `Subscription` we simply request from it directly. Otherwise, we accumulate the requests via the helper method then check again if the `Subscription` arrived or not. If it arrived in the meantime, we atomically exchange the accumulated request value and if nonzero, request it from the newly retrieved `Subscription`. This non-blocking logic makes sure that in case of concurrent invocations of the two methods, no accumulated request is left behind. + +This complex logic and methods, along with other safeguards are available in the (internal) `SubscriptionHelper` utility class and can be used like this: + +```java +final class Operator<T> implements Subscriber<T>, Subscription { + final Subscriber<? super T> child; + + final AtomicReference<Subscription> ref = new AtomicReference<>(); + final AtomicLong requested = new AtomicLong(); + + public Operator(Subscriber<? super T> child) { + this.child = child; + } + + @Override + public void onSubscribe(Subscription s) { + SubscriptionHelper.deferredSetOnce(ref, requested, s); + } + + @Override + public void onNext(T t) { ... } + + @Override + public void onError(Throwable t) { ... } + + @Override + public void onComplete() { ... } + + @Override + public void cancel() { + SubscriptionHelper.cancel(ref); + } + + @Override + public void request(long n) { + SubscriptionHelper.deferredRequested(ref, requested, n); + } +} + +Operator<T> parent = new Operator<T>(child); + +child.onSubscribe(parent); + +source.subscribe(parent); +``` + +The second form is when multiple `Subscription`s replace each other and we not only need to hold onto request amounts when there is none of them but make sure a newer `Subscription` is requested only that much the previous `Subscription`'s upstream didn't deliver. This is called **Subscription arbitration** and the relevant algorithms are quite verbose and will be omitted here. There is, however, an utility class that manages this: (internal) `SubscriptionArbiter`. + +You can extend it (to save on object headers) or have it as a field. Its main use is to send it to the downstream via `onSubscribe` and update its current `Subscription` in the current operator. Note that even though its methods are thread-safe, it is intended for swapping `Subscription`s when the current one finished emitting events. This makes sure that any newer `Subscription` is requested the right amount and not more due to production/switch race. + +```java +final SubscriptionArbiter arbiter = ... + +// ... + +child.onSubscribe(arbiter); + +// ... + +long produced; + +@Override +public void onSubscribe(Subscription s) { + arbiter.setSubscription(s); +} + +@Override +public void onNext(T value) { + produced++; + child.onNext(value); +} + +@Override +public void onComplete() { + long p = produced; + if (p != 0L) { + arbiter.produced(p); + } + subscribeNext(); +} +``` + +For better performance, most operators can count the produced element amount and issue a single `SubscriptionArbiter.produced()` call just before switching to the next `Subscription`. + + +## Atomic error management + +In some cases, multiple sources may signal a `Throwable` at the same time but the contract forbids calling `onError` multiple times. Once can, of course use the **once** approach with `AtomicReference<Throwable>` and throw out but the first one to set the `Throwable` on it. + +The alternative is to collect these `Throwable`s into a `CompositeException` as long as possible and at one point lock out the others. This works by doing a copy-on-write scheme or by linking `CompositeException`s atomically and having a terminal sentinel to indicate all further errors should be dropped. + +```java +static final Throwable TERMINATED = new Throwable(); + +static boolean addThrowable(AtomicReference<Throwable> ref, Throwable e) { + for (;;) { + Throwable current = ref.get(); + if (current == TERMINATED) { + return false; + } + Throwable next; + if (current == null) { + next = e; + } else { + next = new CompositeException(current, e); + } + if (ref.compareAndSet(current, next)) { + return true; + } + } +} + +static Throwable terminate(AtomicReference<Throwable> ref) { + return ref.getAndSet(TERMINATED); +} +``` + +as with most common logic, this is supported by the (internal) `ExceptionHelper` utility class and the (internal) `AtomicThrowable` class. + +The usage pattern looks as follows: + +```java + +final AtomicThrowable errors = ...; + +@Override +public void onError(Throwable e) { + if (errors.addThrowable(e)) { + drain(); + } else { + RxJavaPlugins.onError(e); + } +} + +void drain() { + // ... + if (errors.get() != null) { + child.onError(errors.terminate()); + return; + } + // ... +} +``` + +## Half-serialization + +Sometimes having the queue-drain, `SerializedSubscriber` or `SerializedObserver` is a bit of an overkill. Such cases include when there is only one thread calling `onNext` but other threads may call `onError` or `onComplete` concurrently. Example operators include `takeUntil` where the other source may "interrupt" the main sequence and inject an `onComplete` into it before the main source itself would complete some time later. This is what I call **half-serialization**. + +The approach uses the concepts of the deferred actions and atomic error management discussed above and has 3 methods for the `onNext`, `onError` and `onComplete` management: + +```java +public static <T> void onNext(Subscriber<? super T> subscriber, T value, + AtomicInteger wip, AtomicThrowable error) { + if (wip.get() == 0 && wip.compareAndSet(0, 1)) { + subscriber.onNext(value); + if (wip.decrementAndGet() != 0) { + Throwable ex = error.terminate(); + if (ex != null) { + subscriber.onError(ex); + } else { + subscriber.onComplete(); + } + } + } +} + +public static void onError(Subscriber<?> subscriber, Throwable ex, + AtomicInteger wip, AtomicThrowable error) { + if (error.addThrowable(ex)) { + if (wip.getAndIncrement() == 0) { + subscriber.onError(error.terminate()); + } + } else { + RxJavaPlugins.onError(ex); + } +} + +public static void onComplete(Subscriber<?> subscriber, + AtomicInteger wip, AtomicThrowable error) { + if (wip.getAndIncrement() == 0) { + Throwable ex = error.terminate(); + if (ex != null) { + subscriber.onError(ex); + } else { + subscriber.onComplete(); + } + } +} +``` + +Here, the `wip` counter indicates there is an active emission happening and if found non-zero when trying to leave the `onNext`, it is taken as indication there was a concurrent `onError` or `onComplete()` call and the child must be notified. All subsequent calls to any of these methods are ignored. In this case, the `wip` is never decremented back to zero. + +RxJava 2.x, again, supports these with the (internal) utility class `HalfSerializer` and allows targeting `Subscriber`s and `Observer`s with it. + +## Fast-path queue-drain + +In some operators, it is unlikely concurrent threads try to enter into the drain loop at the same time and having to play the full enqueue-increment-dequeue adds unnecessary overhead. + +Luckily, such situations can be detected by a simple compare-and-set attempt on the work-in-progress counter, trying to change the amount from 0 to 1. If it fails, there is a concurrent drain in progress and we revert back to the classical queue-drain logic. If succeeds, we don't enqueue anything but emit the value / perform the action right there and we try to leave the serialized section. + +```java +public void onNext(T v) { + if (wip.get() == 0 && wip.compareAndSet(0, 1)) { + child.onNext(v); + if (wip.decrementAndGet() == 0) { + break; + } + } else { + queue.offer(v); + if (wip.getAndIncrement() != 0) { + break; + } + } + drainLoop(); +} + +void drain() { + if (getAndIncrement() == 0) { + drainLoop(); + } +} + +void drainLoop() { + // the usual drain loop part after the classical getAndIncrement() +} +``` + +In this pattern, the classical `drain` is spit into `drain` and `drainLoop`. The new `drain` does the increment-check and calls `drainLoop` and `drainLoop` contains the remaining logic with the loop, emission and wip management as usual. + +On the fast path, when we try to leave it, it is possible a concurrent call to `onNext` or `drain` incremented the `wip` counter further and the decrement didn't return it to zero. This is an indication for further work and we call `drainLoop` to process it. + +## FlowableSubscriber + +Version 2.0.7 introduced a new interface, `FlowableSubscriber` that extends `Subscriber` from Reactive-Streams. It has the same methods with the same parameter types but different textual rules attached to it, a set of relaxations to the Reactive-Streams specification to enable better performing RxJava internals while still honoring the specification to the letter for non-RxJava consumers of `Flowable`s. + +The rule relaxations are as follows: + +- §1.3 relaxation: `onSubscribe` may run concurrently with onNext in case the `FlowableSubscriber` calls `request()` from inside `onSubscribe` and it is the resposibility of `FlowableSubscriber` to ensure thread-safety between the remaining instructions in `onSubscribe` and `onNext`. +- §2.3 relaxation: calling `Subscription.cancel` and `Subscription.request` from `FlowableSubscriber.onComplete()` or `FlowableSubscriber.onError()` is considered a no-operation. +- §2.12 relaxation: if the same `FlowableSubscriber` instance is subscribed to multiple sources, it must ensure its `onXXX` methods remain thread safe. +- §3.9 relaxation: issuing a non-positive `request()` will not stop the current stream but signal an error via `RxJavaPlugins.onError`. + +When a `Flowable` gets subscribed by a `Subscriber`, an `instanceof` check will detect `FlowableSubscriber` and not apply the `StrictSubscriber` wrapper that makes sure the relaxations don't happen. In practice, ensuring rule §3.9 has the most overhead because a bad request may happen concurrently with an emission of any normal event and thus has to be serialized with one of the methods described in previous sections. + +**In fact, 2.x was always implemented in this relaxed manner thus looking at existing code and style is the way to go.** + +Therefore, it is strongly recommended one implements custom intermediate and end operators via `FlowableSubscriber`. + +From a source operator's perspective, extending the `Flowable` class and implementing `subscribeActual` has no need for +dispatching over the type of the `Subscriber`; the backing infrastructure already applies wrapping if necessary thus one can be sure in `subscribeActual(Subscriber<? super T> s)` the parameter `s` is a `FlowableSubscriber`. (The signature couldn't be changed for compatibility reasons.) Since the two interfaces on the Java level are the same, no real preferential treating is necessary within sources (i.e., don't cast `s` into `FlowableSubscriber`. + +The other base reactive consumers, `Observer`, `SingleObserver`, `MaybeObserver` and `CompletableObserver` don't need such relaxation, because + +- they are only defined and used in RxJava (i.e., no other library implemented with them), +- they were conceptionally always derived from the relaxed `Subscriber` RxJava had, +- they don't have backpressure thus no `request()` call that would introduce another concurrency to think about, +- there is no way to trigger emission from upstream before `onSubscribe(Disposable)` returns in standard operators (again, no `request()` method). + +# Backpressure and cancellation + +Backpressure (or flow control) in Reactive-Streams is the means to tell the upstream how many elements to produce or to tell it to stop producing elements altogether. Unlike the name suggest, there is no physical pressure preventing the upstream from calling `onNext` but the protocol to honor the request amount. + +## Replenishing + +When dealing with basic transformations in a flow, there are often cases when the number of items the upstream sends should be different what the downstream receives. Some operators may want to filter out certain items, others would batch up items before sending one item to the downstream. + +However, when an item is not forwarded by an operator, the downstream has no way of knowing its `request(1)` triggered an item generation that got dropped/buffered. Therefore, it can't know to (nor should it) repeat `request(1)` to "nudge" the source somewhere more upstream to try producing another item which now hopefully will result in an item being received by the downstream. Unlike, say the ACK-NACK based protocols, the requesting specified by the Reactive Streams are to be treated as cumulative. In the previous example, an impatient downstream would have 2 outstanding requests. + +Therefore, if an operator is not guaranteed to relay an upstream item to downstream, and thus keeping a 1:1 ratio, it has the duty to keep requesting items from the upstream until said operator ends up in a position to supply an item to the downstream. + +This may sound a bit complicated, but perhaps a demonstration of a `filter` operator can help: + +```java +final class FilterOddSubscriber implements FlowableSubscriber<Integer>, Subscription { + + final Subscriber<? super Integer> downstream; + + Subscription upstream; + + // ... + + @Override + public void onSubscribe(Subscription s) { + if (upstream != null) { + s.cancel(); + } else { + upstream = s; + downstream.onSubscribe(this); + } + } + + @Override + public void onNext(Integer item) { + if (item % 2 != 0) { + downstream.onNext(item); + } else { + upstream.request(1); + } + } + + @Override + public void request(long n) { + upstream.request(n); + } + + // the rest omitted for brevity +} +``` + +In such operators, thee downstream's `request` calls are forwarded to the upstream as is, and for `n` times (at most, unless completed) the `onNext` will be invoked. In this operator, we look for the odd numbers of the flow. If we find one, the downstream will be notified. If the incoming item is even, we won't forward it to the downstream. However, the downstream is still expecting at least 1 item, but since the upstream and downstream practically talk to each other directly, the upstream considers its duty to generate items fulfilled. This misalignment is then resolved by requesting 1 more item from the upstream for the previous ignored item. If more items arrive that get ignored, more will be requested as replenishment. + +Given that backpressure involves some overhead in the form of one or more atomic operations, requesting one by one could add a lot of overhead if the number of items filtered out is significantly more than those that passed through. If necessary, this situation can be either solved by [decoupling the upstream and downstream's request management](#stable-prefetching) or using an RxJava-specific type and protocol extension in the form of [ConditionalSubscriber](#conditionalsubscriber)s. + +## Stable prefetching + +In a previous section, we saw primitives to deal with request accounting and delayed `Subscriptions`, but often, operators have to react to request amount changes as well. This comes up when the operator has to decouple the downstream request amount from the amount it requests from upstream, such as `observeOn`. + +Such logic can get quite complicated in operators but one of the simplest manifestation can be the `rebatchRequest` operator that combines request management with serialization to ensure that upstream is requested with a predictable pattern no matter how the downstream requested (less, more or even unbounded): + +```java +final class RebatchRequests<T> extends AtomicInteger +implements FlowableSubscriber<T>, Subscription { + + final Subscriber<? super T> child; + + final AtomicLong requested; + + final SpscArrayQueue<T> queue; + + final int batchSize; + + final int limit; + + Subscription s; + + volatile boolean done; + Throwable error; + + volatile boolean cancelled; + + long emitted; + + public RebatchRequests(Subscriber<? super T> child, int batchSize) { + this.child = child; + this.batchSize = batchSize; + this.limit = batchSize - (batchSize >> 2); // 75% of batchSize + this.requested = new AtomicLong(); + this.queue = new SpscArrayQueue<T>(batchSize); + } + + @Override + public void onSubscribe(Subscription s) { + this.s = s; + child.onSubscribe(this); + s.request(batchSize); + } + + @Override + public void onNext(T t) { + queue.offer(t); + drain(); + } + + @Override + public void onError(Throwable t) { + error = t; + done = true; + drain(); + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + @Override + public void request(long n) { + BackpressureHelper.add(requested, n); + drain(); + } + + @Override + public void cancel() { + cancelled = true; + s.cancel(); + } + + void drain() { + // see next code example + } +} +``` + +Here we extend `AtomicInteger` since the work-in-progress counting happens more often and is worth avoiding the extra indirection. The class extends `Subscription` and it hands itself to the `child` `Subscriber` to capture its `request()` (and `cancel()`) calls and route it to the main `drain` logic. Some operators need only this, some other operators (such as `observeOn` not only routes the downstream request but also does extra cancellations (cancels the asynchrony providing `Worker` as well) in its `cancel()` method. + +**Important**: when implementing operators for `Flowable` and `Observable` in RxJava 2.x, you are not allowed to pass along an upstream `Subscription` or `Disposable` to the child `Subscriber`/`Observer` when the operator logic itself doesn't require hooking the `request`/`cancel`/`dispose` calls. The reason for this is how operator-fusion is implemented on top of `Subscription` and `Disposable` passing through `onSubscribe` in RxJava 2.x (and in **Reactor 3**). See the next section about operator-fusion. There is no fusion in `Single`, `Completable` or `Maybe` (because there is no requesting or unbounded buffering with them) and their operators can pass the upstream `Disposable` along as is. + +Next comes the `drain` method whose pattern appears in many operators (with slight variations on how and what the emission does). + +```java +void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + + for (;;) { + long r = requested.get(); + long e = 0L; + long f = emitted; + + while (e != r) { + if (cancelled) { + return; + } + boolean d = done; + + if (d) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + return; + } + } + + T v = queue.poll(); + boolean empty = v == null; + + if (d && empty) { + child.onComplete(); + return; + } + + if (empty) { + break; + } + + child.onNext(v); + + e++; + if (++f == limit) { + s.request(f); + f = 0L; + } + } + + if (e == r) { + if (cancelled) { + return; + } + + if (done) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + return; + } + if (queue.isEmpty()) { + child.onComplete(); + return; + } + } + } + + if (e != 0L) { + BackpressureHelper.produced(requested, e); + } + + emitted = f; + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } +} +``` + +This particular pattern is called the **stable-request queue-drain**. Another variation doesn't care about request amount stability towards upstream and simply requests the amount it delivered to the child: + +```java +void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + + for (;;) { + long r = requested.get(); + long e = 0L; + + while (e != r) { + if (cancelled) { + return; + } + boolean d = done; + + if (d) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + return; + } + } + + T v = queue.poll(); + boolean empty = v == null; + + if (d && empty) { + child.onComplete(); + return; + } + + if (empty) { + break; + } + + child.onNext(v); + + e++; + } + + if (e == r) { + if (cancelled) { + return; + } + + if (done) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + return; + } + if (queue.isEmpty()) { + child.onComplete(); + return; + } + } + } + + if (e != 0L) { + BackpressureHelper.produced(requested, e); + s.request(e); + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } +} +``` + +The third variation allows delaying a potential error until the upstream has terminated and all normal elements have been delivered to the child: + +```java +final boolean delayError; + +void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + + for (;;) { + long r = requested.get(); + long e = 0L; + + while (e != r) { + if (cancelled) { + return; + } + boolean d = done; + + if (d && !delayError) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + return; + } + } + + T v = queue.poll(); + boolean empty = v == null; + + if (d && empty) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + } else { + child.onComplete(); + } + return; + } + + if (empty) { + break; + } + + child.onNext(v); + + e++; + } + + if (e == r) { + if (cancelled) { + return; + } + + if (done) { + if (delayError) { + if (queue.isEmpty()) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + } else { + child.onComplete(); + } + return; + } + } else { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + return; + } + if (queue.isEmpty()) { + child.onComplete(); + return; + } + } + } + } + + if (e != 0L) { + BackpressureHelper.produced(requested, e); + s.request(e); + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } +} +``` + +If the downstream cancels the operator, the `queue` may still hold elements which may get referenced longer than expected if the operator chain itself is referenced in some way. On the user level, applying `onTerminateDetach` will forget all references going upstream and downstream and can help with this situation. On the operator level, RxJava 2.x usually calls `clear()` on the `queue` when the sequence is cancelled or ends before the queue is drained naturally. This requires some slight change to the drain loop: + +```java +final boolean delayError; + +@Override +public void cancel() { + cancelled = true; + s.cancel(); + if (getAndIncrement() == 0) { + queue.clear(); // <---------------------------- + } +} + +void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + + for (;;) { + long r = requested.get(); + long e = 0L; + + while (e != r) { + if (cancelled) { + queue.clear(); // <---------------------------- + return; + } + boolean d = done; + + if (d && !delayError) { + Throwable ex = error; + if (ex != null) { + queue.clear(); // <---------------------------- + child.onError(ex); + return; + } + } + + T v = queue.poll(); + boolean empty = v == null; + + if (d && empty) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + } else { + child.onComplete(); + } + return; + } + + if (empty) { + break; + } + + child.onNext(v); + + e++; + } + + if (e == r) { + if (cancelled) { + queue.clear(); // <---------------------------- + return; + } + + if (done) { + if (delayError) { + if (queue.isEmpty()) { + Throwable ex = error; + if (ex != null) { + child.onError(ex); + } else { + child.onComplete(); + } + return; + } + } else { + Throwable ex = error; + if (ex != null) { + queue.clear(); // <---------------------------- + child.onError(ex); + return; + } + if (queue.isEmpty()) { + child.onComplete(); + return; + } + } + } + } + + if (e != 0L) { + BackpressureHelper.produced(requested, e); + s.request(e); + } + + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + } +} +``` + +Since the queue is single-producer-single-consumer, its `clear()` must be called from a single thread - which is provided by the serialization loop and is enabled by the `getAndIncrement() == 0` "half-loop" inside `cancel()`. + +An important note on the order of calls to `done` and the `queue`'s state: + +```java +boolean d = done; +T v = queue.poll(); +``` + +and + +```java +boolean d = done; +boolean empty = queue.isEmpty(); +``` + +These must happen in the order specified. If they were swapped, it is possible when the drain runs asynchronously to an `onNext`/`onComplete()`, the queue may appear empty at first, then it gets elements followed by `done = true` and a late `done` check in the drain loop may complete the sequence thinking it delivered all values there was. + +## Single valued results + +Sometimes an operator only emits one single value at some point instead of emitting more or all of its sources. Such operators include `fromCallable`, `reduce`, `any`, `all`, `first`, etc. + +The classical queue-drain works here but is a bit of an overkill to allocate objects to store the work-in-progress counter, request accounting and the queue itself. These elements can be reduced to a single state-machine with one state counter object - often inlinded by extending AtomicInteger - and a plain field for storing the single value to be emitted. + +The state machine handing the possible concurrent downstream requests and normal completion path is a bit complicated to show here and is quite easy to get wrong. + +RxJava 2.x supports this kind of behavior through the (internal) `DeferredScalarSubscription` for operators without an upstream source (`fromCallable`) and the (internal) `DeferredScalarSubscriber` for reduce-like operators with an upstream source. + +Using the `DeferredScalarSubscription` is straightforward, one creates it, sends it to the downstream via `onSubscribe` and later on calls `complete(T)` to signal the end with a single value: + +```java +DeferredScalarSubscription<Integer> dss = new DeferredScalarSubscription<>(child); +child.onSubscribe(dss); + +dss.complete(1); +``` + +Using the `DeferredScalarSubscriber` requires more coding and extending the class itself: + +```java +final class Counter extends DeferredScalarSubscriber<Object, Integer> { + public Counter(Subscriber<? super Integer> child) { + super(child); + value = 0; + hasValue = true; + } + + @Override + public void onNext(Object t) { + value++; + } +} +``` + +By default, the `DeferredScalarSubscriber.onSubscribe()` requests `Long.MAX_VALUE` from the upstream (but the method can be overridden in subclasses). + +## Single-element post-complete + +Some operators have to modulate a sequence of elements in a 1:1 fashion but when the upstream terminates, they need to produce a final element followed by a terminal event (usually `onComplete`). + +```java +final class OnCompleteEndWith implements Subscriber<T>, Subscription { + final Subscriber<? super T> child; + + final T finalElement; + + Subscription s; + + public OnCompleteEndWith(Subscriber<? super T> child, T finalElement) { + this.child = child; + this.finalElement = finalElement; + } + + @Override + public void onSubscribe(Subscription s) { + this.s = s; + child.onSubscribe(this); + } + + @Override + public void onNext(T t) { + child.onNext(t); + } + + @Overide + public void onError(Throwable t) { + child.onError(t); + } + + @Override + public void onComplete() { + child.onNext(finalElement); + child.onComplete(); + } + + @Override + public void request(long n) { + s.request(n); + } + + @Override + public void cancel() { + s.cancel(); + } +} +``` + +This works if the downstream request more than the upstream produces + 1, otherwise the call to `onComplete` may overflow the child `Subscriber`. + +Heavyweight solutions such as queue-drain or `SubscriptionArbiter` with `ScalarSubscriber` can be used here, however, there is a more elegant solution to the problem. + +The idea is that request amounts occupy only 63 bits of a 64 bit (atomic) long type. If we'd mask out the lower 63 bits when working with the amount, we can use the most significant bit to indicate the upstream sequence has finished and then on, any 0 to n request amount change can trigger the emission of the `finalElement`. Since a downstream `request()` can race with an upstream `onComplete`, marking the bit atomically via a compare-and-set ensures correct state transition. + +For this, the `OnCompleteEndWith` has to be changed by adding an `AtomicLong` for accounting requests, a long for counting the production, then updating `request()` and `onComplete()` methods: + +```java + +final class OnCompleteEndWith +extends AtomicLong +implements FlowableSubscriber<T>, Subscription { + final Subscriber<? super T> child; + + final T finalElement; + + Subscription s; + + long produced; + + static final class long REQUEST_MASK = Long.MAX_VALUE; // 0b01111...111L + static final class long COMPLETE_MASK = Long.MIN_VALUE; // 0b10000...000L + + public OnCompleteEndWith(Subscriber<? super T> child, T finalElement) { + this.child = child; + this.finalElement = finalElement; + } + + @Override + public void onSubscribe(Subscription s) { ... } + + @Override + public void onNext(T t) { + produced++; // <------------------------ + child.onNext(t); + } + + @Overide + public void onError(Throwable t) { ... } + + @Override + public void onComplete() { + long p = produced; + if (p != 0L) { + produced = 0L; + BackpressureHelper.produced(this, p); + } + + for (;;) { + long current = get(); + if ((current & COMPLETE_MASK) != 0) { + break; + } + if ((current & REQUEST_MASK) != 0) { + lazySet(Long.MIN_VALUE + 1); + child.onNext(finalElement); + child.onComplete(); + return; + } + if (compareAndSet(current, COMPLETE_MASK)) { + break; + } + } + } + + @Override + public void request(long n) { + for (;;) { + long current = get(); + if ((current & COMPLETE_MASK) != 0) { + if (compareAndSet(current, COMPLETE_MASK + 1)) { + child.onNext(finalElement); + child.onComplete(); + } + break; + } + long u = BackpressureHelper.addCap(current, n); + if (compareAndSet(current, u)) { + s.request(n); + break; + } + } + } + + @Override + public void cancel() { ... } +} +``` + +RxJava 2 has a couple of operators, `materialize`, `mapNotification`, `onErrorReturn`, that require this type of behavior and for that, the (internal) `SinglePostCompleteSubscriber` class captures the algorithms above: + +```java +final class OnCompleteEndWith<T> extends SinglePostCompleteSubscriber<T, T> { + final Subscriber<? super T> child; + + public OnCompleteEndWith(Subscriber<? super T> child, T finalElement) { + this.child = child; + this.value = finalElement; + } + + @Override + public void onNext(T t) { + produced++; // <------------------------ + child.onNext(t); + } + + @Overide + public void onError(Throwable t) { ... } + + @Override + public void onComplete() { + complete(value); + } +} +``` + +## Multi-element post-complete + +Certain operators may need to emit multiple elements after the main sequence completes, which may or may not relay elements from the live upstream before its termination. An example operator is `buffer(int, int)` when the skip < size yielding overlapping buffers. In this operator, it is possible when the upstream completes, several overlapping buffers are waiting to be emitted to the child but that has to happen only when the child actually requested more buffers. + +The state machine for this case is complicated but RxJava has two (internal) utility methods on `QueueDrainHelper` for dealing with the situation: + +```java +<T> void postComplete(Subscriber<? super T> actual, + Queue<T> queue, + AtomicLong state, + BooleanSupplier isCancelled); + +<T> boolean postCompleteRequest(long n, + Subscriber<? super T> actual, + Queue<T> queue, + AtomicLong state, + BooleanSupplier isCancelled); +``` + +They take the child `Subscriber`, the queue to drain from, the state holding the current request amount and a callback to see if the downstream cancelled the sequence. + +Usage of these methods is as follows: + +```java +final class EmitTwice<T> extends AtomicLong +implements FlowableSubscriber<T>, Subscription, BooleanSupplier { + final Subscriber<? super T> child; + + final ArrayDeque<T> buffer; + + volatile boolean cancelled; + + Subscription s; + + long produced; + + public EmitTwice(Subscriber<? super T> child) { + this.child = child; + this.buffer = new ArrayDeque<>(); + } + + @Override + public void onSubscribe(Subscription s) { + this.s = s; + child.onSubscribe(this); + } + + @Override + public void onNext(T t) { + produced++; + buffer.offer(t); + child.onNext(t); + } + + @Override + public void onError(Throwable t) { + buffer.clear(); + child.onError(t); + } + + @Override + public void onComplete() { + long p = produced; + if (p != 0L) { + produced = 0L; + BackpressureHelper.produced(this, p); + } + QueueDrainHelper.postComplete(child, buffer, this, this); + } + + @Override + public boolean getAsBoolean() { + return cancelled; + } + + @Override + public void cancel() { + cancelled = true; + s.cancel(); + } + + @Override + public void request(long n) { + if (!QueueDrainHelper.postCompleteRequest(n, child, buffer, this, this)) { + s.request(n); + } + } +} +``` + +# Creating operator classes + +Creating operator implementations in 2.x is simpler than in 1.x and incurs less allocation as well. You have the choice to implement your operator as a `Subscriber`-transformer to be used via `lift` or as a fully-fledged base reactive class. + +## Operator by extending a base reactive class + +In 1.x, extending `Observable` was possible but convoluted because you had to implement the `OnSubscribe` interface separately and pass it to `Observable.create()` or to the `Observable(OnSubscribe)` protected constructor. + +In 2.x, all base reactive classes are abstract and you can extend them directly without any additional indirection: + +```java +public final class FlowableMyOperator extends Flowable<Integer> { + final Publisher<Integer> source; + + public FlowableMyOperator(Publisher<Integer> source) { + this.source = source; + } + + @Override + protected void subscribeActual(Subscriber<? super Integer> s) { + source.map(v -> v + 1).subscribe(s); + } +} +``` + +When taking other reactive types as inputs in these operators, it is recommended one defines the base reactive interfaces instead of the abstract classes, allowing better interoperability between libraries (especially with `Flowable` operators and other Reactive-Streams `Publisher`s). To recap, these are the class-interface pairs: + + - `Flowable` - `Publisher` - `FlowableSubscriber`/`Subscriber` + - `Observable` - `ObservableSource` - `Observer` + - `Single` - `SingleSource` - `SingleObserver` + - `Completable` - `CompletableSource` - `CompletableObserver` + - `Maybe` - `MaybeSource` - `MaybeObserver` + +RxJava 2.x locks down `Flowable.subscribe` (and the same methods in the other types) in order to provide runtime hooks into the various flows, therefore, implementors are given the `subscribeActual()` to be overridden. When it is invoked, all relevant hooks and wrappers have been applied. Implementors should avoid throwing unchecked exceptions as the library generally can't deliver it to the respective `Subscriber` due to lifecycle restrictions of the Reactive-Streams specification and sends it to the global error consumer via `RxJavaPlugins.onError`. + +Unlike in 1.x, In the example above, the incoming `Subscriber` is simply used directly for subscribing again (but still at most once) without any kind of wrapping. In 1.x, one needs to call `Subscribers.wrap` to avoid double calls to `onStart` and cause unexpected double initialization or double-requesting. + +Unless one contributes a new operator to RxJava, working with such classes may become tedious, especially if they are intermediate operators: + +```java +new FlowableThenSome( + new FlowableOther( + new FlowableMyOperator(Flowable.range(1, 10).map(v -> v * v)) + ) +) +``` + +This is an unfortunate effect of Java lacking extension method support. A possible ease on this burden is by using `compose` to have fluent inline application of the custom operator: + +```java +Flowable.range(1, 10).map(v -> v * v) +.compose(f -> new FlowableOperatorWithParameter(f, 10)); + +Flowable.range(1, 10).map(v -> v * v) +.compose(FlowableMyOperator::new); +``` + +## Operator targeting lift() + +The alternative to the fluent application problem is to have a `Subscription`-transformer implemented instead of extending the whole reactive base class and use the respective type's `lift()` operator to get it into the sequence. + +First one has to implement the respective `XOperator` interface: + +```java +public final class MyOperator implements FlowableOperator<Integer, Integer> { + + @Override + public Subscriber<? super Integer> apply(Subscriber<? super Integer> child) { + return new Op(child); + } + + static final class Op implements FlowableSubscriber<Integer>, Subscription { + final Subscriber<? super Integer> child; + + Subscription s; + + public Op(Subscriber<? super Integer> child) { + this.child = child; + } + + @Override + pubic void onSubscribe(Subscription s) { + this.s = s; + child.onSubscribe(this); + } + + @Override + public void onNext(Integer v) { + child.onNext(v * v); + } + + @Override + public void onError(Throwable e) { + child.onError(e); + } + + @Override + public void onComplete() { + child.onComplete(); + } + + @Override + public void cancel() { + s.cancel(); + } + + @Override + public void request(long n) { + s.request(n); + } + } +} +``` + +You may recognize that implementing operators via extension or lifting looks quite similar. In both cases, one usually implements a `FlowableSubscriber` (`Observer`, etc) that takes a downstream `Subscriber`, implements the business logic in the `onXXX` methods and somehow (manually or as part of `lift()`'s lifecycle) gets subscribed to an upstream source. + +The benefit of applying the Reactive-Streams design to all base reactive types is that each consumer type is now an interface and can be applied to operators that have to extend some class. This was a pain in 1.x because `Subscriber` and `SingleSubscriber` are classes themselves, plus `Subscriber.request()` is a protected-final method and an operator's `Subscriber` can't implement the `Producer` interface at the same time. In 2.x there is no such problem and one can have both `Subscriber`, `Subscription` or even `Observer` together in the same consumer type. + +# Operator fusion + +Operator fusion has the premise that certain operators can be combined into one single operator (macro-fusion) or their internal data structures shared between each other (micro-fusion) that allows fewer allocations, lower overhead and better performance. + +This advanced concept was invented, worked out and studied in the [Reactive-Streams-Commons](https://github.com/reactor/reactive-streams-commons) research project manned by the leads of RxJava and Project Reactor. Both libraries use the results in their implementation, which look the same but are incompatible due to different classes and packages involved. In addition, RxJava 2.x's approach is a more polished version of the invention due to delays between the two project's development. + +Since operator-fusion is optional, you may chose to not bother making your operator fusion-enabled. The `DeferredScalarSubscription` is fusion-enabled and needs no additional development in this regard though. + +If you chose to ignore operator-fusion, you still have to follow the requirement of never forwarding a `Subscription`/`Disposable` coming through `onSubscribe` of `Subscriber`/`Observer` as this may break the fusion protocol and may skip your operator's business logic entirely: + +```java +final class SomeOp<T> implements Subscriber<T>, Subscription { + + // ... + Subscription s; + + public void onSubscribe(Subscription s) { + this.s = s; + child.onSubscribe(this); // <--------------------------- + } + + @Override + public void cancel() { + s.cancel(); + } + + @Override + public void request(long n) { + s.request(n); + } + + // ... +} +``` + +Yes, this adds one more indirection between operators but it is still cheap (and would be necessary for the operator anyway) but enables huge performance gains with the right chain of operators. + +## Generations + +Given this novel approach, a generation number can be assigned to various implementation styles of reactive architectures: + +#### Generation 0 +These are the classical libraries that either use `java.util.Observable` or are listener based (Java Swing's `ActionListener`). Their common property is that they don't support composition (of events and cancellation). See also **Google Agera**. + +#### Generation 1 +This is the level of the **Rx.NET** library (even up to 3.x) that supports composition, but has no notion for backpressure and doesn't properly support synchronous cancellation. Many JavaScript libraries such as **RxJS 5** are still on this level. See also **Google gRPC**. + +#### Generation 2 +This is what **RxJava 1.x** is categorized, it supports composition, backpressure and synchronous cancellation along with the ability to lift an operator into a sequence. + +#### Generation 3 +This is the level of the Reactive-Streams based libraries such as **Reactor 2** and **Akka-Stream**. They are based upon a specification that evolved out of RxJava but left behind its drawbacks (such as the need to return anything from `subscribe()`). This is incompatible with RxJava 1.x and thus 2.x had to be rewritten from scratch. + +#### Generation 4 +This level expands upon the Reactive-Streams interfaces with operator-fusion (in a compatible fashion, that is, op-fusion is optional between two stages and works without them). **Reactor 3** and **RxJava 2** are at this level. The material around **Akka-Stream** mentions operator-fusion as well, however, **Akka-Stream** is not a native Reactive-Streams implementation (requires a materializer to get a `Publisher` out) and as such it is only Gen 3. + +There are discussions among the 4th generation library providers to have the elements of operator-fusion standardized in Reactive-Streams 2.0 specification (or in a neighboring extension) and have **RxJava 3** and **Reactor 4** work together on that aspect as well. + +## Components + +### Callable and ScalarCallable + +Certain `Flowable` sources, similar to `Single` or `Completable` are known to ever emit zero or one item and that single item is known to be constant or is computed synchronously. Well known examples of this are `just()`, `empty()` and `fromCallable`. Subscribing to these sources, like any other sources, adds the same infrastructure overhead which can often be avoided if the consumer could just pick or have the item calculated on the spot. + +For example, `just` and `empty` appears as the mapping result of a `flatMap` operation: + +```java +source.flatMap(v -> { + if (v % 2 == 0) { + return just(v); + } + return empty(); +}) +``` + +Here, if we'd somehow recognize that `empty()` won't emit a value but only `onComplete` we could simply avoid subscribing to it inside `flatMap`, saving on the overhead. Similarly, recognizing that `just` emits exactly one item we can route it differently inside `flatMap` and again, avoiding creating a lot of objects to get to the same single item. + +In other times, knowing the emission property can simplify or chose a different operator instead of the applied one. For example, applying `flatMap` to an `empty()` source has no use since there won't be any item to be flattened into a sequence; the whole flattened sequence is going to be empty. Knowing that a source is `just` to `flatMap`, there is no need for the complicated inner mechanisms as there is going to be only one mapped inner source and one can subscribe the downstream's `Subscriber` to it directly. + +```java +Flowable.just(1).flatMap(v -> Flowable.range(v, 5)).subscribe(...); + +// in some specialized operator: + +T value; // from just() + +@Override +public void subscribeActual(Subscriber<? super T> s) { + mapper.apply(value).subscribe(s); +} +``` + +There could be other sources with these properties, therefore, RxJava 2 uses the `io.reactivex.internal.fusion.ScalarCallable` and `java.util.Callable` interfaces to indicate a source is a constant or sequentially computable. When a source `Flowable` or `Observable` is marked with one of these interfaces, many fusion enabled operators will perform special actions to avoid the overhead of a normal and general source. + +We use Java's own and preexisting `java.util.Callable` interface to indicate a synchronously computable source. The `ScalarCallable` is an extension to this interface by which it suppresses the `throws Exception` of `Callable.call()`: + +```java +interface Callable<T> { + T call() throws Exception; +} + +interface ScalarCallable<T> extends Callable<T> { + @Override + T call(); +} +``` + +The reason for the two separate interfaces is that if a source is constant, like `just`, one can perform assembly-time optimizations with it knowing that each regular `subscribe` invocation would have resulted in the same single value. + +`Callable` denotes sources, such as `fromCallable` that indicates the single value has to be calculated at runtime of the flow. By this logic, you can see that `ScalarCallable` is a `Callable` on its own right because the constant can be "calculated" as late as the runtime phase of the flow. + +Since Reactive-Streams forbids using `null`s as emission values, we can use `null` in `(Scalar)Callable` marked sources to indicate there is no value to be emitted, thus one can't mistake an user's `null` with the empty indicator `null`. For example, this is how `empty()` is implemented: + +```java +final class FlowableEmpty extends Flowable<Object> implements ScalarCallable<Object> { + @Override + public void subscribeActual(Subscriber<? super T> s) { + EmptySubscription.complete(s); + } + + @Override + public Object call() { + return null; // interpreted as no value available + } +} +``` + +Sources implementing `Callable` may throw checked exceptions from `call()` which is handled by the consumer operators as an indication to signal `onError` in an operator specific manner (such as delayed). + +```java +final class FlowableIOException extends Flowable<Object> implements Callable<Object> { + @Override + public void subscribeActual(Subscriber<? super T> s) { + EmptySubscription.error(new IOException(), s); + } + + @Override + public Object call() throws Exception { + throw new IOException(); + } +} +``` + +However, implementors of `ScalarCallable` should avoid throwing any exception and limit the code in `call()` be constant or simple computation that can be legally executed during assembly time. + +As the consumer of sources, one may want to deal with such kind of special `Flowable`s or `Observable`s. For example, if you create an operator that can leverage the knowledge of a single element source as its main input, you can check the types and extract the value of a `ScalarCallable` at assembly time right in the operator: + +```java +// Flowable.java +public final Flowable<Integer> plusOne() { + if (this instanceof ScalarCallable) { + Integer value = ((ScalarCallable<Integer>)this).call(); + if (value == null) { + return empty(); + } + return just(value + 1); + } + return cast(Integer.class).map(v -> v + 1); +} +``` + +or as a `FlowableTransformer`: + +```java +FlowableTransformer<Integer, Integer> plusOneTransformer = source -> { + if (source instanceof ScalarCallable) { + Integer value = ((ScalarCallable<Integer>)source).call(); + if (value == null) { + return empty(); + } + return just(value + 1); + } + return source.map(v -> v + 1); +}; +``` + +However, it is not mandatory to handle `ScalarCallable`s and `Callable`s separately. Since the former extends the latter, the type check can be deferred till subscription time and handled with the same code path: + +```java +final class FlowablePlusOne extends Flowable<Integer> { + final Publisher<Integer> source; + + FlowablePlusOne(Publisher<Integer> source) { + this.source = source; + } + + @Override + public void subscribeActual(Subscriber<? super Integer> s) { + if (source instanceof Callable) { + Integer value; + + try { + value = ((Callable<Integer>)source).call(); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + EmptySubscription.error(ex, s); + return; + } + + s.onSubscribe(new ScalarSubscription<Integer>(s, value + 1)); + } else { + new FlowableMap<>(source, v -> v + 1).subscribe(s); + } + } +} +``` + +### ConditionalSubscriber + +TBD + +### QueueSubscription and QueueDisposable + +TBD + +# Example implementations + +TBD + +## `map` + `filter` hybrid + +TBD + +## Ordered `merge` + +TBD diff --git a/docs/_Footer.md b/docs/_Footer.md new file mode 100644 index 0000000000..8ecc48ce6f --- /dev/null +++ b/docs/_Footer.md @@ -0,0 +1,2 @@ +**Copyright (c) 2016-present, RxJava Contributors.** +[Twitter @RxJava](https://twitter.com/#!/RxJava) | [Gitter @RxJava](https://gitter.im/ReactiveX/RxJava) diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md new file mode 100644 index 0000000000..d27b620b10 --- /dev/null +++ b/docs/_Sidebar.md @@ -0,0 +1,26 @@ +* [[Getting Started]] +* [[How To Use RxJava]] +* [[Additional Reading]] +* [[Observable]] + * [[Creating Observables]] + * [[Transforming Observables]] + * [[Filtering Observables]] + * [[Combining Observables]] + * [[Error Handling Operators]] + * [[Observable Utility Operators]] + * [[Conditional and Boolean Operators]] + * [[Mathematical and Aggregate Operators]] + * [[Async Operators]] + * [[Connectable Observable Operators]] + * [[Blocking Observable Operators]] + * [[String Observables]] + * [[Alphabetical List of Observable Operators]] + * [[Implementing Your Own Operators]] +* [[Subject]] +* [[Scheduler]] +* [[Plugins]] +* [[Backpressure]] +* [[Error Handling]] +* [[The RxJava Android Module]] +* [[How to Contribute]] +* [Javadoc](http://reactivex.io/RxJava/javadoc/rx/Observable.html) \ No newline at end of file diff --git a/docs/_Sidebar.md.md b/docs/_Sidebar.md.md new file mode 100644 index 0000000000..a07aa3d93e --- /dev/null +++ b/docs/_Sidebar.md.md @@ -0,0 +1,35 @@ +* [Introduction](https://github.com/ReactiveX/RxJava/wiki/Home) +* [Getting Started](https://github.com/ReactiveX/RxJava/wiki/Getting-Started) +* [JavaDoc](http://reactivex.io/RxJava/javadoc) + * [1.x](http://reactivex.io/RxJava/1.x/javadoc/rx/Observable.html) + * [2.x](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html) +* [How to Use RxJava](https://github.com/ReactiveX/RxJava/wiki/How-To-Use-RxJava) +* [Additional Reading](https://github.com/ReactiveX/RxJava/wiki/Additional-Reading) +* [The Observable](https://github.com/ReactiveX/RxJava/wiki/Observable) +* Operators [(Alphabetical List)](http://reactivex.io/documentation/operators.html#alphabetical) + * [Async](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) + * [Blocking Observable](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) + * [Combining](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables) + * [Conditional & Boolean](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators) + * [Connectable Observable](https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators) + * [Error Handling Operators](https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators) + * [Filtering](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) + * [Mathematical and Aggregate](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators) + * [Observable Creation](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables) + * [Parallel flows](https://github.com/ReactiveX/RxJava/wiki/Parallel-flows) + * [String](https://github.com/ReactiveX/RxJava/wiki/String-Observables) + * [Transformational](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables) + * [Utility Operators](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) + * [Implementing Custom Operators](https://github.com/ReactiveX/RxJava/wiki/Implementing-custom-operators-(draft)), [previous](https://github.com/ReactiveX/RxJava/wiki/Implementing-Your-Own-Operators) +* [Backpressure](https://github.com/ReactiveX/RxJava/wiki/Backpressure) +* [Error Handling](https://github.com/ReactiveX/RxJava/wiki/Error-Handling) +* [Plugins](https://github.com/ReactiveX/RxJava/wiki/Plugins) +* [Schedulers](https://github.com/ReactiveX/RxJava/wiki/Scheduler) +* [Subjects](https://github.com/ReactiveX/RxJava/wiki/Subject) +* [The RxJava Android Module](https://github.com/ReactiveX/RxAndroid/wiki) +* RxJava 2.0 + * [Reactive Streams](https://github.com/ReactiveX/RxJava/wiki/Reactive-Streams) + * [What's different](https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0) + * [Writing operators](https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0) + * [Backpressure](https://github.com/ReactiveX/RxJava/wiki/Backpressure-(2.0)) +* [How to Contribute](https://github.com/ReactiveX/RxJava/wiki/How-to-Contribute) \ No newline at end of file From e6b852d5c3826421d351d8e02af890c2f99641a9 Mon Sep 17 00:00:00 2001 From: Roman Petrenko <petrenko_r@mail.ru> Date: Mon, 18 Jun 2018 21:14:54 +1000 Subject: [PATCH 204/417] Make it explicit that throttleWithTimout is an alias of debounce (#6049) * Make it explicit that throttleWithTimout is an alias of debounce * feedback * fixed marble images --- src/main/java/io/reactivex/Flowable.java | 68 +++++++--------------- src/main/java/io/reactivex/Observable.java | 67 +++++++-------------- 2 files changed, 44 insertions(+), 91 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 387f36c5cd..13853d4603 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -8035,25 +8035,19 @@ public final <U> Flowable<T> debounce(Function<? super T, ? extends Publisher<U> * will be emitted by the resulting Publisher. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.png" alt=""> - * <p> - * Information on debounce vs throttle: - * <ul> - * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> - * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> - * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> - * </ul> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> - * <dd>This version of {@code debounce} operates by default on the {@code computation} {@link Scheduler}.</dd> + * <dd>{@code debounce} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timeout - * the time each item has to be "the most recent" of those emitted by the source Publisher to - * ensure that it's not dropped + * the length of the window of time that must pass after the emission of an item from the source + * Publisher in which that Publisher emits no items in order for the item to be emitted by the + * resulting Publisher * @param unit - * the {@link TimeUnit} for the timeout + * the unit of time for the specified {@code timeout} * @return a Flowable that filters out items from the source Publisher that are too quickly followed by * newer items * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> @@ -8076,13 +8070,6 @@ public final Flowable<T> debounce(long timeout, TimeUnit unit) { * will be emitted by the resulting Publisher. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.s.png" alt=""> - * <p> - * Information on debounce vs throttle: - * <ul> - * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> - * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> - * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> - * </ul> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> @@ -8094,7 +8081,7 @@ public final Flowable<T> debounce(long timeout, TimeUnit unit) { * the time each item has to be "the most recent" of those emitted by the source Publisher to * ensure that it's not dropped * @param unit - * the unit of time for the specified timeout + * the unit of time for the specified {@code timeout} * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle the timeout for each * item @@ -15774,20 +15761,14 @@ public final Flowable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler s } /** - * Returns a Flowable that only emits those items emitted by the source Publisher that are not followed - * by another emitted item within a specified time window. + * Returns a Flowable that mirrors the source Publisher, except that it drops items emitted by the + * source Publisher that are followed by newer items before a timeout value expires. The timer resets on + * each emission (alias to {@link #debounce(long, TimeUnit)}). * <p> - * <em>Note:</em> If the source Publisher keeps emitting items more frequently than the length of the time - * window then no items will be emitted by the resulting Publisher. + * <em>Note:</em> If items keep being emitted by the source Publisher faster than the timeout then no items + * will be emitted by the resulting Publisher. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleWithTimeout.png" alt=""> - * <p> - * Information on debounce vs throttle: - * <ul> - * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> - * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> - * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> - * </ul> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> @@ -15800,8 +15781,9 @@ public final Flowable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler s * Publisher in which that Publisher emits no items in order for the item to be emitted by the * resulting Publisher * @param unit - * the {@link TimeUnit} of {@code timeout} - * @return a Flowable that filters out items that are too quickly followed by newer items + * the unit of time for the specified {@code timeout} + * @return a Flowable that filters out items from the source Publisher that are too quickly followed by + * newer items * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> * @see #debounce(long, TimeUnit) @@ -15814,21 +15796,14 @@ public final Flowable<T> throttleWithTimeout(long timeout, TimeUnit unit) { } /** - * Returns a Flowable that only emits those items emitted by the source Publisher that are not followed - * by another emitted item within a specified time window, where the time window is governed by a specified - * Scheduler. + * Returns a Flowable that mirrors the source Publisher, except that it drops items emitted by the + * source Publisher that are followed by newer items before a timeout value expires on a specified + * Scheduler. The timer resets on each emission (alias to {@link #debounce(long, TimeUnit, Scheduler)}). * <p> - * <em>Note:</em> If the source Publisher keeps emitting items more frequently than the length of the time - * window then no items will be emitted by the resulting Publisher. + * <em>Note:</em> If items keep being emitted by the source Publisher faster than the timeout then no items + * will be emitted by the resulting Publisher. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleWithTimeout.s.png" alt=""> - * <p> - * Information on debounce vs throttle: - * <ul> - * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> - * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> - * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> - * </ul> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> @@ -15841,11 +15816,12 @@ public final Flowable<T> throttleWithTimeout(long timeout, TimeUnit unit) { * Publisher in which that Publisher emits no items in order for the item to be emitted by the * resulting Publisher * @param unit - * the {@link TimeUnit} of {@code timeout} + * the unit of time for the specified {@code timeout} * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle the timeout for each * item - * @return a Flowable that filters out items that are too quickly followed by newer items + * @return a Flowable that filters out items from the source Publisher that are too quickly followed by + * newer items * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> * @see #debounce(long, TimeUnit, Scheduler) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index c30ca995f1..feddca1fed 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7196,23 +7196,17 @@ public final <U> Observable<T> debounce(Function<? super T, ? extends Observable * will be emitted by the resulting ObservableSource. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.png" alt=""> - * <p> - * Information on debounce vs throttle: - * <ul> - * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> - * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> - * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> - * </ul> * <dl> * <dt><b>Scheduler:</b></dt> - * <dd>This version of {@code debounce} operates by default on the {@code computation} {@link Scheduler}.</dd> + * <dd>{@code debounce} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timeout - * the time each item has to be "the most recent" of those emitted by the source ObservableSource to - * ensure that it's not dropped + * the length of the window of time that must pass after the emission of an item from the source + * ObservableSource in which that ObservableSource emits no items in order for the item to be emitted by the + * resulting ObservableSource * @param unit - * the {@link TimeUnit} for the timeout + * the unit of time for the specified {@code timeout} * @return an Observable that filters out items from the source ObservableSource that are too quickly followed by * newer items * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> @@ -7233,13 +7227,6 @@ public final Observable<T> debounce(long timeout, TimeUnit unit) { * will be emitted by the resulting ObservableSource. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.s.png" alt=""> - * <p> - * Information on debounce vs throttle: - * <ul> - * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> - * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> - * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> - * </ul> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> @@ -7249,7 +7236,7 @@ public final Observable<T> debounce(long timeout, TimeUnit unit) { * the time each item has to be "the most recent" of those emitted by the source ObservableSource to * ensure that it's not dropped * @param unit - * the unit of time for the specified timeout + * the unit of time for the specified {@code timeout} * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle the timeout for each * item @@ -13180,20 +13167,15 @@ public final Observable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler } /** - * Returns an Observable that only emits those items emitted by the source ObservableSource that are not followed - * by another emitted item within a specified time window. + * Returns an Observable that mirrors the source ObservableSource, except that it drops items emitted by the + * source ObservableSource that are followed by newer items before a timeout value expires. The timer resets on + * each emission (alias to {@link #debounce(long, TimeUnit, Scheduler)}). * <p> - * <em>Note:</em> If the source ObservableSource keeps emitting items more frequently than the length of the time - * window then no items will be emitted by the resulting ObservableSource. + * <em>Note:</em> If items keep being emitted by the source ObservableSource faster than the timeout then no items + * will be emitted by the resulting ObservableSource. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleWithTimeout.png" alt=""> * <p> - * Information on debounce vs throttle: - * <ul> - * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> - * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> - * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> - * </ul> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code throttleWithTimeout} operates by default on the {@code computation} {@link Scheduler}.</dd> @@ -13204,8 +13186,9 @@ public final Observable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler * ObservableSource in which that ObservableSource emits no items in order for the item to be emitted by the * resulting ObservableSource * @param unit - * the {@link TimeUnit} of {@code timeout} - * @return an Observable that filters out items that are too quickly followed by newer items + * the unit of time for the specified {@code timeout} + * @return an Observable that filters out items from the source ObservableSource that are too quickly followed by + * newer items * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> * @see #debounce(long, TimeUnit) */ @@ -13216,21 +13199,14 @@ public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit) { } /** - * Returns an Observable that only emits those items emitted by the source ObservableSource that are not followed - * by another emitted item within a specified time window, where the time window is governed by a specified - * Scheduler. + * Returns an Observable that mirrors the source ObservableSource, except that it drops items emitted by the + * source ObservableSource that are followed by newer items before a timeout value expires on a specified + * Scheduler. The timer resets on each emission (Alias to {@link #debounce(long, TimeUnit, Scheduler)}). * <p> - * <em>Note:</em> If the source ObservableSource keeps emitting items more frequently than the length of the time - * window then no items will be emitted by the resulting ObservableSource. + * <em>Note:</em> If items keep being emitted by the source ObservableSource faster than the timeout then no items + * will be emitted by the resulting ObservableSource. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleWithTimeout.s.png" alt=""> - * <p> - * Information on debounce vs throttle: - * <ul> - * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> - * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> - * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> - * </ul> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> @@ -13241,11 +13217,12 @@ public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit) { * ObservableSource in which that ObservableSource emits no items in order for the item to be emitted by the * resulting ObservableSource * @param unit - * the {@link TimeUnit} of {@code timeout} + * the unit of time for the specified {@code timeout} * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle the timeout for each * item - * @return an Observable that filters out items that are too quickly followed by newer items + * @return an Observable that filters out items from the source ObservableSource that are too quickly followed by + * newer items * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> * @see #debounce(long, TimeUnit, Scheduler) */ From cc186bc692de9a0a4b489db8cfdb24c798f6286f Mon Sep 17 00:00:00 2001 From: Marc Bramaud <sircelsius@users.noreply.github.com> Date: Thu, 21 Jun 2018 09:22:20 +0200 Subject: [PATCH 205/417] #5980 made subscribeActual protected (#6052) --- src/main/java/io/reactivex/processors/PublishProcessor.java | 2 +- src/main/java/io/reactivex/subjects/PublishSubject.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index 8756a28e35..725b5fed91 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -92,7 +92,7 @@ public static <T> PublishProcessor<T> create() { @Override - public void subscribeActual(Subscriber<? super T> t) { + protected void subscribeActual(Subscriber<? super T> t) { PublishSubscription<T> ps = new PublishSubscription<T>(t, this); t.onSubscribe(ps); if (add(ps)) { diff --git a/src/main/java/io/reactivex/subjects/PublishSubject.java b/src/main/java/io/reactivex/subjects/PublishSubject.java index 2b1bbc60ad..b99fe9f6cc 100644 --- a/src/main/java/io/reactivex/subjects/PublishSubject.java +++ b/src/main/java/io/reactivex/subjects/PublishSubject.java @@ -131,7 +131,7 @@ public static <T> PublishSubject<T> create() { @Override - public void subscribeActual(Observer<? super T> t) { + protected void subscribeActual(Observer<? super T> t) { PublishDisposable<T> ps = new PublishDisposable<T>(t, this); t.onSubscribe(ps); if (add(ps)) { From 6dd16486b39ce26c929cff6af97f3e36e7aa61a9 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 21 Jun 2018 11:32:33 +0200 Subject: [PATCH 206/417] 2.x: Add Maybe marble diagrams 06/21/a (#6053) --- src/main/java/io/reactivex/Maybe.java | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 164ef91b3b..de4cbec178 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -52,6 +52,8 @@ public abstract class Maybe<T> implements MaybeSource<T> { /** * Runs multiple MaybeSources and signals the events of the first one that signals (cancelling * the rest). + * <p> + * <img width="640" height="519" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> @@ -71,6 +73,8 @@ public static <T> Maybe<T> amb(final Iterable<? extends MaybeSource<? extends T> /** * Runs multiple MaybeSources and signals the events of the first one that signals (cancelling * the rest). + * <p> + * <img width="640" height="519" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.ambArray.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ambArray} does not operate by default on a particular {@link Scheduler}.</dd> @@ -96,6 +100,8 @@ public static <T> Maybe<T> ambArray(final MaybeSource<? extends T>... sources) { /** * Concatenate the single values, in a non-overlapping fashion, of the MaybeSource sources provided by * an Iterable sequence. + * <p> + * <img width="640" height="526" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.i.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -215,6 +221,8 @@ public static <T> Flowable<T> concat( /** * Concatenate the single values, in a non-overlapping fashion, of the MaybeSource sources provided by * a Publisher sequence. + * <p> + * <img width="640" height="416" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer and @@ -237,6 +245,8 @@ public static <T> Flowable<T> concat(Publisher<? extends MaybeSource<? extends T /** * Concatenate the single values, in a non-overlapping fashion, of the MaybeSource sources provided by * a Publisher sequence. + * <p> + * <img width="640" height="416" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.pn.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer and @@ -263,6 +273,8 @@ public static <T> Flowable<T> concat(Publisher<? extends MaybeSource<? extends T /** * Concatenate the single values, in a non-overlapping fashion, of the MaybeSource sources in the array. * <dl> + * <p> + * <img width="640" height="526" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArray.png" alt=""> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> * <dt><b>Scheduler:</b></dt> @@ -291,7 +303,7 @@ public static <T> Flowable<T> concatArray(MaybeSource<? extends T>... sources) { * Concatenates a variable number of MaybeSource sources and delays errors from any of them * till all terminate. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concat.png" alt=""> + * <img width="640" height="425" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArrayDelayError.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> @@ -323,6 +335,8 @@ public static <T> Flowable<T> concatArrayDelayError(MaybeSource<? extends T>... * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source MaybeSources. The operator buffers the value emitted by these MaybeSources and then drains them * in order, each one after the previous one completes. + * <p> + * <img width="640" height="489" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArrayEager.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> @@ -344,7 +358,8 @@ public static <T> Flowable<T> concatArrayEager(MaybeSource<? extends T>... sourc /** * Concatenates the Iterable sequence of MaybeSources into a single sequence by subscribing to each MaybeSource, * one after the other, one at a time and delays any errors till the all inner MaybeSources terminate. - * + * <p> + * <img width="640" height="469" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatDelayError.i.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure from downstream.</dd> @@ -368,7 +383,8 @@ public static <T> Flowable<T> concatDelayError(Iterable<? extends MaybeSource<? /** * Concatenates the Publisher sequence of Publishers into a single sequence by subscribing to each inner Publisher, * one after the other, one at a time and delays any errors till the all inner and the outer Publishers terminate. - * + * <p> + * <img width="640" height="360" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatDelayError.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>{@code concatDelayError} fully supports backpressure.</dd> @@ -394,6 +410,8 @@ public static <T> Flowable<T> concatDelayError(Publisher<? extends MaybeSource<? * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source MaybeSources. The operator buffers the values emitted by these MaybeSources and then drains them * in order, each one after the previous one completes. + * <p> + * <img width="640" height="526" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEager.i.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream.</dd> @@ -418,6 +436,8 @@ public static <T> Flowable<T> concatEager(Iterable<? extends MaybeSource<? exten * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source Publishers as they are observed. The operator buffers the values emitted by these * Publishers and then drains them in order, each one after the previous one completes. + * <p> + * <img width="640" height="511" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEager.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream and the outer Publisher is From b041e3237da2e49df35cfc50c46b5a836f8d9ad5 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 21 Jun 2018 23:23:59 +0200 Subject: [PATCH 207/417] 2.x: Use different wording on blockingForEach() JavaDocs (#6057) --- src/main/java/io/reactivex/Flowable.java | 20 +++++++++----------- src/main/java/io/reactivex/Observable.java | 20 +++++++++----------- 2 files changed, 18 insertions(+), 22 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 13853d4603..406198507c 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -5472,20 +5472,18 @@ public final T blockingFirst(T defaultItem) { } /** - * Invokes a method on each item emitted by this {@code Flowable} and blocks until the Flowable - * completes. - * <p> - * <em>Note:</em> This will block even if the underlying Flowable is asynchronous. + * Consumes the upstream {@code Flowable} in a blocking fashion and invokes the given + * {@code Consumer} with each upstream item on the <em>current thread</em> until the + * upstream terminates. * <p> * <img width="640" height="330" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/B.forEach.png" alt=""> * <p> - * This is similar to {@link Flowable#subscribe(Subscriber)}, but it blocks. Because it blocks it does not - * need the {@link Subscriber#onComplete()} or {@link Subscriber#onError(Throwable)} methods. If the - * underlying Flowable terminates with an error, rather than calling {@code onError}, this method will - * throw an exception. - * - * <p>The difference between this method and {@link #subscribe(Consumer)} is that the {@code onNext} action - * is executed on the emission thread instead of the current thread. + * <em>Note:</em> the method will only return if the upstream terminates or the current + * thread is interrupted. + * <p> + * <p>This method executes the {@code Consumer} on the current thread while + * {@link #subscribe(Consumer)} executes the consumer on the original caller thread of the + * sequence. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator consumes the source {@code Flowable} in an unbounded manner diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index feddca1fed..045fe3d987 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -5018,20 +5018,18 @@ public final T blockingFirst(T defaultItem) { } /** - * Invokes a method on each item emitted by this {@code Observable} and blocks until the Observable - * completes. - * <p> - * <em>Note:</em> This will block even if the underlying Observable is asynchronous. + * Consumes the upstream {@code Observable} in a blocking fashion and invokes the given + * {@code Consumer} with each upstream item on the <em>current thread</em> until the + * upstream terminates. * <p> * <img width="640" height="330" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingForEach.o.png" alt=""> * <p> - * This is similar to {@link Observable#subscribe(Observer)}, but it blocks. Because it blocks it does not - * need the {@link Observer#onComplete()} or {@link Observer#onError(Throwable)} methods. If the - * underlying Observable terminates with an error, rather than calling {@code onError}, this method will - * throw an exception. - * - * <p>The difference between this method and {@link #subscribe(Consumer)} is that the {@code onNext} action - * is executed on the emission thread instead of the current thread. + * <em>Note:</em> the method will only return if the upstream terminates or the current + * thread is interrupted. + * <p> + * <p>This method executes the {@code Consumer} on the current thread while + * {@link #subscribe(Consumer)} executes the consumer on the original caller thread of the + * sequence. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingForEach} does not operate by default on a particular {@link Scheduler}.</dd> From 2e39d9923e034cd8648bba8cfd7fd15f3d3031b9 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 22 Jun 2018 00:38:18 +0200 Subject: [PATCH 208/417] 2.x: Expand {X}Processor JavaDocs by syncing with {X}Subject docs (#6054) * 2.x: Expand {X}Processor JavaDocs by syncing with {X}Subject docs * A-an * Fix javadoc warnings --- src/main/java/io/reactivex/Maybe.java | 2 +- src/main/java/io/reactivex/Observable.java | 1 - .../reactivex/processors/AsyncProcessor.java | 109 +++++++++++++-- .../processors/BehaviorProcessor.java | 20 +-- .../processors/PublishProcessor.java | 85 +++++++++--- .../reactivex/processors/ReplayProcessor.java | 130 +++++++++++++----- .../processors/UnicastProcessor.java | 122 ++++++++++++++-- .../io/reactivex/subjects/UnicastSubject.java | 17 ++- 8 files changed, 388 insertions(+), 98 deletions(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index de4cbec178..918dbeccd5 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -272,9 +272,9 @@ public static <T> Flowable<T> concat(Publisher<? extends MaybeSource<? extends T /** * Concatenate the single values, in a non-overlapping fashion, of the MaybeSource sources in the array. - * <dl> * <p> * <img width="640" height="526" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArray.png" alt=""> + * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> * <dt><b>Scheduler:</b></dt> diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 045fe3d987..70fff76e3a 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -13173,7 +13173,6 @@ public final Observable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler * will be emitted by the resulting ObservableSource. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleWithTimeout.png" alt=""> - * <p> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code throttleWithTimeout} operates by default on the {@code computation} {@link Scheduler}.</dd> diff --git a/src/main/java/io/reactivex/processors/AsyncProcessor.java b/src/main/java/io/reactivex/processors/AsyncProcessor.java index 37d6937e49..6ef3044d6d 100644 --- a/src/main/java/io/reactivex/processors/AsyncProcessor.java +++ b/src/main/java/io/reactivex/processors/AsyncProcessor.java @@ -28,9 +28,90 @@ * <p> * <img width="640" height="239" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/AsyncProcessor.png" alt=""> * <p> - * The implementation of onXXX methods are technically thread-safe but non-serialized calls - * to them may lead to undefined state in the currently subscribed Subscribers. + * This processor does not have a public constructor by design; a new empty instance of this + * {@code AsyncProcessor} can be created via the {@link #create()} method. + * <p> + * Since an {@code AsyncProcessor} is a Reactive Streams {@code Processor} type, + * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) + * as parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the processor's state is not changed. + * <p> + * {@code AsyncProcessor} is a {@link io.reactivex.Flowable} as well as a {@link FlowableProcessor} and supports backpressure from the downstream but + * its {@link Subscriber}-side consumes items in an unbounded manner. + * <p> + * When this {@code AsyncProcessor} is terminated via {@link #onError(Throwable)}, the + * last observed item (if any) is cleared and late {@link Subscriber}s only receive + * the {@code onError} event. + * <p> + * The {@code AsyncProcessor} caches the latest item internally and it emits this item only when {@code onComplete} is called. + * Therefore, it is not recommended to use this {@code Processor} with infinite or never-completing sources. + * <p> + * Even though {@code AsyncProcessor} implements the {@link Subscriber} interface, calling + * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>) + * if the processor is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code AsyncProcessor} reached its terminal state will result in the + * given {@link Subscription} being canceled immediately. + * <p> + * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@code FlowableProcessor}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} + * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). + * The implementation of {@code onXXX} methods are technically thread-safe but non-serialized calls + * to them may lead to undefined state in the currently subscribed {@code Subscriber}s. + * <p> + * This {@code AsyncProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the very last observed value - + * after this {@code AsyncProcessor} has been completed - in a non-blocking and thread-safe + * manner via {@link #hasValue()}, {@link #getValue()}, {@link #getValues()} or {@link #getValues(Object[])}. + * <dl> + * <dt><b>Backpressure:</b></dt> + * <dd>The {@code AsyncProcessor} honors the backpressure of the downstream {@code Subscriber}s and won't emit + * its single value to a particular {@code Subscriber} until that {@code Subscriber} has requested an item. + * When the {@code AsyncProcessor} is subscribed to a {@link io.reactivex.Flowable}, the processor consumes this + * {@code Flowable} in an unbounded manner (requesting `Long.MAX_VALUE`) as only the very last upstream item is + * retained by it. + * </dd> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code AsyncProcessor} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code Subscriber}s get notified on the thread where the terminating {@code onError} or {@code onComplete} + * methods were invoked.</dd> + * <dt><b>Error handling:</b></dt> + * <dd>When the {@link #onError(Throwable)} is called, the {@code AsyncProcessor} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code Subscriber}s. During this emission, + * if one or more {@code Subscriber}s dispose their respective {@code Subscription}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Subscriber}s + * cancel at once). + * If there were no {@code Subscriber}s subscribed to this {@code AsyncProcessor} when the {@code onError()} + * was called, the global error handler is not invoked. + * </dd> + * </dl> + * <p> + * Example usage: + * <pre><code> + * AsyncProcessor<Object> processor = AsyncProcessor.create(); + * + * TestSubscriber<Object> ts1 = processor.test(); + * + * ts1.assertEmpty(); + * + * processor.onNext(1); + * + * // AsyncProcessor only emits when onComplete was called. + * ts1.assertEmpty(); + * + * processor.onNext(2); + * processor.onComplete(); + * + * // onComplete triggers the emission of the last cached item and the onComplete event. + * ts1.assertResult(2); + * + * TestSubscriber<Object> ts2 = processor.test(); * + * // late Subscribers receive the last cached item too + * ts2.assertResult(2); + * </code></pre> * @param <T> the value type */ public final class AsyncProcessor<T> extends FlowableProcessor<T> { @@ -75,7 +156,7 @@ public void onSubscribe(Subscription s) { s.cancel(); return; } - // PublishSubject doesn't bother with request coordination. + // AsyncProcessor doesn't bother with request coordination. s.request(Long.MAX_VALUE); } @@ -168,9 +249,9 @@ protected void subscribeActual(Subscriber<? super T> s) { /** * Tries to add the given subscriber to the subscribers array atomically - * or returns false if the subject has terminated. + * or returns false if the processor has terminated. * @param ps the subscriber to add - * @return true if successful, false if the subject has terminated + * @return true if successful, false if the processor has terminated */ boolean add(AsyncSubscription<T> ps) { for (;;) { @@ -192,8 +273,8 @@ boolean add(AsyncSubscription<T> ps) { } /** - * Atomically removes the given subscriber if it is subscribed to the subject. - * @param ps the subject to remove + * Atomically removes the given subscriber if it is subscribed to this processor. + * @param ps the subscriber's subscription wrapper to remove */ @SuppressWarnings("unchecked") void remove(AsyncSubscription<T> ps) { @@ -232,18 +313,18 @@ void remove(AsyncSubscription<T> ps) { } /** - * Returns true if the subject has any value. + * Returns true if this processor has any value. * <p>The method is thread-safe. - * @return true if the subject has any value + * @return true if this processor has any value */ public boolean hasValue() { return subscribers.get() == TERMINATED && value != null; } /** - * Returns a single value the Subject currently has or null if no such value exists. + * Returns a single value this processor currently has or null if no such value exists. * <p>The method is thread-safe. - * @return a single value the Subject currently has or null if no such value exists + * @return a single value this processor currently has or null if no such value exists */ @Nullable public T getValue() { @@ -251,9 +332,9 @@ public T getValue() { } /** - * Returns an Object array containing snapshot all values of the Subject. + * Returns an Object array containing snapshot all values of this processor. * <p>The method is thread-safe. - * @return the array containing the snapshot of all values of the Subject + * @return the array containing the snapshot of all values of this processor * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x */ @Deprecated @@ -263,7 +344,7 @@ public Object[] getValues() { } /** - * Returns a typed array containing a snapshot of all values of the Subject. + * Returns a typed array containing a snapshot of all values of this processor. * <p>The method follows the conventions of Collection.toArray by setting the array element * after the last value to null (if the capacity permits). * <p>The method is thread-safe. diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index 4c407a7e7f..5ee462824f 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -85,11 +85,13 @@ * after the {@code BehaviorProcessor} reached its terminal state will result in the * given {@code Subscription} being cancelled immediately. * <p> - * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * Calling {@link #onNext(Object)}, {@link #offer(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} * is required to be serialized (called from the same thread or called non-overlappingly from different threads * through external means of serialization). The {@link #toSerialized()} method available to all {@code FlowableProcessor}s * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). + * Note that serializing over {@link #offer(Object)} is not supported through {@code toSerialized()} because it is a method + * available on the {@code PublishProcessor} and {@code BehaviorProcessor} classes only. * <p> * This {@code BehaviorProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the latest observed value @@ -127,34 +129,34 @@ * Example usage: * <pre> {@code - // observer will receive all events. + // subscriber will receive all events. BehaviorProcessor<Object> processor = BehaviorProcessor.create("default"); - processor.subscribe(observer); + processor.subscribe(subscriber); processor.onNext("one"); processor.onNext("two"); processor.onNext("three"); - // observer will receive the "one", "two" and "three" events, but not "zero" + // subscriber will receive the "one", "two" and "three" events, but not "zero" BehaviorProcessor<Object> processor = BehaviorProcessor.create("default"); processor.onNext("zero"); processor.onNext("one"); - processor.subscribe(observer); + processor.subscribe(subscriber); processor.onNext("two"); processor.onNext("three"); - // observer will receive only onComplete + // subscriber will receive only onComplete BehaviorProcessor<Object> processor = BehaviorProcessor.create("default"); processor.onNext("zero"); processor.onNext("one"); processor.onComplete(); - processor.subscribe(observer); + processor.subscribe(subscriber); - // observer will receive only onError + // subscriber will receive only onError BehaviorProcessor<Object> processor = BehaviorProcessor.create("default"); processor.onNext("zero"); processor.onNext("one"); processor.onError(new RuntimeException("error")); - processor.subscribe(observer); + processor.subscribe(subscriber); } </pre> * * @param <T> diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index 725b5fed91..3f409555df 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -28,17 +28,67 @@ * * <p> * <img width="640" height="278" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/PublishProcessor.png" alt=""> - * - * <p>The processor does not coordinate backpressure for its subscribers and implements a weaker onSubscribe which - * calls requests Long.MAX_VALUE from the incoming Subscriptions. This makes it possible to subscribe the PublishProcessor - * to multiple sources (note on serialization though) unlike the standard Subscriber contract. Child subscribers, however, are not overflown but receive an - * IllegalStateException in case their requested amount is zero. - * - * <p>The implementation of onXXX methods are technically thread-safe but non-serialized calls - * to them may lead to undefined state in the currently subscribed Subscribers. - * - * <p>Due to the nature Flowables are constructed, the PublishProcessor can't be instantiated through - * {@code new} but must be created via the {@link #create()} method. + * <p> + * This processor does not have a public constructor by design; a new empty instance of this + * {@code PublishProcessor} can be created via the {@link #create()} method. + * <p> + * Since a {@code PublishProcessor} is a Reactive Streams {@code Processor} type, + * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as + * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the processor's state is not changed. + * <p> + * {@code PublishProcessor} is a {@link io.reactivex.Flowable} as well as a {@link FlowableProcessor}, + * however, it does not coordinate backpressure between different subscribers and between an + * upstream source and a subscriber. If an upstream item is received via {@link #onNext(Object)}, if + * a subscriber is not ready to receive an item, that subscriber is terminated via a {@link MissingBackpressureException}. + * To avoid this case, use {@link #offer(Object)} and retry sometime later if it returned false. + * The {@code PublishProcessor}'s {@link Subscriber}-side consumes items in an unbounded manner. + * <p> + * For a multicasting processor type that also coordinates between the downstream {@code Subscriber}s and the upstream + * source as well, consider using {@link MulticastProcessor}. + * <p> + * When this {@code PublishProcessor} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, + * late {@link Subscriber}s only receive the respective terminal event. + * <p> + * Unlike a {@link BehaviorProcessor}, a {@code PublishProcessor} doesn't retain/cache items, therefore, a new + * {@code Subscriber} won't receive any past items. + * <p> + * Even though {@code PublishProcessor} implements the {@link Subscriber} interface, calling + * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>) + * if the processor is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code PublishProcessor} reached its terminal state will result in the + * given {@link Subscription} being canceled immediately. + * <p> + * Calling {@link #onNext(Object)}, {@link #offer(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@link FlowableProcessor}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} + * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). + * Note that serializing over {@link #offer(Object)} is not supported through {@code toSerialized()} because it is a method + * available on the {@code PublishProcessor} and {@code BehaviorProcessor} classes only. + * <p> + * This {@code PublishProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasSubscribers()}. + * <dl> + * <dt><b>Backpressure:</b></dt> + * <dd>The processor does not coordinate backpressure for its subscribers and implements a weaker {@code onSubscribe} which + * calls requests Long.MAX_VALUE from the incoming Subscriptions. This makes it possible to subscribe the {@code PublishProcessor} + * to multiple sources (note on serialization though) unlike the standard {@code Subscriber} contract. Child subscribers, however, are not overflown but receive an + * {@link IllegalStateException} in case their requested amount is zero.</dd> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code PublishProcessor} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code Subscriber}s get notified on the thread the respective {@code onXXX} methods were invoked.</dd> + * <dt><b>Error handling:</b></dt> + * <dd>When the {@link #onError(Throwable)} is called, the {@code PublishProcessor} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code Subscriber}s. During this emission, + * if one or more {@code Subscriber}s cancel their respective {@code Subscription}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Subscriber}s + * cancel at once). + * If there were no {@code Subscriber}s subscribed to this {@code PublishProcessor} when the {@code onError()} + * was called, the global error handler is not invoked. + * </dd> + * </dl> * * Example usage: * <pre> {@code @@ -55,6 +105,7 @@ } </pre> * @param <T> the value type multicasted to Subscribers. + * @see MulticastProcessor */ public final class PublishProcessor<T> extends FlowableProcessor<T> { /** The terminated indicator for the subscribers array. */ @@ -113,9 +164,9 @@ protected void subscribeActual(Subscriber<? super T> t) { /** * Tries to add the given subscriber to the subscribers array atomically - * or returns false if the subject has terminated. + * or returns false if this processor has terminated. * @param ps the subscriber to add - * @return true if successful, false if the subject has terminated + * @return true if successful, false if this processor has terminated */ boolean add(PublishSubscription<T> ps) { for (;;) { @@ -137,8 +188,8 @@ boolean add(PublishSubscription<T> ps) { } /** - * Atomically removes the given subscriber if it is subscribed to the subject. - * @param ps the subject to remove + * Atomically removes the given subscriber if it is subscribed to this processor. + * @param ps the subscription wrapping a subscriber to remove */ @SuppressWarnings("unchecked") void remove(PublishSubscription<T> ps) { @@ -182,7 +233,7 @@ public void onSubscribe(Subscription s) { s.cancel(); return; } - // PublishSubject doesn't bother with request coordination. + // PublishProcessor doesn't bother with request coordination. s.request(Long.MAX_VALUE); } @@ -288,7 +339,7 @@ static final class PublishSubscription<T> extends AtomicLong implements Subscrip private static final long serialVersionUID = 3562861878281475070L; /** The actual subscriber. */ final Subscriber<? super T> actual; - /** The subject state. */ + /** The parent processor servicing this subscriber. */ final PublishProcessor<T> parent; /** diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index 3d2fc83f5d..b16ef80f68 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -56,19 +56,73 @@ * </li> * </ul> * <p> - * The ReplayProcessor can be created in bounded and unbounded mode. It can be bounded by + * The {@code ReplayProcessor} can be created in bounded and unbounded mode. It can be bounded by * size (maximum number of elements retained at most) and/or time (maximum age of elements replayed). - * - * <p>This Processor respects the backpressure behavior of its Subscribers (individually) but - * does not coordinate their request amounts towards the upstream (because there might not be any). - * - * <p>Note that Subscribers receive a continuous sequence of values after they subscribed even - * if an individual item gets delayed due to backpressure. - * * <p> + * Since a {@code ReplayProcessor} is a Reactive Streams {@code Processor}, + * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as + * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the processor's state is not changed. + * <p> + * This {@code ReplayProcessor} respects the individual backpressure behavior of its {@code Subscriber}s but + * does not coordinate their request amounts towards the upstream (because there might not be any) and + * consumes the upstream in an unbounded manner (requesting {@code Long.MAX_VALUE}). + * Note that {@code Subscriber}s receive a continuous sequence of values after they subscribed even + * if an individual item gets delayed due to backpressure. * Due to concurrency requirements, a size-bounded {@code ReplayProcessor} may hold strong references to more source * emissions than specified. - * + * <p> + * When this {@code ReplayProcessor} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, + * late {@link Subscriber}s will receive the retained/cached items first (if any) followed by the respective + * terminal event. If the {@code ReplayProcessor} has a time-bound, the age of the retained/cached items are still considered + * when replaying and thus it may result in no items being emitted before the terminal event. + * <p> + * Once an {@code Subscriber} has subscribed, it will receive items continuously from that point on. Bounds only affect how + * many past items a new {@code Subscriber} will receive before it catches up with the live event feed. + * <p> + * Even though {@code ReplayProcessor} implements the {@code Subscriber} interface, calling + * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>) + * if the processor is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code ReplayProcessor} reached its terminal state will result in the + * given {@code Subscription} being canceled immediately. + * <p> + * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@code FlowableProcessor}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} + * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). + * <p> + * This {@code ReplayProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the retained/cached items + * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()}, + * {@link #getValues()} or {@link #getValues(Object[])}. + * <p> + * Note that due to concurrency requirements, a size- and time-bounded {@code ReplayProcessor} may hold strong references to more + * source emissions than specified while it isn't terminated yet. Use the {@link #cleanupBuffer()} to allow + * such inaccessible items to be cleaned up by GC once no consumer references them anymore. + * <dl> + * <dt><b>Backpressure:</b></dt> + * <dd>This {@code ReplayProcessor} respects the individual backpressure behavior of its {@code Subscriber}s but + * does not coordinate their request amounts towards the upstream (because there might not be any) and + * consumes the upstream in an unbounded manner (requesting {@code Long.MAX_VALUE}). + * Note that {@code Subscriber}s receive a continuous sequence of values after they subscribed even + * if an individual item gets delayed due to backpressure.</dd> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code ReplayProcessor} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the {@code Subscriber}s get notified on the thread the respective {@code onXXX} methods were invoked. + * Time-bound {@code ReplayProcessor}s use the given {@code Scheduler} in their {@code create} methods + * as time source to timestamp of items received for the age checks.</dd> + * <dt><b>Error handling:</b></dt> + * <dd>When the {@link #onError(Throwable)} is called, the {@code ReplayProcessor} enters into a terminal state + * and emits the same {@code Throwable} instance to the last set of {@code Subscriber}s. During this emission, + * if one or more {@code Subscriber}s cancel their respective {@code Subscription}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Subscriber}s + * cancel at once). + * If there were no {@code Subscriber}s subscribed to this {@code ReplayProcessor} when the {@code onError()} + * was called, the global error handler is not invoked. + * </dd> + * </dl> * <p> * Example usage: * <pre> {@code @@ -132,10 +186,10 @@ public static <T> ReplayProcessor<T> create() { * due to frequent array-copying. * * @param <T> - * the type of items observed and emitted by the Subject + * the type of items observed and emitted by this type of processor * @param capacityHint * the initial buffer capacity - * @return the created subject + * @return the created processor */ @CheckReturnValue @NonNull @@ -149,19 +203,19 @@ public static <T> ReplayProcessor<T> create(int capacityHint) { * In this setting, the {@code ReplayProcessor} holds at most {@code size} items in its internal buffer and * discards the oldest item. * <p> - * When observers subscribe to a terminated {@code ReplayProcessor}, they are guaranteed to see at most + * When {@code Subscriber}s subscribe to a terminated {@code ReplayProcessor}, they are guaranteed to see at most * {@code size} {@code onNext} events followed by a termination event. * <p> - * If an observer subscribes while the {@code ReplayProcessor} is active, it will observe all items in the + * If a {@code Subscriber} subscribes while the {@code ReplayProcessor} is active, it will observe all items in the * buffer at that point in time and each item observed afterwards, even if the buffer evicts items due to - * the size constraint in the mean time. In other words, once an Observer subscribes, it will receive items + * the size constraint in the mean time. In other words, once a {@code Subscriber} subscribes, it will receive items * without gaps in the sequence. * * @param <T> - * the type of items observed and emitted by the Subject + * the type of items observed and emitted by this type of processor * @param maxSize * the maximum number of buffered items - * @return the created subject + * @return the created processor */ @CheckReturnValue @NonNull @@ -179,8 +233,8 @@ public static <T> ReplayProcessor<T> createWithSize(int maxSize) { * of the bounded implementations without the interference of the eviction policies. * * @param <T> - * the type of items observed and emitted by the Subject - * @return the created subject + * the type of items observed and emitted by this type of processor + * @return the created processor */ /* test */ static <T> ReplayProcessor<T> createUnbounded() { return new ReplayProcessor<T>(new SizeBoundReplayBuffer<T>(Integer.MAX_VALUE)); @@ -194,29 +248,29 @@ public static <T> ReplayProcessor<T> createWithSize(int maxSize) { * converted to milliseconds. For example, an item arrives at T=0 and the max age is set to 5; at T>=5 * this first item is then evicted by any subsequent item or termination event, leaving the buffer empty. * <p> - * Once the subject is terminated, observers subscribing to it will receive items that remained in the + * Once the processor is terminated, {@code Subscriber}s subscribing to it will receive items that remained in the * buffer after the terminal event, regardless of their age. * <p> - * If an observer subscribes while the {@code ReplayProcessor} is active, it will observe only those items + * If a {@code Subscriber} subscribes while the {@code ReplayProcessor} is active, it will observe only those items * from within the buffer that have an age less than the specified time, and each item observed thereafter, - * even if the buffer evicts items due to the time constraint in the mean time. In other words, once an - * observer subscribes, it observes items without gaps in the sequence except for any outdated items at the + * even if the buffer evicts items due to the time constraint in the mean time. In other words, once a + * {@code Subscriber} subscribes, it observes items without gaps in the sequence except for any outdated items at the * beginning of the sequence. * <p> * Note that terminal notifications ({@code onError} and {@code onComplete}) trigger eviction as well. For * example, with a max age of 5, the first item is observed at T=0, then an {@code onComplete} notification - * arrives at T=10. If an observer subscribes at T=11, it will find an empty {@code ReplayProcessor} with just + * arrives at T=10. If a {@code Subscriber} subscribes at T=11, it will find an empty {@code ReplayProcessor} with just * an {@code onComplete} notification. * * @param <T> - * the type of items observed and emitted by the Subject + * the type of items observed and emitted by this type of processor * @param maxAge * the maximum age of the contained items * @param unit * the time unit of {@code time} * @param scheduler * the {@link Scheduler} that provides the current time - * @return the created subject + * @return the created processor */ @CheckReturnValue @NonNull @@ -232,22 +286,22 @@ public static <T> ReplayProcessor<T> createWithTime(long maxAge, TimeUnit unit, * items from the start of the buffer if their age becomes less-than or equal to the supplied age in * milliseconds or the buffer reaches its {@code size} limit. * <p> - * When observers subscribe to a terminated {@code ReplayProcessor}, they observe the items that remained in + * When {@code Subscriber}s subscribe to a terminated {@code ReplayProcessor}, they observe the items that remained in * the buffer after the terminal notification, regardless of their age, but at most {@code size} items. * <p> - * If an observer subscribes while the {@code ReplayProcessor} is active, it will observe only those items + * If a {@code Subscriber} subscribes while the {@code ReplayProcessor} is active, it will observe only those items * from within the buffer that have age less than the specified time and each subsequent item, even if the - * buffer evicts items due to the time constraint in the mean time. In other words, once an observer + * buffer evicts items due to the time constraint in the mean time. In other words, once a {@code Subscriber} * subscribes, it observes items without gaps in the sequence except for the outdated items at the beginning * of the sequence. * <p> * Note that terminal notifications ({@code onError} and {@code onComplete}) trigger eviction as well. For * example, with a max age of 5, the first item is observed at T=0, then an {@code onComplete} notification - * arrives at T=10. If an observer subscribes at T=11, it will find an empty {@code ReplayProcessor} with just + * arrives at T=10. If a {@code Subscriber} subscribes at T=11, it will find an empty {@code ReplayProcessor} with just * an {@code onComplete} notification. * * @param <T> - * the type of items observed and emitted by the Subject + * the type of items observed and emitted by this type of processor * @param maxAge * the maximum age of the contained items * @param unit @@ -256,7 +310,7 @@ public static <T> ReplayProcessor<T> createWithTime(long maxAge, TimeUnit unit, * the maximum number of buffered items * @param scheduler * the {@link Scheduler} that provides the current time - * @return the created subject + * @return the created processor */ @CheckReturnValue @NonNull @@ -387,18 +441,18 @@ public void cleanupBuffer() { } /** - * Returns a single value the Subject currently has or null if no such value exists. + * Returns the latest value this processor has or null if no such value exists. * <p>The method is thread-safe. - * @return a single value the Subject currently has or null if no such value exists + * @return the latest value this processor currently has or null if no such value exists */ public T getValue() { return buffer.getValue(); } /** - * Returns an Object array containing snapshot all values of the Subject. + * Returns an Object array containing snapshot all values of this processor. * <p>The method is thread-safe. - * @return the array containing the snapshot of all values of the Subject + * @return the array containing the snapshot of all values of this processor */ public Object[] getValues() { @SuppressWarnings("unchecked") @@ -412,7 +466,7 @@ public Object[] getValues() { } /** - * Returns a typed array containing a snapshot of all values of the Subject. + * Returns a typed array containing a snapshot of all values of this processor. * <p>The method follows the conventions of Collection.toArray by setting the array element * after the last value to null (if the capacity permits). * <p>The method is thread-safe. @@ -436,9 +490,9 @@ public boolean hasThrowable() { } /** - * Returns true if the subject has any value. + * Returns true if this processor has any value. * <p>The method is thread-safe. - * @return true if the subject has any value + * @return true if the processor has any value */ public boolean hasValue() { return buffer.size() != 0; // NOPMD diff --git a/src/main/java/io/reactivex/processors/UnicastProcessor.java b/src/main/java/io/reactivex/processors/UnicastProcessor.java index e712f1f5c8..62abd68cd4 100644 --- a/src/main/java/io/reactivex/processors/UnicastProcessor.java +++ b/src/main/java/io/reactivex/processors/UnicastProcessor.java @@ -29,18 +29,122 @@ import io.reactivex.plugins.RxJavaPlugins; /** - * Processor that allows only a single Subscriber to subscribe to it during its lifetime. - * - * <p>This processor buffers notifications and replays them to the Subscriber as requested. - * - * <p>This processor holds an unbounded internal buffer. - * - * <p>If more than one Subscriber attempts to subscribe to this Processor, they - * will receive an IllegalStateException if this Processor hasn't terminated yet, + * A {@link FlowableProcessor} variant that queues up events until a single {@link Subscriber} subscribes to it, replays + * those events to it until the {@code Subscriber} catches up and then switches to relaying events live to + * this single {@code Subscriber} until this {@code UnicastProcessor} terminates or the {@code Subscriber} cancels + * its subscription. + * <p> + * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/UnicastProcessor.png" alt=""> + * <p> + * This processor does not have a public constructor by design; a new empty instance of this + * {@code UnicastProcessor} can be created via the following {@code create} methods that + * allow specifying the retention policy for items: + * <ul> + * <li>{@link #create()} - creates an empty, unbounded {@code UnicastProcessor} that + * caches all items and the terminal event it receives.</li> + * <li>{@link #create(int)} - creates an empty, unbounded {@code UnicastProcessor} + * with a hint about how many <b>total</b> items one expects to retain.</li> + * <li>{@link #create(boolean)} - creates an empty, unbounded {@code UnicastProcessor} that + * optionally delays an error it receives and replays it after the regular items have been emitted.</li> + * <li>{@link #create(int, Runnable)} - creates an empty, unbounded {@code UnicastProcessor} + * with a hint about how many <b>total</b> items one expects to retain and a callback that will be + * called exactly once when the {@code UnicastProcessor} gets terminated or the single {@code Subscriber} cancels.</li> + * <li>{@link #create(int, Runnable, boolean)} - creates an empty, unbounded {@code UnicastProcessor} + * with a hint about how many <b>total</b> items one expects to retain and a callback that will be + * called exactly once when the {@code UnicastProcessor} gets terminated or the single {@code Subscriber} cancels + * and optionally delays an error it receives and replays it after the regular items have been emitted.</li> + * </ul> + * <p> + * If more than one {@code Subscriber} attempts to subscribe to this Processor, they + * will receive an {@link IllegalStateException} if this {@link UnicastProcessor} hasn't terminated yet, * or the Subscribers receive the terminal event (error or completion) if this * Processor has terminated. * <p> - * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/UnicastProcessor.png" alt=""> + * The {@code UnicastProcessor} buffers notifications and replays them to the single {@code Subscriber} as requested, + * for which it holds upstream items an unbounded internal buffer until they can be emitted. + * <p> + * Since a {@code UnicastProcessor} is a Reactive Streams {@code Processor}, + * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as + * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a + * {@link NullPointerException} being thrown and the processor's state is not changed. + * <p> + * Since a {@code UnicastProcessor} is a {@link io.reactivex.Flowable} as well as a {@link FlowableProcessor}, it + * honors the downstream backpressure but consumes an upstream source in an unbounded manner (requesting {@code Long.MAX_VALUE}). + * <p> + * When this {@code UnicastProcessor} is terminated via {@link #onError(Throwable)} the current or late single {@code Subscriber} + * may receive the {@code Throwable} before any available items could be emitted. To make sure an {@code onError} event is delivered + * to the {@code Subscriber} after the normal items, create a {@code UnicastProcessor} with the {@link #create(boolean)} or + * {@link #create(int, Runnable, boolean)} factory methods. + * <p> + * Even though {@code UnicastProcessor} implements the {@code Subscriber} interface, calling + * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>) + * if the processor is used as a standalone source. However, calling {@code onSubscribe} + * after the {@code UnicastProcessor} reached its terminal state will result in the + * given {@code Subscription} being canceled immediately. + * <p> + * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} + * is required to be serialized (called from the same thread or called non-overlappingly from different threads + * through external means of serialization). The {@link #toSerialized()} method available to all {@link FlowableProcessor}s + * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} + * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). + * <p> + * This {@code UnicastProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, + * {@link #getThrowable()} and {@link #hasSubscribers()}. + * <dl> + * <dt><b>Backpressure:</b></dt> + * <dd>{@code UnicastProcessor} honors the downstream backpressure but consumes an upstream source + * (if any) in an unbounded manner (requesting {@code Long.MAX_VALUE}).</dd> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code UnicastProcessor} does not operate by default on a particular {@link io.reactivex.Scheduler} and + * the single {@code Subscriber} gets notified on the thread the respective {@code onXXX} methods were invoked.</dd> + * <dt><b>Error handling:</b></dt> + * <dd>When the {@link #onError(Throwable)} is called, the {@code UnicastProcessor} enters into a terminal state + * and emits the same {@code Throwable} instance to the current single {@code Subscriber}. During this emission, + * if the single {@code Subscriber}s cancels its respective {@code Subscription}s, the + * {@code Throwable} is delivered to the global error handler via + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. + * If there were no {@code Subscriber}s subscribed to this {@code UnicastProcessor} when the {@code onError()} + * was called, the global error handler is not invoked. + * </dd> + * </dl> + * <p> + * Example usage: + * <pre><code> + * UnicastProcessor<Integer> processor = UnicastProcessor.create(); + * + * TestSubscriber<Integer> ts1 = processor.test(); + * + * // fresh UnicastProcessors are empty + * ts1.assertEmpty(); + * + * TestSubscriber<Integer> ts2 = processor.test(); + * + * // A UnicastProcessor only allows one Subscriber during its lifetime + * ts2.assertFailure(IllegalStateException.class); + * + * processor.onNext(1); + * ts1.assertValue(1); + * + * processor.onNext(2); + * ts1.assertValues(1, 2); + * + * processor.onComplete(); + * ts1.assertResult(1, 2); + * + * // ---------------------------------------------------- + * + * UnicastProcessor<Integer> processor2 = UnicastProcessor.create(); + * + * // a UnicastProcessor caches events until its single Subscriber subscribes + * processor2.onNext(1); + * processor2.onNext(2); + * processor2.onComplete(); + * + * TestSubscriber<Integer> ts3 = processor2.test(); + * + * // the cached events are emitted in order + * ts3.assertResult(1, 2); + * </code></pre> * * @param <T> the value type received and emitted by this Processor subclass * @since 2.0 diff --git a/src/main/java/io/reactivex/subjects/UnicastSubject.java b/src/main/java/io/reactivex/subjects/UnicastSubject.java index 61700dec55..f19a8b0a38 100644 --- a/src/main/java/io/reactivex/subjects/UnicastSubject.java +++ b/src/main/java/io/reactivex/subjects/UnicastSubject.java @@ -90,14 +90,13 @@ * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code UnicastSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and - * the {@code Observer}s get notified on the thread the respective {@code onXXX} methods were invoked.</dd> + * the single {@code Observer} gets notified on the thread the respective {@code onXXX} methods were invoked.</dd> * <dt><b>Error handling:</b></dt> * <dd>When the {@link #onError(Throwable)} is called, the {@code UnicastSubject} enters into a terminal state - * and emits the same {@code Throwable} instance to the last set of {@code Observer}s. During this emission, - * if one or more {@code Observer}s dispose their respective {@code Disposable}s, the + * and emits the same {@code Throwable} instance to the current single {@code Observer}. During this emission, + * if the single {@code Observer}s disposes its respective {@code Disposable}, the * {@code Throwable} is delivered to the global error handler via - * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Observer}s - * cancel at once). + * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}. * If there were no {@code Observer}s subscribed to this {@code UnicastSubject} when the {@code onError()} * was called, the global error handler is not invoked. * </dd> @@ -130,10 +129,10 @@ * * UnicastSubject<Integer> subject2 = UnicastSubject.create(); * - * // a UnicastSubject caches events util its single Observer subscribes - * subject.onNext(1); - * subject.onNext(2); - * subject.onComplete(); + * // a UnicastSubject caches events until its single Observer subscribes + * subject2.onNext(1); + * subject2.onNext(2); + * subject2.onComplete(); * * TestObserver<Integer> to3 = subject2.test(); * From 869c2aaefa2f6bd88265816992d5d1bf9fa10588 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 22 Jun 2018 09:39:12 +0200 Subject: [PATCH 209/417] Release 2.1.15 --- CHANGES.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 0cfef94c45..2e23a0c7e4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,41 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.15 - June 22, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.15%7C)) + +#### API changes + +- [Pull 6026](https://github.com/ReactiveX/RxJava/pull/6026): Add `blockingSubscribe` overload with prefetch amount allowing bounded backpressure. +- [Pull 6052](https://github.com/ReactiveX/RxJava/pull/6052): Change `{PublishSubject|PublishProcessor}.subscribeActual` to `protected`. They were accidentally made public and there is no reason to call them outside of RxJava internals. + +#### Documentation changes + +- [Pull 6031](https://github.com/ReactiveX/RxJava/pull/6031): Inline `CompositeDisposable` JavaDoc. +- [Pull 6042](https://github.com/ReactiveX/RxJava/pull/6042): Fix `MulticastProcessor` JavaDoc comment. +- [Pull 6049](https://github.com/ReactiveX/RxJava/pull/6049): Make it explicit that `throttleWithTimout` is an alias of `debounce`. +- [Pull 6053](https://github.com/ReactiveX/RxJava/pull/6053): Add `Maybe` marble diagrams 06/21/a +- [Pull 6057](https://github.com/ReactiveX/RxJava/pull/6057): Use different wording on `blockingForEach()` JavaDocs. +- [Pull 6054](https://github.com/ReactiveX/RxJava/pull/6054): Expand `{X}Processor` JavaDocs by syncing with `{X}Subject` docs. + +#### Performance enhancements + +- [Pull 6021](https://github.com/ReactiveX/RxJava/pull/6021): Add full implementation for `Single.flatMapPublisher` so it doesn't batch requests. +- [Pull 6024](https://github.com/ReactiveX/RxJava/pull/6024): Dedicated `{Single|Maybe}.flatMap{Publisher|Observable}` & `andThen(Observable|Publisher)` implementations. +- [Pull 6028](https://github.com/ReactiveX/RxJava/pull/6028): Improve `Observable.takeUntil`. + +#### Bugfixes + +- [Pull 6019](https://github.com/ReactiveX/RxJava/pull/6019): Fix `Single.takeUntil`, `Maybe.takeUntil` dispose behavior. +- [Pull 5947](https://github.com/ReactiveX/RxJava/pull/5947): Fix `groupBy` eviction so that source is cancelled and reduce volatile reads. +- [Pull 6036](https://github.com/ReactiveX/RxJava/pull/6036): Fix disposed `LambdaObserver.onError` to route to global error handler. +- [Pull 6045](https://github.com/ReactiveX/RxJava/pull/6045): Fix check in `BlockingSubscriber` that would always be false due to wrong variable. + +#### Other changes + +- [Pull 6022](https://github.com/ReactiveX/RxJava/pull/6022): Add TCK for `MulticastProcessor` & `{0..1}.flatMapPublisher` +- [Pull 6029](https://github.com/ReactiveX/RxJava/pull/6029): Upgrade to Gradle 4.3.1, add `TakeUntilPerf`. +- [Pull 6033](https://github.com/ReactiveX/RxJava/pull/6033): Update & fix grammar of `DESIGN.md` + ### Version 2.1.14 - May 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.14%7C)) #### API changes From 8bbe51d10519fc8a5c4f0fbf15f4af3e265e80b7 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 22 Jun 2018 15:58:44 +0200 Subject: [PATCH 210/417] 2.x: Fix concatMap{Single|Maybe} null emission on dispose race (#6060) --- .../mixed/FlowableConcatMapMaybe.java | 1 + .../mixed/FlowableConcatMapSingle.java | 1 + .../mixed/ObservableConcatMapMaybe.java | 1 + .../mixed/ObservableConcatMapSingle.java | 1 + .../mixed/FlowableConcatMapMaybeTest.java | 31 +++++++++++++++++++ .../mixed/FlowableConcatMapSingleTest.java | 30 ++++++++++++++++++ .../mixed/ObservableConcatMapMaybeTest.java | 30 ++++++++++++++++++ .../mixed/ObservableConcatMapSingleTest.java | 31 +++++++++++++++++++ 8 files changed, 126 insertions(+) diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java index 0b7eb3bd7d..bafc9d4aab 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java @@ -218,6 +218,7 @@ void drain() { if (cancelled) { queue.clear(); item = null; + break; } int s = state; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java index 3164d16a4b..654e7cabe5 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java @@ -213,6 +213,7 @@ void drain() { if (cancelled) { queue.clear(); item = null; + break; } int s = state; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java index 8331c38f23..f62669b705 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java @@ -199,6 +199,7 @@ void drain() { if (cancelled) { queue.clear(); item = null; + break; } int s = state; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java index 45799e8916..82afca6341 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java @@ -194,6 +194,7 @@ void drain() { if (cancelled) { queue.clear(); item = null; + break; } int s = state; diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java index 334b2e4d69..5e6ef2c82b 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybeTest.java @@ -394,4 +394,35 @@ public void cancelNoConcurrentClean() { assertTrue(operator.queue.isEmpty()); } + + @Test + public void innerSuccessDisposeRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final MaybeSubject<Integer> ms = MaybeSubject.create(); + + final TestSubscriber<Integer> ts = Flowable.just(1) + .hide() + .concatMapMaybe(Functions.justFunction(ms)) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ms.onSuccess(1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.dispose(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertNoErrors(); + } + } + } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java index c572e9ba30..6f07102918 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingleTest.java @@ -309,4 +309,34 @@ public void cancelNoConcurrentClean() { assertTrue(operator.queue.isEmpty()); } + + @Test + public void innerSuccessDisposeRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final SingleSubject<Integer> ss = SingleSubject.create(); + + final TestSubscriber<Integer> ts = Flowable.just(1) + .hide() + .concatMapSingle(Functions.justFunction(ss)) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ss.onSuccess(1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.dispose(); + } + }; + + TestHelper.race(r1, r2); + + ts.assertNoErrors(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java index 8fbd2937f1..fb732ff878 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java @@ -416,4 +416,34 @@ public void checkUnboundedInnerQueue() { to.assertResult(1, 2, 3, 4); } + + @Test + public void innerSuccessDisposeRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final MaybeSubject<Integer> ms = MaybeSubject.create(); + + final TestObserver<Integer> to = Observable.just(1) + .hide() + .concatMapMaybe(Functions.justFunction(ms)) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ms.onSuccess(1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + to.dispose(); + } + }; + + TestHelper.race(r1, r2); + + to.assertNoErrors(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java index bdd4f9e4cc..b5743dd5d7 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java @@ -353,4 +353,35 @@ public void checkUnboundedInnerQueue() { to.assertResult(1, 2, 3, 4); } + + @Test + public void innerSuccessDisposeRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final SingleSubject<Integer> ss = SingleSubject.create(); + + final TestObserver<Integer> to = Observable.just(1) + .hide() + .concatMapSingle(Functions.justFunction(ss)) + .test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ss.onSuccess(1); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + to.dispose(); + } + }; + + TestHelper.race(r1, r2); + + to.assertNoErrors(); + } + } + } From 83f2bd771ee172a2154e0fb30c5ffcaf8f71433c Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 26 Jun 2018 09:45:57 +0200 Subject: [PATCH 211/417] Release 2.1.16 --- CHANGES.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 2e23a0c7e4..91bd6b465c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,14 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.16 - June 26, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.16%7C)) + +This is a hotfix release for a late-identified issue with `concatMapMaybe` and `concatMapSingle`. + +#### Bugfixes + +- [Pull 6060](https://github.com/ReactiveX/RxJava/pull/6060): Fix `concatMap{Single|Maybe}` null emission on success-dispose race. + ### Version 2.1.15 - June 22, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.15%7C)) #### API changes From 27ce955dfc9b2457ae09cdbbe3c9a0542c5eb2a6 Mon Sep 17 00:00:00 2001 From: akarnokd <akarnokd@gmail.com> Date: Wed, 27 Jun 2018 12:10:16 +0200 Subject: [PATCH 212/417] 2.x: Fix Javadoc warnings on empty <p> --- src/main/java/io/reactivex/Flowable.java | 2 +- src/main/java/io/reactivex/Observable.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 406198507c..04a31f471d 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -5481,7 +5481,7 @@ public final T blockingFirst(T defaultItem) { * <em>Note:</em> the method will only return if the upstream terminates or the current * thread is interrupted. * <p> - * <p>This method executes the {@code Consumer} on the current thread while + * This method executes the {@code Consumer} on the current thread while * {@link #subscribe(Consumer)} executes the consumer on the original caller thread of the * sequence. * <dl> diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 70fff76e3a..c74ab3f7d4 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -5027,7 +5027,7 @@ public final T blockingFirst(T defaultItem) { * <em>Note:</em> the method will only return if the upstream terminates or the current * thread is interrupted. * <p> - * <p>This method executes the {@code Consumer} on the current thread while + * This method executes the {@code Consumer} on the current thread while * {@link #subscribe(Consumer)} executes the consumer on the original caller thread of the * sequence. * <dl> From 6b07923f2c51d76c45e3879f9c7b9d9ed9ccfb93 Mon Sep 17 00:00:00 2001 From: Aleksandr Podkutin <apodkutin@gmail.com> Date: Sat, 30 Jun 2018 13:20:06 +0200 Subject: [PATCH 213/417] Fix links for Single class (#6066) * Change observable.html to single.html * Delete completable.html link which doesn't exist --- src/main/java/io/reactivex/Single.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 89fe25c6f9..84e96defbb 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -51,7 +51,7 @@ * <p> * <img width="640" height="301" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.legend.png" alt=""> * <p> - * For more information see the <a href="http://reactivex.io/documentation/observable.html">ReactiveX + * For more information see the <a href="http://reactivex.io/documentation/single.html">ReactiveX * documentation</a>. * * @param <T> @@ -3591,7 +3591,6 @@ public final <R> R to(Function<? super Single<T>, R> convert) { * * @return a {@link Completable} that calls {@code onComplete} on it's subscriber when the source {@link Single} * calls {@code onSuccess}. - * @see <a href="http://reactivex.io/documentation/completable.html">ReactiveX documentation: Completable</a> * @since 2.0 * @deprecated see {@link #ignoreElement()} instead, will be removed in 3.0 */ @@ -3614,7 +3613,6 @@ public final Completable toCompletable() { * * @return a {@link Completable} that calls {@code onComplete} on it's observer when the source {@link Single} * calls {@code onSuccess}. - * @see <a href="http://reactivex.io/documentation/completable.html">ReactiveX documentation: Completable</a> * @since 2.1.13 */ @CheckReturnValue From 909920a5f13f5acc6507d6de2b62370df7e86573 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 4 Jul 2018 11:13:17 +0200 Subject: [PATCH 214/417] 2.x: Adjust JavaDocs dl/dd entry stylesheet (#6070) --- build.gradle | 1 + gradle/stylesheet.css | 346 +++++++++++++++++++++++++++--------------- 2 files changed, 224 insertions(+), 123 deletions(-) diff --git a/build.gradle b/build.gradle index 8b9203ee06..2f33e66093 100644 --- a/build.gradle +++ b/build.gradle @@ -91,6 +91,7 @@ javadoc { options.addStringOption("top").value = "" options.addStringOption("doctitle").value = "" options.addStringOption("header").value = "" + options.stylesheetFile = new File(projectDir, "gradle/stylesheet.css"); options.links( "https://docs.oracle.com/javase/7/docs/api/", diff --git a/gradle/stylesheet.css b/gradle/stylesheet.css index 7f1f6e733b..52b6b690b0 100644 --- a/gradle/stylesheet.css +++ b/gradle/stylesheet.css @@ -2,16 +2,19 @@ /* Overall document style */ + +@import url('http://github.com/resources/fonts/dejavu.css'); + body { background-color:#ffffff; color:#353833; - font-family:Arial, Helvetica, sans-serif; - font-size:76%; + font-family:'DejaVu Sans', Arial, Helvetica, sans-serif; + font-size:14px; margin:0; } a:link, a:visited { text-decoration:none; - color:#4c6b87; + color:#4A6782; } a:hover, a:focus { text-decoration:none; @@ -19,7 +22,7 @@ a:hover, a:focus { } a:active { text-decoration:none; - color:#4c6b87; + color:#4A6782; } a[name] { color:#353833; @@ -29,41 +32,51 @@ a[name]:hover { color:#353833; } pre { - font-size:1.3em; + font-family:'DejaVu Sans Mono', monospace; + font-size:14px; } h1 { - font-size:1.8em; + font-size:20px; } h2 { - font-size:1.5em; + font-size:18px; } h3 { - font-size:1.4em; + font-size:16px; + font-style:italic; } h4 { - font-size:1.3em; + font-size:13px; } h5 { - font-size:1.2em; + font-size:12px; } h6 { - font-size:1.1em; + font-size:11px; } ul { list-style-type:disc; } code, tt { - font-size:1.2em; + font-family:'DejaVu Sans Mono', monospace; + font-size:14px; + padding-top:4px; + margin-top:8px; + line-height:1.4em; } dt code { - font-size:1.2em; + font-family:'DejaVu Sans Mono', monospace; + font-size:14px; + padding-top:4px; } table tr td dt code { - font-size:1.2em; + font-family:'DejaVu Sans Mono', monospace; + font-size:14px; vertical-align:top; + padding-top:4px; } sup { - font-size:.6em; + font-size:8px; } /* Document title and Copyright styles @@ -76,9 +89,9 @@ Document title and Copyright styles .aboutLanguage { float:right; padding:0px 21px; - font-size:.8em; + font-size:11px; z-index:200; - margin-top:-7px; + margin-top:-9px; } .legalCopy { margin-left:.5em; @@ -92,9 +105,6 @@ Document title and Copyright styles } .tab { background-color:#0066FF; - background-image:url(http://github.com/resources/titlebar.gif); - background-position:left top; - background-repeat:no-repeat; color:#ffffff; padding:8px; width:5em; @@ -104,17 +114,15 @@ Document title and Copyright styles Navigation bar styles */ .bar { - background-image:url(http://github.com/resources/background.gif); - background-repeat:repeat-x; + background-color:#4D7A97; color:#FFFFFF; padding:.8em .5em .4em .8em; height:auto;/*height:1.8em;*/ - font-size:1em; + font-size:11px; margin:0; } .topNav { - background-image:url(http://github.com/resources/background.gif); - background-repeat:repeat-x; + background-color:#4D7A97; color:#FFFFFF; float:left; padding:0; @@ -123,11 +131,11 @@ Navigation bar styles height:2.8em; padding-top:10px; overflow:hidden; + font-size:12px; } .bottomNav { margin-top:10px; - background-image:url(http://github.com/resources/background.gif); - background-repeat:repeat-x; + background-color:#4D7A97; color:#FFFFFF; float:left; padding:0; @@ -136,18 +144,20 @@ Navigation bar styles height:2.8em; padding-top:10px; overflow:hidden; + font-size:12px; } .subNav { background-color:#dee3e9; - border-bottom:1px solid #9eadc0; float:left; width:100%; overflow:hidden; + font-size:12px; } .subNav div { clear:left; float:left; padding:0 0 5px 6px; + text-transform:uppercase; } ul.navList, ul.subNavList { float:left; @@ -157,27 +167,33 @@ ul.navList, ul.subNavList { ul.navList li{ list-style:none; float:left; - padding:3px 6px; + padding: 5px 6px; + text-transform:uppercase; } ul.subNavList li{ list-style:none; float:left; - font-size:90%; } .topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited { color:#FFFFFF; text-decoration:none; + text-transform:uppercase; } .topNav a:hover, .bottomNav a:hover { text-decoration:none; color:#bb7a2a; + text-transform:uppercase; } .navBarCell1Rev { - background-image:url(http://github.com/resources/tab.gif); - background-color:#a88834; - color:#FFFFFF; + background-color:#F8981D; + color:#253441; margin: auto 5px; - border:1px solid #c9aa44; +} +.skipNav { + position:absolute; + top:auto; + left:-9999px; + overflow:hidden; } /* Page header and footer styles @@ -191,8 +207,11 @@ Page header and footer styles margin:10px; position:relative; } +.indexHeader span{ + margin-right:15px; +} .indexHeader h1 { - font-size:1.3em; + font-size:13px; } .title { color:#2c4557; @@ -202,7 +221,7 @@ Page header and footer styles margin:5px 0 0 0; } .header ul { - margin:0 0 25px 0; + margin:0 0 15px 0; padding:0; } .footer ul { @@ -210,24 +229,22 @@ Page header and footer styles } .header ul li, .footer ul li { list-style:none; - font-size:1.2em; + font-size:13px; } /* Heading styles */ div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 { background-color:#dee3e9; - border-top:1px solid #9eadc0; - border-bottom:1px solid #9eadc0; + border:1px solid #d0d9e0; margin:0 0 6px -8px; - padding:2px 5px; + padding:7px 5px; } ul.blockList ul.blockList ul.blockList li.blockList h3 { background-color:#dee3e9; - border-top:1px solid #9eadc0; - border-bottom:1px solid #9eadc0; + border:1px solid #d0d9e0; margin:0 0 6px -8px; - padding:2px 5px; + padding:7px 5px; } ul.blockList ul.blockList li.blockList h3 { padding:0; @@ -247,10 +264,10 @@ Page layout container styles .indexContainer { margin:10px; position:relative; - font-size:1.0em; + font-size:12px; } .indexContainer h2 { - font-size:1.1em; + font-size:13px; padding:0 0 3px 0; } .indexContainer ul { @@ -259,15 +276,18 @@ Page layout container styles } .indexContainer ul li { list-style:none; + padding-top:2px; } .contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt { - font-size:1.1em; + font-size:12px; font-weight:bold; margin:10px 0 0 0; color:#4E4E4E; } -.contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd { - margin:10px 0 10px 20px; +/*.contentContainer .description dl dd, */.contentContainer .details dl dd, .serializedFormContainer dl dd { + margin:5px 0 10px 0px; + font-size:14px; + font-family:'DejaVu Sans Mono',monospace; } .serializedFormContainer dl.nameValue dt { margin-left:1px; @@ -306,25 +326,24 @@ ul.blockList, ul.blockListLast { } ul.blockList li.blockList, ul.blockListLast li.blockList { list-style:none; - margin-bottom:25px; + margin-bottom:15px; + line-height:1.4; } ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList { padding:0px 20px 5px 10px; - border:1px solid #9eadc0; - background-color:#f9f9f9; + border:1px solid #ededed; + background-color:#f8f8f8; } ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList { padding:0 0 5px 8px; background-color:#ffffff; - border:1px solid #9eadc0; - border-top:none; + border:none; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockList { margin-left:0; padding-left:0; padding-bottom:15px; border:none; - border-bottom:1px solid #9eadc0; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast { list-style:none; @@ -338,107 +357,155 @@ table tr td dl, table tr td dl dt, table tr td dl dd { /* Table styles */ -.contentContainer table, .classUseContainer table, .constantValuesContainer table { - border-bottom:1px solid #9eadc0; - width:100%; -} -.contentContainer ul li table, .classUseContainer ul li table, .constantValuesContainer ul li table { +.overviewSummary, .memberSummary, .typeSummary, .useSummary, .constantsSummary, .deprecatedSummary { width:100%; + border-left:1px solid #EEE; + border-right:1px solid #EEE; + border-bottom:1px solid #EEE; } -.contentContainer .description table, .contentContainer .details table { - border-bottom:none; -} -.contentContainer ul li table th.colOne, .contentContainer ul li table th.colFirst, .contentContainer ul li table th.colLast, .classUseContainer ul li table th, .constantValuesContainer ul li table th, .contentContainer ul li table td.colOne, .contentContainer ul li table td.colFirst, .contentContainer ul li table td.colLast, .classUseContainer ul li table td, .constantValuesContainer ul li table td{ - vertical-align:top; - padding-right:20px; -} -.contentContainer ul li table th.colLast, .classUseContainer ul li table th.colLast,.constantValuesContainer ul li table th.colLast, -.contentContainer ul li table td.colLast, .classUseContainer ul li table td.colLast,.constantValuesContainer ul li table td.colLast, -.contentContainer ul li table th.colOne, .classUseContainer ul li table th.colOne, -.contentContainer ul li table td.colOne, .classUseContainer ul li table td.colOne { - padding-right:3px; +.overviewSummary, .memberSummary { + padding:0px; } -.overviewSummary caption, .packageSummary caption, .contentContainer ul.blockList li.blockList caption, .summary caption, .classUseContainer caption, .constantValuesContainer caption { +.overviewSummary caption, .memberSummary caption, .typeSummary caption, +.useSummary caption, .constantsSummary caption, .deprecatedSummary caption { position:relative; text-align:left; background-repeat:no-repeat; - color:#FFFFFF; + color:#253441; font-weight:bold; clear:none; overflow:hidden; padding:0px; + padding-top:10px; + padding-left:1px; margin:0px; -} -caption a:link, caption a:hover, caption a:active, caption a:visited { + white-space:pre; +} +.overviewSummary caption a:link, .memberSummary caption a:link, .typeSummary caption a:link, +.useSummary caption a:link, .constantsSummary caption a:link, .deprecatedSummary caption a:link, +.overviewSummary caption a:hover, .memberSummary caption a:hover, .typeSummary caption a:hover, +.useSummary caption a:hover, .constantsSummary caption a:hover, .deprecatedSummary caption a:hover, +.overviewSummary caption a:active, .memberSummary caption a:active, .typeSummary caption a:active, +.useSummary caption a:active, .constantsSummary caption a:active, .deprecatedSummary caption a:active, +.overviewSummary caption a:visited, .memberSummary caption a:visited, .typeSummary caption a:visited, +.useSummary caption a:visited, .constantsSummary caption a:visited, .deprecatedSummary caption a:visited { color:#FFFFFF; } -.overviewSummary caption span, .packageSummary caption span, .contentContainer ul.blockList li.blockList caption span, .summary caption span, .classUseContainer caption span, .constantValuesContainer caption span { +.overviewSummary caption span, .memberSummary caption span, .typeSummary caption span, +.useSummary caption span, .constantsSummary caption span, .deprecatedSummary caption span { white-space:nowrap; - padding-top:8px; - padding-left:8px; - display:block; + padding-top:5px; + padding-left:12px; + padding-right:12px; + padding-bottom:7px; + display:inline-block; float:left; - background-image:url(http://github.com/resources/titlebar.gif); - height:18px; + background-color:#F8981D; + border: none; + height:16px; } -.overviewSummary .tabEnd, .packageSummary .tabEnd, .contentContainer ul.blockList li.blockList .tabEnd, .summary .tabEnd, .classUseContainer .tabEnd, .constantValuesContainer .tabEnd { - width:10px; - background-image:url(http://github.com/resources/titlebar_end.gif); - background-repeat:no-repeat; - background-position:top right; - position:relative; +.memberSummary caption span.activeTableTab span { + white-space:nowrap; + padding-top:5px; + padding-left:12px; + padding-right:12px; + margin-right:3px; + display:inline-block; float:left; + background-color:#F8981D; + height:16px; } -ul.blockList ul.blockList li.blockList table { - margin:0 0 12px 0px; - width:100%; +.memberSummary caption span.tableTab span { + white-space:nowrap; + padding-top:5px; + padding-left:12px; + padding-right:12px; + margin-right:3px; + display:inline-block; + float:left; + background-color:#4D7A97; + height:16px; +} +.memberSummary caption span.tableTab, .memberSummary caption span.activeTableTab { + padding-top:0px; + padding-left:0px; + padding-right:0px; + background-image:none; + float:none; + display:inline; } -.tableSubHeadingColor { - background-color: #EEEEFF; +.overviewSummary .tabEnd, .memberSummary .tabEnd, .typeSummary .tabEnd, +.useSummary .tabEnd, .constantsSummary .tabEnd, .deprecatedSummary .tabEnd { + display:none; + width:5px; + position:relative; + float:left; + background-color:#F8981D; } -.altColor { - background-color:#eeeeef; +.memberSummary .activeTableTab .tabEnd { + display:none; + width:5px; + margin-right:3px; + position:relative; + float:left; + background-color:#F8981D; } -.rowColor { - background-color:#ffffff; +.memberSummary .tableTab .tabEnd { + display:none; + width:5px; + margin-right:3px; + position:relative; + background-color:#4D7A97; + float:left; + } -.overviewSummary td, .packageSummary td, .contentContainer ul.blockList li.blockList td, .summary td, .classUseContainer td, .constantValuesContainer td { +.overviewSummary td, .memberSummary td, .typeSummary td, +.useSummary td, .constantsSummary td, .deprecatedSummary td { text-align:left; - padding:3px 3px 3px 7px; + padding:0px 0px 12px 10px; +} +th.colOne, th.colFirst, th.colLast, .useSummary th, .constantsSummary th, +td.colOne, td.colFirst, td.colLast, .useSummary td, .constantsSummary td{ + vertical-align:top; + padding-right:0px; + padding-top:8px; + padding-bottom:3px; } -th.colFirst, th.colLast, th.colOne, .constantValuesContainer th { +th.colFirst, th.colLast, th.colOne, .constantsSummary th { background:#dee3e9; - border-top:1px solid #9eadc0; - border-bottom:1px solid #9eadc0; text-align:left; - padding:3px 3px 3px 7px; -} -td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover { - font-weight:bold; + padding:8px 3px 3px 7px; } td.colFirst, th.colFirst { - border-left:1px solid #9eadc0; white-space:nowrap; + font-size:13px; } td.colLast, th.colLast { - border-right:1px solid #9eadc0; + font-size:13px; } td.colOne, th.colOne { - border-right:1px solid #9eadc0; - border-left:1px solid #9eadc0; + font-size:13px; +} +.overviewSummary td.colFirst, .overviewSummary th.colFirst, +.useSummary td.colFirst, .useSummary th.colFirst, +.overviewSummary td.colOne, .overviewSummary th.colOne, +.memberSummary td.colFirst, .memberSummary th.colFirst, +.memberSummary td.colOne, .memberSummary th.colOne, +.typeSummary td.colFirst{ + width:25%; + vertical-align:top; } -table.overviewSummary { - padding:0px; - margin-left:0px; +td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover { + font-weight:bold; } -table.overviewSummary td.colFirst, table.overviewSummary th.colFirst, -table.overviewSummary td.colOne, table.overviewSummary th.colOne { - width:25%; - vertical-align:middle; +.tableSubHeadingColor { + background-color:#EEEEFF; } -table.packageSummary td.colFirst, table.overviewSummary th.colFirst { - width:25%; - vertical-align:middle; +.altColor { + background-color:#FFFFFF; +} +.rowColor { + background-color:#EEEEEF; } /* Content styles @@ -453,6 +520,24 @@ Content styles .docSummary { padding:0; } + +ul.blockList ul.blockList ul.blockList li.blockList h3 { + font-style:normal; +} + +div.block { + font-size:14px; + font-family:'DejaVu Serif', Georgia, "Times New Roman", Times, serif; +} + +td.colLast div { + padding-top:0px; +} + + +td.colLast a { + padding-bottom:3px; +} /* Formatting effect styles */ @@ -463,12 +548,27 @@ Formatting effect styles h1.hidden { visibility:hidden; overflow:hidden; - font-size:.9em; + font-size:10px; } .block { display:block; - margin:3px 0 0 0; + margin:3px 10px 2px 0px; + color:#474747; } -.strong { +.deprecatedLabel, .descfrmTypeLabel, .memberNameLabel, .memberNameLink, +.overrideSpecifyLabel, .packageHierarchyLabel, .paramLabel, .returnLabel, +.seeLabel, .simpleTagLabel, .throwsLabel, .typeNameLabel, .typeNameLink { font-weight:bold; -} \ No newline at end of file +} +.deprecationComment, .emphasizedPhrase, .interfaceName { + font-style:italic; +} + +div.block div.block span.deprecationComment, div.block div.block span.emphasizedPhrase, +div.block div.block span.interfaceName { + font-style:normal; +} + +div.contentContainer ul.blockList li.blockList h2{ + padding-bottom:0px; +} From e29b57b666954d37129da17430e592631ff17a79 Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Sun, 8 Jul 2018 12:58:17 +0200 Subject: [PATCH 215/417] Add marble diagram to the Single.never method (#6074) * Add marble diagram to the Single.never method * Use correct marble diagram URL for Single.never method --- src/main/java/io/reactivex/Single.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 84e96defbb..7385455421 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -1162,6 +1162,8 @@ public static <T> Flowable<T> mergeDelayError( /** * Returns a singleton instance of a never-signalling Single (only calls onSubscribe). + * <p> + * <img width="640" height="244" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.never.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code never} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2603,7 +2605,7 @@ public final T blockingGet() { * Example: * <pre><code> * // Step 1: Create the consumer type that will be returned by the SingleOperator.apply(): - * + * * public final class CustomSingleObserver<T> implements SingleObserver<T>, Disposable { * * // The downstream's SingleObserver that will receive the onXXX events From c8a98520ee38152d8acce56bdb0a9e9127ccf7cc Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Sun, 8 Jul 2018 20:27:18 +0200 Subject: [PATCH 216/417] Add marble diagram to the Single.filter method (#6075) * Add marble diagram to the Single.filter method * Use correct marble diagram URL for Single.filter method --- src/main/java/io/reactivex/Single.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 7385455421..a97e3f1efa 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2373,7 +2373,7 @@ public final Single<T> doOnDispose(final Action onDispose) { * Filters the success item of the Single via a predicate function and emitting it if the predicate * returns true, completing otherwise. * <p> - * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/filter.png" alt=""> + * <img width="640" height="457" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.filter.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code filter} does not operate by default on a particular {@link Scheduler}.</dd> From e51cf16db0d9d100da09476aa0dab5b1c3c35de8 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 9 Jul 2018 10:35:45 +0200 Subject: [PATCH 217/417] 2.x: Add Maybe.hide() marble diagram (#6078) --- src/main/java/io/reactivex/Maybe.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 918dbeccd5..3a4ec3a76d 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3090,6 +3090,8 @@ public final Completable flatMapCompletable(final Function<? super T, ? extends /** * Hides the identity of this Maybe and its Disposable. + * <p> + * <img width="640" height="300" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.hide.png" alt=""> * <p>Allows preventing certain identity-based * optimizations (fusion). * <dl> From fd76594dc7e19d4da889613f2d9afdf6043879b9 Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Tue, 10 Jul 2018 09:44:54 +0200 Subject: [PATCH 218/417] Add marble diagrams to the Single.delay method (#6076) * Add marble diagrams to the Single.delay method * Update marbles for Single.delay with error events * Use correct marble diagram URLs for Single.delay methods --- src/main/java/io/reactivex/Single.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index a97e3f1efa..0d8677ea73 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -1980,6 +1980,8 @@ public final Flowable<T> concatWith(SingleSource<? extends T> other) { /** * Delays the emission of the success signal from the current Single by the specified amount. * An error signal will not be delayed. + * <p> + * <img width="640" height="457" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delay.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code delay} operates by default on the {@code computation} {@link Scheduler}.</dd> @@ -1998,6 +2000,8 @@ public final Single<T> delay(long time, TimeUnit unit) { /** * Delays the emission of the success or error signal from the current Single by the specified amount. + * <p> + * <img width="640" height="457" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delay.e.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code delay} operates by default on the {@code computation} {@link Scheduler}.</dd> @@ -2019,6 +2023,8 @@ public final Single<T> delay(long time, TimeUnit unit, boolean delayError) { /** * Delays the emission of the success signal from the current Single by the specified amount. * An error signal will not be delayed. + * <p> + * <img width="640" height="457" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delay.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify the {@link Scheduler} where the non-blocking wait and emission happens</dd> @@ -2041,6 +2047,8 @@ public final Single<T> delay(final long time, final TimeUnit unit, final Schedul /** * Delays the emission of the success or error signal from the current Single by the specified amount. + * <p> + * <img width="640" height="457" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delay.se.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify the {@link Scheduler} where the non-blocking wait and emission happens</dd> From 7e301d44d6dee9dce12f5417b41134f3a9eda12f Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 11 Jul 2018 09:19:02 +0200 Subject: [PATCH 219/417] 2.x: Add Completable.takeUntil(Completable) operator (#6079) --- src/main/java/io/reactivex/Completable.java | 26 ++ .../CompletableTakeUntilCompletable.java | 145 +++++++++++ .../completable/CompletableTakeUntilTest.java | 235 ++++++++++++++++++ 3 files changed, 406 insertions(+) create mode 100644 src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java create mode 100644 src/test/java/io/reactivex/internal/operators/completable/CompletableTakeUntilTest.java diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index c07ba8ae6a..bc9cd271dc 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -2031,6 +2031,32 @@ public final Completable subscribeOn(final Scheduler scheduler) { return RxJavaPlugins.onAssembly(new CompletableSubscribeOn(this, scheduler)); } + /** + * Terminates the downstream if this or the other {@code Completable} + * terminates (wins the termination race) while disposing the connection to the losing source. + * <p> + * <img width="640" height="468" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.takeuntil.c.png" alt=""> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> + * <dd>If both this and the other sources signal an error, only one of the errors + * is signaled to the downstream and the other error is signaled to the global + * error handler via {@link RxJavaPlugins#onError(Throwable)}.</dd> + * </dl> + * @param other the other completable source to observe for the terminal signals + * @return the new Completable instance + * @since 2.1.17 - experimental + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.NONE) + public final Completable takeUntil(CompletableSource other) { + ObjectHelper.requireNonNull(other, "other is null"); + + return RxJavaPlugins.onAssembly(new CompletableTakeUntilCompletable(this, other)); + } + /** * Returns a Completable that runs this Completable and emits a TimeoutException in case * this Completable doesn't complete within the given time. diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java new file mode 100644 index 0000000000..1343d35b98 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java @@ -0,0 +1,145 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Terminates the sequence if either the main or the other Completable terminate. + * @since 2.1.17 - experimental + */ +@Experimental +public final class CompletableTakeUntilCompletable extends Completable { + + final Completable source; + + final CompletableSource other; + + public CompletableTakeUntilCompletable(Completable source, + CompletableSource other) { + this.source = source; + this.other = other; + } + + @Override + protected void subscribeActual(CompletableObserver s) { + TakeUntilMainObserver parent = new TakeUntilMainObserver(s); + s.onSubscribe(parent); + + other.subscribe(parent.other); + source.subscribe(parent); + } + + static final class TakeUntilMainObserver extends AtomicReference<Disposable> + implements CompletableObserver, Disposable { + + private static final long serialVersionUID = 3533011714830024923L; + + final CompletableObserver downstream; + + final OtherObserver other; + + final AtomicBoolean once; + + TakeUntilMainObserver(CompletableObserver downstream) { + this.downstream = downstream; + this.other = new OtherObserver(this); + this.once = new AtomicBoolean(); + } + + @Override + public void dispose() { + if (once.compareAndSet(false, true)) { + DisposableHelper.dispose(this); + DisposableHelper.dispose(other); + } + } + + @Override + public boolean isDisposed() { + return once.get(); + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onComplete() { + if (once.compareAndSet(false, true)) { + DisposableHelper.dispose(other); + downstream.onComplete(); + } + } + + @Override + public void onError(Throwable e) { + if (once.compareAndSet(false, true)) { + DisposableHelper.dispose(other); + downstream.onError(e); + } else { + RxJavaPlugins.onError(e); + } + } + + void innerComplete() { + if (once.compareAndSet(false, true)) { + DisposableHelper.dispose(this); + downstream.onComplete(); + } + } + + void innerError(Throwable e) { + if (once.compareAndSet(false, true)) { + DisposableHelper.dispose(this); + downstream.onError(e); + } else { + RxJavaPlugins.onError(e); + } + } + + static final class OtherObserver extends AtomicReference<Disposable> + implements CompletableObserver { + + private static final long serialVersionUID = 5176264485428790318L; + final TakeUntilMainObserver parent; + + OtherObserver(TakeUntilMainObserver parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); + } + + @Override + public void onComplete() { + parent.innerComplete(); + } + + @Override + public void onError(Throwable e) { + parent.innerError(e); + } + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableTakeUntilTest.java new file mode 100644 index 0000000000..586e0c3207 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableTakeUntilTest.java @@ -0,0 +1,235 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.disposables.Disposables; +import io.reactivex.exceptions.TestException; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subjects.CompletableSubject; + +public class CompletableTakeUntilTest { + + @Test + public void consumerDisposes() { + CompletableSubject cs1 = CompletableSubject.create(); + CompletableSubject cs2 = CompletableSubject.create(); + + TestObserver<Void> to = cs1.takeUntil(cs2).test(); + + to.assertEmpty(); + + assertTrue(cs1.hasObservers()); + assertTrue(cs2.hasObservers()); + + to.dispose(); + + assertFalse(cs1.hasObservers()); + assertFalse(cs2.hasObservers()); + } + + @Test + public void mainCompletes() { + CompletableSubject cs1 = CompletableSubject.create(); + CompletableSubject cs2 = CompletableSubject.create(); + + TestObserver<Void> to = cs1.takeUntil(cs2).test(); + + to.assertEmpty(); + + assertTrue(cs1.hasObservers()); + assertTrue(cs2.hasObservers()); + + cs1.onComplete(); + + assertFalse(cs1.hasObservers()); + assertFalse(cs2.hasObservers()); + + to.assertResult(); + } + + @Test + public void otherCompletes() { + CompletableSubject cs1 = CompletableSubject.create(); + CompletableSubject cs2 = CompletableSubject.create(); + + TestObserver<Void> to = cs1.takeUntil(cs2).test(); + + to.assertEmpty(); + + assertTrue(cs1.hasObservers()); + assertTrue(cs2.hasObservers()); + + cs2.onComplete(); + + assertFalse(cs1.hasObservers()); + assertFalse(cs2.hasObservers()); + + to.assertResult(); + } + + @Test + public void mainErrors() { + CompletableSubject cs1 = CompletableSubject.create(); + CompletableSubject cs2 = CompletableSubject.create(); + + TestObserver<Void> to = cs1.takeUntil(cs2).test(); + + to.assertEmpty(); + + assertTrue(cs1.hasObservers()); + assertTrue(cs2.hasObservers()); + + cs1.onError(new TestException()); + + assertFalse(cs1.hasObservers()); + assertFalse(cs2.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void otherErrors() { + CompletableSubject cs1 = CompletableSubject.create(); + CompletableSubject cs2 = CompletableSubject.create(); + + TestObserver<Void> to = cs1.takeUntil(cs2).test(); + + to.assertEmpty(); + + assertTrue(cs1.hasObservers()); + assertTrue(cs2.hasObservers()); + + cs2.onError(new TestException()); + + assertFalse(cs1.hasObservers()); + assertFalse(cs2.hasObservers()); + + to.assertFailure(TestException.class); + } + + @Test + public void isDisposed() { + CompletableSubject cs1 = CompletableSubject.create(); + CompletableSubject cs2 = CompletableSubject.create(); + + TestHelper.checkDisposed(cs1.takeUntil(cs2)); + } + + @Test + public void mainErrorLate() { + + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + + new Completable() { + @Override + protected void subscribeActual(CompletableObserver s) { + s.onSubscribe(Disposables.empty()); + s.onError(new TestException()); + } + }.takeUntil(Completable.complete()) + .test() + .assertResult(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void mainCompleteLate() { + + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + + new Completable() { + @Override + protected void subscribeActual(CompletableObserver s) { + s.onSubscribe(Disposables.empty()); + s.onComplete(); + } + }.takeUntil(Completable.complete()) + .test() + .assertResult(); + + assertTrue(errors.isEmpty()); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void otherErrorLate() { + + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + + final AtomicReference<CompletableObserver> ref = new AtomicReference<CompletableObserver>(); + + Completable.complete() + .takeUntil(new Completable() { + @Override + protected void subscribeActual(CompletableObserver s) { + s.onSubscribe(Disposables.empty()); + ref.set(s); + } + }) + .test() + .assertResult(); + + ref.get().onError(new TestException()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void otherCompleteLate() { + + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + + final AtomicReference<CompletableObserver> ref = new AtomicReference<CompletableObserver>(); + + Completable.complete() + .takeUntil(new Completable() { + @Override + protected void subscribeActual(CompletableObserver s) { + s.onSubscribe(Disposables.empty()); + ref.set(s); + } + }) + .test() + .assertResult(); + + ref.get().onComplete(); + + assertTrue(errors.isEmpty()); + } finally { + RxJavaPlugins.reset(); + } + } +} From d4c1da01b157262b326b21cd97a844fcdedc7c6e Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Thu, 12 Jul 2018 09:28:57 +0200 Subject: [PATCH 220/417] Add marble diagram for Single.hide operator (#6077) * Add marble diagram for Single.hide operator * Use correct marble diagram URL for Single.hide method --- src/main/java/io/reactivex/Single.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 0d8677ea73..4a3573a8d8 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -1877,6 +1877,8 @@ public final <R> R as(@NonNull SingleConverter<T, ? extends R> converter) { /** * Hides the identity of the current Single, including the Disposable that is sent * to the downstream via {@code onSubscribe()}. + * <p> + * <img width="640" height="458" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.hide.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code hide} does not operate by default on a particular {@link Scheduler}.</dd> From 535ab3534851609e25750f50b9a1366f22a80ac9 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sat, 14 Jul 2018 21:42:01 +0200 Subject: [PATCH 221/417] 2.x: Improve class Javadoc of Single, Maybe and Completable (#6080) --- src/main/java/io/reactivex/Completable.java | 69 +++++++++++++++++++- src/main/java/io/reactivex/Maybe.java | 70 +++++++++++++++++++-- src/main/java/io/reactivex/Single.java | 67 +++++++++++++++++--- 3 files changed, 192 insertions(+), 14 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index bc9cd271dc..1c49af16a0 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -33,9 +33,74 @@ import io.reactivex.schedulers.Schedulers; /** - * Represents a deferred computation without any value but only indication for completion or exception. + * The {@code Completable} class represents a deferred computation without any value but + * only indication for completion or exception. + * <p> + * {@code Completable} behaves similarly to {@link Observable} except that it can only emit either + * a completion or error signal (there is no {@code onNext} or {@code onSuccess} as with the other + * reactive types). + * <p> + * The {@code Completable} class implements the {@link CompletableSource} base interface and the default consumer + * type it interacts with is the {@link CompletableObserver} via the {@link #subscribe(CompletableObserver)} method. + * The {@code Completable} operates with the following sequential protocol: + * <pre><code> + * onSubscribe (onError | onComplete)? + * </code></pre> + * <p> + * Note that as with the {@code Observable} protocol, {@code onError} and {@code onComplete} are mutually exclusive events. + * <p> + * Like {@link Observable}, a running {@code Completable} can be stopped through the {@link Disposable} instance + * provided to consumers through {@link SingleObserver#onSubscribe}. + * <p> + * Like an {@code Observable}, a {@code Completable} is lazy, can be either "hot" or "cold", synchronous or + * asynchronous. {@code Completable} instances returned by the methods of this class are <em>cold</em> + * and there is a standard <em>hot</em> implementation in the form of a subject: + * {@link io.reactivex.subjects.CompletableSubject CompletableSubject}. + * <p> + * The documentation for this class makes use of marble diagrams. The following legend explains these diagrams: + * <p> + * <img width="640" height="577" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.png" alt=""> + * <p> + * See {@link Flowable} or {@link Observable} for the + * implementation of the Reactive Pattern for a stream or vector of values. + * <p> + * Example: + * <pre><code> + * Disposable d = Completable.complete() + * .delay(10, TimeUnit.SECONDS, Schedulers.io()) + * .subscribeWith(new DisposableCompletableObserver() { + * @Override + * public void onStart() { + * System.out.println("Started"); + * } * - * The class follows a similar event pattern as Reactive-Streams: onSubscribe (onError|onComplete)? + * @Override + * public void onError(Throwable error) { + * error.printStackTrace(); + * } + * + * @Override + * public void onComplete() { + * System.out.println("Done!"); + * } + * }); + * + * Thread.sleep(5000); + * + * d.dispose(); + * </code></pre> + * <p> + * Note that by design, subscriptions via {@link #subscribe(CompletableObserver)} can't be cancelled/disposed + * from the outside (hence the + * {@code void} return of the {@link #subscribe(CompletableObserver)} method) and it is the + * responsibility of the implementor of the {@code CompletableObserver} to allow this to happen. + * RxJava supports such usage with the standard + * {@link io.reactivex.observers.DisposableCompletableObserver DisposableCompletableObserver} instance. + * For convenience, the {@link #subscribeWith(CompletableObserver)} method is provided as well to + * allow working with a {@code CompletableObserver} (or subclass) instance to be applied with in + * a fluent manner (such as in the example above). + * + * @see io.reactivex.observers.DisposableCompletableObserver */ public abstract class Completable implements CompletableSource { /** diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 3a4ec3a76d..7b040b58f9 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -34,18 +34,78 @@ import io.reactivex.schedulers.Schedulers; /** - * Represents a deferred computation and emission of a maybe value or exception. + * The {@code Maybe} class represents a deferred computation and emission of a single value, no value at all or an exception. * <p> - * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/maybe.png" alt=""> + * The {@code Maybe} class implements the {@link MaybeSource} base interface and the default consumer + * type it interacts with is the {@link MaybeObserver} via the {@link #subscribe(MaybeObserver)} method. * <p> - * The main consumer type of Maybe is {@link MaybeObserver} whose methods are called - * in a sequential fashion following this protocol:<br> - * {@code onSubscribe (onSuccess | onError | onComplete)?}. + * The {@code Maybe} operates with the following sequential protocol: + * <pre><code> + * onSubscribe (onSuccess | onError | onComplete)? + * </code></pre> * <p> * Note that {@code onSuccess}, {@code onError} and {@code onComplete} are mutually exclusive events; unlike {@code Observable}, * {@code onSuccess} is never followed by {@code onError} or {@code onComplete}. + * <p> + * Like {@link Observable}, a running {@code Maybe} can be stopped through the {@link Disposable} instance + * provided to consumers through {@link MaybeObserver#onSubscribe}. + * <p> + * Like an {@code Observable}, a {@code Maybe} is lazy, can be either "hot" or "cold", synchronous or + * asynchronous. {@code Maybe} instances returned by the methods of this class are <em>cold</em> + * and there is a standard <em>hot</em> implementation in the form of a subject: + * {@link io.reactivex.subjects.MaybeSubject MaybeSubject}. + * <p> + * The documentation for this class makes use of marble diagrams. The following legend explains these diagrams: + * <p> + * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/maybe.png" alt=""> + * <p> + * See {@link Flowable} or {@link Observable} for the + * implementation of the Reactive Pattern for a stream or vector of values. + * <p> + * Example: + * <pre><code> + * Disposable d = Maybe.just("Hello World") + * .delay(10, TimeUnit.SECONDS, Schedulers.io()) + * .subscribeWith(new DisposableMaybeObserver<String>() { + * @Override + * public void onStart() { + * System.out.println("Started"); + * } + * + * @Override + * public void onSuccess(String value) { + * System.out.println("Success: " + value); + * } + * + * @Override + * public void onError(Throwable error) { + * error.printStackTrace(); + * } + * + * @Override + * public void onComplete() { + * System.out.println("Done!"); + * } + * }); + * + * Thread.sleep(5000); + * + * d.dispose(); + * </code></pre> + * <p> + * Note that by design, subscriptions via {@link #subscribe(MaybeObserver)} can't be cancelled/disposed + * from the outside (hence the + * {@code void} return of the {@link #subscribe(MaybeObserver)} method) and it is the + * responsibility of the implementor of the {@code MaybeObserver} to allow this to happen. + * RxJava supports such usage with the standard + * {@link io.reactivex.observers.DisposableMaybeObserver DisposableMaybeObserver} instance. + * For convenience, the {@link #subscribeWith(MaybeObserver)} method is provided as well to + * allow working with a {@code MaybeObserver} (or subclass) instance to be applied with in + * a fluent manner (such as in the example above). + * * @param <T> the value type * @since 2.0 + * @see io.reactivex.observers.DisposableMaybeObserver */ public abstract class Maybe<T> implements MaybeSource<T> { diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 4a3573a8d8..62ff373d0e 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -37,26 +37,79 @@ import io.reactivex.schedulers.Schedulers; /** - * The Single class implements the Reactive Pattern for a single value response. - * See {@link Flowable} or {@link Observable} for the - * implementation of the Reactive Pattern for a stream or vector of values. + * The {@code Single} class implements the Reactive Pattern for a single value response. + * <p> + * {@code Single} behaves similarly to {@link Observable} except that it can only emit either a single successful + * value or an error (there is no "onComplete" notification as there is for an {@link Observable}). + * <p> + * The {@code Single} class implements the {@link SingleSource} base interface and the default consumer + * type it interacts with is the {@link SingleObserver} via the {@link #subscribe(SingleObserver)} method. + * <p> + * The {@code Single} operates with the following sequential protocol: + * <pre> + * <code>onSubscribe (onSuccess | onError)?</code> + * </pre> + * <p> + * Note that {@code onSuccess} and {@code onError} are mutually exclusive events; unlike {@code Observable}, + * {@code onSuccess} is never followed by {@code onError}. * <p> - * {@code Single} behaves the same as {@link Observable} except that it can only emit either a single successful - * value, or an error (there is no "onComplete" notification as there is for {@link Observable}) + * Like {@code Observable}, a running {@code Single} can be stopped through the {@link Disposable} instance + * provided to consumers through {@link SingleObserver#onSubscribe}. * <p> - * Like an {@link Observable}, a {@code Single} is lazy, can be either "hot" or "cold", synchronous or - * asynchronous. + * Like an {@code Observable}, a {@code Single} is lazy, can be either "hot" or "cold", synchronous or + * asynchronous. {@code Single} instances returned by the methods of this class are <em>cold</em> + * and there is a standard <em>hot</em> implementation in the form of a subject: + * {@link io.reactivex.subjects.SingleSubject SingleSubject}. * <p> * The documentation for this class makes use of marble diagrams. The following legend explains these diagrams: * <p> * <img width="640" height="301" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.legend.png" alt=""> * <p> + * See {@link Flowable} or {@link Observable} for the + * implementation of the Reactive Pattern for a stream or vector of values. + * <p> * For more information see the <a href="http://reactivex.io/documentation/single.html">ReactiveX * documentation</a>. + * <p> + * Example: + * <pre><code> + * Disposable d = Single.just("Hello World") + * .delay(10, TimeUnit.SECONDS, Schedulers.io()) + * .subscribeWith(new DisposableSingleObserver<String>() { + * @Override + * public void onStart() { + * System.out.println("Started"); + * } + * + * @Override + * public void onSuccess(String value) { + * System.out.println("Success: " + value); + * } * + * @Override + * public void onError(Throwable error) { + * error.printStackTrace(); + * } + * }); + * + * Thread.sleep(5000); + * + * d.dispose(); + * </code></pre> + * <p> + * Note that by design, subscriptions via {@link #subscribe(SingleObserver)} can't be cancelled/disposed + * from the outside (hence the + * {@code void} return of the {@link #subscribe(SingleObserver)} method) and it is the + * responsibility of the implementor of the {@code SingleObserver} to allow this to happen. + * RxJava supports such usage with the standard + * {@link io.reactivex.observers.DisposableSingleObserver DisposableSingleObserver} instance. + * For convenience, the {@link #subscribeWith(SingleObserver)} method is provided as well to + * allow working with a {@code SingleObserver} (or subclass) instance to be applied with in + * a fluent manner (such as in the example above). * @param <T> * the type of the item emitted by the Single * @since 2.0 + * @see io.reactivex.observers.DisposableSingleObserver */ public abstract class Single<T> implements SingleSource<T> { From 53dd15fcb5c3e154b58ecb1768732d55aa49f5c9 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 17 Jul 2018 11:19:13 +0200 Subject: [PATCH 222/417] 2.x: Add Completable marble diagrams (07/17a) (#6083) --- src/main/java/io/reactivex/Completable.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 1c49af16a0..319e31272d 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -106,6 +106,8 @@ public abstract class Completable implements CompletableSource { /** * Returns a Completable which terminates as soon as one of the source Completables * terminates (normally or with an error) and cancels all other Completables. + * <p> + * <img width="640" height="518" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.ambArray.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ambArray} does not operate by default on a particular {@link Scheduler}.</dd> @@ -132,6 +134,8 @@ public static Completable ambArray(final CompletableSource... sources) { /** * Returns a Completable which terminates as soon as one of the source Completables * terminates (normally or with an error) and cancels all other Completables. + * <p> + * <img width="640" height="518" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> @@ -151,6 +155,8 @@ public static Completable amb(final Iterable<? extends CompletableSource> source /** * Returns a Completable instance that completes immediately when subscribed to. + * <p> + * <img width="640" height="472" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.complete.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code complete} does not operate by default on a particular {@link Scheduler}.</dd> @@ -165,6 +171,8 @@ public static Completable complete() { /** * Returns a Completable which completes only when all sources complete, one after another. + * <p> + * <img width="640" height="283" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.concatArray.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatArray} does not operate by default on a particular {@link Scheduler}.</dd> @@ -188,6 +196,8 @@ public static Completable concatArray(CompletableSource... sources) { /** * Returns a Completable which completes only when all sources complete, one after another. + * <p> + * <img width="640" height="303" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.concat.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> @@ -206,6 +216,8 @@ public static Completable concat(Iterable<? extends CompletableSource> sources) /** * Returns a Completable which completes only when all sources complete, one after another. + * <p> + * <img width="640" height="237" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.concat.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Completable} honors the backpressure of the downstream consumer @@ -226,6 +238,8 @@ public static Completable concat(Publisher<? extends CompletableSource> sources) /** * Returns a Completable which completes only when all sources complete, one after another. + * <p> + * <img width="640" height="237" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.concat.pn.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Completable} honors the backpressure of the downstream consumer @@ -312,6 +326,8 @@ public static Completable unsafeCreate(CompletableSource source) { /** * Defers the subscription to a Completable instance returned by a supplier. + * <p> + * <img width="640" height="298" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.defer.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code defer} does not operate by default on a particular {@link Scheduler}.</dd> @@ -330,6 +346,8 @@ public static Completable defer(final Callable<? extends CompletableSource> comp * Creates a Completable which calls the given error supplier for each subscriber * and emits its returned Throwable. * <p> + * <img width="640" height="462" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.error.f.png" alt=""> + * <p> * If the errorSupplier returns null, the child CompletableObservers will receive a * NullPointerException. * <dl> @@ -349,6 +367,8 @@ public static Completable error(final Callable<? extends Throwable> errorSupplie /** * Creates a Completable instance that emits the given Throwable exception to subscribers. + * <p> + * <img width="640" height="462" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.error.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd> From c8bcb3c92bebde39616597bd46ddb93d6f0f6e18 Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Tue, 17 Jul 2018 15:06:10 +0200 Subject: [PATCH 223/417] Add marble diagrams for Single.repeat operators (#6081) * Add marble diagrams for Single.repeat operators * Use correct marble diagram URLs --- src/main/java/io/reactivex/Single.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 62ff373d0e..441d0b6a43 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -3051,6 +3051,8 @@ public final Single<T> onTerminateDetach() { /** * Repeatedly re-subscribes to the current Single and emits each success value. + * <p> + * <img width="640" height="457" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.repeat.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -3069,6 +3071,8 @@ public final Flowable<T> repeat() { /** * Re-subscribes to the current Single at most the given number of times and emits each success value. + * <p> + * <img width="640" height="457" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.repeat.n.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -3090,6 +3094,8 @@ public final Flowable<T> repeat(long times) { * Re-subscribes to the current Single if * the Publisher returned by the handler function signals a value in response to a * value signalled through the Flowable the handle receives. + * <p> + * <img width="640" height="1478" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.repeatWhen.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer. From ccfa4bf521fae76e1b7157c1880625333304e304 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 17 Jul 2018 15:15:25 +0200 Subject: [PATCH 224/417] 2.x: More Completable marbles, add C.fromMaybe (#6085) --- src/main/java/io/reactivex/Completable.java | 58 +++++++++++++++++++ .../completable/CompletableFromMaybeTest.java | 46 +++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 src/test/java/io/reactivex/internal/operators/completable/CompletableFromMaybeTest.java diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 319e31272d..e82664e0a6 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -388,6 +388,8 @@ public static Completable error(final Throwable error) { /** * Returns a Completable instance that runs the given Action for each subscriber and * emits either an unchecked exception or simply completes. + * <p> + * <img width="640" height="297" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromAction.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromAction} does not operate by default on a particular {@link Scheduler}.</dd> @@ -406,6 +408,8 @@ public static Completable fromAction(final Action run) { /** * Returns a Completable which when subscribed, executes the callable function, ignores its * normal result and emits onError or onComplete only. + * <p> + * <img width="640" height="286" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromCallable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd> @@ -423,6 +427,8 @@ public static Completable fromCallable(final Callable<?> callable) { /** * Returns a Completable instance that reacts to the termination of the given Future in a blocking fashion. * <p> + * <img width="640" height="628" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromFuture.png" alt=""> + * <p> * Note that cancellation from any of the subscribers to this Completable will cancel the future. * <dl> * <dt><b>Scheduler:</b></dt> @@ -438,9 +444,33 @@ public static Completable fromFuture(final Future<?> future) { return fromAction(Functions.futureAction(future)); } + /** + * Returns a Completable instance that when subscribed to, subscribes to the {@code Maybe} instance and + * emits a completion event if the maybe emits {@code onSuccess}/{@code onComplete} or forwards any + * {@code onError} events. + * <p> + * <img width="640" height="235" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromMaybe.png" alt=""> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code fromMaybe} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * @param <T> the value type of the {@link MaybeSource} element + * @param maybe the Maybe instance to subscribe to, not null + * @return the new Completable instance + * @throws NullPointerException if single is null + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public static <T> Completable fromMaybe(final MaybeSource<T> maybe) { + ObjectHelper.requireNonNull(maybe, "maybe is null"); + return RxJavaPlugins.onAssembly(new MaybeIgnoreElementCompletable<T>(maybe)); + } + /** * Returns a Completable instance that runs the given Runnable for each subscriber and * emits either its exception or simply completes. + * <p> + * <img width="640" height="297" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromRunnable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromRunnable} does not operate by default on a particular {@link Scheduler}.</dd> @@ -459,6 +489,8 @@ public static Completable fromRunnable(final Runnable run) { /** * Returns a Completable instance that subscribes to the given Observable, ignores all values and * emits only the terminal event. + * <p> + * <img width="640" height="414" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromObservable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromObservable} does not operate by default on a particular {@link Scheduler}.</dd> @@ -479,6 +511,8 @@ public static <T> Completable fromObservable(final ObservableSource<T> observabl * Returns a Completable instance that subscribes to the given publisher, ignores all values and * emits only the terminal event. * <p> + * <img width="640" height="442" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromPublisher.png" alt=""> + * <p> * The {@link Publisher} must follow the * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive-Streams specification</a>. * Violating the specification may result in undefined behavior. @@ -513,6 +547,8 @@ public static <T> Completable fromPublisher(final Publisher<T> publisher) { /** * Returns a Completable instance that when subscribed to, subscribes to the Single instance and * emits a completion event if the single emits onSuccess or forwards any onError events. + * <p> + * <img width="640" height="356" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromSingle.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromSingle} does not operate by default on a particular {@link Scheduler}.</dd> @@ -532,6 +568,8 @@ public static <T> Completable fromSingle(final SingleSource<T> single) { /** * Returns a Completable instance that subscribes to all sources at once and * completes only when all source Completables complete or one of them emits an error. + * <p> + * <img width="640" height="270" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.mergeArray.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeArray} does not operate by default on a particular {@link Scheduler}.</dd> @@ -569,6 +607,8 @@ public static Completable mergeArray(CompletableSource... sources) { /** * Returns a Completable instance that subscribes to all sources at once and * completes only when all source Completables complete or one of them emits an error. + * <p> + * <img width="640" height="311" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.merge.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> @@ -601,6 +641,8 @@ public static Completable merge(Iterable<? extends CompletableSource> sources) { /** * Returns a Completable instance that subscribes to all sources at once and * completes only when all source Completables complete or one of them emits an error. + * <p> + * <img width="640" height="336" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.merge.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Completable} honors the backpressure of the downstream consumer @@ -635,6 +677,8 @@ public static Completable merge(Publisher<? extends CompletableSource> sources) /** * Returns a Completable instance that keeps subscriptions to a limited number of sources at once and * completes only when all source Completables complete or one of them emits an error. + * <p> + * <img width="640" height="269" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.merge.pn.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Completable} honors the backpressure of the downstream consumer @@ -699,6 +743,8 @@ private static Completable merge0(Publisher<? extends CompletableSource> sources * Returns a CompletableConsumable that subscribes to all Completables in the source array and delays * any error emitted by either the sources observable or any of the inner Completables until all of * them terminate in a way or another. + * <p> + * <img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.mergeArrayDelayError.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd> @@ -718,6 +764,8 @@ public static Completable mergeArrayDelayError(CompletableSource... sources) { * Returns a Completable that subscribes to all Completables in the source sequence and delays * any error emitted by either the sources observable or any of the inner Completables until all of * them terminate in a way or another. + * <p> + * <img width="640" height="475" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.mergeDelayError.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> @@ -738,6 +786,8 @@ public static Completable mergeDelayError(Iterable<? extends CompletableSource> * Returns a Completable that subscribes to all Completables in the source sequence and delays * any error emitted by either the sources observable or any of the inner Completables until all of * them terminate in a way or another. + * <p> + * <img width="640" height="466" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.mergeDelayError.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Completable} honors the backpressure of the downstream consumer @@ -761,6 +811,8 @@ public static Completable mergeDelayError(Publisher<? extends CompletableSource> * the source sequence and delays any error emitted by either the sources * observable or any of the inner Completables until all of * them terminate in a way or another. + * <p> + * <img width="640" height="440" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.mergeDelayError.pn.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Completable} honors the backpressure of the downstream consumer @@ -782,6 +834,8 @@ public static Completable mergeDelayError(Publisher<? extends CompletableSource> /** * Returns a Completable that never calls onError or onComplete. + * <p> + * <img width="640" height="512" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.never.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code never} does not operate by default on a particular {@link Scheduler}.</dd> @@ -796,6 +850,8 @@ public static Completable never() { /** * Returns a Completable instance that fires its onComplete event after the given delay elapsed. + * <p> + * <img width="640" height="413" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.timer.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timer} does operate by default on the {@code computation} {@link Scheduler}.</dd> @@ -813,6 +869,8 @@ public static Completable timer(long delay, TimeUnit unit) { /** * Returns a Completable instance that fires its onComplete event after the given delay elapsed * by using the supplied scheduler. + * <p> + * <img width="640" height="413" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.timer.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timer} operates on the {@link Scheduler} you specify.</dd> diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromMaybeTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromMaybeTest.java new file mode 100644 index 0000000000..46f62d0b7a --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromMaybeTest.java @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import io.reactivex.Completable; +import io.reactivex.Maybe; +import org.junit.Test; + +public class CompletableFromMaybeTest { + @Test(expected = NullPointerException.class) + public void fromMaybeNull() { + Completable.fromMaybe(null); + } + + @Test + public void fromMaybe() { + Completable.fromMaybe(Maybe.just(1)) + .test() + .assertResult(); + } + + @Test + public void fromMaybeEmpty() { + Completable.fromMaybe(Maybe.<Integer>empty()) + .test() + .assertResult(); + } + + @Test + public void fromMaybeError() { + Completable.fromMaybe(Maybe.error(new UnsupportedOperationException())) + .test() + .assertFailure(UnsupportedOperationException.class); + } +} From 97ebd2c0ba3d1505631b844d2ff5000944be2ae6 Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Tue, 17 Jul 2018 15:45:35 +0200 Subject: [PATCH 225/417] Add marble diagram for Single.repeatUntil operator (#6084) * Add marble diagram for Single.repeatUntil operator * Use proper URL for marble --- src/main/java/io/reactivex/Single.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 441d0b6a43..25adddd0eb 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -3119,6 +3119,8 @@ public final Flowable<T> repeatWhen(Function<? super Flowable<Object>, ? extends /** * Re-subscribes to the current Single until the given BooleanSupplier returns true. + * <p> + * <img width="640" height="463" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.repeatUntil.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> From 396f2f6d15a52e5c79d0ee7b4dcfb62f6a8029b7 Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Wed, 18 Jul 2018 09:22:44 +0200 Subject: [PATCH 226/417] Add marbles for Single.from operators (#6087) --- src/main/java/io/reactivex/Single.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 25adddd0eb..a87b7e5ad4 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -554,6 +554,8 @@ public static <T> Single<T> error(final Throwable exception) { * Allows you to defer execution of passed function until SingleObserver subscribes to the {@link Single}. * It makes passed function "lazy". * Result of the function invocation will be emitted by the {@link Single}. + * <p> + * <img width="640" height="467" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.fromCallable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd> @@ -714,6 +716,8 @@ public static <T> Single<T> fromFuture(Future<? extends T> future, Scheduler sch * Note that even though {@link Publisher} appears to be a functional interface, it * is not recommended to implement it through a lambda as the specification requires * state management that is not achievable with a stateless lambda. + * <p> + * <img width="640" height="322" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.fromPublisher.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The {@code publisher} is consumed in an unbounded fashion but will be cancelled @@ -738,6 +742,8 @@ public static <T> Single<T> fromPublisher(final Publisher<? extends T> publisher * Wraps a specific ObservableSource into a Single and signals its single element or error. * <p>If the ObservableSource is empty, a NoSuchElementException is signalled. * If the source has more than one element, an IndexOutOfBoundsException is signalled. + * <p> + * <img width="640" height="343" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.fromObservable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromObservable} does not operate by default on a particular {@link Scheduler}.</dd> From fd4b614d4a4f1b136f51c4bb0d29e8bfbf91fa0c Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Wed, 18 Jul 2018 09:36:25 +0200 Subject: [PATCH 227/417] Single error operators marbles (#6086) * Add marbles for Single.error operators * Add marbles for Single.onError operators * Use proper URLs for marble diagrams --- src/main/java/io/reactivex/Single.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index a87b7e5ad4..874f8adcd6 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -507,6 +507,8 @@ public static <T> Single<T> defer(final Callable<? extends SingleSource<? extend /** * Signals a Throwable returned by the callback function for each individual SingleObserver. + * <p> + * <img width="640" height="283" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.error.c.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd> @@ -527,7 +529,7 @@ public static <T> Single<T> error(final Callable<? extends Throwable> errorSuppl * Returns a Single that invokes a subscriber's {@link SingleObserver#onError onError} method when the * subscriber subscribes to it. * <p> - * <img width="640" height="190" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.error.png" alt=""> + * <img width="640" height="283" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.error.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2921,7 +2923,7 @@ public final Single<T> observeOn(final Scheduler scheduler) { * Instructs a Single to emit an item (returned by a specified function) rather than invoking * {@link SingleObserver#onError onError} if it encounters an error. * <p> - * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onErrorReturn.png" alt=""> + * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onErrorReturn.png" alt=""> * <p> * By default, when a Single encounters an error that prevents it from emitting the expected item to its * subscriber, the Single invokes its subscriber's {@link SingleObserver#onError} method, and then quits @@ -2952,6 +2954,8 @@ public final Single<T> onErrorReturn(final Function<Throwable, ? extends T> resu /** * Signals the specified value as success in case the current Single signals an error. + * <p> + * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onErrorReturnItem.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorReturnItem} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2971,7 +2975,7 @@ public final Single<T> onErrorReturnItem(final T value) { * Instructs a Single to pass control to another Single rather than invoking * {@link SingleObserver#onError(Throwable)} if it encounters an error. * <p> - * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onErrorResumeNext.png" alt=""> + * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onErrorResumeNext.png" alt=""> * <p> * By default, when a Single encounters an error that prevents it from emitting the expected item to * its {@link SingleObserver}, the Single invokes its SingleObserver's {@code onError} method, and then quits @@ -3005,7 +3009,7 @@ public final Single<T> onErrorResumeNext(final Single<? extends T> resumeSingleI * Instructs a Single to pass control to another Single rather than invoking * {@link SingleObserver#onError(Throwable)} if it encounters an error. * <p> - * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onErrorResumeNext.png" alt=""> + * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onErrorResumeNext.f.png" alt=""> * <p> * By default, when a Single encounters an error that prevents it from emitting the expected item to * its {@link SingleObserver}, the Single invokes its SingleObserver's {@code onError} method, and then quits From 4a744153e9cea4e32f4c88bc49893e0b13b85359 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 18 Jul 2018 12:21:02 +0200 Subject: [PATCH 228/417] 2.x: Add missing Completable marbles (07/18a) (#6090) --- src/main/java/io/reactivex/Completable.java | 34 +++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index e82664e0a6..c1d6b2fb07 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -903,6 +903,8 @@ private static NullPointerException toNpe(Throwable ex) { * Returns a Completable instance which manages a resource along * with a custom Completable instance while the subscription is active. * <p> + * <img width="640" height="388" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.using.png" alt=""> + * <p> * This overload disposes eagerly before the terminal event is emitted. * <dl> * <dt><b>Scheduler:</b></dt> @@ -927,6 +929,8 @@ public static <R> Completable using(Callable<R> resourceSupplier, * with a custom Completable instance while the subscription is active and performs eager or lazy * resource disposition. * <p> + * <img width="640" height="332" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.using.b.png" alt=""> + * <p> * If this overload performs a lazy cancellation after the terminal event is emitted. * Exceptions thrown at this time will be delivered to RxJavaPlugins only. * <dl> @@ -959,6 +963,8 @@ public static <R> Completable using( /** * Wraps the given CompletableSource into a Completable * if not already Completable. + * <p> + * <img width="640" height="354" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.wrap.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code wrap} does not operate by default on a particular {@link Scheduler}.</dd> @@ -980,6 +986,8 @@ public static Completable wrap(CompletableSource source) { /** * Returns a Completable that emits the a terminated event of either this Completable * or the other Completable whichever fires first. + * <p> + * <img width="640" height="484" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.ambWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ambWith} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1001,6 +1009,8 @@ public final Completable ambWith(CompletableSource other) { * will subscribe to the {@code next} ObservableSource. An error event from this Completable will be * propagated to the downstream subscriber and will result in skipping the subscription of the * Observable. + * <p> + * <img width="640" height="278" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.andThen.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code andThen} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1022,6 +1032,8 @@ public final <T> Observable<T> andThen(ObservableSource<T> next) { * will subscribe to the {@code next} Flowable. An error event from this Completable will be * propagated to the downstream subscriber and will result in skipping the subscription of the * Publisher. + * <p> + * <img width="640" height="249" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.andThen.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer @@ -1047,6 +1059,8 @@ public final <T> Flowable<T> andThen(Publisher<T> next) { * will subscribe to the {@code next} SingleSource. An error event from this Completable will be * propagated to the downstream subscriber and will result in skipping the subscription of the * Single. + * <p> + * <img width="640" height="437" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.andThen.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code andThen} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1068,6 +1082,8 @@ public final <T> Single<T> andThen(SingleSource<T> next) { * will subscribe to the {@code next} MaybeSource. An error event from this Completable will be * propagated to the downstream subscriber and will result in skipping the subscription of the * Maybe. + * <p> + * <img width="640" height="280" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.andThen.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code andThen} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1088,6 +1104,8 @@ public final <T> Maybe<T> andThen(MaybeSource<T> next) { * Returns a Completable that first runs this Completable * and then the other completable. * <p> + * <img width="640" height="437" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.andThen.c.png" alt=""> + * <p> * This is an alias for {@link #concatWith(CompletableSource)}. * <dl> * <dt><b>Scheduler:</b></dt> @@ -1106,6 +1124,8 @@ public final Completable andThen(CompletableSource next) { /** * Calls the specified converter function during assembly time and returns its resulting value. * <p> + * <img width="640" height="751" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.as.png" alt=""> + * <p> * This allows fluent conversion to any other type. * <dl> * <dt><b>Scheduler:</b></dt> @@ -1128,6 +1148,8 @@ public final <R> R as(@NonNull CompletableConverter<? extends R> converter) { /** * Subscribes to and awaits the termination of this Completable instance in a blocking manner and * rethrows any exception emitted. + * <p> + * <img width="640" height="432" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.blockingAwait.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingAwait} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1148,6 +1170,8 @@ public final void blockingAwait() { /** * Subscribes to and awaits the termination of this Completable instance in a blocking manner * with a specific timeout and rethrows any exception emitted within the timeout window. + * <p> + * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.blockingAwait.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingAwait} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1174,6 +1198,8 @@ public final boolean blockingAwait(long timeout, TimeUnit unit) { /** * Subscribes to this Completable instance and blocks until it terminates, then returns null or * the emitted exception if any. + * <p> + * <img width="640" height="435" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.blockingGet.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingGet} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1192,6 +1218,8 @@ public final Throwable blockingGet() { /** * Subscribes to this Completable instance and blocks until it terminates or the specified timeout * elapses, then returns null for normal termination or the emitted exception if any. + * <p> + * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.blockingGet.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingGet} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1216,6 +1244,8 @@ public final Throwable blockingGet(long timeout, TimeUnit unit) { * subscribes to the result Completable, caches its terminal event * and relays/replays it to observers. * <p> + * <img width="640" height="375" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.cache.png" alt=""> + * <p> * Note that this operator doesn't allow disposing the connection * of the upstream source. * <dl> @@ -1235,6 +1265,8 @@ public final Completable cache() { /** * Calls the given transformer function with this instance and returns the function's resulting * Completable. + * <p> + * <img width="640" height="625" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.compose.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code compose} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2308,6 +2340,8 @@ private Completable timeout0(long timeout, TimeUnit unit, Scheduler scheduler, C /** * Allows fluent conversion to another type via a function callback. + * <p> + * <img width="640" height="751" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.to.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code to} does not operate by default on a particular {@link Scheduler}.</dd> From 1aeac067ae3c9844f77d264e47de6a31f3eb1a53 Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Wed, 18 Jul 2018 13:12:27 +0200 Subject: [PATCH 229/417] Add marbles for Single.amb operators (#6091) --- src/main/java/io/reactivex/Single.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 874f8adcd6..5cef88c846 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -116,6 +116,8 @@ public abstract class Single<T> implements SingleSource<T> { /** * Runs multiple SingleSources and signals the events of the first one that signals (cancelling * the rest). + * <p> + * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> @@ -136,6 +138,8 @@ public static <T> Single<T> amb(final Iterable<? extends SingleSource<? extends /** * Runs multiple SingleSources and signals the events of the first one that signals (cancelling * the rest). + * <p> + * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.ambArray.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ambArray} does not operate by default on a particular {@link Scheduler}.</dd> From 27c63b6a4c2074657aed4e7ee6e39a52173bbed5 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 19 Jul 2018 10:45:25 +0200 Subject: [PATCH 230/417] 2.x: Improve Completable.delay operator internals (#6096) --- .../completable/CompletableDelay.java | 78 ++++++++++++------- .../completable/CompletableDelayTest.java | 76 ++++++++++++++++-- 2 files changed, 117 insertions(+), 37 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDelay.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDelay.java index fa600c64b1..79b0a49383 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDelay.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDelay.java @@ -14,9 +14,11 @@ package io.reactivex.internal.operators.completable; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import io.reactivex.*; -import io.reactivex.disposables.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; public final class CompletableDelay extends Completable { @@ -40,54 +42,70 @@ public CompletableDelay(CompletableSource source, long delay, TimeUnit unit, Sch @Override protected void subscribeActual(final CompletableObserver s) { - final CompositeDisposable set = new CompositeDisposable(); - - source.subscribe(new Delay(set, s)); + source.subscribe(new Delay(s, delay, unit, scheduler, delayError)); } - final class Delay implements CompletableObserver { + static final class Delay extends AtomicReference<Disposable> + implements CompletableObserver, Runnable, Disposable { + + private static final long serialVersionUID = 465972761105851022L; + + final CompletableObserver downstream; + + final long delay; + + final TimeUnit unit; - private final CompositeDisposable set; - final CompletableObserver s; + final Scheduler scheduler; - Delay(CompositeDisposable set, CompletableObserver s) { - this.set = set; - this.s = s; + final boolean delayError; + + Throwable error; + + Delay(CompletableObserver downstream, long delay, TimeUnit unit, Scheduler scheduler, boolean delayError) { + this.downstream = downstream; + this.delay = delay; + this.unit = unit; + this.scheduler = scheduler; + this.delayError = delayError; + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(this, d)) { + downstream.onSubscribe(this); + } } @Override public void onComplete() { - set.add(scheduler.scheduleDirect(new OnComplete(), delay, unit)); + DisposableHelper.replace(this, scheduler.scheduleDirect(this, delay, unit)); } @Override public void onError(final Throwable e) { - set.add(scheduler.scheduleDirect(new OnError(e), delayError ? delay : 0, unit)); + error = e; + DisposableHelper.replace(this, scheduler.scheduleDirect(this, delayError ? delay : 0, unit)); } @Override - public void onSubscribe(Disposable d) { - set.add(d); - s.onSubscribe(set); + public void dispose() { + DisposableHelper.dispose(this); } - final class OnComplete implements Runnable { - @Override - public void run() { - s.onComplete(); - } + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(get()); } - final class OnError implements Runnable { - private final Throwable e; - - OnError(Throwable e) { - this.e = e; - } - - @Override - public void run() { - s.onError(e); + @Override + public void run() { + Throwable e = error; + error = null; + if (e != null) { + downstream.onError(e); + } else { + downstream.onComplete(); } } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java index 78393b39ae..174a520e0f 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java @@ -13,17 +13,18 @@ package io.reactivex.internal.operators.completable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; +import static org.junit.Assert.assertNotEquals; + +import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; -import io.reactivex.functions.Consumer; import org.junit.Test; -import io.reactivex.Completable; -import io.reactivex.schedulers.Schedulers; - -import static org.junit.Assert.assertNotEquals; +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.*; +import io.reactivex.observers.TestObserver; +import io.reactivex.schedulers.*; public class CompletableDelayTest { @@ -58,4 +59,65 @@ public void accept(Throwable throwable) throws Exception { assertNotEquals(Thread.currentThread(), thread.get()); } + @Test + public void disposed() { + TestHelper.checkDisposed(Completable.never().delay(1, TimeUnit.MINUTES)); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeCompletable(new Function<Completable, CompletableSource>() { + @Override + public CompletableSource apply(Completable c) throws Exception { + return c.delay(1, TimeUnit.MINUTES); + } + }); + } + + @Test + public void normal() { + Completable.complete() + .delay(1, TimeUnit.MILLISECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(); + } + + @Test + public void errorNotDelayed() { + TestScheduler scheduler = new TestScheduler(); + + TestObserver<Void> to = Completable.error(new TestException()) + .delay(100, TimeUnit.MILLISECONDS, scheduler, false) + .test(); + + to.assertEmpty(); + + scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); + + to.assertFailure(TestException.class); + + scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); + + to.assertFailure(TestException.class); + } + + @Test + public void errorDelayed() { + TestScheduler scheduler = new TestScheduler(); + + TestObserver<Void> to = Completable.error(new TestException()) + .delay(100, TimeUnit.MILLISECONDS, scheduler, true) + .test(); + + to.assertEmpty(); + + scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); + + to.assertEmpty(); + + scheduler.advanceTimeBy(99, TimeUnit.MILLISECONDS); + + to.assertFailure(TestException.class); + } } From 382ba69afe6fdaab90682f9d37c32b4f538bb5c0 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 19 Jul 2018 13:27:57 +0200 Subject: [PATCH 231/417] 2.x: Add missing Completable marbles (+19, 07/19a) (#6097) --- src/main/java/io/reactivex/Completable.java | 48 +++++++++++++++++++-- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index c1d6b2fb07..06a9cd79da 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1283,6 +1283,8 @@ public final Completable compose(CompletableTransformer transformer) { /** * Concatenates this Completable with another Completable. + * <p> + * <img width="640" height="317" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.concatWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatWith} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1304,6 +1306,8 @@ public final Completable concatWith(CompletableSource other) { /** * Returns a Completable which delays the emission of the completion event by the given time. + * <p> + * <img width="640" height="343" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.delay.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code delay} does operate by default on the {@code computation} {@link Scheduler}.</dd> @@ -1322,6 +1326,8 @@ public final Completable delay(long delay, TimeUnit unit) { /** * Returns a Completable which delays the emission of the completion event by the given time while * running on the specified scheduler. + * <p> + * <img width="640" height="313" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.delay.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code delay} operates on the {@link Scheduler} you specify.</dd> @@ -1341,6 +1347,8 @@ public final Completable delay(long delay, TimeUnit unit, Scheduler scheduler) { /** * Returns a Completable which delays the emission of the completion event, and optionally the error as well, by the given time while * running on the specified scheduler. + * <p> + * <img width="640" height="253" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.delay.sb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code delay} operates on the {@link Scheduler} you specify.</dd> @@ -1362,6 +1370,8 @@ public final Completable delay(final long delay, final TimeUnit unit, final Sche /** * Returns a Completable which calls the given onComplete callback if this Completable completes. + * <p> + * <img width="640" height="304" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.doOnComplete.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnComplete} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1382,6 +1392,8 @@ public final Completable doOnComplete(Action onComplete) { /** * Calls the shared {@code Action} if a CompletableObserver subscribed to the current * Completable disposes the common Disposable it received via onSubscribe. + * <p> + * <img width="640" height="589" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.doOnDispose.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnDispose} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1400,6 +1412,8 @@ public final Completable doOnDispose(Action onDispose) { /** * Returns a Completable which calls the given onError callback if this Completable emits an error. + * <p> + * <img width="640" height="304" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.doOnError.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnError} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1420,6 +1434,8 @@ public final Completable doOnError(Consumer<? super Throwable> onError) { /** * Returns a Completable which calls the given onEvent callback with the (throwable) for an onError * or (null) for an onComplete signal from this Completable before delivering said signal to the downstream. + * <p> + * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.doOnEvent.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnEvent} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1470,6 +1486,8 @@ private Completable doOnLifecycle( /** * Returns a Completable instance that calls the given onSubscribe callback with the disposable * that child subscribers receive on subscription. + * <p> + * <img width="640" height="304" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.doOnSubscribe.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1489,6 +1507,8 @@ public final Completable doOnSubscribe(Consumer<? super Disposable> onSubscribe) /** * Returns a Completable instance that calls the given onTerminate callback just before this Completable * completes normally or with an exception. + * <p> + * <img width="640" height="304" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.doOnTerminate.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnTerminate} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1508,6 +1528,8 @@ public final Completable doOnTerminate(final Action onTerminate) { /** * Returns a Completable instance that calls the given onTerminate callback after this Completable * completes normally or with an exception. + * <p> + * <img width="640" height="304" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.doAfterTerminate.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doAfterTerminate} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1530,9 +1552,13 @@ public final Completable doAfterTerminate(final Action onAfterTerminate) { /** * Calls the specified action after this Completable signals onError or onComplete or gets disposed by * the downstream. - * <p>In case of a race between a terminal event and a dispose call, the provided {@code onFinally} action + * <p> + * <img width="640" height="331" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.doFinally.png" alt=""> + * <p> + * In case of a race between a terminal event and a dispose call, the provided {@code onFinally} action * is executed once per subscription. - * <p>Note that the {@code onFinally} action is shared between subscriptions and as such + * <p> + * Note that the {@code onFinally} action is shared between subscriptions and as such * should be thread-safe. * <dl> * <dt><b>Scheduler:</b></dt> @@ -1688,6 +1714,8 @@ public final Completable lift(final CompletableOperator onLift) { /** * Returns a Completable which subscribes to this and the other Completable and completes * when both of them complete or one emits an error. + * <p> + * <img width="640" height="442" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.mergeWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1705,6 +1733,8 @@ public final Completable mergeWith(CompletableSource other) { /** * Returns a Completable which emits the terminal events from the thread of the specified scheduler. + * <p> + * <img width="640" height="523" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.observeOn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code observeOn} operates on a {@link Scheduler} you specify.</dd> @@ -1723,6 +1753,8 @@ public final Completable observeOn(final Scheduler scheduler) { /** * Returns a Completable instance that if this Completable emits an error, it will emit an onComplete * and swallow the throwable. + * <p> + * <img width="640" height="585" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.onErrorComplete.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorComplete} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1738,6 +1770,8 @@ public final Completable onErrorComplete() { /** * Returns a Completable instance that if this Completable emits an error and the predicate returns * true, it will emit an onComplete and swallow the throwable. + * <p> + * <img width="640" height="283" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.onErrorComplete.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorComplete} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1758,6 +1792,8 @@ public final Completable onErrorComplete(final Predicate<? super Throwable> pred * Returns a Completable instance that when encounters an error from this Completable, calls the * specified mapper function that returns another Completable instance for it and resumes the * execution with it. + * <p> + * <img width="640" height="426" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.onErrorResumeNext.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1776,6 +1812,8 @@ public final Completable onErrorResumeNext(final Function<? super Throwable, ? e /** * Nulls out references to the upstream producer and downstream CompletableObserver if * the sequence is terminated or downstream calls dispose(). + * <p> + * <img width="640" height="326" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.onTerminateDetach.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2050,8 +2088,10 @@ public final <T> Flowable<T> startWith(Publisher<T> other) { /** * Hides the identity of this Completable and its Disposable. - * <p>Allows preventing certain identity-based - * optimizations (fusion). + * <p> + * <img width="640" height="432" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.hide.png" alt=""> + * <p> + * Allows preventing certain identity-based optimizations (fusion). * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code hide} does not operate by default on a particular {@link Scheduler}.</dd> From 8b9740840f21d131595dac2115241b1f739b03f2 Mon Sep 17 00:00:00 2001 From: akarnokd <akarnokd@gmail.com> Date: Thu, 19 Jul 2018 15:20:26 +0200 Subject: [PATCH 232/417] 2.x: Fix aspect of some Completable marbles. --- src/main/java/io/reactivex/Completable.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 06a9cd79da..de9f021277 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -511,7 +511,7 @@ public static <T> Completable fromObservable(final ObservableSource<T> observabl * Returns a Completable instance that subscribes to the given publisher, ignores all values and * emits only the terminal event. * <p> - * <img width="640" height="442" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromPublisher.png" alt=""> + * <img width="640" height="422" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromPublisher.png" alt=""> * <p> * The {@link Publisher} must follow the * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive-Streams specification</a>. @@ -2427,8 +2427,6 @@ public final <T> Flowable<T> toFlowable() { /** * Converts this Completable into a {@link Maybe}. - * <p> - * <img width="640" height="293" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.toObservable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toMaybe} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2451,6 +2449,8 @@ public final <T> Maybe<T> toMaybe() { /** * Returns an Observable which when subscribed to subscribes to this Completable and * relays the terminal events to the subscriber. + * <p> + * <img width="640" height="293" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.toObservable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toObservable} does not operate by default on a particular {@link Scheduler}.</dd> From a80b657e2dfa213061ea43ffa1e6096ef319d3a8 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 19 Jul 2018 16:11:01 +0200 Subject: [PATCH 233/417] 2.x: Several more Completable marbles (7/19b) (#6098) --- src/main/java/io/reactivex/Completable.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index de9f021277..42ae598e35 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -2230,6 +2230,8 @@ public final Disposable subscribe(final Action onComplete) { /** * Returns a Completable which subscribes the child subscriber on the specified scheduler, making * sure the subscription side-effects happen on that specific thread of the scheduler. + * <p> + * <img width="640" height="686" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.subscribeOn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribeOn} operates on a {@link Scheduler} you specify.</dd> @@ -2405,6 +2407,8 @@ public final <U> U to(Function<? super Completable, U> converter) { /** * Returns a Flowable which when subscribed to subscribes to this Completable and * relays the terminal events to the subscriber. + * <p> + * <img width="640" height="585" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.toFlowable.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -2427,6 +2431,8 @@ public final <T> Flowable<T> toFlowable() { /** * Converts this Completable into a {@link Maybe}. + * <p> + * <img width="640" height="585" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.toMaybe.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toMaybe} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2471,6 +2477,8 @@ public final <T> Observable<T> toObservable() { /** * Converts this Completable into a Single which when this Completable completes normally, * calls the given supplier and emits its returned value through onSuccess. + * <p> + * <img width="640" height="583" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.toSingle.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toSingle} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2490,6 +2498,8 @@ public final <T> Single<T> toSingle(final Callable<? extends T> completionValueS /** * Converts this Completable into a Single which when this Completable completes normally, * emits the given value through onSuccess. + * <p> + * <img width="640" height="583" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.toSingleDefault.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toSingleDefault} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2509,6 +2519,8 @@ public final <T> Single<T> toSingleDefault(final T completionValue) { /** * Returns a Completable which makes sure when a subscriber cancels the subscription, the * dispose is called on the specified scheduler. + * <p> + * <img width="640" height="716" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.unsubscribeOn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.</dd> From ca5119cde5b5761d12d0c8071f17f1b2406971c4 Mon Sep 17 00:00:00 2001 From: Jason Neufeld <jneufeld@google.com> Date: Thu, 19 Jul 2018 12:54:37 -0700 Subject: [PATCH 234/417] Update TestHelper.java: trivial typo fix (#6099) --- src/test/java/io/reactivex/TestHelper.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/io/reactivex/TestHelper.java b/src/test/java/io/reactivex/TestHelper.java index 60a7fdfd81..6ac1e5cc75 100644 --- a/src/test/java/io/reactivex/TestHelper.java +++ b/src/test/java/io/reactivex/TestHelper.java @@ -482,7 +482,7 @@ public static <E extends Enum<E>> void checkEnum(Class<E> enumClass) { } /** - * Returns an Consumer that asserts the TestSubscriber has exaclty one value + completed + * Returns an Consumer that asserts the TestSubscriber has exactly one value + completed * normally and that single value is not the value specified. * @param <T> the value type * @param value the value not expected @@ -505,7 +505,7 @@ public void accept(TestSubscriber<T> ts) throws Exception { } /** - * Returns an Consumer that asserts the TestObserver has exaclty one value + completed + * Returns an Consumer that asserts the TestObserver has exactly one value + completed * normally and that single value is not the value specified. * @param <T> the value type * @param value the value not expected From f4a18fdb9b7ccb9cd868aaf1e31605df55046230 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 20 Jul 2018 13:15:09 +0200 Subject: [PATCH 235/417] 2.x: Final set of missing Completable marbles (#6101) --- src/main/java/io/reactivex/Completable.java | 52 +++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 42ae598e35..d00cd9b451 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -264,6 +264,8 @@ public static Completable concat(Publisher<? extends CompletableSource> sources, /** * Provides an API (via a cold Completable) that bridges the reactive world with the callback-style world. * <p> + * <img width="640" height="442" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.create.png" alt=""> + * <p> * Example: * <pre><code> * Completable.create(emitter -> { @@ -305,6 +307,8 @@ public static Completable create(CompletableOnSubscribe source) { * Constructs a Completable instance by wrapping the given source callback * <strong>without any safeguards; you should manage the lifecycle and response * to downstream cancellation/dispose</strong>. + * <p> + * <img width="640" height="260" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.unsafeCreate.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code unsafeCreate} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1585,6 +1589,8 @@ public final Completable doFinally(Action onFinally) { * and providing a new {@code CompletableObserver}, containing the custom operator's intended business logic, that will be * used in the subscription process going further upstream. * <p> + * <img width="640" height="313" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.lift.png" alt=""> + * <p> * Generally, such a new {@code CompletableObserver} will wrap the downstream's {@code CompletableObserver} and forwards the * {@code onError} and {@code onComplete} events from the upstream directly or according to the * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the @@ -1831,6 +1837,8 @@ public final Completable onTerminateDetach() { /** * Returns a Completable that repeatedly subscribes to this Completable until cancelled. + * <p> + * <img width="640" height="373" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.repeat.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeat} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1845,6 +1853,8 @@ public final Completable repeat() { /** * Returns a Completable that subscribes repeatedly at most the given times to this Completable. + * <p> + * <img width="640" height="408" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.repeat.n.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeat} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1862,6 +1872,8 @@ public final Completable repeat(long times) { /** * Returns a Completable that repeatedly subscribes to this Completable so long as the given * stop supplier returns false. + * <p> + * <img width="640" height="381" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.repeatUntil.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeatUntil} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1879,6 +1891,8 @@ public final Completable repeatUntil(BooleanSupplier stop) { /** * Returns a Completable instance that repeats when the Publisher returned by the handler * emits an item or completes when this Publisher emits a completed event. + * <p> + * <img width="640" height="586" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.repeatWhen.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeatWhen} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1897,6 +1911,8 @@ public final Completable repeatWhen(Function<? super Flowable<Object>, ? extends /** * Returns a Completable that retries this Completable as long as it emits an onError event. + * <p> + * <img width="640" height="368" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.retry.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1912,6 +1928,8 @@ public final Completable retry() { /** * Returns a Completable that retries this Completable in case of an error as long as the predicate * returns true. + * <p> + * <img width="640" height="325" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.retry.ff.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1929,6 +1947,8 @@ public final Completable retry(BiPredicate<? super Integer, ? super Throwable> p /** * Returns a Completable that when this Completable emits an error, retries at most the given * number of times before giving up and emitting the last error. + * <p> + * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.retry.n.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1946,6 +1966,8 @@ public final Completable retry(long times) { /** * Returns a Completable that when this Completable emits an error, retries at most times * or until the predicate returns false, whichever happens first and emitting the last error. + * <p> + * <img width="640" height="361" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.retry.nf.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1968,6 +1990,8 @@ public final Completable retry(long times, Predicate<? super Throwable> predicat /** * Returns a Completable that when this Completable emits an error, calls the given predicate with * the latest exception to decide whether to resubscribe to this or not. + * <p> + * <img width="640" height="336" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.retry.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1988,6 +2012,8 @@ public final Completable retry(Predicate<? super Throwable> predicate) { * that error through a Flowable and the Publisher should signal a value indicating a retry in response * or a terminal event indicating a termination. * <p> + * <img width="640" height="586" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.retryWhen.png" alt=""> + * <p> * Note that the inner {@code Publisher} returned by the handler function should signal * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to @@ -2030,6 +2056,8 @@ public final Completable retryWhen(Function<? super Flowable<Throwable>, ? exten /** * Returns a Completable which first runs the other Completable * then this completable if the other completed normally. + * <p> + * <img width="640" height="437" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.startWith.c.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2048,6 +2076,8 @@ public final Completable startWith(CompletableSource other) { /** * Returns an Observable which first delivers the events * of the other Observable then runs this CompletableConsumable. + * <p> + * <img width="640" height="289" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.startWith.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2066,6 +2096,8 @@ public final <T> Observable<T> startWith(Observable<T> other) { /** * Returns a Flowable which first delivers the events * of the other Publisher then runs this Completable. + * <p> + * <img width="640" height="250" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.startWith.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer @@ -2109,6 +2141,8 @@ public final Completable hide() { /** * Subscribes to this CompletableConsumable and returns a Disposable which can be used to cancel * the subscription. + * <p> + * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.subscribe.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2153,6 +2187,8 @@ public final void subscribe(CompletableObserver s) { /** * Subscribes a given CompletableObserver (subclass) to this Completable and returns the given * CompletableObserver as is. + * <p> + * <img width="640" height="349" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.subscribeWith.png" alt=""> * <p>Usage example: * <pre><code> * Completable source = Completable.complete().delay(1, TimeUnit.SECONDS); @@ -2183,6 +2219,8 @@ public final <E extends CompletableObserver> E subscribeWith(E observer) { /** * Subscribes to this Completable and calls back either the onError or onComplete functions. + * <p> + * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.subscribe.ff.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2207,6 +2245,8 @@ public final Disposable subscribe(final Action onComplete, final Consumer<? supe * Subscribes to this Completable and calls the given Action when this Completable * completes normally. * <p> + * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.subscribe.f.png" alt=""> + * <p> * If the Completable emits an error, it is wrapped into an * {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} * and routed to the RxJavaPlugins.onError handler. @@ -2277,6 +2317,8 @@ public final Completable takeUntil(CompletableSource other) { /** * Returns a Completable that runs this Completable and emits a TimeoutException in case * this Completable doesn't complete within the given time. + * <p> + * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.timeout.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} signals the TimeoutException on the {@code computation} {@link Scheduler}.</dd> @@ -2295,6 +2337,8 @@ public final Completable timeout(long timeout, TimeUnit unit) { /** * Returns a Completable that runs this Completable and switches to the other Completable * in case this Completable doesn't complete within the given time. + * <p> + * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.timeout.c.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} subscribes to the other CompletableSource on @@ -2317,6 +2361,8 @@ public final Completable timeout(long timeout, TimeUnit unit, CompletableSource * Returns a Completable that runs this Completable and emits a TimeoutException in case * this Completable doesn't complete within the given time while "waiting" on the specified * Scheduler. + * <p> + * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.timeout.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} signals the TimeoutException on the {@link Scheduler} you specify.</dd> @@ -2337,6 +2383,8 @@ public final Completable timeout(long timeout, TimeUnit unit, Scheduler schedule * Returns a Completable that runs this Completable and switches to the other Completable * in case this Completable doesn't complete within the given time while "waiting" on * the specified scheduler. + * <p> + * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.timeout.sc.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} subscribes to the other CompletableSource on @@ -2542,6 +2590,8 @@ public final Completable unsubscribeOn(final Scheduler scheduler) { /** * Creates a TestObserver and subscribes * it to this Completable. + * <p> + * <img width="640" height="458" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.test.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code test} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2561,6 +2611,8 @@ public final TestObserver<Void> test() { * Creates a TestObserver optionally in cancelled state, then subscribes it to this Completable. * @param cancelled if true, the TestObserver will be cancelled before subscribing to this * Completable. + * <p> + * <img width="640" height="499" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.test.b.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code test} does not operate by default on a particular {@link Scheduler}.</dd> From 4c89100dbb237c4d549ec503d5ef6bbee802ae9d Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 20 Jul 2018 14:26:44 +0200 Subject: [PATCH 236/417] 2.x: Adjust JavaDoc stylesheet of dt/dd within the method details (#6102) --- gradle/stylesheet.css | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gradle/stylesheet.css b/gradle/stylesheet.css index 52b6b690b0..5e381dce8b 100644 --- a/gradle/stylesheet.css +++ b/gradle/stylesheet.css @@ -284,10 +284,10 @@ Page layout container styles margin:10px 0 0 0; color:#4E4E4E; } -/*.contentContainer .description dl dd, */.contentContainer .details dl dd, .serializedFormContainer dl dd { - margin:5px 0 10px 0px; +.contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd { + /* margin:5px 0 10px 0px; */ font-size:14px; - font-family:'DejaVu Sans Mono',monospace; + font-family:'DejaVu Serif', Georgia, "Times New Roman", Times, serif; } .serializedFormContainer dl.nameValue dt { margin-left:1px; From c5a42a273836c4d1f87d07843bef2789354ac710 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 20 Jul 2018 14:44:11 +0200 Subject: [PATCH 237/417] 2.x: Fix Completable mergeX JavaDoc missing dt before dd (#6103) --- src/main/java/io/reactivex/Completable.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index d00cd9b451..08485ee3f5 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -577,6 +577,7 @@ public static <T> Completable fromSingle(final SingleSource<T> single) { * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeArray} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the @@ -653,6 +654,7 @@ public static Completable merge(Iterable<? extends CompletableSource> sources) { * and expects the other {@code Publisher} to honor it as well.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the @@ -689,6 +691,7 @@ public static Completable merge(Publisher<? extends CompletableSource> sources) * and expects the other {@code Publisher} to honor it as well.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the From 0155b69866f07f02902674c1d57311d273f4325c Mon Sep 17 00:00:00 2001 From: lcybo <chuanyili0625@gmail.com> Date: Sun, 22 Jul 2018 19:26:52 +0800 Subject: [PATCH 238/417] Fixing javadoc's code example of Observable#lift. (#6104) --- src/main/java/io/reactivex/Observable.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index c74ab3f7d4..a3f204206b 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -9414,7 +9414,7 @@ public final Single<T> lastOrError() { * @Override * public void onSubscribe(Disposable s) { * if (upstream != null) { - * s.cancel(); + * s.dispose(); * } else { * upstream = s; * downstream.onSubscribe(this); @@ -9473,10 +9473,10 @@ public final Single<T> lastOrError() { * // Such class may define additional parameters to be submitted to * // the custom consumer type. * - * final class CustomOperator<T> implements ObservableOperator<String> { + * final class CustomOperator<T> implements ObservableOperator<String, T> { * @Override - * public Observer<? super String> apply(Observer<? super T> upstream) { - * return new CustomObserver<T>(upstream); + * public Observer<T> apply(Observer<? super String> downstream) { + * return new CustomObserver<T>(downstream); * } * } * From ce5ce4bbb2e2da38d0098d228cc81812f430f44c Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 23 Jul 2018 09:21:10 +0200 Subject: [PATCH 239/417] Release 2.1.17 --- CHANGES.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 91bd6b465c..2312403710 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,40 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.1.17 - July 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.17%7C)) + +#### API changes + + - [Pull 6079](https://github.com/ReactiveX/RxJava/pull/6079): Add `Completable.takeUntil(Completable)` operator. + - [Pull 6085](https://github.com/ReactiveX/RxJava/pull/6085): Add `Completable.fromMaybe` operator. + +#### Performance improvements + + - [Pull 6096](https://github.com/ReactiveX/RxJava/pull/6096): Improve `Completable.delay` operator internals. + +#### Documentation changes +- [Pull 6066](https://github.com/ReactiveX/RxJava/pull/6066): Fix links for `Single` class. +- [Pull 6070](https://github.com/ReactiveX/RxJava/pull/6070): Adjust JavaDocs `dl`/`dd` entry stylesheet. +- [Pull 6080](https://github.com/ReactiveX/RxJava/pull/6080): Improve class JavaDoc of `Single`, `Maybe` and `Completable`. +- [Pull 6102](https://github.com/ReactiveX/RxJava/pull/6102): Adjust JavaDoc stylesheet of `dt`/`dd` within the method details. +- [Pull 6103](https://github.com/ReactiveX/RxJava/pull/6103): Fix `Completable` `mergeX` JavaDoc missing `dt` before `dd`. +- [Pull 6104](https://github.com/ReactiveX/RxJava/pull/6104): Fixing javadoc's code example of `Observable#lift`. +- Marble diagrams ([Tracking issue 5789](https://github.com/ReactiveX/RxJava/issues/5789)) + - [Pull 6074](https://github.com/ReactiveX/RxJava/pull/6074): `Single.never` method. + - [Pull 6075](https://github.com/ReactiveX/RxJava/pull/6075): `Single.filter` method. + - [Pull 6078](https://github.com/ReactiveX/RxJava/pull/6078): `Maybe.hide` marble diagram. + - [Pull 6076](https://github.com/ReactiveX/RxJava/pull/6076): `Single.delay` method. + - [Pull 6077](https://github.com/ReactiveX/RxJava/pull/6077): `Single.hide` operator. + - [Pull 6083](https://github.com/ReactiveX/RxJava/pull/6083): Add `Completable` marble diagrams (07/17a). + - [Pull 6081](https://github.com/ReactiveX/RxJava/pull/6081): `Single.repeat` operators. + - [Pull 6085](https://github.com/ReactiveX/RxJava/pull/6085): More `Completable` marbles. + - [Pull 6084](https://github.com/ReactiveX/RxJava/pull/6084): `Single.repeatUntil` operator. + - [Pull 6090](https://github.com/ReactiveX/RxJava/pull/6090): Add missing `Completable` marbles (+17, 07/18a). + - [Pull 6091](https://github.com/ReactiveX/RxJava/pull/6091): `Single.amb` operators. + - [Pull 6097](https://github.com/ReactiveX/RxJava/pull/6097): Add missing `Completable` marbles (+19, 07/19a). + - [Pull 6098](https://github.com/ReactiveX/RxJava/pull/6098): Several more `Completable` marbles (7/19b). + - [Pull 6101](https://github.com/ReactiveX/RxJava/pull/6101): Final set of missing `Completable` marbles (+26). + ### Version 2.1.16 - June 26, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.16%7C)) This is a hotfix release for a late-identified issue with `concatMapMaybe` and `concatMapSingle`. From e8930c2830869f1089ac7627dda044e8d861fb6b Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 30 Jul 2018 15:56:37 +0200 Subject: [PATCH 240/417] 2.x: Promote all Experimental/Beta API to standard (#6105) --- src/main/java/io/reactivex/Completable.java | 19 +- .../io/reactivex/CompletableConverter.java | 5 +- .../java/io/reactivex/CompletableEmitter.java | 4 +- src/main/java/io/reactivex/Flowable.java | 179 ++++++++---------- .../java/io/reactivex/FlowableConverter.java | 5 +- .../java/io/reactivex/FlowableEmitter.java | 4 +- .../java/io/reactivex/FlowableSubscriber.java | 5 +- src/main/java/io/reactivex/Maybe.java | 15 +- .../java/io/reactivex/MaybeConverter.java | 5 +- src/main/java/io/reactivex/MaybeEmitter.java | 4 +- src/main/java/io/reactivex/Observable.java | 136 +++++++------ .../io/reactivex/ObservableConverter.java | 5 +- .../java/io/reactivex/ObservableEmitter.java | 4 +- src/main/java/io/reactivex/Single.java | 50 +++-- .../java/io/reactivex/SingleConverter.java | 5 +- src/main/java/io/reactivex/SingleEmitter.java | 4 +- .../annotations/SchedulerSupport.java | 4 +- .../OnErrorNotImplementedException.java | 5 +- .../ProtocolViolationException.java | 7 +- .../exceptions/UndeliverableException.java | 7 +- .../flowables/ConnectableFlowable.java | 20 +- .../completable/CompletableCache.java | 6 +- .../completable/CompletableDetach.java | 6 +- .../completable/CompletableDoFinally.java | 6 +- .../CompletableTakeUntilCompletable.java | 5 +- .../FlowableConcatMapEagerPublisher.java | 3 +- .../FlowableConcatWithCompletable.java | 3 +- .../flowable/FlowableConcatWithMaybe.java | 3 +- .../flowable/FlowableConcatWithSingle.java | 3 +- .../flowable/FlowableDoAfterNext.java | 4 +- .../operators/flowable/FlowableDoFinally.java | 5 +- .../operators/flowable/FlowableLimit.java | 6 +- .../flowable/FlowableMapPublisher.java | 4 +- .../FlowableMergeWithCompletable.java | 4 +- .../flowable/FlowableMergeWithMaybe.java | 4 +- .../flowable/FlowableMergeWithSingle.java | 4 +- .../flowable/FlowableTakePublisher.java | 4 +- .../flowable/FlowableThrottleLatest.java | 6 +- .../operators/maybe/MaybeDoAfterSuccess.java | 5 +- .../operators/maybe/MaybeDoFinally.java | 6 +- .../maybe/MaybeFlatMapSingleElement.java | 6 +- .../operators/maybe/MaybeToObservable.java | 5 +- .../mixed/FlowableConcatMapCompletable.java | 5 +- .../mixed/FlowableConcatMapMaybe.java | 7 +- .../mixed/FlowableConcatMapSingle.java | 7 +- .../mixed/FlowableSwitchMapCompletable.java | 6 +- .../mixed/FlowableSwitchMapMaybe.java | 6 +- .../mixed/FlowableSwitchMapSingle.java | 6 +- .../mixed/ObservableConcatMapCompletable.java | 5 +- .../mixed/ObservableConcatMapMaybe.java | 7 +- .../mixed/ObservableConcatMapSingle.java | 7 +- .../mixed/ObservableSwitchMapCompletable.java | 6 +- .../mixed/ObservableSwitchMapMaybe.java | 6 +- .../mixed/ObservableSwitchMapSingle.java | 6 +- .../operators/mixed/ScalarXMapZHelper.java | 5 +- .../ObservableConcatWithCompletable.java | 3 +- .../observable/ObservableConcatWithMaybe.java | 3 +- .../ObservableConcatWithSingle.java | 3 +- .../observable/ObservableDoAfterNext.java | 5 +- .../observable/ObservableDoFinally.java | 6 +- .../ObservableMergeWithCompletable.java | 4 +- .../observable/ObservableMergeWithMaybe.java | 4 +- .../observable/ObservableMergeWithSingle.java | 4 +- .../observable/ObservableThrottleLatest.java | 6 +- .../parallel/ParallelDoOnNextTry.java | 4 +- .../operators/parallel/ParallelMapTry.java | 4 +- .../operators/single/SingleDetach.java | 6 +- .../single/SingleDoAfterSuccess.java | 5 +- .../single/SingleDoAfterTerminate.java | 3 +- .../operators/single/SingleDoFinally.java | 6 +- .../operators/single/SingleToObservable.java | 5 +- .../SchedulerMultiWorkerSupport.java | 5 +- .../internal/schedulers/SchedulerWhen.java | 4 +- .../observables/ConnectableObservable.java | 20 +- .../reactivex/observers/BaseTestConsumer.java | 56 +++--- .../LambdaConsumerIntrospection.java | 9 +- .../parallel/ParallelFailureHandling.java | 5 +- .../reactivex/parallel/ParallelFlowable.java | 43 ++--- .../parallel/ParallelFlowableConverter.java | 5 +- .../parallel/ParallelTransformer.java | 6 +- .../io/reactivex/plugins/RxJavaPlugins.java | 15 +- .../processors/BehaviorProcessor.java | 4 +- .../processors/MulticastProcessor.java | 4 +- .../processors/PublishProcessor.java | 4 +- .../reactivex/processors/ReplayProcessor.java | 4 +- .../processors/UnicastProcessor.java | 13 +- .../SchedulerRunnableIntrospection.java | 5 +- .../io/reactivex/subjects/ReplaySubject.java | 4 +- .../io/reactivex/subjects/UnicastSubject.java | 17 +- 89 files changed, 428 insertions(+), 535 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 08485ee3f5..8993524b46 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -458,10 +458,12 @@ public static Completable fromFuture(final Future<?> future) { * <dt><b>Scheduler:</b></dt> * <dd>{@code fromMaybe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.17 - beta * @param <T> the value type of the {@link MaybeSource} element * @param maybe the Maybe instance to subscribe to, not null * @return the new Completable instance * @throws NullPointerException if single is null + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -1138,14 +1140,13 @@ public final Completable andThen(CompletableSource next) { * <dt><b>Scheduler:</b></dt> * <dd>{@code as} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.7 - experimental * @param <R> the resulting object type * @param converter the function that receives the current Completable instance and returns a value * @return the converted value * @throws NullPointerException if converter is null - * @since 2.1.7 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final <R> R as(@NonNull CompletableConverter<? extends R> converter) { @@ -1827,11 +1828,11 @@ public final Completable onErrorResumeNext(final Function<? super Throwable, ? e * <dt><b>Scheduler:</b></dt> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.5 - experimental * @return a Completable which nulls out references to the upstream producer and downstream CompletableObserver if * the sequence is terminated or downstream calls dispose() - * @since 2.1.5 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Completable onTerminateDetach() { @@ -1975,15 +1976,15 @@ public final Completable retry(long times) { * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.8 - experimental * @param times the number of times the returned Completable should retry this Completable * @param predicate the predicate that is called with the latest throwable and should return * true to indicate the returned Completable should resubscribe to this Completable. * @return the new Completable instance * @throws NullPointerException if predicate is null * @throws IllegalArgumentException if times is negative - * @since 2.1.8 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Completable retry(long times, Predicate<? super Throwable> predicate) { @@ -2304,12 +2305,12 @@ public final Completable subscribeOn(final Scheduler scheduler) { * is signaled to the downstream and the other error is signaled to the global * error handler via {@link RxJavaPlugins#onError(Throwable)}.</dd> * </dl> + * <p>History: 2.1.17 - experimental * @param other the other completable source to observe for the terminal signals * @return the new Completable instance - * @since 2.1.17 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.NONE) public final Completable takeUntil(CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); diff --git a/src/main/java/io/reactivex/CompletableConverter.java b/src/main/java/io/reactivex/CompletableConverter.java index 39ec9b452b..1bea8631c8 100644 --- a/src/main/java/io/reactivex/CompletableConverter.java +++ b/src/main/java/io/reactivex/CompletableConverter.java @@ -18,11 +18,10 @@ /** * Convenience interface and callback used by the {@link Completable#as} operator to turn a Completable into another * value fluently. - * + * <p>History: 2.1.7 - experimental * @param <R> the output type - * @since 2.1.7 - experimental + * @since 2.2 */ -@Experimental public interface CompletableConverter<R> { /** * Applies a function to the upstream Completable and returns a converted value of type {@code R}. diff --git a/src/main/java/io/reactivex/CompletableEmitter.java b/src/main/java/io/reactivex/CompletableEmitter.java index 7a8d2e1e75..b32e329c3b 100644 --- a/src/main/java/io/reactivex/CompletableEmitter.java +++ b/src/main/java/io/reactivex/CompletableEmitter.java @@ -88,11 +88,11 @@ public interface CompletableEmitter { * <p> * Unlike {@link #onError(Throwable)}, the {@code RxJavaPlugins.onError} is not called * if the error could not be delivered. + * <p>History: 2.1.1 - experimental * @param t the throwable error to signal if possible * @return true if successful, false if the downstream is not able to accept further * events - * @since 2.1.1 - experimental + * @since 2.2 */ - @Experimental boolean tryOnError(@NonNull Throwable t); } diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 04a31f471d..84d4e6bba5 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -5392,14 +5392,13 @@ public final Single<Boolean> any(Predicate<? super T> predicate) { * <dt><b>Scheduler:</b></dt> * <dd>{@code as} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.7 - experimental * @param <R> the resulting object type * @param converter the function that receives the current Flowable instance and returns a value * @return the converted value * @throws NullPointerException if converter is null - * @since 2.1.7 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) @@ -5870,15 +5869,15 @@ public final void blockingSubscribe(Consumer<? super T> onNext) { * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.15 - experimental * @param onNext the callback action for each source value * @param bufferSize the size of the buffer - * @since 2.1.15 - experimental * @see #blockingSubscribe(Consumer, Consumer) * @see #blockingSubscribe(Consumer, Consumer, Action) + * @since 2.2 */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final void blockingSubscribe(Consumer<? super T> onNext, int bufferSize) { FlowableBlockingSubscribe.subscribe(this, onNext, Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION, bufferSize); } @@ -5920,15 +5919,15 @@ public final void blockingSubscribe(Consumer<? super T> onNext, Consumer<? super * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.15 - experimental * @param onNext the callback action for each source value * @param onError the callback action for an error event * @param bufferSize the size of the buffer - * @since 2.1.15 - experimental + * @since 2.2 * @see #blockingSubscribe(Consumer, Consumer, Action) */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final void blockingSubscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, int bufferSize) { FlowableBlockingSubscribe.subscribe(this, onNext, onError, Functions.EMPTY_ACTION, bufferSize); @@ -5971,15 +5970,15 @@ public final void blockingSubscribe(Consumer<? super T> onNext, Consumer<? super * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.15 - experimental * @param onNext the callback action for each source value * @param onError the callback action for an error event * @param onComplete the callback action for the completion event. * @param bufferSize the size of the buffer - * @since 2.1.15 - experimental + * @since 2.2 */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final void blockingSubscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Action onComplete, int bufferSize) { FlowableBlockingSubscribe.subscribe(this, onNext, onError, onComplete, bufferSize); @@ -7067,17 +7066,17 @@ public final <R> Flowable<R> concatMap(Function<? super T, ? extends Publisher<? * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with the upstream item and should return * a {@code CompletableSource} to become the next source to * be subscribed to * @return a new Completable instance - * @since 2.1.11 - experimental * @see #concatMapCompletableDelayError(Function) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) - @Experimental public final Completable concatMapCompletable(Function<? super T, ? extends CompletableSource> mapper) { return concatMapCompletable(mapper, 2); } @@ -7094,6 +7093,7 @@ public final Completable concatMapCompletable(Function<? super T, ? extends Comp * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with the upstream item and should return * a {@code CompletableSource} to become the next source to * be subscribed to @@ -7102,13 +7102,12 @@ public final Completable concatMapCompletable(Function<? super T, ? extends Comp * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code CompletableSource}s. * @return a new Completable instance - * @since 2.1.11 - experimental * @see #concatMapCompletableDelayError(Function, boolean, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) - @Experimental public final Completable concatMapCompletable(Function<? super T, ? extends CompletableSource> mapper, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -7128,17 +7127,17 @@ public final Completable concatMapCompletable(Function<? super T, ? extends Comp * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with the upstream item and should return * a {@code CompletableSource} to become the next source to * be subscribed to * @return a new Completable instance - * @since 2.1.11 - experimental * @see #concatMapCompletable(Function, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) - @Experimental public final Completable concatMapCompletableDelayError(Function<? super T, ? extends CompletableSource> mapper) { return concatMapCompletableDelayError(mapper, true, 2); } @@ -7156,6 +7155,7 @@ public final Completable concatMapCompletableDelayError(Function<? super T, ? ex * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with the upstream item and should return * a {@code CompletableSource} to become the next source to * be subscribed to @@ -7166,13 +7166,12 @@ public final Completable concatMapCompletableDelayError(Function<? super T, ? ex * {@code CompletableSource} terminates and only then is * it emitted to the downstream. * @return a new Completable instance - * @since 2.1.11 - experimental * @see #concatMapCompletable(Function) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) - @Experimental public final Completable concatMapCompletableDelayError(Function<? super T, ? extends CompletableSource> mapper, boolean tillTheEnd) { return concatMapCompletableDelayError(mapper, tillTheEnd, 2); } @@ -7190,6 +7189,7 @@ public final Completable concatMapCompletableDelayError(Function<? super T, ? ex * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with the upstream item and should return * a {@code CompletableSource} to become the next source to * be subscribed to @@ -7204,13 +7204,12 @@ public final Completable concatMapCompletableDelayError(Function<? super T, ? ex * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code CompletableSource}s. * @return a new Completable instance - * @since 2.1.11 - experimental * @see #concatMapCompletable(Function, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) - @Experimental public final Completable concatMapCompletableDelayError(Function<? super T, ? extends CompletableSource> mapper, boolean tillTheEnd, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -7495,19 +7494,19 @@ public final <U> Flowable<U> concatMapIterable(final Function<? super T, ? exten * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapMaybe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code MaybeSource}s * @param mapper the function called with the upstream item and should return * a {@code MaybeSource} to become the next source to * be subscribed to * @return a new Flowable instance - * @since 2.1.11 - experimental * @see #concatMapMaybeDelayError(Function) * @see #concatMapMaybe(Function, int) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> concatMapMaybe(Function<? super T, ? extends MaybeSource<? extends R>> mapper) { return concatMapMaybe(mapper, 2); } @@ -7526,6 +7525,7 @@ public final <R> Flowable<R> concatMapMaybe(Function<? super T, ? extends MaybeS * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapMaybe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code MaybeSource}s * @param mapper the function called with the upstream item and should return * a {@code MaybeSource} to become the next source to @@ -7535,14 +7535,13 @@ public final <R> Flowable<R> concatMapMaybe(Function<? super T, ? extends MaybeS * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code MaybeSource}s. * @return a new Flowable instance - * @since 2.1.11 - experimental * @see #concatMapMaybe(Function) * @see #concatMapMaybeDelayError(Function, boolean, int) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> concatMapMaybe(Function<? super T, ? extends MaybeSource<? extends R>> mapper, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -7563,19 +7562,19 @@ public final <R> Flowable<R> concatMapMaybe(Function<? super T, ? extends MaybeS * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code MaybeSource}s * @param mapper the function called with the upstream item and should return * a {@code MaybeSource} to become the next source to * be subscribed to * @return a new Flowable instance - * @since 2.1.11 - experimental * @see #concatMapMaybe(Function) * @see #concatMapMaybeDelayError(Function, boolean) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> concatMapMaybeDelayError(Function<? super T, ? extends MaybeSource<? extends R>> mapper) { return concatMapMaybeDelayError(mapper, true, 2); } @@ -7594,6 +7593,7 @@ public final <R> Flowable<R> concatMapMaybeDelayError(Function<? super T, ? exte * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code MaybeSource}s * @param mapper the function called with the upstream item and should return * a {@code MaybeSource} to become the next source to @@ -7605,14 +7605,13 @@ public final <R> Flowable<R> concatMapMaybeDelayError(Function<? super T, ? exte * {@code MaybeSource} terminates and only then is * it emitted to the downstream. * @return a new Flowable instance - * @since 2.1.11 - experimental * @see #concatMapMaybe(Function, int) * @see #concatMapMaybeDelayError(Function, boolean, int) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> concatMapMaybeDelayError(Function<? super T, ? extends MaybeSource<? extends R>> mapper, boolean tillTheEnd) { return concatMapMaybeDelayError(mapper, tillTheEnd, 2); } @@ -7631,6 +7630,7 @@ public final <R> Flowable<R> concatMapMaybeDelayError(Function<? super T, ? exte * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code MaybeSource}s * @param mapper the function called with the upstream item and should return * a {@code MaybeSource} to become the next source to @@ -7646,13 +7646,12 @@ public final <R> Flowable<R> concatMapMaybeDelayError(Function<? super T, ? exte * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code MaybeSource}s. * @return a new Flowable instance - * @since 2.1.11 - experimental * @see #concatMapMaybe(Function, int) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> concatMapMaybeDelayError(Function<? super T, ? extends MaybeSource<? extends R>> mapper, boolean tillTheEnd, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -7673,19 +7672,19 @@ public final <R> Flowable<R> concatMapMaybeDelayError(Function<? super T, ? exte * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code SingleSource}s * @param mapper the function called with the upstream item and should return * a {@code SingleSource} to become the next source to * be subscribed to * @return a new Flowable instance - * @since 2.1.11 - experimental * @see #concatMapSingleDelayError(Function) * @see #concatMapSingle(Function, int) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> concatMapSingle(Function<? super T, ? extends SingleSource<? extends R>> mapper) { return concatMapSingle(mapper, 2); } @@ -7704,6 +7703,7 @@ public final <R> Flowable<R> concatMapSingle(Function<? super T, ? extends Singl * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code SingleSource}s * @param mapper the function called with the upstream item and should return * a {@code SingleSource} to become the next source to @@ -7713,14 +7713,13 @@ public final <R> Flowable<R> concatMapSingle(Function<? super T, ? extends Singl * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code SingleSource}s. * @return a new Flowable instance - * @since 2.1.11 - experimental * @see #concatMapSingle(Function) * @see #concatMapSingleDelayError(Function, boolean, int) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> concatMapSingle(Function<? super T, ? extends SingleSource<? extends R>> mapper, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -7741,19 +7740,19 @@ public final <R> Flowable<R> concatMapSingle(Function<? super T, ? extends Singl * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code SingleSource}s * @param mapper the function called with the upstream item and should return * a {@code SingleSource} to become the next source to * be subscribed to * @return a new Flowable instance - * @since 2.1.11 - experimental * @see #concatMapSingle(Function) * @see #concatMapSingleDelayError(Function, boolean) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper) { return concatMapSingleDelayError(mapper, true, 2); } @@ -7772,6 +7771,7 @@ public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? ext * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code SingleSource}s * @param mapper the function called with the upstream item and should return * a {@code SingleSource} to become the next source to @@ -7783,14 +7783,13 @@ public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? ext * {@code SingleSource} terminates and only then is * it emitted to the downstream. * @return a new Flowable instance - * @since 2.1.11 - experimental * @see #concatMapSingle(Function, int) * @see #concatMapSingleDelayError(Function, boolean, int) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean tillTheEnd) { return concatMapSingleDelayError(mapper, tillTheEnd, 2); } @@ -7809,6 +7808,7 @@ public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? ext * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code SingleSource}s * @param mapper the function called with the upstream item and should return * a {@code SingleSource} to become the next source to @@ -7824,13 +7824,12 @@ public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? ext * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code SingleSource}s. * @return a new Flowable instance - * @since 2.1.11 - experimental * @see #concatMapSingle(Function, int) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean tillTheEnd, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -7877,14 +7876,14 @@ public final Flowable<T> concatWith(Publisher<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code concatWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.10 - experimental * @param other the SingleSource whose signal should be emitted after this {@code Flowable} completes normally. * @return the new Flowable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Flowable<T> concatWith(@NonNull SingleSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new FlowableConcatWithSingle<T>(this, other)); @@ -7902,14 +7901,14 @@ public final Flowable<T> concatWith(@NonNull SingleSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code concatWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.10 - experimental * @param other the MaybeSource whose signal should be emitted after this Flowable completes normally. * @return the new Flowable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Flowable<T> concatWith(@NonNull MaybeSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new FlowableConcatWithMaybe<T>(this, other)); @@ -7929,14 +7928,14 @@ public final Flowable<T> concatWith(@NonNull MaybeSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code concatWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.10 - experimental * @param other the {@code CompletableSource} to subscribe to once the current {@code Flowable} completes normally * @return the new Flowable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Flowable<T> concatWith(@NonNull CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new FlowableConcatWithCompletable<T>(this, other)); @@ -10468,7 +10467,7 @@ public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, * <dt><b>Scheduler:</b></dt> * <dd>{@code groupBy} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.10 - beta * @param keySelector * a function that extracts the key for each item * @param valueSelector @@ -10493,12 +10492,11 @@ public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, * key value * @see <a href="http://reactivex.io/documentation/operators/groupby.html">ReactiveX operators documentation: GroupBy</a> * - * @since 2.1.10 + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Beta public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, ? extends K> keySelector, Function<? super T, ? extends V> valueSelector, boolean delayError, int bufferSize, @@ -10936,16 +10934,15 @@ public final <R> Flowable<R> lift(FlowableOperator<? extends R, ? super T> lifte * <dt><b>Scheduler:</b></dt> * <dd>{@code limit} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - + * <p>History: 2.1.6 - experimental * @param count the maximum number of items and the total request amount, non-negative. * Zero will immediately cancel the upstream on subscription and complete * the downstream. * @return the new Flowable instance * @see #take(long) * @see #rebatchRequests(int) - * @since 2.1.6 - experimental + * @since 2.2 */ - @Experimental @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue @@ -11050,15 +11047,14 @@ public final Flowable<T> mergeWith(Publisher<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.10 - experimental * @param other the {@code SingleSource} whose success value to merge with * @return the new Flowable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Flowable<T> mergeWith(@NonNull SingleSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new FlowableMergeWithSingle<T>(this, other)); @@ -11079,15 +11075,14 @@ public final Flowable<T> mergeWith(@NonNull SingleSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.10 - experimental * @param other the {@code MaybeSource} which provides a success value to merge with or completes * @return the new Flowable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Flowable<T> mergeWith(@NonNull MaybeSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new FlowableMergeWithMaybe<T>(this, other)); @@ -11105,15 +11100,14 @@ public final Flowable<T> mergeWith(@NonNull MaybeSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.10 - experimental * @param other the {@code CompletableSource} to await for completion * @return the new Flowable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Flowable<T> mergeWith(@NonNull CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new FlowableMergeWithCompletable<T>(this, other)); @@ -11842,14 +11836,13 @@ public final Flowable<T> onTerminateDetach() { * <dt><b>Scheduler:</b></dt> * <dd>{@code parallel} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * <p>History: 2.0.5 - experimental + * <p>History: 2.0.5 - experimental; 2.1 - beta * @return the new ParallelFlowable instance - * @since 2.1 - beta + * @since 2.2 */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue - @Beta public final ParallelFlowable<T> parallel() { return ParallelFlowable.from(this); } @@ -11872,15 +11865,14 @@ public final ParallelFlowable<T> parallel() { * <dt><b>Scheduler:</b></dt> * <dd>{@code parallel} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * <p>History: 2.0.5 - experimental + * <p>History: 2.0.5 - experimental; 2.1 - beta * @param parallelism the number of 'rails' to use * @return the new ParallelFlowable instance - * @since 2.1 - beta + * @since 2.2 */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue - @Beta public final ParallelFlowable<T> parallel(int parallelism) { ObjectHelper.verifyPositive(parallelism, "parallelism"); return ParallelFlowable.from(this, parallelism); @@ -11905,16 +11897,15 @@ public final ParallelFlowable<T> parallel(int parallelism) { * <dt><b>Scheduler:</b></dt> * <dd>{@code parallel} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * <p>History: 2.0.5 - experimental + * <p>History: 2.0.5 - experimental; 2.1 - beta * @param parallelism the number of 'rails' to use * @param prefetch the number of items each 'rail' should prefetch * @return the new ParallelFlowable instance - * @since 2.1 - beta + * @since 2.2 */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue - @Beta public final ParallelFlowable<T> parallel(int parallelism, int prefetch) { ObjectHelper.verifyPositive(parallelism, "parallelism"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -14402,13 +14393,12 @@ public final void subscribe(Subscriber<? super T> s) { * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * <p>History: 2.0.7 - experimental + * <p>History: 2.0.7 - experimental; 2.1 - beta * @param s the FlowableSubscriber that will consume signals from this Flowable - * @since 2.1 - beta + * @since 2.2 */ @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) - @Beta public final void subscribe(FlowableSubscriber<? super T> s) { ObjectHelper.requireNonNull(s, "s is null"); try { @@ -14525,7 +14515,7 @@ public final Flowable<T> subscribeOn(@NonNull Scheduler scheduler) { * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> * </dl> - * + * <p>History: 2.1.1 - experimental * @param scheduler * the {@link Scheduler} to perform subscription actions on * @param requestOn if true, requests are rerouted to the given Scheduler as well (strong pipelining) @@ -14536,12 +14526,11 @@ public final Flowable<T> subscribeOn(@NonNull Scheduler scheduler) { * @see <a href="http://reactivex.io/documentation/operators/subscribeon.html">ReactiveX operators documentation: SubscribeOn</a> * @see <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a> * @see #observeOn - * @since 2.1.1 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.CUSTOM) - @Experimental public final Flowable<T> subscribeOn(@NonNull Scheduler scheduler, boolean requestOn) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new FlowableSubscribeOn<T>(this, scheduler, requestOn)); @@ -14675,17 +14664,17 @@ public final <R> Flowable<R> switchMap(Function<? super T, ? extends Publisher<? * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. * </dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with each upstream item and should return a * {@link CompletableSource} to be subscribed to and awaited for * (non blockingly) for its terminal event * @return the new Completable instance - * @since 2.1.11 - experimental * @see #switchMapCompletableDelayError(Function) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Completable switchMapCompletable(@NonNull Function<? super T, ? extends CompletableSource> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new FlowableSwitchMapCompletable<T>(this, mapper, false)); @@ -14721,17 +14710,17 @@ public final Completable switchMapCompletable(@NonNull Function<? super T, ? ext * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. * </dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with each upstream item and should return a * {@link CompletableSource} to be subscribed to and awaited for * (non blockingly) for its terminal event * @return the new Completable instance - * @since 2.1.11 - experimental * @see #switchMapCompletableDelayError(Function) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Completable switchMapCompletableDelayError(@NonNull Function<? super T, ? extends CompletableSource> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new FlowableSwitchMapCompletable<T>(this, mapper, true)); @@ -14846,18 +14835,18 @@ <R> Flowable<R> switchMap0(Function<? super T, ? extends Publisher<? extends R>> * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} as * {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the output value type * @param mapper the function called with the current upstream event and should * return a {@code MaybeSource} to replace the current active inner source * and get subscribed to. * @return the new Flowable instance - * @since 2.1.11 - experimental * @see #switchMapMaybe(Function) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> switchMapMaybe(@NonNull Function<? super T, ? extends MaybeSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new FlowableSwitchMapMaybe<T, R>(this, mapper, false)); @@ -14876,18 +14865,18 @@ public final <R> Flowable<R> switchMapMaybe(@NonNull Function<? super T, ? exten * <dt><b>Scheduler:</b></dt> * <dd>{@code switchMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the output value type * @param mapper the function called with the current upstream event and should * return a {@code MaybeSource} to replace the current active inner source * and get subscribed to. * @return the new Flowable instance - * @since 2.1.11 - experimental * @see #switchMapMaybe(Function) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> switchMapMaybeDelayError(@NonNull Function<? super T, ? extends MaybeSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new FlowableSwitchMapMaybe<T, R>(this, mapper, true)); @@ -14916,18 +14905,18 @@ public final <R> Flowable<R> switchMapMaybeDelayError(@NonNull Function<? super * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} as * {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the output value type * @param mapper the function called with the current upstream event and should * return a {@code SingleSource} to replace the current active inner source * and get subscribed to. * @return the new Flowable instance - * @since 2.1.11 - experimental * @see #switchMapSingle(Function) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> switchMapSingle(@NonNull Function<? super T, ? extends SingleSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new FlowableSwitchMapSingle<T, R>(this, mapper, false)); @@ -14946,18 +14935,18 @@ public final <R> Flowable<R> switchMapSingle(@NonNull Function<? super T, ? exte * <dt><b>Scheduler:</b></dt> * <dd>{@code switchMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the output value type * @param mapper the function called with the current upstream event and should * return a {@code SingleSource} to replace the current active inner source * and get subscribed to. * @return the new Flowable instance - * @since 2.1.11 - experimental * @see #switchMapSingle(Function) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Flowable<R> switchMapSingleDelayError(@NonNull Function<? super T, ? extends SingleSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new FlowableSwitchMapSingle<T, R>(this, mapper, true)); @@ -15627,15 +15616,15 @@ public final Flowable<T> throttleLast(long intervalDuration, TimeUnit unit, Sche * <dt><b>Scheduler:</b></dt> * <dd>{@code throttleLatest} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait after an item emission towards the downstream * before trying to emit the latest item from upstream again * @param unit the time unit * @return the new Flowable instance - * @since 2.1.14 - experimental + * @since 2.2 * @see #throttleLatest(long, TimeUnit, boolean) * @see #throttleLatest(long, TimeUnit, Scheduler) */ - @Experimental @CheckReturnValue @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.COMPUTATION) @@ -15661,6 +15650,7 @@ public final Flowable<T> throttleLatest(long timeout, TimeUnit unit) { * <dt><b>Scheduler:</b></dt> * <dd>{@code throttleLatest} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait after an item emission towards the downstream * before trying to emit the latest item from upstream again * @param unit the time unit @@ -15669,10 +15659,9 @@ public final Flowable<T> throttleLatest(long timeout, TimeUnit unit) { * a timeout window active or not. If {@code false}, the very last * upstream item is ignored and the flow terminates. * @return the new Flowable instance - * @since 2.1.14 - experimental * @see #throttleLatest(long, TimeUnit, Scheduler, boolean) + * @since 2.2 */ - @Experimental @CheckReturnValue @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.COMPUTATION) @@ -15701,16 +15690,16 @@ public final Flowable<T> throttleLatest(long timeout, TimeUnit unit, boolean emi * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait after an item emission towards the downstream * before trying to emit the latest item from upstream again * @param unit the time unit * @param scheduler the {@link Scheduler} where the timed wait and latest item * emission will be performed * @return the new Flowable instance - * @since 2.1.14 - experimental * @see #throttleLatest(long, TimeUnit, Scheduler, boolean) + * @since 2.2 */ - @Experimental @CheckReturnValue @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) @@ -15736,6 +15725,7 @@ public final Flowable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler s * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait after an item emission towards the downstream * before trying to emit the latest item from upstream again * @param unit the time unit @@ -15746,9 +15736,8 @@ public final Flowable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler s * a timeout window active or not. If {@code false}, the very last * upstream item is ignored and the flow terminates. * @return the new Flowable instance - * @since 2.1.14 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) diff --git a/src/main/java/io/reactivex/FlowableConverter.java b/src/main/java/io/reactivex/FlowableConverter.java index 541e335bcd..cf9176bf6d 100644 --- a/src/main/java/io/reactivex/FlowableConverter.java +++ b/src/main/java/io/reactivex/FlowableConverter.java @@ -18,12 +18,11 @@ /** * Convenience interface and callback used by the {@link Flowable#as} operator to turn a Flowable into another * value fluently. - * + * <p>History: 2.1.7 - experimental * @param <T> the upstream type * @param <R> the output type - * @since 2.1.7 - experimental + * @since 2.2 */ -@Experimental public interface FlowableConverter<T, R> { /** * Applies a function to the upstream Flowable and returns a converted value of type {@code R}. diff --git a/src/main/java/io/reactivex/FlowableEmitter.java b/src/main/java/io/reactivex/FlowableEmitter.java index f3c1d8e0cb..06636449c4 100644 --- a/src/main/java/io/reactivex/FlowableEmitter.java +++ b/src/main/java/io/reactivex/FlowableEmitter.java @@ -94,11 +94,11 @@ public interface FlowableEmitter<T> extends Emitter<T> { * <p> * Unlike {@link #onError(Throwable)}, the {@code RxJavaPlugins.onError} is not called * if the error could not be delivered. + * <p>History: 2.1.1 - experimental * @param t the throwable error to signal if possible * @return true if successful, false if the downstream is not able to accept further * events - * @since 2.1.1 - experimental + * @since 2.2 */ - @Experimental boolean tryOnError(@NonNull Throwable t); } diff --git a/src/main/java/io/reactivex/FlowableSubscriber.java b/src/main/java/io/reactivex/FlowableSubscriber.java index e483064610..2ef1019acf 100644 --- a/src/main/java/io/reactivex/FlowableSubscriber.java +++ b/src/main/java/io/reactivex/FlowableSubscriber.java @@ -20,11 +20,10 @@ * Represents a Reactive-Streams inspired Subscriber that is RxJava 2 only * and weakens rules §1.3 and §3.9 of the specification for gaining performance. * - * <p>History: 2.0.7 - experimental + * <p>History: 2.0.7 - experimental; 2.1 - beta * @param <T> the value type - * @since 2.1 - beta + * @since 2.2 */ -@Beta public interface FlowableSubscriber<T> extends Subscriber<T> { /** diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 7b040b58f9..9c50ef8518 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -1331,7 +1331,7 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends MaybeSource<? * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.9 - experimental * @param <T> the common element base type * @param sources * a Publisher that emits MaybeSources @@ -1339,13 +1339,12 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends MaybeSource<? * @return a Flowable that emits all of the items emitted by the Publishers emitted by the * {@code source} Publisher * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> - * @since 2.1.9 - experimental + * @since 2.2 */ @SuppressWarnings({ "unchecked", "rawtypes" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public static <T> Flowable<T> mergeDelayError(Publisher<? extends MaybeSource<? extends T>> sources, int maxConcurrency) { ObjectHelper.requireNonNull(sources, "source is null"); ObjectHelper.verifyPositive(maxConcurrency, "maxConcurrency"); @@ -2241,14 +2240,13 @@ public final Maybe<T> ambWith(MaybeSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code as} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.7 - experimental * @param <R> the resulting object type * @param converter the function that receives the current Maybe instance and returns a value * @return the converted value * @throws NullPointerException if converter is null - * @since 2.1.7 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final <R> R as(@NonNull MaybeConverter<T, ? extends R> converter) { @@ -4259,14 +4257,13 @@ public final Maybe<T> switchIfEmpty(MaybeSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.4 - experimental * @param other * the alternate SingleSource to subscribe to if the main does not emit any items * @return a Single that emits the items emitted by the source Maybe or the item of an * alternate SingleSource if the source Maybe is empty. - * @since 2.1.4 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> switchIfEmpty(SingleSource<? extends T> other) { diff --git a/src/main/java/io/reactivex/MaybeConverter.java b/src/main/java/io/reactivex/MaybeConverter.java index e156ed5944..c997399d99 100644 --- a/src/main/java/io/reactivex/MaybeConverter.java +++ b/src/main/java/io/reactivex/MaybeConverter.java @@ -18,12 +18,11 @@ /** * Convenience interface and callback used by the {@link Maybe#as} operator to turn a Maybe into another * value fluently. - * + * <p>History: 2.1.7 - experimental * @param <T> the upstream type * @param <R> the output type - * @since 2.1.7 - experimental + * @since 2.2 */ -@Experimental public interface MaybeConverter<T, R> { /** * Applies a function to the upstream Maybe and returns a converted value of type {@code R}. diff --git a/src/main/java/io/reactivex/MaybeEmitter.java b/src/main/java/io/reactivex/MaybeEmitter.java index c772430730..f0e6ed6266 100644 --- a/src/main/java/io/reactivex/MaybeEmitter.java +++ b/src/main/java/io/reactivex/MaybeEmitter.java @@ -97,11 +97,11 @@ public interface MaybeEmitter<T> { * <p> * Unlike {@link #onError(Throwable)}, the {@code RxJavaPlugins.onError} is not called * if the error could not be delivered. + * <p>History: 2.1.1 - experimental * @param t the throwable error to signal if possible * @return true if successful, false if the downstream is not able to accept further * events - * @since 2.1.1 - experimental + * @since 2.2 */ - @Experimental boolean tryOnError(@NonNull Throwable t); } diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index a3f204206b..918bfea14c 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -4951,14 +4951,13 @@ public final Single<Boolean> any(Predicate<? super T> predicate) { * <dt><b>Scheduler:</b></dt> * <dd>{@code as} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.7 - experimental * @param <R> the resulting object type * @param converter the function that receives the current Observable instance and returns a value * @return the converted value * @throws NullPointerException if converter is null - * @since 2.1.7 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final <R> R as(@NonNull ObservableConverter<T, ? extends R> converter) { @@ -6536,13 +6535,12 @@ public final <R> Observable<R> concatMapEagerDelayError(Function<? super T, ? ex * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.6 - experimental * @param mapper * a function that, when applied to an item emitted by the source ObservableSource, returns a CompletableSource * @return a Completable that signals {@code onComplete} when the upstream and all CompletableSources complete - * @since 2.1.6 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Completable concatMapCompletable(Function<? super T, ? extends CompletableSource> mapper) { @@ -6558,7 +6556,7 @@ public final Completable concatMapCompletable(Function<? super T, ? extends Comp * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.6 - experimental * @param mapper * a function that, when applied to an item emitted by the source ObservableSource, returns a CompletableSource * @@ -6566,9 +6564,8 @@ public final Completable concatMapCompletable(Function<? super T, ? extends Comp * the number of upstream items expected to be buffered until the current CompletableSource, mapped from * the current item, completes. * @return a Completable that signals {@code onComplete} when the upstream and all CompletableSources complete - * @since 2.1.6 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Completable concatMapCompletable(Function<? super T, ? extends CompletableSource> mapper, int capacityHint) { @@ -6587,16 +6584,16 @@ public final Completable concatMapCompletable(Function<? super T, ? extends Comp * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with the upstream item and should return * a {@code CompletableSource} to become the next source to * be subscribed to * @return a new Completable instance - * @since 2.1.11 - experimental * @see #concatMapCompletable(Function, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Completable concatMapCompletableDelayError(Function<? super T, ? extends CompletableSource> mapper) { return concatMapCompletableDelayError(mapper, true, 2); } @@ -6611,6 +6608,7 @@ public final Completable concatMapCompletableDelayError(Function<? super T, ? ex * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with the upstream item and should return * a {@code CompletableSource} to become the next source to * be subscribed to @@ -6621,12 +6619,11 @@ public final Completable concatMapCompletableDelayError(Function<? super T, ? ex * {@code CompletableSource} terminates and only then is * it emitted to the downstream. * @return a new Completable instance - * @since 2.1.11 - experimental * @see #concatMapCompletable(Function) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Completable concatMapCompletableDelayError(Function<? super T, ? extends CompletableSource> mapper, boolean tillTheEnd) { return concatMapCompletableDelayError(mapper, tillTheEnd, 2); } @@ -6641,6 +6638,7 @@ public final Completable concatMapCompletableDelayError(Function<? super T, ? ex * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with the upstream item and should return * a {@code CompletableSource} to become the next source to * be subscribed to @@ -6655,12 +6653,11 @@ public final Completable concatMapCompletableDelayError(Function<? super T, ? ex * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code CompletableSource}s. * @return a new Completable instance - * @since 2.1.11 - experimental * @see #concatMapCompletable(Function, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Completable concatMapCompletableDelayError(Function<? super T, ? extends CompletableSource> mapper, boolean tillTheEnd, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -6734,18 +6731,18 @@ public final <U> Observable<U> concatMapIterable(final Function<? super T, ? ext * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapMaybe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code MaybeSource}s * @param mapper the function called with the upstream item and should return * a {@code MaybeSource} to become the next source to * be subscribed to * @return a new Observable instance - * @since 2.1.11 - experimental * @see #concatMapMaybeDelayError(Function) * @see #concatMapMaybe(Function, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> concatMapMaybe(Function<? super T, ? extends MaybeSource<? extends R>> mapper) { return concatMapMaybe(mapper, 2); } @@ -6760,6 +6757,7 @@ public final <R> Observable<R> concatMapMaybe(Function<? super T, ? extends Mayb * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapMaybe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code MaybeSource}s * @param mapper the function called with the upstream item and should return * a {@code MaybeSource} to become the next source to @@ -6769,13 +6767,12 @@ public final <R> Observable<R> concatMapMaybe(Function<? super T, ? extends Mayb * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code MaybeSource}s. * @return a new Observable instance - * @since 2.1.11 - experimental * @see #concatMapMaybe(Function) * @see #concatMapMaybeDelayError(Function, boolean, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> concatMapMaybe(Function<? super T, ? extends MaybeSource<? extends R>> mapper, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -6792,18 +6789,18 @@ public final <R> Observable<R> concatMapMaybe(Function<? super T, ? extends Mayb * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code MaybeSource}s * @param mapper the function called with the upstream item and should return * a {@code MaybeSource} to become the next source to * be subscribed to * @return a new Observable instance - * @since 2.1.11 - experimental * @see #concatMapMaybe(Function) * @see #concatMapMaybeDelayError(Function, boolean) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? extends MaybeSource<? extends R>> mapper) { return concatMapMaybeDelayError(mapper, true, 2); } @@ -6818,6 +6815,7 @@ public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? ex * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code MaybeSource}s * @param mapper the function called with the upstream item and should return * a {@code MaybeSource} to become the next source to @@ -6829,13 +6827,12 @@ public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? ex * {@code MaybeSource} terminates and only then is * it emitted to the downstream. * @return a new Observable instance - * @since 2.1.11 - experimental * @see #concatMapMaybe(Function, int) * @see #concatMapMaybeDelayError(Function, boolean, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? extends MaybeSource<? extends R>> mapper, boolean tillTheEnd) { return concatMapMaybeDelayError(mapper, tillTheEnd, 2); } @@ -6850,6 +6847,7 @@ public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? ex * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code MaybeSource}s * @param mapper the function called with the upstream item and should return * a {@code MaybeSource} to become the next source to @@ -6865,12 +6863,11 @@ public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? ex * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code MaybeSource}s. * @return a new Observable instance - * @since 2.1.11 - experimental * @see #concatMapMaybe(Function, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? extends MaybeSource<? extends R>> mapper, boolean tillTheEnd, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -6887,18 +6884,18 @@ public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? ex * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code SingleSource}s * @param mapper the function called with the upstream item and should return * a {@code SingleSource} to become the next source to * be subscribed to * @return a new Observable instance - * @since 2.1.11 - experimental * @see #concatMapSingleDelayError(Function) * @see #concatMapSingle(Function, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> concatMapSingle(Function<? super T, ? extends SingleSource<? extends R>> mapper) { return concatMapSingle(mapper, 2); } @@ -6913,6 +6910,7 @@ public final <R> Observable<R> concatMapSingle(Function<? super T, ? extends Sin * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code SingleSource}s * @param mapper the function called with the upstream item and should return * a {@code SingleSource} to become the next source to @@ -6922,13 +6920,12 @@ public final <R> Observable<R> concatMapSingle(Function<? super T, ? extends Sin * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code SingleSource}s. * @return a new Observable instance - * @since 2.1.11 - experimental * @see #concatMapSingle(Function) * @see #concatMapSingleDelayError(Function, boolean, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> concatMapSingle(Function<? super T, ? extends SingleSource<? extends R>> mapper, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -6945,18 +6942,18 @@ public final <R> Observable<R> concatMapSingle(Function<? super T, ? extends Sin * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code SingleSource}s * @param mapper the function called with the upstream item and should return * a {@code SingleSource} to become the next source to * be subscribed to * @return a new Observable instance - * @since 2.1.11 - experimental * @see #concatMapSingle(Function) * @see #concatMapSingleDelayError(Function, boolean) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper) { return concatMapSingleDelayError(mapper, true, 2); } @@ -6971,6 +6968,7 @@ public final <R> Observable<R> concatMapSingleDelayError(Function<? super T, ? e * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code SingleSource}s * @param mapper the function called with the upstream item and should return * a {@code SingleSource} to become the next source to @@ -6982,13 +6980,12 @@ public final <R> Observable<R> concatMapSingleDelayError(Function<? super T, ? e * {@code SingleSource} terminates and only then is * it emitted to the downstream. * @return a new Observable instance - * @since 2.1.11 - experimental * @see #concatMapSingle(Function, int) * @see #concatMapSingleDelayError(Function, boolean, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean tillTheEnd) { return concatMapSingleDelayError(mapper, tillTheEnd, 2); } @@ -7003,6 +7000,7 @@ public final <R> Observable<R> concatMapSingleDelayError(Function<? super T, ? e * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the result type of the inner {@code SingleSource}s * @param mapper the function called with the upstream item and should return * a {@code SingleSource} to become the next source to @@ -7018,12 +7016,11 @@ public final <R> Observable<R> concatMapSingleDelayError(Function<? super T, ? e * The operator replenishes after half of the prefetch amount has been consumed * and turned into {@code SingleSource}s. * @return a new Observable instance - * @since 2.1.11 - experimental * @see #concatMapSingle(Function, int) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean tillTheEnd, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); @@ -7062,13 +7059,13 @@ public final Observable<T> concatWith(ObservableSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code concatWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.10 - experimental * @param other the SingleSource whose signal should be emitted after this {@code Observable} completes normally. * @return the new Observable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Observable<T> concatWith(@NonNull SingleSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new ObservableConcatWithSingle<T>(this, other)); @@ -7083,13 +7080,13 @@ public final Observable<T> concatWith(@NonNull SingleSource<? extends T> other) * <dt><b>Scheduler:</b></dt> * <dd>{@code concatWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.10 - experimental * @param other the MaybeSource whose signal should be emitted after this Observable completes normally. * @return the new Observable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Observable<T> concatWith(@NonNull MaybeSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new ObservableConcatWithMaybe<T>(this, other)); @@ -7104,13 +7101,13 @@ public final Observable<T> concatWith(@NonNull MaybeSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code concatWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.10 - experimental * @param other the {@code CompletableSource} to subscribe to once the current {@code Observable} completes normally * @return the new Observable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Observable<T> concatWith(@NonNull CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new ObservableConcatWithCompletable<T>(this, other)); @@ -9604,14 +9601,13 @@ public final Observable<T> mergeWith(ObservableSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.10 - experimental * @param other the {@code SingleSource} whose success value to merge with * @return the new Observable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Observable<T> mergeWith(@NonNull SingleSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new ObservableMergeWithSingle<T>(this, other)); @@ -9629,14 +9625,13 @@ public final Observable<T> mergeWith(@NonNull SingleSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.10 - experimental * @param other the {@code MaybeSource} which provides a success value to merge with or completes * @return the new Observable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Observable<T> mergeWith(@NonNull MaybeSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new ObservableMergeWithMaybe<T>(this, other)); @@ -9651,14 +9646,13 @@ public final Observable<T> mergeWith(@NonNull MaybeSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.10 - experimental * @param other the {@code CompletableSource} to await for completion * @return the new Observable instance - * @since 2.1.10 - experimental + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Observable<T> mergeWith(@NonNull CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new ObservableMergeWithCompletable<T>(this, other)); @@ -12228,16 +12222,16 @@ public final <R> Observable<R> switchMap(Function<? super T, ? extends Observabl * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. * </dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with each upstream item and should return a * {@link CompletableSource} to be subscribed to and awaited for * (non blockingly) for its terminal event * @return the new Completable instance - * @since 2.1.11 - experimental * @see #switchMapCompletableDelayError(Function) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Completable switchMapCompletable(@NonNull Function<? super T, ? extends CompletableSource> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new ObservableSwitchMapCompletable<T>(this, mapper, false)); @@ -12270,16 +12264,16 @@ public final Completable switchMapCompletable(@NonNull Function<? super T, ? ext * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. * </dd> * </dl> + * <p>History: 2.1.11 - experimental * @param mapper the function called with each upstream item and should return a * {@link CompletableSource} to be subscribed to and awaited for * (non blockingly) for its terminal event * @return the new Completable instance - * @since 2.1.11 - experimental * @see #switchMapCompletableDelayError(Function) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final Completable switchMapCompletableDelayError(@NonNull Function<? super T, ? extends CompletableSource> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new ObservableSwitchMapCompletable<T>(this, mapper, true)); @@ -12305,17 +12299,17 @@ public final Completable switchMapCompletableDelayError(@NonNull Function<? supe * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} as * {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the output value type * @param mapper the function called with the current upstream event and should * return a {@code MaybeSource} to replace the current active inner source * and get subscribed to. * @return the new Observable instance - * @since 2.1.11 - experimental * @see #switchMapMaybe(Function) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> switchMapMaybe(@NonNull Function<? super T, ? extends MaybeSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new ObservableSwitchMapMaybe<T, R>(this, mapper, false)); @@ -12331,17 +12325,17 @@ public final <R> Observable<R> switchMapMaybe(@NonNull Function<? super T, ? ext * <dt><b>Scheduler:</b></dt> * <dd>{@code switchMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.11 - experimental * @param <R> the output value type * @param mapper the function called with the current upstream event and should * return a {@code MaybeSource} to replace the current active inner source * and get subscribed to. * @return the new Observable instance - * @since 2.1.11 - experimental * @see #switchMapMaybe(Function) + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public final <R> Observable<R> switchMapMaybeDelayError(@NonNull Function<? super T, ? extends MaybeSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return RxJavaPlugins.onAssembly(new ObservableSwitchMapMaybe<T, R>(this, mapper, true)); @@ -12360,16 +12354,15 @@ public final <R> Observable<R> switchMapMaybeDelayError(@NonNull Function<? supe * <dt><b>Scheduler:</b></dt> * <dd>{@code switchMapSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.0.8 - experimental * @param <R> the element type of the inner SingleSources and the output * @param mapper * a function that, when applied to an item emitted by the source ObservableSource, returns a * SingleSource * @return an Observable that emits the item emitted by the SingleSource returned from applying {@code func} to the most recently emitted item emitted by the source ObservableSource * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> - * @since 2.0.8 + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @@ -12392,16 +12385,15 @@ public final <R> Observable<R> switchMapSingle(@NonNull Function<? super T, ? ex * <dt><b>Scheduler:</b></dt> * <dd>{@code switchMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.0.8 - experimental * @param <R> the element type of the inner SingleSources and the output * @param mapper * a function that, when applied to an item emitted by the source ObservableSource, returns a * SingleSource * @return an Observable that emits the item emitted by the SingleSource returned from applying {@code func} to the most recently emitted item emitted by the source ObservableSource * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> - * @since 2.0.8 + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @@ -13052,15 +13044,15 @@ public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit, Sc * <dt><b>Scheduler:</b></dt> * <dd>{@code throttleLatest} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait after an item emission towards the downstream * before trying to emit the latest item from upstream again * @param unit the time unit * @return the new Observable instance - * @since 2.1.14 - experimental * @see #throttleLatest(long, TimeUnit, boolean) * @see #throttleLatest(long, TimeUnit, Scheduler) + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Observable<T> throttleLatest(long timeout, TimeUnit unit) { @@ -13080,6 +13072,7 @@ public final Observable<T> throttleLatest(long timeout, TimeUnit unit) { * <dt><b>Scheduler:</b></dt> * <dd>{@code throttleLatest} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait after an item emission towards the downstream * before trying to emit the latest item from upstream again * @param unit the time unit @@ -13088,10 +13081,9 @@ public final Observable<T> throttleLatest(long timeout, TimeUnit unit) { * a timeout window active or not. If {@code false}, the very last * upstream item is ignored and the flow terminates. * @return the new Observable instance - * @since 2.1.14 - experimental * @see #throttleLatest(long, TimeUnit, Scheduler, boolean) + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Observable<T> throttleLatest(long timeout, TimeUnit unit, boolean emitLast) { @@ -13114,16 +13106,16 @@ public final Observable<T> throttleLatest(long timeout, TimeUnit unit, boolean e * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait after an item emission towards the downstream * before trying to emit the latest item from upstream again * @param unit the time unit * @param scheduler the {@link Scheduler} where the timed wait and latest item * emission will be performed * @return the new Observable instance - * @since 2.1.14 - experimental * @see #throttleLatest(long, TimeUnit, Scheduler, boolean) + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) public final Observable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler scheduler) { @@ -13143,6 +13135,7 @@ public final Observable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait after an item emission towards the downstream * before trying to emit the latest item from upstream again * @param unit the time unit @@ -13153,9 +13146,8 @@ public final Observable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler * a timeout window active or not. If {@code false}, the very last * upstream item is ignored and the flow terminates. * @return the new Observable instance - * @since 2.1.14 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) public final Observable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler scheduler, boolean emitLast) { diff --git a/src/main/java/io/reactivex/ObservableConverter.java b/src/main/java/io/reactivex/ObservableConverter.java index b413de69de..12c461523d 100644 --- a/src/main/java/io/reactivex/ObservableConverter.java +++ b/src/main/java/io/reactivex/ObservableConverter.java @@ -18,12 +18,11 @@ /** * Convenience interface and callback used by the {@link Observable#as} operator to turn an Observable into another * value fluently. - * + * <p>History: 2.1.7 - experimental * @param <T> the upstream type * @param <R> the output type - * @since 2.1.7 - experimental + * @since 2.2 */ -@Experimental public interface ObservableConverter<T, R> { /** * Applies a function to the upstream Observable and returns a converted value of type {@code R}. diff --git a/src/main/java/io/reactivex/ObservableEmitter.java b/src/main/java/io/reactivex/ObservableEmitter.java index 68c81207b6..0adbdb3a8d 100644 --- a/src/main/java/io/reactivex/ObservableEmitter.java +++ b/src/main/java/io/reactivex/ObservableEmitter.java @@ -86,11 +86,11 @@ public interface ObservableEmitter<T> extends Emitter<T> { * <p> * Unlike {@link #onError(Throwable)}, the {@code RxJavaPlugins.onError} is not called * if the error could not be delivered. + * <p>History: 2.1.1 - experimental * @param t the throwable error to signal if possible * @return true if successful, false if the downstream is not able to accept further * events - * @since 2.1.1 - experimental + * @since 2.2 */ - @Experimental boolean tryOnError(@NonNull Throwable t); } diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 5cef88c846..a42e9eaa5b 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -1060,16 +1060,16 @@ public static <T> Flowable<T> merge( * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.9 - experimental * @param <T> the common and resulting value type * @param sources the Iterable sequence of SingleSource sources * @return the new Flowable instance - * @since 2.1.9 - experimental * @see #merge(Iterable) + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) - @Experimental public static <T> Flowable<T> mergeDelayError(Iterable<? extends SingleSource<? extends T>> sources) { return mergeDelayError(Flowable.fromIterable(sources)); } @@ -1083,17 +1083,17 @@ public static <T> Flowable<T> mergeDelayError(Iterable<? extends SingleSource<? * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.9 - experimental * @param <T> the common and resulting value type * @param sources the Flowable sequence of SingleSource sources * @return the new Flowable instance * @see #merge(Publisher) - * @since 2.1.9 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) - @Experimental public static <T> Flowable<T> mergeDelayError(Publisher<? extends SingleSource<? extends T>> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); return RxJavaPlugins.onAssembly(new FlowableFlatMapPublisher(sources, SingleInternalHelper.toFlowable(), true, Integer.MAX_VALUE, Flowable.bufferSize())); @@ -1114,7 +1114,7 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends SingleSource<? * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.9 - experimental * @param <T> the common value type * @param source1 * a SingleSource to be merged @@ -1123,13 +1123,12 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends SingleSource<? * @return a Flowable that emits all of the items emitted by the source Singles * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #merge(SingleSource, SingleSource) - * @since 2.1.9 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") - @Experimental public static <T> Flowable<T> mergeDelayError( SingleSource<? extends T> source1, SingleSource<? extends T> source2 ) { @@ -1152,7 +1151,7 @@ public static <T> Flowable<T> mergeDelayError( * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.9 - experimental * @param <T> the common value type * @param source1 * a SingleSource to be merged @@ -1163,13 +1162,12 @@ public static <T> Flowable<T> mergeDelayError( * @return a Flowable that emits all of the items emitted by the source Singles * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #merge(SingleSource, SingleSource, SingleSource) - * @since 2.1.9 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") - @Experimental public static <T> Flowable<T> mergeDelayError( SingleSource<? extends T> source1, SingleSource<? extends T> source2, SingleSource<? extends T> source3 @@ -1194,7 +1192,7 @@ public static <T> Flowable<T> mergeDelayError( * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.9 - experimental * @param <T> the common value type * @param source1 * a SingleSource to be merged @@ -1207,13 +1205,12 @@ public static <T> Flowable<T> mergeDelayError( * @return a Flowable that emits all of the items emitted by the source Singles * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #merge(SingleSource, SingleSource, SingleSource, SingleSource) - * @since 2.1.9 - experimental + * @since 2.2 */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") - @Experimental public static <T> Flowable<T> mergeDelayError( SingleSource<? extends T> source1, SingleSource<? extends T> source2, SingleSource<? extends T> source3, SingleSource<? extends T> source4 @@ -1925,14 +1922,13 @@ public final Single<T> ambWith(SingleSource<? extends T> other) { * <dt><b>Scheduler:</b></dt> * <dd>{@code as} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.7 - experimental * @param <R> the resulting object type * @param converter the function that receives the current Single instance and returns a value * @return the converted value * @throws NullPointerException if converter is null - * @since 2.1.7 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final <R> R as(@NonNull SingleConverter<T, ? extends R> converter) { @@ -2073,14 +2069,13 @@ public final Single<T> delay(long time, TimeUnit unit) { * <dt><b>Scheduler:</b></dt> * <dd>{@code delay} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> - * + * <p>History: 2.1.5 - experimental * @param time the amount of time the success or error signal should be delayed for * @param unit the time unit * @param delayError if true, both success and error signals are delayed. if false, only success signals are delayed. * @return the new Single instance - * @since 2.1.5 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Single<T> delay(long time, TimeUnit unit, boolean delayError) { @@ -2120,7 +2115,7 @@ public final Single<T> delay(final long time, final TimeUnit unit, final Schedul * <dt><b>Scheduler:</b></dt> * <dd>you specify the {@link Scheduler} where the non-blocking wait and emission happens</dd> * </dl> - * + * <p>History: 2.1.5 - experimental * @param time the amount of time the success or error signal should be delayed for * @param unit the time unit * @param scheduler the target scheduler to use for the non-blocking wait and emission @@ -2129,9 +2124,8 @@ public final Single<T> delay(final long time, final TimeUnit unit, final Schedul * @throws NullPointerException * if unit is null, or * if scheduler is null - * @since 2.1.5 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) public final Single<T> delay(final long time, final TimeUnit unit, final Scheduler scheduler, boolean delayError) { @@ -3052,11 +3046,11 @@ public final Single<T> onErrorResumeNext( * <dt><b>Scheduler:</b></dt> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.5 - experimental * @return a Single which nulls out references to the upstream producer and downstream SingleObserver if * the sequence is terminated or downstream calls dispose() - * @since 2.1.5 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> onTerminateDetach() { @@ -3210,13 +3204,13 @@ public final Single<T> retry(BiPredicate<? super Integer, ? super Throwable> pre * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.8 - experimental * @param times the number of times to resubscribe if the current Single fails * @param predicate the predicate called with the failure Throwable * and should return true if a resubscription should happen * @return the new Single instance - * @since 2.1.8 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> retry(long times, Predicate<? super Throwable> predicate) { @@ -3798,14 +3792,14 @@ public final Observable<T> toObservable() { * <dt><b>Scheduler:</b></dt> * <dd>{@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.</dd> * </dl> + * <p>History: 2.0.9 - experimental * @param scheduler the target scheduler where to execute the cancellation * @return the new Single instance * @throws NullPointerException if scheduler is null - * @since 2.0.9 - experimental + * @since 2.2 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) - @Experimental public final Single<T> unsubscribeOn(final Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new SingleUnsubscribeOn<T>(this, scheduler)); diff --git a/src/main/java/io/reactivex/SingleConverter.java b/src/main/java/io/reactivex/SingleConverter.java index 9938b22cc7..1e3944f73b 100644 --- a/src/main/java/io/reactivex/SingleConverter.java +++ b/src/main/java/io/reactivex/SingleConverter.java @@ -18,12 +18,11 @@ /** * Convenience interface and callback used by the {@link Single#as} operator to turn a Single into another * value fluently. - * + * <p>History: 2.1.7 - experimental * @param <T> the upstream type * @param <R> the output type - * @since 2.1.7 - experimental + * @since 2.2 */ -@Experimental public interface SingleConverter<T, R> { /** * Applies a function to the upstream Single and returns a converted value of type {@code R}. diff --git a/src/main/java/io/reactivex/SingleEmitter.java b/src/main/java/io/reactivex/SingleEmitter.java index c623638ef7..9e98f130e0 100644 --- a/src/main/java/io/reactivex/SingleEmitter.java +++ b/src/main/java/io/reactivex/SingleEmitter.java @@ -91,11 +91,11 @@ public interface SingleEmitter<T> { * <p> * Unlike {@link #onError(Throwable)}, the {@code RxJavaPlugins.onError} is not called * if the error could not be delivered. + * <p>History: 2.1.1 - experimental * @param t the throwable error to signal if possible * @return true if successful, false if the downstream is not able to accept further * events - * @since 2.1.1 - experimental + * @since 2.2 */ - @Experimental boolean tryOnError(@NonNull Throwable t); } diff --git a/src/main/java/io/reactivex/annotations/SchedulerSupport.java b/src/main/java/io/reactivex/annotations/SchedulerSupport.java index 737c4dbf1e..09acaa6dea 100644 --- a/src/main/java/io/reactivex/annotations/SchedulerSupport.java +++ b/src/main/java/io/reactivex/annotations/SchedulerSupport.java @@ -63,9 +63,9 @@ /** * The operator/class runs on RxJava's {@linkplain Schedulers#single() single scheduler} * or takes timing information from it. - * @since 2.0.8 - experimental + * <p>History: 2.0.8 - experimental + * @since 2.2 */ - @Experimental String SINGLE = "io.reactivex:single"; /** diff --git a/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java b/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java index e0e4d8e336..994a5c25a5 100644 --- a/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java +++ b/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java @@ -19,10 +19,9 @@ * Represents an exception used to signal to the {@code RxJavaPlugins.onError()} that a * callback-based subscribe() method on a base reactive type didn't specify * an onError handler. - * <p>History: 2.0.6 - experimental - * @since 2.1 - beta + * <p>History: 2.0.6 - experimental; 2.1 - beta + * @since 2.2 */ -@Beta public final class OnErrorNotImplementedException extends RuntimeException { private static final long serialVersionUID = -6298857009889503852L; diff --git a/src/main/java/io/reactivex/exceptions/ProtocolViolationException.java b/src/main/java/io/reactivex/exceptions/ProtocolViolationException.java index 00a3ee3bbc..09c0361108 100644 --- a/src/main/java/io/reactivex/exceptions/ProtocolViolationException.java +++ b/src/main/java/io/reactivex/exceptions/ProtocolViolationException.java @@ -13,15 +13,12 @@ package io.reactivex.exceptions; -import io.reactivex.annotations.Beta; - /** * Explicitly named exception to indicate a Reactive-Streams * protocol violation. - * <p>History: 2.0.6 - experimental - * @since 2.1 - beta + * <p>History: 2.0.6 - experimental; 2.1 - beta + * @since 2.2 */ -@Beta public final class ProtocolViolationException extends IllegalStateException { private static final long serialVersionUID = 1644750035281290266L; diff --git a/src/main/java/io/reactivex/exceptions/UndeliverableException.java b/src/main/java/io/reactivex/exceptions/UndeliverableException.java index 030ba755ba..6f6aec0938 100644 --- a/src/main/java/io/reactivex/exceptions/UndeliverableException.java +++ b/src/main/java/io/reactivex/exceptions/UndeliverableException.java @@ -13,14 +13,11 @@ package io.reactivex.exceptions; -import io.reactivex.annotations.Beta; - /** * Wrapper for Throwable errors that are sent to `RxJavaPlugins.onError`. - * <p>History: 2.0.6 - experimental - * @since 2.1 - beta + * <p>History: 2.0.6 - experimental; 2.1 - beta + * @since 2.2 */ -@Beta public final class UndeliverableException extends IllegalStateException { private static final long serialVersionUID = 1644750035281290266L; diff --git a/src/main/java/io/reactivex/flowables/ConnectableFlowable.java b/src/main/java/io/reactivex/flowables/ConnectableFlowable.java index e62ea61494..21636e67da 100644 --- a/src/main/java/io/reactivex/flowables/ConnectableFlowable.java +++ b/src/main/java/io/reactivex/flowables/ConnectableFlowable.java @@ -102,12 +102,12 @@ public Flowable<T> refCount() { * <dt><b>Scheduler:</b></dt> * <dd>This {@code refCount} overload does not operate on any particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param subscriberCount the number of subscribers required to connect to the upstream * @return the new Flowable instance - * @since 2.1.14 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.PASS_THROUGH) public final Flowable<T> refCount(int subscriberCount) { @@ -125,14 +125,14 @@ public final Flowable<T> refCount(int subscriberCount) { * <dt><b>Scheduler:</b></dt> * <dd>This {@code refCount} overload operates on the {@code computation} {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait before disconnecting after all subscribers unsubscribed * @param unit the time unit of the timeout * @return the new Flowable instance - * @since 2.1.14 - experimental * @see #refCount(long, TimeUnit, Scheduler) + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.COMPUTATION) @BackpressureSupport(BackpressureKind.PASS_THROUGH) public final Flowable<T> refCount(long timeout, TimeUnit unit) { @@ -150,14 +150,14 @@ public final Flowable<T> refCount(long timeout, TimeUnit unit) { * <dt><b>Scheduler:</b></dt> * <dd>This {@code refCount} overload operates on the specified {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait before disconnecting after all subscribers unsubscribed * @param unit the time unit of the timeout * @param scheduler the target scheduler to wait on before disconnecting * @return the new Flowable instance - * @since 2.1.14 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.CUSTOM) @BackpressureSupport(BackpressureKind.PASS_THROUGH) public final Flowable<T> refCount(long timeout, TimeUnit unit, Scheduler scheduler) { @@ -175,15 +175,15 @@ public final Flowable<T> refCount(long timeout, TimeUnit unit, Scheduler schedul * <dt><b>Scheduler:</b></dt> * <dd>This {@code refCount} overload operates on the {@code computation} {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param subscriberCount the number of subscribers required to connect to the upstream * @param timeout the time to wait before disconnecting after all subscribers unsubscribed * @param unit the time unit of the timeout * @return the new Flowable instance - * @since 2.1.14 - experimental * @see #refCount(int, long, TimeUnit, Scheduler) + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.COMPUTATION) @BackpressureSupport(BackpressureKind.PASS_THROUGH) public final Flowable<T> refCount(int subscriberCount, long timeout, TimeUnit unit) { @@ -201,15 +201,15 @@ public final Flowable<T> refCount(int subscriberCount, long timeout, TimeUnit un * <dt><b>Scheduler:</b></dt> * <dd>This {@code refCount} overload operates on the specified {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param subscriberCount the number of subscribers required to connect to the upstream * @param timeout the time to wait before disconnecting after all subscribers unsubscribed * @param unit the time unit of the timeout * @param scheduler the target scheduler to wait on before disconnecting * @return the new Flowable instance - * @since 2.1.14 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.CUSTOM) @BackpressureSupport(BackpressureKind.PASS_THROUGH) public final Flowable<T> refCount(int subscriberCount, long timeout, TimeUnit unit, Scheduler scheduler) { diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java index b3e0aee7fa..9b1652087e 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java @@ -16,15 +16,13 @@ import java.util.concurrent.atomic.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; /** * Consume the upstream source exactly once and cache its terminal event. - * - * @since 2.0.4 - experimental + * <p>History: 2.0.4 - experimental + * @since 2.1 */ -@Experimental public final class CompletableCache extends Completable implements CompletableObserver { static final InnerCompletableCache[] EMPTY = new InnerCompletableCache[0]; diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java index 48de66f017..14e74c0485 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java @@ -14,16 +14,14 @@ package io.reactivex.internal.operators.completable; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; /** * Breaks the references between the upstream and downstream when the Completable terminates. - * - * @since 2.1.5 - experimental + * <p>History: 2.1.5 - experimental + * @since 2.2 */ -@Experimental public final class CompletableDetach extends Completable { final CompletableSource source; diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java index 4077270dfb..c1b695220a 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java @@ -16,7 +16,6 @@ import java.util.concurrent.atomic.AtomicInteger; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Action; @@ -25,10 +24,9 @@ /** * Execute an action after an onError, onComplete or a dispose event. - * - * @since 2.0.1 - experimental + * <p>History: 2.0.1 - experimental + * @since 2.1 */ -@Experimental public final class CompletableDoFinally extends Completable { final CompletableSource source; diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java index 1343d35b98..391795846e 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java @@ -16,16 +16,15 @@ import java.util.concurrent.atomic.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.plugins.RxJavaPlugins; /** * Terminates the sequence if either the main or the other Completable terminate. - * @since 2.1.17 - experimental + * <p>History: 2.1.17 - experimental + * @since 2.2 */ -@Experimental public final class CompletableTakeUntilCompletable extends Completable { final Completable source; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerPublisher.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerPublisher.java index a88e05953d..43785a6fc5 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerPublisher.java @@ -22,9 +22,10 @@ /** * ConcatMapEager which works with an arbitrary Publisher source. + * <p>History: 2.0.7 - experimental * @param <T> the input value type * @param <R> the output type - * @since 2.0.7 - experimental + * @since 2.1 */ public final class FlowableConcatMapEagerPublisher<T, R> extends Flowable<R> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java index d683d3e788..5523614a9a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java @@ -25,8 +25,9 @@ /** * Subscribe to a main Flowable first, then when it completes normally, subscribe to a Completable * and terminate when it terminates. + * <p>History: 2.1.10 - experimental * @param <T> the element type of the main source and output type - * @since 2.1.10 - experimental + * @since 2.2 */ public final class FlowableConcatWithCompletable<T> extends AbstractFlowableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java index a3128b6e37..3250e0c82c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java @@ -26,8 +26,9 @@ /** * Subscribe to a main Flowable first, then when it completes normally, subscribe to a Maybe, * signal its success value followed by a completion or signal its error or completion signal as is. + * <p>History: 2.1.10 - experimental * @param <T> the element type of the main source and output type - * @since 2.1.10 - experimental + * @since 2.2 */ public final class FlowableConcatWithMaybe<T> extends AbstractFlowableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java index bf86de2003..a85090166b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java @@ -26,8 +26,9 @@ /** * Subscribe to a main Flowable first, then when it completes normally, subscribe to a Single, * signal its success value followed by a completion or signal its error as is. + * <p>History: 2.1.10 - experimental * @param <T> the element type of the main source and output type - * @since 2.1.10 - experimental + * @since 2.2 */ public final class FlowableConcatWithSingle<T> extends AbstractFlowableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNext.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNext.java index 039dd86311..f7a079d4b7 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNext.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNext.java @@ -23,10 +23,10 @@ /** * Calls a consumer after pushing the current item to the downstream. + * <p>History: 2.0.1 - experimental * @param <T> the value type - * @since 2.0.1 - experimental + * @since 2.1 */ -@Experimental public final class FlowableDoAfterNext<T> extends AbstractFlowableWithUpstream<T, T> { final Consumer<? super T> onAfterNext; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoFinally.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoFinally.java index e15faff21a..116f81b712 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoFinally.java @@ -25,11 +25,10 @@ /** * Execute an action after an onError, onComplete or a cancel event. - * + * <p>History: 2.0.1 - experimental * @param <T> the value type - * @since 2.0.1 - experimental + * @since 2.1 */ -@Experimental public final class FlowableDoFinally<T> extends AbstractFlowableWithUpstream<T, T> { final Action onFinally; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java index 01b1f24f76..a49758dd53 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java @@ -18,17 +18,15 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.internal.subscriptions.*; import io.reactivex.plugins.RxJavaPlugins; /** * Limits both the total request amount and items received from the upstream. - * + * <p>History: 2.1.6 - experimental * @param <T> the source and output value type - * @since 2.1.6 - experimental + * @since 2.2 */ -@Experimental public final class FlowableLimit<T> extends AbstractFlowableWithUpstream<T, T> { final long n; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapPublisher.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapPublisher.java index 03b9fe9634..ac9fee861e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapPublisher.java @@ -22,10 +22,10 @@ /** * Map working with an arbitrary Publisher source. - * + * <p>History: 2.0.7 - experimental * @param <T> the input value type * @param <U> the output value type - * @since 2.0.7 - experimental + * @since 2.1 */ public final class FlowableMapPublisher<T, U> extends Flowable<U> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java index cfdd0974f3..a62b10b1e2 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java @@ -26,9 +26,9 @@ /** * Merges a Flowable and a Completable by emitting the items of the Flowable and waiting until * both the Flowable and Completable complete normally. - * + * <p>History: 2.1.10 - experimental * @param <T> the element type of the Flowable - * @since 2.1.10 - experimental + * @since 2.2 */ public final class FlowableMergeWithCompletable<T> extends AbstractFlowableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java index 7a48d38875..97c81551eb 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java @@ -29,9 +29,9 @@ /** * Merges an Observable and a Maybe by emitting the items of the Observable and the success * value of the Maybe and waiting until both the Observable and Maybe terminate normally. - * + * <p>History: 2.1.10 - experimental * @param <T> the element type of the Observable - * @since 2.1.10 - experimental + * @since 2.2 */ public final class FlowableMergeWithMaybe<T> extends AbstractFlowableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java index fca1812b78..05bf79f5f2 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java @@ -29,9 +29,9 @@ /** * Merges an Observable and a Maybe by emitting the items of the Observable and the success * value of the Maybe and waiting until both the Observable and Maybe terminate normally. - * + * <p>History: 2.1.10 - experimental * @param <T> the element type of the Observable - * @since 2.1.10 - experimental + * @since 2.2 */ public final class FlowableMergeWithSingle<T> extends AbstractFlowableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakePublisher.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakePublisher.java index c1f52d22a8..a79501dccf 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakePublisher.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakePublisher.java @@ -20,9 +20,9 @@ /** * Take with a generic Publisher source. - * + * <p>History: 2.0.7 - experimental * @param <T> the value type - * @since 2.0.7 - experimental + * @since 2.1 */ public final class FlowableTakePublisher<T> extends Flowable<T> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatest.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatest.java index 1ce2dddc25..b3fe22e129 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatest.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatest.java @@ -19,7 +19,6 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.exceptions.MissingBackpressureException; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.BackpressureHelper; @@ -31,11 +30,10 @@ * it tries to emit the latest item from upstream. If there was no upstream item, * in the meantime, the next upstream item is emitted immediately and the * timed process repeats. - * + * <p>History: 2.1.14 - experimental * @param <T> the upstream and downstream value type - * @since 2.1.14 - experimental + * @since 2.2 */ -@Experimental public final class FlowableThrottleLatest<T> extends AbstractFlowableWithUpstream<T, T> { final long timeout; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java index d6045032ba..99c77a7b2b 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.maybe; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Consumer; @@ -23,10 +22,10 @@ /** * Calls a consumer after pushing the current item to the downstream. + * <p>History: 2.0.1 - experimental * @param <T> the value type - * @since 2.0.1 - experimental + * @since 2.1 */ -@Experimental public final class MaybeDoAfterSuccess<T> extends AbstractMaybeWithUpstream<T, T> { final Consumer<? super T> onAfterSuccess; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java index 354f98270f..9bba726878 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java @@ -16,7 +16,6 @@ import java.util.concurrent.atomic.AtomicInteger; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Action; @@ -25,11 +24,10 @@ /** * Execute an action after an onSuccess, onError, onComplete or a dispose event. - * + * <p>History: 2.0.1 - experimental * @param <T> the value type - * @since 2.0.1 - experimental + * @since 2.1 */ -@Experimental public final class MaybeDoFinally<T> extends AbstractMaybeWithUpstream<T, T> { final Action onFinally; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingleElement.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingleElement.java index 3b0ca21850..91e41562d1 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingleElement.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingleElement.java @@ -16,7 +16,6 @@ import java.util.concurrent.atomic.AtomicReference; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; @@ -25,12 +24,11 @@ /** * Maps the success value of the source MaybeSource into a Single. + * <p>History: 2.0.2 - experimental * @param <T> the input value type * @param <R> the result value type - * - * @since 2.0.2 - experimental + * @since 2.1 */ -@Experimental public final class MaybeFlatMapSingleElement<T, R> extends Maybe<R> { final MaybeSource<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java index 53f87e743c..b0777bf5ac 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.maybe; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.fuseable.HasUpstreamMaybeSource; @@ -46,12 +45,12 @@ protected void subscribeActual(Observer<? super T> s) { /** * Creates a {@link MaybeObserver} wrapper around a {@link Observer}. + * <p>History: 2.1.11 - experimental * @param <T> the value type * @param downstream the downstream {@code Observer} to talk to * @return the new MaybeObserver instance - * @since 2.1.11 - experimental + * @since 2.2 */ - @Experimental public static <T> MaybeObserver<T> create(Observer<? super T> downstream) { return new MaybeToObservableObserver<T>(downstream); } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java index 17e32779eb..5e7da33f2e 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java @@ -18,7 +18,6 @@ import org.reactivestreams.Subscription; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; @@ -33,10 +32,10 @@ /** * Maps the upstream items into {@link CompletableSource}s and subscribes to them one after the * other completes or terminates (in error-delaying mode). + * <p>History: 2.1.11 - experimental * @param <T> the upstream value type - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class FlowableConcatMapCompletable<T> extends Completable { final Flowable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java index bafc9d4aab..82a3009a6c 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapMaybe.java @@ -18,7 +18,6 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; @@ -34,13 +33,11 @@ * Maps each upstream item into a {@link MaybeSource}, subscribes to them one after the other terminates * and relays their success values, optionally delaying any errors till the main and inner sources * terminate. - * + * <p>History: 2.1.11 - experimental * @param <T> the upstream element type * @param <R> the output element type - * - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class FlowableConcatMapMaybe<T, R> extends Flowable<R> { final Flowable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java index 654e7cabe5..9be42fcb7b 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java @@ -18,7 +18,6 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; @@ -34,13 +33,11 @@ * Maps each upstream item into a {@link SingleSource}, subscribes to them one after the other terminates * and relays their success values, optionally delaying any errors till the main and inner sources * terminate. - * + * <p>History: 2.1.11 - experimental * @param <T> the upstream element type * @param <R> the output element type - * - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class FlowableConcatMapSingle<T, R> extends Flowable<R> { final Flowable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java index 2d0f753fc8..0bcc6041e0 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java @@ -18,7 +18,6 @@ import org.reactivestreams.Subscription; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; @@ -32,11 +31,10 @@ * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one * active {@code CompletableSource} running. - * + * <p>History: 2.1.11 - experimental * @param <T> the upstream value type - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class FlowableSwitchMapCompletable<T> extends Completable { final Flowable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybe.java index 95b0436321..7bb3941d93 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybe.java @@ -18,7 +18,6 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; @@ -32,12 +31,11 @@ * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones * while disposing the older ones and emits the latest success value if available, optionally delaying * errors from the main source or the inner sources. - * + * <p>History: 2.1.11 - experimental * @param <T> the upstream value type * @param <R> the downstream value type - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class FlowableSwitchMapMaybe<T, R> extends Flowable<R> { final Flowable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java index 3e15dfc7ed..752ee852b9 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java @@ -18,7 +18,6 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; @@ -32,12 +31,11 @@ * Maps the upstream items into {@link SingleSource}s and switches (subscribes) to the newer ones * while disposing the older ones and emits the latest success value, optionally delaying * errors from the main source or the inner sources. - * + * <p>History: 2.1.11 - experimental * @param <T> the upstream value type * @param <R> the downstream value type - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class FlowableSwitchMapSingle<T, R> extends Flowable<R> { final Flowable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java index 30b463c666..60151de5c0 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java @@ -16,7 +16,6 @@ import java.util.concurrent.atomic.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; @@ -30,10 +29,10 @@ /** * Maps the upstream items into {@link CompletableSource}s and subscribes to them one after the * other completes or terminates (in error-delaying mode). + * <p>History: 2.1.11 - experimental * @param <T> the upstream value type - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class ObservableConcatMapCompletable<T> extends Completable { final Observable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java index f62669b705..f83388b5b7 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java @@ -16,7 +16,6 @@ import java.util.concurrent.atomic.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; @@ -31,13 +30,11 @@ * Maps each upstream item into a {@link MaybeSource}, subscribes to them one after the other terminates * and relays their success values, optionally delaying any errors till the main and inner sources * terminate. - * + * <p>History: 2.1.11 - experimental * @param <T> the upstream element type * @param <R> the output element type - * - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class ObservableConcatMapMaybe<T, R> extends Observable<R> { final Observable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java index 82afca6341..faca30b70f 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java @@ -16,7 +16,6 @@ import java.util.concurrent.atomic.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; @@ -31,13 +30,11 @@ * Maps each upstream item into a {@link SingleSource}, subscribes to them one after the other terminates * and relays their success values, optionally delaying any errors till the main and inner sources * terminate. - * + * <p>History: 2.1.11 - experimental * @param <T> the upstream element type * @param <R> the output element type - * - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class ObservableConcatMapSingle<T, R> extends Observable<R> { final Observable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java index 4b98e63bf2..4482a797c1 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java @@ -16,7 +16,6 @@ import java.util.concurrent.atomic.AtomicReference; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; @@ -29,11 +28,10 @@ * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one * active {@code CompletableSource} running. - * + * <p>History: 2.1.11 - experimental * @param <T> the upstream value type - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class ObservableSwitchMapCompletable<T> extends Completable { final Observable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java index 57baef78ea..a4e2586f95 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java @@ -16,7 +16,6 @@ import java.util.concurrent.atomic.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; @@ -29,12 +28,11 @@ * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones * while disposing the older ones and emits the latest success value if available, optionally delaying * errors from the main source or the inner sources. - * + * <p>History: 2.1.11 - experimental * @param <T> the upstream value type * @param <R> the downstream value type - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class ObservableSwitchMapMaybe<T, R> extends Observable<R> { final Observable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java index 1000e1bd81..166dce2b74 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java @@ -16,7 +16,6 @@ import java.util.concurrent.atomic.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; @@ -29,12 +28,11 @@ * Maps the upstream items into {@link SingleSource}s and switches (subscribes) to the newer ones * while disposing the older ones and emits the latest success value if available, optionally delaying * errors from the main source or the inner sources. - * + * <p>History: 2.1.11 - experimental * @param <T> the upstream value type * @param <R> the downstream value type - * @since 2.1.11 - experimental + * @since 2.2 */ -@Experimental public final class ObservableSwitchMapSingle<T, R> extends Observable<R> { final Observable<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelper.java b/src/main/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelper.java index 901cbd5cbf..2755a42c9d 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelper.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ScalarXMapZHelper.java @@ -16,7 +16,6 @@ import java.util.concurrent.Callable; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; import io.reactivex.internal.disposables.EmptyDisposable; @@ -28,9 +27,9 @@ * Utility class to extract a value from a scalar source reactive type, * map it to a 0-1 type then subscribe the output type's consumer to it, * saving on the overhead of the regular subscription channel. - * @since 2.1.11 - experimental + * <p>History: 2.1.11 - experimental + * @since 2.2 */ -@Experimental final class ScalarXMapZHelper { private ScalarXMapZHelper() { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java index 518e2f7b28..a80795b370 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java @@ -22,8 +22,9 @@ /** * Subscribe to a main Observable first, then when it completes normally, subscribe to a Single, * signal its success value followed by a completion or signal its error as is. + * <p>History: 2.1.10 - experimental * @param <T> the element type of the main source and output type - * @since 2.1.10 - experimental + * @since 2.2 */ public final class ObservableConcatWithCompletable<T> extends AbstractObservableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java index e8bcbfa766..26af9856eb 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java @@ -22,8 +22,9 @@ /** * Subscribe to a main Observable first, then when it completes normally, subscribe to a Maybe, * signal its success value followed by a completion or signal its error or completion signal as is. + * <p>History: 2.1.10 - experimental * @param <T> the element type of the main source and output type - * @since 2.1.10 - experimental + * @since 2.2 */ public final class ObservableConcatWithMaybe<T> extends AbstractObservableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java index 516580f507..09b4da0fdb 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java @@ -22,8 +22,9 @@ /** * Subscribe to a main Observable first, then when it completes normally, subscribe to a Single, * signal its success value followed by a completion or signal its error as is. + * <p>History: 2.1.10 - experimental * @param <T> the element type of the main source and output type - * @since 2.1.10 - experimental + * @since 2.2 */ public final class ObservableConcatWithSingle<T> extends AbstractObservableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java index dc01638d96..e1346d2dbe 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java @@ -14,17 +14,16 @@ package io.reactivex.internal.operators.observable; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.annotations.Nullable; import io.reactivex.functions.Consumer; import io.reactivex.internal.observers.BasicFuseableObserver; /** * Calls a consumer after pushing the current item to the downstream. + * <p>History: 2.0.1 - experimental * @param <T> the value type - * @since 2.0.1 - experimental + * @since 2.1 */ -@Experimental public final class ObservableDoAfterNext<T> extends AbstractObservableWithUpstream<T, T> { final Consumer<? super T> onAfterNext; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java index cf474c164d..99720ce5cc 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.annotations.Nullable; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; @@ -26,11 +25,10 @@ /** * Execute an action after an onError, onComplete or a dispose event. - * + * <p>History: 2.0.1 - experimental * @param <T> the value type - * @since 2.0.1 - experimental + * @since 2.1 */ -@Experimental public final class ObservableDoFinally<T> extends AbstractObservableWithUpstream<T, T> { final Action onFinally; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java index 7d0945def8..8fa2f7e2cd 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java @@ -23,9 +23,9 @@ /** * Merges an Observable and a Completable by emitting the items of the Observable and waiting until * both the Observable and Completable complete normally. - * + * <p>History: 2.1.10 - experimental * @param <T> the element type of the Observable - * @since 2.1.10 - experimental + * @since 2.2 */ public final class ObservableMergeWithCompletable<T> extends AbstractObservableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java index c1714df168..cefa778ebd 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java @@ -26,9 +26,9 @@ /** * Merges an Observable and a Maybe by emitting the items of the Observable and the success * value of the Maybe and waiting until both the Observable and Maybe terminate normally. - * + * <p>History: 2.1.10 - experimental * @param <T> the element type of the Observable - * @since 2.1.10 - experimental + * @since 2.2 */ public final class ObservableMergeWithMaybe<T> extends AbstractObservableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java index 458786dff5..28f6596915 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java @@ -26,9 +26,9 @@ /** * Merges an Observable and a Single by emitting the items of the Observable and the success * value of the Single and waiting until both the Observable and Single terminate normally. - * + * <p>History: 2.1.10 - experimental * @param <T> the element type of the Observable - * @since 2.1.10 - experimental + * @since 2.2 */ public final class ObservableMergeWithSingle<T> extends AbstractObservableWithUpstream<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java index 51df6abd1f..41130d56e2 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java @@ -17,7 +17,6 @@ import java.util.concurrent.atomic.*; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; @@ -28,11 +27,10 @@ * it tries to emit the latest item from upstream. If there was no upstream item, * in the meantime, the next upstream item is emitted immediately and the * timed process repeats. - * + * <p>History: 2.1.14 - experimental * @param <T> the upstream and downstream value type - * @since 2.1.14 - experimental + * @since 2.2 */ -@Experimental public final class ObservableThrottleLatest<T> extends AbstractObservableWithUpstream<T, T> { final long timeout; diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelDoOnNextTry.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelDoOnNextTry.java index 4a599b2435..ae74461419 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelDoOnNextTry.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelDoOnNextTry.java @@ -26,9 +26,9 @@ /** * Calls a Consumer for each upstream value passing by * and handles any failure with a handler function. - * + * <p>History: 2.0.8 - experimental * @param <T> the input value type - * @since 2.0.8 - experimental + * @since 2.2 */ public final class ParallelDoOnNextTry<T> extends ParallelFlowable<T> { diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelMapTry.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelMapTry.java index 59c8b85fde..493b5f5dc3 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelMapTry.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelMapTry.java @@ -26,10 +26,10 @@ /** * Maps each 'rail' of the source ParallelFlowable with a mapper function * and handle any failure based on a handler function. - * + * <p>History: 2.0.8 - experimental * @param <T> the input value type * @param <R> the output value type - * @since 2.0.8 - experimental + * @since 2.2 */ public final class ParallelMapTry<T, R> extends ParallelFlowable<R> { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java b/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java index d51eb2d4a6..dd077d259e 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java @@ -14,17 +14,15 @@ package io.reactivex.internal.operators.single; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; /** * Breaks the references between the upstream and downstream when the Maybe terminates. - * + * <p>History: 2.1.5 - experimental * @param <T> the value type - * @since 2.1.5 - experimental + * @since 2.2 */ -@Experimental public final class SingleDetach<T> extends Single<T> { final SingleSource<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java index 348a0edf9d..570def7896 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.single; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Consumer; @@ -23,10 +22,10 @@ /** * Calls a consumer after pushing the current item to the downstream. + * <p>History: 2.0.1 - experimental * @param <T> the value type - * @since 2.0.1 - experimental + * @since 2.1 */ -@Experimental public final class SingleDoAfterSuccess<T> extends Single<T> { final SingleSource<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java index b4b7d58f89..f9d17de184 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java @@ -24,8 +24,9 @@ /** * Calls an action after pushing the current item or an error to the downstream. + * <p>History: 2.0.6 - experimental * @param <T> the value type - * @since 2.0.6 - experimental + * @since 2.1 */ public final class SingleDoAfterTerminate<T> extends Single<T> { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java index fddf36d050..f575e25b7e 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java @@ -16,7 +16,6 @@ import java.util.concurrent.atomic.AtomicInteger; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Action; @@ -25,11 +24,10 @@ /** * Execute an action after an onSuccess, onError or a dispose event. - * + * <p>History: 2.0.1 - experimental * @param <T> the value type - * @since 2.0.1 - experimental + * @since 2.1 */ -@Experimental public final class SingleDoFinally<T> extends Single<T> { final SingleSource<T> source; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java index 4515cf606a..332f910476 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.single; import io.reactivex.*; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.observers.DeferredScalarDisposable; @@ -38,12 +37,12 @@ public void subscribeActual(final Observer<? super T> s) { /** * Creates a {@link SingleObserver} wrapper around a {@link Observer}. + * <p>History: 2.0.1 - experimental * @param <T> the value type * @param downstream the downstream {@code Observer} to talk to * @return the new SingleObserver instance - * @since 2.1.11 - experimental + * @since 2.2 */ - @Experimental public static <T> SingleObserver<T> create(Observer<? super T> downstream) { return new SingleToObservableObserver<T>(downstream); } diff --git a/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java b/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java index 31f7ed2a33..9eec7eef0c 100644 --- a/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java +++ b/src/main/java/io/reactivex/internal/schedulers/SchedulerMultiWorkerSupport.java @@ -22,10 +22,9 @@ * at most the parallelism level of the Scheduler, those * {@link io.reactivex.Scheduler.Worker} instances will be running * with different backing threads. - * - * @since 2.1.8 - experimental + * <p>History: 2.1.8 - experimental + * @since 2.2 */ -@Experimental public interface SchedulerMultiWorkerSupport { /** diff --git a/src/main/java/io/reactivex/internal/schedulers/SchedulerWhen.java b/src/main/java/io/reactivex/internal/schedulers/SchedulerWhen.java index 9b97ee6a36..4d56335527 100644 --- a/src/main/java/io/reactivex/internal/schedulers/SchedulerWhen.java +++ b/src/main/java/io/reactivex/internal/schedulers/SchedulerWhen.java @@ -24,7 +24,6 @@ import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Scheduler; -import io.reactivex.annotations.Experimental; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; @@ -100,8 +99,9 @@ * })); * }); * </pre> + * <p>History 2.0.1 - experimental + * @since 2.1 */ -@Experimental public class SchedulerWhen extends Scheduler implements Disposable { private final Scheduler actualScheduler; private final FlowableProcessor<Flowable<Completable>> workerProcessor; diff --git a/src/main/java/io/reactivex/observables/ConnectableObservable.java b/src/main/java/io/reactivex/observables/ConnectableObservable.java index 04d1648077..1858397e65 100644 --- a/src/main/java/io/reactivex/observables/ConnectableObservable.java +++ b/src/main/java/io/reactivex/observables/ConnectableObservable.java @@ -93,12 +93,12 @@ public Observable<T> refCount() { * <dt><b>Scheduler:</b></dt> * <dd>This {@code refCount} overload does not operate on any particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param subscriberCount the number of subscribers required to connect to the upstream * @return the new Observable instance - * @since 2.1.14 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.NONE) public final Observable<T> refCount(int subscriberCount) { return refCount(subscriberCount, 0, TimeUnit.NANOSECONDS, Schedulers.trampoline()); @@ -112,14 +112,14 @@ public final Observable<T> refCount(int subscriberCount) { * <dt><b>Scheduler:</b></dt> * <dd>This {@code refCount} overload operates on the {@code computation} {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait before disconnecting after all subscribers unsubscribed * @param unit the time unit of the timeout * @return the new Observable instance - * @since 2.1.14 - experimental * @see #refCount(long, TimeUnit, Scheduler) + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Observable<T> refCount(long timeout, TimeUnit unit) { return refCount(1, timeout, unit, Schedulers.computation()); @@ -133,14 +133,14 @@ public final Observable<T> refCount(long timeout, TimeUnit unit) { * <dt><b>Scheduler:</b></dt> * <dd>This {@code refCount} overload operates on the specified {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param timeout the time to wait before disconnecting after all subscribers unsubscribed * @param unit the time unit of the timeout * @param scheduler the target scheduler to wait on before disconnecting * @return the new Observable instance - * @since 2.1.14 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.CUSTOM) public final Observable<T> refCount(long timeout, TimeUnit unit, Scheduler scheduler) { return refCount(1, timeout, unit, scheduler); @@ -154,15 +154,15 @@ public final Observable<T> refCount(long timeout, TimeUnit unit, Scheduler sched * <dt><b>Scheduler:</b></dt> * <dd>This {@code refCount} overload operates on the {@code computation} {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param subscriberCount the number of subscribers required to connect to the upstream * @param timeout the time to wait before disconnecting after all subscribers unsubscribed * @param unit the time unit of the timeout * @return the new Observable instance - * @since 2.1.14 - experimental * @see #refCount(int, long, TimeUnit, Scheduler) + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Observable<T> refCount(int subscriberCount, long timeout, TimeUnit unit) { return refCount(subscriberCount, timeout, unit, Schedulers.computation()); @@ -176,15 +176,15 @@ public final Observable<T> refCount(int subscriberCount, long timeout, TimeUnit * <dt><b>Scheduler:</b></dt> * <dd>This {@code refCount} overload operates on the specified {@link Scheduler}.</dd> * </dl> + * <p>History: 2.1.14 - experimental * @param subscriberCount the number of subscribers required to connect to the upstream * @param timeout the time to wait before disconnecting after all subscribers unsubscribed * @param unit the time unit of the timeout * @param scheduler the target scheduler to wait on before disconnecting * @return the new Observable instance - * @since 2.1.14 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @SchedulerSupport(SchedulerSupport.CUSTOM) public final Observable<T> refCount(int subscriberCount, long timeout, TimeUnit unit, Scheduler scheduler) { ObjectHelper.verifyPositive(subscriberCount, "subscriberCount"); diff --git a/src/main/java/io/reactivex/observers/BaseTestConsumer.java b/src/main/java/io/reactivex/observers/BaseTestConsumer.java index 84a6fe889d..373339f020 100644 --- a/src/main/java/io/reactivex/observers/BaseTestConsumer.java +++ b/src/main/java/io/reactivex/observers/BaseTestConsumer.java @@ -17,7 +17,6 @@ import java.util.concurrent.*; import io.reactivex.Notification; -import io.reactivex.annotations.Experimental; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.CompositeException; import io.reactivex.functions.Predicate; @@ -235,7 +234,7 @@ public final boolean await(long time, TimeUnit unit) throws InterruptedException /** * Assert that this TestObserver/TestSubscriber received exactly one onComplete event. - * @return this; + * @return this */ @SuppressWarnings("unchecked") public final U assertComplete() { @@ -251,7 +250,7 @@ public final U assertComplete() { /** * Assert that this TestObserver/TestSubscriber has not received any onComplete event. - * @return this; + * @return this */ @SuppressWarnings("unchecked") public final U assertNotComplete() { @@ -267,7 +266,7 @@ public final U assertNotComplete() { /** * Assert that this TestObserver/TestSubscriber has not received any onError event. - * @return this; + * @return this */ @SuppressWarnings("unchecked") public final U assertNoErrors() { @@ -286,7 +285,7 @@ public final U assertNoErrors() { * overload to test against the class of an error instead of an instance of an error * or {@link #assertError(Predicate)} to test with different condition. * @param error the error to check - * @return this; + * @return this * @see #assertError(Class) * @see #assertError(Predicate) */ @@ -298,7 +297,7 @@ public final U assertError(Throwable error) { * Asserts that this TestObserver/TestSubscriber received exactly one onError event which is an * instance of the specified errorClass class. * @param errorClass the error class to expect - * @return this; + * @return this */ @SuppressWarnings({ "unchecked", "rawtypes", "cast" }) public final U assertError(Class<? extends Throwable> errorClass) { @@ -347,7 +346,7 @@ public final U assertError(Predicate<Throwable> errorPredicate) { * Assert that this TestObserver/TestSubscriber received exactly one onNext value which is equal to * the given value with respect to Objects.equals. * @param value the value to expect - * @return this; + * @return this */ @SuppressWarnings("unchecked") public final U assertValue(T value) { @@ -433,13 +432,13 @@ public final U assertNever(Predicate<? super T> valuePredicate) { /** * Asserts that this TestObserver/TestSubscriber received an onNext value at the given index * which is equal to the given value with respect to null-safe Object.equals. + * <p>History: 2.1.3 - experimental * @param index the position to assert on * @param value the value to expect * @return this - * @since 2.1.3 - experimental + * @since 2.2 */ @SuppressWarnings("unchecked") - @Experimental public final U assertValueAt(int index, T value) { int s = values.size(); if (s == 0) { @@ -508,7 +507,7 @@ public static String valueAndClass(Object o) { /** * Assert that this TestObserver/TestSubscriber received the specified number onNext events. * @param count the expected number of onNext events - * @return this; + * @return this */ @SuppressWarnings("unchecked") public final U assertValueCount(int count) { @@ -521,7 +520,7 @@ public final U assertValueCount(int count) { /** * Assert that this TestObserver/TestSubscriber has not received any onNext events. - * @return this; + * @return this */ public final U assertNoValues() { return assertValueCount(0); @@ -530,7 +529,7 @@ public final U assertNoValues() { /** * Assert that the TestObserver/TestSubscriber received only the specified values in the specified order. * @param values the values expected - * @return this; + * @return this * @see #assertValueSet(Collection) */ @SuppressWarnings("unchecked") @@ -552,12 +551,12 @@ public final U assertValues(T... values) { /** * Assert that the TestObserver/TestSubscriber received only the specified values in the specified order without terminating. + * <p>History: 2.1.4 - experimental * @param values the values expected - * @return this; - * @since 2.1.4 + * @return this + * @since 2.2 */ @SuppressWarnings("unchecked") - @Experimental public final U assertValuesOnly(T... values) { return assertSubscribed() .assertValues(values) @@ -571,7 +570,7 @@ public final U assertValuesOnly(T... values) { * asynchronous streams. * * @param expected the collection of values expected in any order - * @return this; + * @return this */ @SuppressWarnings("unchecked") public final U assertValueSet(Collection<? extends T> expected) { @@ -589,12 +588,11 @@ public final U assertValueSet(Collection<? extends T> expected) { /** * Assert that the TestObserver/TestSubscriber received only the specified values in any order without terminating. + * <p>History: 2.1.14 - experimental * @param expected the collection of values expected in any order - * @return this; - * @since 2.1.14 - experimental + * @return this + * @since 2.2 */ - @SuppressWarnings("unchecked") - @Experimental public final U assertValueSetOnly(Collection<? extends T> expected) { return assertSubscribed() .assertValueSet(expected) @@ -605,7 +603,7 @@ public final U assertValueSetOnly(Collection<? extends T> expected) { /** * Assert that the TestObserver/TestSubscriber received only the specified sequence of values in the same order. * @param sequence the sequence of expected values in order - * @return this; + * @return this */ @SuppressWarnings("unchecked") public final U assertValueSequence(Iterable<? extends T> sequence) { @@ -642,12 +640,11 @@ public final U assertValueSequence(Iterable<? extends T> sequence) { /** * Assert that the TestObserver/TestSubscriber received only the specified values in the specified order without terminating. + * <p>History: 2.1.14 - experimental * @param sequence the sequence of expected values in order - * @return this; - * @since 2.1.14 - experimental + * @return this + * @since 2.2 */ - @SuppressWarnings("unchecked") - @Experimental public final U assertValueSequenceOnly(Iterable<? extends T> sequence) { return assertSubscribed() .assertValueSequence(sequence) @@ -657,7 +654,7 @@ public final U assertValueSequenceOnly(Iterable<? extends T> sequence) { /** * Assert that the TestObserver/TestSubscriber terminated (i.e., the terminal latch reached zero). - * @return this; + * @return this */ @SuppressWarnings("unchecked") public final U assertTerminated() { @@ -681,7 +678,7 @@ public final U assertTerminated() { /** * Assert that the TestObserver/TestSubscriber has not terminated (i.e., the terminal latch is still non-zero). - * @return this; + * @return this */ @SuppressWarnings("unchecked") public final U assertNotTerminated() { @@ -771,13 +768,13 @@ public final List<List<Object>> getEvents() { /** * Assert that the onSubscribe method was called exactly once. - * @return this; + * @return this */ public abstract U assertSubscribed(); /** * Assert that the onSubscribe method hasn't been called at all. - * @return this; + * @return this */ public abstract U assertNotSubscribed(); @@ -1024,6 +1021,7 @@ public final U awaitCount(int atLeast, Runnable waitStrategy, long timeoutMillis } /** + * Returns true if an await timed out. * @return true if one of the timeout-based await methods has timed out. * <p>History: 2.0.7 - experimental * @see #clearTimeout() diff --git a/src/main/java/io/reactivex/observers/LambdaConsumerIntrospection.java b/src/main/java/io/reactivex/observers/LambdaConsumerIntrospection.java index 8bcf1f694c..31588ab0c9 100644 --- a/src/main/java/io/reactivex/observers/LambdaConsumerIntrospection.java +++ b/src/main/java/io/reactivex/observers/LambdaConsumerIntrospection.java @@ -13,24 +13,21 @@ package io.reactivex.observers; -import io.reactivex.annotations.Experimental; - /** * An interface that indicates that the implementing type is composed of individual components and exposes information * about their behavior. * * <p><em>NOTE:</em> This is considered a read-only public API and is not intended to be implemented externally. - * - * @since 2.1.4 - experimental + * <p>History: 2.1.4 - experimental + * @since 2.2 */ -@Experimental public interface LambdaConsumerIntrospection { /** + * Returns true or false if a custom onError consumer has been provided. * @return {@code true} if a custom onError consumer implementation was supplied. Returns {@code false} if the * implementation is missing an error consumer and thus using a throwing default implementation. */ - @Experimental boolean hasCustomOnError(); } diff --git a/src/main/java/io/reactivex/parallel/ParallelFailureHandling.java b/src/main/java/io/reactivex/parallel/ParallelFailureHandling.java index dd53aa622a..867c7496b5 100644 --- a/src/main/java/io/reactivex/parallel/ParallelFailureHandling.java +++ b/src/main/java/io/reactivex/parallel/ParallelFailureHandling.java @@ -13,14 +13,13 @@ package io.reactivex.parallel; -import io.reactivex.annotations.Experimental; import io.reactivex.functions.BiFunction; /** * Enumerations for handling failure within a parallel operator. - * @since 2.0.8 - experimental + * <p>History: 2.0.8 - experimental + * @since 2.2 */ -@Experimental public enum ParallelFailureHandling implements BiFunction<Long, Throwable, ParallelFailureHandling> { /** * The current rail is stopped and the error is dropped. diff --git a/src/main/java/io/reactivex/parallel/ParallelFlowable.java b/src/main/java/io/reactivex/parallel/ParallelFlowable.java index 4dd6dfd93d..519e731776 100644 --- a/src/main/java/io/reactivex/parallel/ParallelFlowable.java +++ b/src/main/java/io/reactivex/parallel/ParallelFlowable.java @@ -34,11 +34,10 @@ * Use {@code runOn()} to introduce where each 'rail' should run on thread-vise. * Use {@code sequential()} to merge the sources back into a single Flowable. * - * <p>History: 2.0.5 - experimental + * <p>History: 2.0.5 - experimental; 2.1 - beta * @param <T> the value type - * @since 2.1 - beta + * @since 2.2 */ -@Beta public abstract class ParallelFlowable<T> { /** @@ -126,14 +125,13 @@ public static <T> ParallelFlowable<T> from(@NonNull Publisher<? extends T> sourc * Calls the specified converter function during assembly time and returns its resulting value. * <p> * This allows fluent conversion to any other type. - * + * <p>History: 2.1.7 - experimental * @param <R> the resulting object type * @param converter the function that receives the current ParallelFlowable instance and returns a value * @return the converted value * @throws NullPointerException if converter is null - * @since 2.1.7 - experimental + * @since 2.2 */ - @Experimental @CheckReturnValue @NonNull public final <R> R as(@NonNull ParallelFlowableConverter<T, R> converter) { @@ -160,15 +158,15 @@ public final <R> ParallelFlowable<R> map(@NonNull Function<? super T, ? extends * handles errors based on the given {@link ParallelFailureHandling} enumeration value. * <p> * Note that the same mapper function may be called from multiple threads concurrently. + * <p>History: 2.0.8 - experimental * @param <R> the output value type * @param mapper the mapper function turning Ts into Us. * @param errorHandler the enumeration that defines how to handle errors thrown * from the mapper function * @return the new ParallelFlowable instance - * @since 2.0.8 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @NonNull public final <R> ParallelFlowable<R> map(@NonNull Function<? super T, ? extends R> mapper, @NonNull ParallelFailureHandling errorHandler) { ObjectHelper.requireNonNull(mapper, "mapper"); @@ -181,16 +179,16 @@ public final <R> ParallelFlowable<R> map(@NonNull Function<? super T, ? extends * handles errors based on the returned value by the handler function. * <p> * Note that the same mapper function may be called from multiple threads concurrently. + * <p>History: 2.0.8 - experimental * @param <R> the output value type * @param mapper the mapper function turning Ts into Us. * @param errorHandler the function called with the current repeat count and * failure Throwable and should return one of the {@link ParallelFailureHandling} * enumeration values to indicate how to proceed. * @return the new ParallelFlowable instance - * @since 2.0.8 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @NonNull public final <R> ParallelFlowable<R> map(@NonNull Function<? super T, ? extends R> mapper, @NonNull BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { ObjectHelper.requireNonNull(mapper, "mapper"); @@ -216,14 +214,14 @@ public final ParallelFlowable<T> filter(@NonNull Predicate<? super T> predicate) * handles errors based on the given {@link ParallelFailureHandling} enumeration value. * <p> * Note that the same predicate may be called from multiple threads concurrently. + * <p>History: 2.0.8 - experimental * @param predicate the function returning true to keep a value or false to drop a value * @param errorHandler the enumeration that defines how to handle errors thrown * from the predicate * @return the new ParallelFlowable instance - * @since 2.0.8 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental public final ParallelFlowable<T> filter(@NonNull Predicate<? super T> predicate, @NonNull ParallelFailureHandling errorHandler) { ObjectHelper.requireNonNull(predicate, "predicate"); ObjectHelper.requireNonNull(errorHandler, "errorHandler is null"); @@ -236,15 +234,15 @@ public final ParallelFlowable<T> filter(@NonNull Predicate<? super T> predicate, * handles errors based on the returned value by the handler function. * <p> * Note that the same predicate may be called from multiple threads concurrently. + * <p>History: 2.0.8 - experimental * @param predicate the function returning true to keep a value or false to drop a value * @param errorHandler the function called with the current repeat count and * failure Throwable and should return one of the {@link ParallelFailureHandling} * enumeration values to indicate how to proceed. * @return the new ParallelFlowable instance - * @since 2.0.8 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental public final ParallelFlowable<T> filter(@NonNull Predicate<? super T> predicate, @NonNull BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { ObjectHelper.requireNonNull(predicate, "predicate"); ObjectHelper.requireNonNull(errorHandler, "errorHandler is null"); @@ -401,15 +399,15 @@ public final Flowable<T> sequential(int prefetch) { * <dt><b>Scheduler:</b></dt> * <dd>{@code sequentialDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.0.7 - experimental * @return the new Flowable instance * @see ParallelFlowable#sequentialDelayError(int) * @see ParallelFlowable#sequential() - * @since 2.0.7 - experimental + * @since 2.2 */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue - @Experimental @NonNull public final Flowable<T> sequentialDelayError() { return sequentialDelayError(Flowable.bufferSize()); @@ -426,11 +424,12 @@ public final Flowable<T> sequentialDelayError() { * <dt><b>Scheduler:</b></dt> * <dd>{@code sequentialDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> + * <p>History: 2.0.7 - experimental * @param prefetch the prefetch amount to use for each rail * @return the new Flowable instance * @see ParallelFlowable#sequential() * @see ParallelFlowable#sequentialDelayError() - * @since 2.0.7 - experimental + * @since 2.2 */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @@ -541,15 +540,14 @@ public final ParallelFlowable<T> doOnNext(@NonNull Consumer<? super T> onNext) { /** * Call the specified consumer with the current element passing through any 'rail' and * handles errors based on the given {@link ParallelFailureHandling} enumeration value. - * + * <p>History: 2.0.8 - experimental * @param onNext the callback * @param errorHandler the enumeration that defines how to handle errors thrown * from the onNext consumer * @return the new ParallelFlowable instance - * @since 2.0.8 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @NonNull public final ParallelFlowable<T> doOnNext(@NonNull Consumer<? super T> onNext, @NonNull ParallelFailureHandling errorHandler) { ObjectHelper.requireNonNull(onNext, "onNext is null"); @@ -560,16 +558,15 @@ public final ParallelFlowable<T> doOnNext(@NonNull Consumer<? super T> onNext, @ /** * Call the specified consumer with the current element passing through any 'rail' and * handles errors based on the returned value by the handler function. - * + * <p>History: 2.0.8 - experimental * @param onNext the callback * @param errorHandler the function called with the current repeat count and * failure Throwable and should return one of the {@link ParallelFailureHandling} * enumeration values to indicate how to proceed. * @return the new ParallelFlowable instance - * @since 2.0.8 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @NonNull public final ParallelFlowable<T> doOnNext(@NonNull Consumer<? super T> onNext, @NonNull BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { ObjectHelper.requireNonNull(onNext, "onNext is null"); diff --git a/src/main/java/io/reactivex/parallel/ParallelFlowableConverter.java b/src/main/java/io/reactivex/parallel/ParallelFlowableConverter.java index f782eb7bb0..9d1b287849 100644 --- a/src/main/java/io/reactivex/parallel/ParallelFlowableConverter.java +++ b/src/main/java/io/reactivex/parallel/ParallelFlowableConverter.java @@ -18,12 +18,11 @@ /** * Convenience interface and callback used by the {@link ParallelFlowable#as} operator to turn a ParallelFlowable into * another value fluently. - * + * <p>History: 2.1.7 - experimental * @param <T> the upstream type * @param <R> the output type - * @since 2.1.7 - experimental + * @since 2.2 */ -@Experimental public interface ParallelFlowableConverter<T, R> { /** * Applies a function to the upstream ParallelFlowable and returns a converted value of type {@code R}. diff --git a/src/main/java/io/reactivex/parallel/ParallelTransformer.java b/src/main/java/io/reactivex/parallel/ParallelTransformer.java index f6837bf948..9981934867 100644 --- a/src/main/java/io/reactivex/parallel/ParallelTransformer.java +++ b/src/main/java/io/reactivex/parallel/ParallelTransformer.java @@ -17,13 +17,11 @@ /** * Interface to compose ParallelFlowable. - * + * <p>History: 2.0.8 - experimental * @param <Upstream> the upstream value type * @param <Downstream> the downstream value type - * - * @since 2.0.8 - experimental + * @since 2.2 */ -@Experimental public interface ParallelTransformer<Upstream, Downstream> { /** * Applies a function to the upstream ParallelFlowable and returns a ParallelFlowable with diff --git a/src/main/java/io/reactivex/plugins/RxJavaPlugins.java b/src/main/java/io/reactivex/plugins/RxJavaPlugins.java index 339036c134..4da3a30122 100644 --- a/src/main/java/io/reactivex/plugins/RxJavaPlugins.java +++ b/src/main/java/io/reactivex/plugins/RxJavaPlugins.java @@ -1104,11 +1104,10 @@ public static Completable onAssembly(@NonNull Completable source) { /** * Sets the specific hook function. - * <p>History: 2.0.6 - experimental + * <p>History: 2.0.6 - experimental; 2.1 - beta * @param handler the hook function to set, null allowed - * @since 2.1 - beta + * @since 2.2 */ - @Beta @SuppressWarnings("rawtypes") public static void setOnParallelAssembly(@Nullable Function<? super ParallelFlowable, ? extends ParallelFlowable> handler) { if (lockdown) { @@ -1119,11 +1118,10 @@ public static void setOnParallelAssembly(@Nullable Function<? super ParallelFlow /** * Returns the current hook function. - * <p>History: 2.0.6 - experimental + * <p>History: 2.0.6 - experimental; 2.1 - beta * @return the hook function, may be null - * @since 2.1 - beta + * @since 2.2 */ - @Beta @SuppressWarnings("rawtypes") @Nullable public static Function<? super ParallelFlowable, ? extends ParallelFlowable> getOnParallelAssembly() { @@ -1132,13 +1130,12 @@ public static void setOnParallelAssembly(@Nullable Function<? super ParallelFlow /** * Calls the associated hook function. - * <p>History: 2.0.6 - experimental + * <p>History: 2.0.6 - experimental; 2.1 - beta * @param <T> the value type of the source * @param source the hook's input value * @return the value returned by the hook - * @since 2.1 - beta + * @since 2.2 */ - @Beta @SuppressWarnings({ "rawtypes", "unchecked" }) @NonNull public static <T> ParallelFlowable<T> onAssembly(@NonNull ParallelFlowable<T> source) { diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index 5ee462824f..0c4af463e0 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -315,11 +315,11 @@ public void onComplete() { * <p> * Calling with null will terminate the PublishProcessor and a NullPointerException * is signalled to the Subscribers. + * <p>History: 2.0.8 - experimental * @param t the item to emit, not null * @return true if the item was emitted to all Subscribers - * @since 2.0.8 - experimental + * @since 2.2 */ - @Experimental public boolean offer(T t) { if (t == null) { onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); diff --git a/src/main/java/io/reactivex/processors/MulticastProcessor.java b/src/main/java/io/reactivex/processors/MulticastProcessor.java index 71d8a2dd8e..3d0923a8ab 100644 --- a/src/main/java/io/reactivex/processors/MulticastProcessor.java +++ b/src/main/java/io/reactivex/processors/MulticastProcessor.java @@ -123,10 +123,10 @@ mp2.test().assertResult(1, 2, 3, 4); * </code></pre> + * <p>History: 2.1.14 - experimental * @param <T> the input and output value type - * @since 2.1.14 - experimental + * @since 2.2 */ -@Experimental @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final class MulticastProcessor<T> extends FlowableProcessor<T> { diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index 3f409555df..38f0aa874c 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -280,11 +280,11 @@ public void onComplete() { * <p> * Calling with null will terminate the PublishProcessor and a NullPointerException * is signalled to the Subscribers. + * <p>History: 2.0.8 - experimental * @param t the item to emit, not null * @return true if the item was emitted to all Subscribers - * @since 2.0.8 - experimental + * @since 2.2 */ - @Experimental public boolean offer(T t) { if (t == null) { onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index b16ef80f68..95bcf5d263 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -433,9 +433,9 @@ public Throwable getThrowable() { * <p> * The method must be called sequentially, similar to the standard * {@code onXXX} methods. - * @since 2.1.11 - experimental + * <p>History: 2.1.11 - experimental + * @since 2.2 */ - @Experimental public void cleanupBuffer() { buffer.trimHead(); } diff --git a/src/main/java/io/reactivex/processors/UnicastProcessor.java b/src/main/java/io/reactivex/processors/UnicastProcessor.java index 62abd68cd4..c9fb44f7eb 100644 --- a/src/main/java/io/reactivex/processors/UnicastProcessor.java +++ b/src/main/java/io/reactivex/processors/UnicastProcessor.java @@ -16,7 +16,6 @@ import io.reactivex.annotations.CheckReturnValue; import java.util.concurrent.atomic.*; -import io.reactivex.annotations.Experimental; import io.reactivex.annotations.Nullable; import io.reactivex.annotations.NonNull; import org.reactivestreams.*; @@ -198,13 +197,13 @@ public static <T> UnicastProcessor<T> create(int capacityHint) { /** * Creates an UnicastProcessor with default internal buffer capacity hint and delay error flag. + * <p>History: 2.0.8 - experimental * @param <T> the value type * @param delayError deliver pending onNext events before onError * @return an UnicastProcessor instance - * @since 2.0.8 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @NonNull public static <T> UnicastProcessor<T> create(boolean delayError) { return new UnicastProcessor<T>(bufferSize(), null, delayError); @@ -235,16 +234,15 @@ public static <T> UnicastProcessor<T> create(int capacityHint, Runnable onCancel * * <p>The callback, if not null, is called exactly once and * non-overlapped with any active replay. - * + * <p>History: 2.0.8 - experimental * @param <T> the value type * @param capacityHint the hint to size the internal unbounded buffer * @param onCancelled the non null callback * @param delayError deliver pending onNext events before onError * @return an UnicastProcessor instance - * @since 2.0.8 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @NonNull public static <T> UnicastProcessor<T> create(int capacityHint, Runnable onCancelled, boolean delayError) { ObjectHelper.requireNonNull(onCancelled, "onTerminate"); @@ -274,10 +272,11 @@ public static <T> UnicastProcessor<T> create(int capacityHint, Runnable onCancel /** * Creates an UnicastProcessor with the given capacity hint and callback * for when the Processor is terminated normally or its single Subscriber cancels. + * <p>History: 2.0.8 - experimental * @param capacityHint the capacity hint for the internal, unbounded queue * @param onTerminate the callback to run when the Processor is terminated or cancelled, null not allowed * @param delayError deliver pending onNext events before onError - * @since 2.0.8 - experimental + * @since 2.2 */ UnicastProcessor(int capacityHint, Runnable onTerminate, boolean delayError) { this.queue = new SpscLinkedArrayQueue<T>(ObjectHelper.verifyPositive(capacityHint, "capacityHint")); diff --git a/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java b/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java index 810fd6f408..aa930e4f97 100644 --- a/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java +++ b/src/main/java/io/reactivex/schedulers/SchedulerRunnableIntrospection.java @@ -24,10 +24,9 @@ * task in a custom {@link RxJavaPlugins#onSchedule(Runnable)} hook set via * the {@link RxJavaPlugins#setScheduleHandler(Function)} method multiple times due to internal delegation * of the default {@code Scheduler.scheduleDirect} or {@code Scheduler.Worker.schedule} methods. - * - * @since 2.1.7 - experimental + * <p>History: 2.1.7 - experimental + * @since 2.2 */ -@Experimental public interface SchedulerRunnableIntrospection { /** diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java index 2a553f51d5..9454de50d0 100644 --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java @@ -431,9 +431,9 @@ public T getValue() { * <p> * The method must be called sequentially, similar to the standard * {@code onXXX} methods. - * @since 2.1.11 - experimental + * <p>History: 2.1.11 - experimental + * @since 2.2 */ - @Experimental public void cleanupBuffer() { buffer.trimHead(); } diff --git a/src/main/java/io/reactivex/subjects/UnicastSubject.java b/src/main/java/io/reactivex/subjects/UnicastSubject.java index f19a8b0a38..e6cc271073 100644 --- a/src/main/java/io/reactivex/subjects/UnicastSubject.java +++ b/src/main/java/io/reactivex/subjects/UnicastSubject.java @@ -13,7 +13,6 @@ package io.reactivex.subjects; -import io.reactivex.annotations.Experimental; import io.reactivex.annotations.Nullable; import io.reactivex.annotations.NonNull; import io.reactivex.plugins.RxJavaPlugins; @@ -221,16 +220,15 @@ public static <T> UnicastSubject<T> create(int capacityHint, Runnable onTerminat * * <p>The callback, if not null, is called exactly once and * non-overlapped with any active replay. - * + * <p>History: 2.0.8 - experimental * @param <T> the value type * @param capacityHint the hint to size the internal unbounded buffer * @param onTerminate the callback to run when the Subject is terminated or cancelled, null not allowed * @param delayError deliver pending onNext events before onError * @return an UnicastSubject instance - * @since 2.0.8 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @NonNull public static <T> UnicastSubject<T> create(int capacityHint, Runnable onTerminate, boolean delayError) { return new UnicastSubject<T>(capacityHint, onTerminate, delayError); @@ -241,14 +239,13 @@ public static <T> UnicastSubject<T> create(int capacityHint, Runnable onTerminat * * <p>The callback, if not null, is called exactly once and * non-overlapped with any active replay. - * + * <p>History: 2.0.8 - experimental * @param <T> the value type * @param delayError deliver pending onNext events before onError * @return an UnicastSubject instance - * @since 2.0.8 - experimental + * @since 2.2 */ @CheckReturnValue - @Experimental @NonNull public static <T> UnicastSubject<T> create(boolean delayError) { return new UnicastSubject<T>(bufferSize(), delayError); @@ -257,9 +254,10 @@ public static <T> UnicastSubject<T> create(boolean delayError) { /** * Creates an UnicastSubject with the given capacity hint and delay error flag. + * <p>History: 2.0.8 - experimental * @param capacityHint the capacity hint for the internal, unbounded queue * @param delayError deliver pending onNext events before onError - * @since 2.0.8 - experimental + * @since 2.2 */ UnicastSubject(int capacityHint, boolean delayError) { this.queue = new SpscLinkedArrayQueue<T>(ObjectHelper.verifyPositive(capacityHint, "capacityHint")); @@ -285,10 +283,11 @@ public static <T> UnicastSubject<T> create(boolean delayError) { /** * Creates an UnicastSubject with the given capacity hint, delay error flag and callback * for when the Subject is terminated normally or its single Subscriber cancels. + * <p>History: 2.0.8 - experimental * @param capacityHint the capacity hint for the internal, unbounded queue * @param onTerminate the callback to run when the Subject is terminated or cancelled, null not allowed * @param delayError deliver pending onNext events before onError - * @since 2.0.8 - experimental + * @since 2.2 */ UnicastSubject(int capacityHint, Runnable onTerminate, boolean delayError) { this.queue = new SpscLinkedArrayQueue<T>(ObjectHelper.verifyPositive(capacityHint, "capacityHint")); From 839c70fe58b812ca5914ef5ec65a7120081d4252 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 31 Jul 2018 09:28:56 +0200 Subject: [PATCH 241/417] Release 2.2 --- CHANGES.md | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 2312403710..86d4eda074 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,86 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.0 - July 31, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.0%7C)) + +#### Summary + +Version 2.2.0 is the next minor release of the 2.x era and contains the standardization of many experimental API additions from the past year since version 2.1.0. Therefore, the following components are now considered stable and will be supported throughout the rest of the life of RxJava 2.x. + +**Classes, Enums, Annotations** + +- **Annotation**: N/A +- **Subject**: `MulticastProcessor` +- **Classes**: `ParallelFlowable`, `UndeliverableException`, `OnErrorNotImplementedException` +- **Enum**: `ParallelFailureHandling` +- **Interfaces**: `{Completable|Single|Maybe|Observable|Flowable|Parallel}Emitter`, `{Completable|Single|Maybe|Observable|Flowable|Parallel}Converter`, `LambdaConsumerIntrospection`, `ScheduledRunnableIntrospection` + +**Operators** + +- **`Flowable`**: `as`, `concatMap{Single|Maybe|Completable}`, `limit`, `parallel`, `switchMap{Single|Maybe|Completable}`, `throttleLatest` +- **`Observable`**: `as`, `concatMap{Single|Maybe|Completable}`, `switchMap{Single|Maybe|Completable}`, `throttleLatest` +- **`Single`**: `as`, `mergeDelayError`, `onTerminateDetach`, `unsubscribeOn` +- **`Maybe`**: `as`, `mergeDelayError`, `switchIfEmpty` +- **`Completable`**: `as`, `fromMaybe`, `onTerminateDetach`, `takeUntil` +- **`ParallelFlowable`**: `as`, `map|filter|doOnNext(errorHandling)`˙, `sequentialDelayError` +- **`Connectable{Flowable, Observable}`**: `refCount(count + timeout)` +- **`Subject`/`FlowableProcessor`**: `offer`, `cleanupBuffer`, `create(..., delayError)` +- **`Test{Observer, Subscriber}`**: `assertValueAt`, `assertValuesOnly`, `assertValueSetOnly` + +*(For the complete list and details on the promotions, see [PR 6105](https://github.com/ReactiveX/RxJava/pull/6105).)* + +Release 2.2.0 is functionally identical to 2.1.17. Also to clarify, just like with previous minor version increments with RxJava, there won't be any further development or updates on the version 2.1.x (patch) level. + +##### Other promotions + +All Experimental/Beta APIs introduced up to version 2.1.17 are now standard with 2.2. + +#### Project statistics + +- Unique contributors: **75** +- Issues closed: [**283**](https://github.com/ReactiveX/RxJava/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aclosed+created%3A2017-04-29..2018-07-31+label%3A2.x+) +- Bugs reported: [**20**](https://github.com/ReactiveX/RxJava/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aclosed+created%3A2017-04-29..2018-07-31+label%3A2.x+label%3Abug) + - by community: [**19**](https://github.com/ReactiveX/RxJava/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aclosed+created%3A2017-04-29..2018-07-31+label%3A2.x+label%3Abug+-author%3Aakarnokd) (95%) +- Commits: [**320**](https://github.com/ReactiveX/RxJava/compare/v2.1.0...2.x) +- PRs: [**296**](https://github.com/ReactiveX/RxJava/pulls?q=is%3Apr+is%3Aclosed+created%3A2017-04-29..2018-07-31+label%3A2.x) + - PRs accepted: [**268**](https://github.com/ReactiveX/RxJava/pulls?q=is%3Apr+is%3Aclosed+created%3A2017-04-29..2018-07-31+label%3A2.x) (90.54%) + - Community PRs: [**96**](https://github.com/ReactiveX/RxJava/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aclosed+created%3A2017-04-29..2018-07-31+label%3A2.x+-author%3Aakarnokd+) (35.82% of all accepted) +- Bugs fixed: [**39**](https://github.com/ReactiveX/RxJava/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aclosed+merged%3A2017-04-29..2018-07-31+label%3A2.x+label%3Abug) + - by community: [**8**](https://github.com/ReactiveX/RxJava/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aclosed+merged%3A2017-04-29..2018-07-31+label%3A2.x+label%3Abug+-author%3Aakarnokd) (20.51%) +- Documentation enhancements: [**117**](https://github.com/ReactiveX/RxJava/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aclosed+merged%3A2017-04-29..2018-07-31+label%3A2.x+label%3Adocumentation) + - by community: [**40**](https://github.com/ReactiveX/RxJava/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aclosed+merged%3A2017-04-29..2018-07-31+label%3A2.x+label%3Adocumentation+-author%3Aakarnokd) (34.19%) +- Cleanup: [**50**](https://github.com/ReactiveX/RxJava/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aclosed+merged%3A2017-04-29..2018-07-31+label%3A2.x+label%3Acleanup) + - by community: [**21**](https://github.com/ReactiveX/RxJava/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aclosed+merged%3A2017-04-29..2018-07-31+label%3A2.x+label%3Acleanup+-author%3Aakarnokd) (42%) +- Performance enhancements: [**12**](https://github.com/ReactiveX/RxJava/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aclosed+merged%3A2017-04-29..2018-07-31+label%3A2.x+label%3A%22performance%22+) + - by community: [**1**](https://github.com/ReactiveX/RxJava/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aclosed+merged%3A2017-04-29..2018-07-31+label%3A2.x+label%3A%22performance%22+-author%3Aakarnokd) (8.33%) +- Lines + - added: **70,465** + - removed: **12,373** + +#### Acknowledgements + +The project would like to thank the following contributors for their work on various code and documentation improvements (in the order they appear on the [commit](https://github.com/ReactiveX/RxJava/commits/2.x) page): + +@lcybo, @jnlopar, @UMFsimke, @apodkutin, @sircelsius, +@romanzes, @Kiskae, @RomanWuattier, @satoshun, @hans123456, +@fjoshuajr, @davidmoten, @vanniktech, @antego, @strekha, +@artfullyContrived, @VeskoI, @Desislav-Petrov, @Apsaliya, @sidjain270592, +@Milack27, @mekarthedev, @kjkrum, @zhyuri, @artem-zinnatullin, +@vpriscan, @aaronhe42, @adamsp, @bangarharshit, @zhukic, +@afeozzz, @btilbrook-nextfaze, @eventualbuddha, @shaishavgandhi05, @lukaszguz, +@runningcode, @kimkevin, @JakeWharton, @hzsweers, @ggikko, +@philleonard, @sadegh, @dsrees, @benwicks, @dweebo, +@dimsuz, @levaja, @takuaraki, @PhilGlass, @bmaslakov, +@tylerbwong, @AllanWang, @NickFirmani, @plackemacher, @matgabriel, +@jemaystermind, @ansman, @Ganapathi004, @leonardortlima, @pwittchen, +@youngam, @Sroka, @serj-lotutovici, @nathankooij, @mithunsasidharan, +@devisnik, @mg6maciej, @Rémon S, @hvesalai, @kojilin, +@ragunathjawahar, @brucezz, @paulblessing, @cypressf, @langara + +**(75 contributors)** + +The project would also thank its tireless reviewer @vanniktech for all his efforts on verifying and providing feedback on the many PRs from the project lead himself. :+1: + ### Version 2.1.17 - July 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.1.17%7C)) #### API changes From 749d60546a52c72b158af2ecd2ddcc88afccc942 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 31 Jul 2018 10:04:41 +0200 Subject: [PATCH 242/417] 2.x: Update Readme.md about the parallel() operator (#6117) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d3b6533eb..1fadd32ba6 100644 --- a/README.md +++ b/README.md @@ -240,7 +240,7 @@ Note, however, that `flatMap` doesn't guarantee any order and the end result fro - `concatMap` that maps and runs one inner flow at a time and - `concatMapEager` which runs all inner flows "at once" but the output flow will be in the order those inner flows were created. -Alternatively, there is a [*beta*](#beta) operator `Flowable.parallel()` and type `ParallelFlowable` that helps achieve the same parallel processing pattern: +Alternatively, the `Flowable.parallel()` operator and the `ParallelFlowable` type help achieve the same parallel processing pattern: ```java Flowable.range(1, 10) From a20f993dfc9f30ee1635f7ced155eee188926f9a Mon Sep 17 00:00:00 2001 From: Marc Bramaud <sircelsius@users.noreply.github.com> Date: Tue, 31 Jul 2018 10:14:26 +0200 Subject: [PATCH 243/417] 6108 changed README to use Gradle's implementation instead of compile (#6116) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1fadd32ba6..957d1a05e6 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ The [1.x version](https://github.com/ReactiveX/RxJava/tree/1.x) is end-of-life a The first step is to include RxJava 2 into your project, for example, as a Gradle compile dependency: ```groovy -compile "io.reactivex.rxjava2:rxjava:2.x.y" +implementation "io.reactivex.rxjava2:rxjava:2.x.y" ``` (Please replace `x` and `y` with the latest version numbers: [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.reactivex.rxjava2/rxjava/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.reactivex.rxjava2/rxjava) From 45cc53db6d9211a8fc2f62b8167ed54d4f7fda83 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 1 Aug 2018 10:23:11 +0200 Subject: [PATCH 244/417] 2.x: Test cleanup (#6119) * 2.x: Test error printout, local naming, mocking cleanup * Fix additional local variable names * Fix Observers with wrong variable names * Fix nit * More time to MulticastProcessorRefCountedTckTest --- .../InputWithIncrementingInteger.java | 4 +- .../io/reactivex/OperatorFlatMapPerf.java | 6 +- .../java/io/reactivex/OperatorMergePerf.java | 4 +- src/main/java/io/reactivex/Completable.java | 30 +- .../java/io/reactivex/FlowableOperator.java | 4 +- src/main/java/io/reactivex/Observable.java | 48 +- src/main/java/io/reactivex/Single.java | 22 +- .../internal/disposables/EmptyDisposable.java | 42 +- .../observers/QueueDrainObserver.java | 12 +- .../SubscriberCompletableObserver.java | 4 +- .../operators/completable/CompletableAmb.java | 24 +- .../completable/CompletableCache.java | 10 +- .../completable/CompletableConcat.java | 4 +- .../completable/CompletableConcatArray.java | 6 +- .../CompletableConcatIterable.java | 8 +- .../completable/CompletableCreate.java | 6 +- .../completable/CompletableDefer.java | 6 +- .../completable/CompletableDelay.java | 4 +- .../completable/CompletableDisposeOn.java | 16 +- .../completable/CompletableDoFinally.java | 4 +- .../completable/CompletableDoOnEvent.java | 4 +- .../completable/CompletableEmpty.java | 4 +- .../completable/CompletableError.java | 4 +- .../completable/CompletableErrorSupplier.java | 4 +- .../completable/CompletableFromAction.java | 8 +- .../completable/CompletableFromCallable.java | 8 +- .../CompletableFromObservable.java | 4 +- .../completable/CompletableFromRunnable.java | 8 +- .../completable/CompletableFromSingle.java | 4 +- .../completable/CompletableLift.java | 4 +- .../completable/CompletableMerge.java | 4 +- .../completable/CompletableMergeArray.java | 6 +- .../CompletableMergeDelayErrorArray.java | 14 +- .../CompletableMergeDelayErrorIterable.java | 12 +- .../completable/CompletableMergeIterable.java | 8 +- .../completable/CompletableNever.java | 4 +- .../completable/CompletableObserveOn.java | 4 +- .../CompletableOnErrorComplete.java | 20 +- .../completable/CompletablePeek.java | 4 +- .../completable/CompletableResumeNext.java | 22 +- .../completable/CompletableSubscribeOn.java | 6 +- .../CompletableTakeUntilCompletable.java | 6 +- .../completable/CompletableTimeout.java | 30 +- .../completable/CompletableTimer.java | 6 +- .../completable/CompletableToSingle.java | 4 +- .../flowable/BlockingFlowableNext.java | 14 +- .../operators/flowable/FlowableAllSingle.java | 4 +- .../operators/flowable/FlowableAnySingle.java | 4 +- .../flowable/FlowableCollectSingle.java | 6 +- .../flowable/FlowableCountSingle.java | 4 +- .../operators/flowable/FlowableDistinct.java | 6 +- .../flowable/FlowableElementAtMaybe.java | 4 +- .../flowable/FlowableElementAtSingle.java | 4 +- .../flowable/FlowableFlatMapCompletable.java | 8 +- .../FlowableMergeWithCompletable.java | 6 +- .../flowable/FlowableMergeWithMaybe.java | 6 +- .../flowable/FlowableMergeWithSingle.java | 6 +- .../operators/flowable/FlowableReplay.java | 12 +- .../flowable/FlowableSequenceEqualSingle.java | 6 +- .../flowable/FlowableSingleMaybe.java | 4 +- .../flowable/FlowableSingleSingle.java | 4 +- .../flowable/FlowableToListSingle.java | 6 +- .../internal/operators/maybe/MaybeCreate.java | 6 +- .../maybe/MaybeDelayWithCompletable.java | 4 +- .../operators/maybe/MaybeDoAfterSuccess.java | 4 +- .../operators/maybe/MaybeDoFinally.java | 4 +- .../maybe/MaybeFlatMapCompletable.java | 6 +- .../maybe/MaybeFlatMapIterableObservable.java | 4 +- .../operators/maybe/MaybeToObservable.java | 4 +- .../mixed/CompletableAndThenObservable.java | 6 +- .../mixed/FlowableConcatMapCompletable.java | 4 +- .../mixed/FlowableSwitchMapCompletable.java | 4 +- .../mixed/MaybeFlatMapObservable.java | 6 +- .../mixed/ObservableConcatMapCompletable.java | 6 +- .../mixed/ObservableConcatMapMaybe.java | 6 +- .../mixed/ObservableConcatMapSingle.java | 6 +- .../mixed/ObservableSwitchMapCompletable.java | 6 +- .../mixed/ObservableSwitchMapMaybe.java | 6 +- .../mixed/ObservableSwitchMapSingle.java | 6 +- .../mixed/SingleFlatMapObservable.java | 6 +- .../operators/observable/ObservableAmb.java | 12 +- .../observable/ObservableCombineLatest.java | 10 +- .../observable/ObservableConcatMap.java | 8 +- .../operators/observable/ObservableDefer.java | 6 +- .../operators/observable/ObservableDelay.java | 8 +- .../observable/ObservableDetach.java | 4 +- .../ObservableDistinctUntilChanged.java | 4 +- .../observable/ObservableDoAfterNext.java | 4 +- .../observable/ObservableDoFinally.java | 4 +- .../operators/observable/ObservableError.java | 4 +- .../observable/ObservableFilter.java | 4 +- .../observable/ObservableFlatMapMaybe.java | 4 +- .../observable/ObservableFlatMapSingle.java | 4 +- .../observable/ObservableFromArray.java | 6 +- .../observable/ObservableFromCallable.java | 8 +- .../observable/ObservableFromFuture.java | 8 +- .../observable/ObservableFromIterable.java | 12 +- .../observable/ObservableGenerate.java | 8 +- .../observable/ObservableGroupBy.java | 8 +- .../observable/ObservableGroupJoin.java | 6 +- .../observable/ObservableInterval.java | 6 +- .../observable/ObservableIntervalRange.java | 6 +- .../operators/observable/ObservableJoin.java | 6 +- .../operators/observable/ObservableJust.java | 6 +- .../operators/observable/ObservableLift.java | 8 +- .../observable/ObservableRefCount.java | 4 +- .../observable/ObservableRepeat.java | 6 +- .../observable/ObservableRepeatUntil.java | 6 +- .../ObservableRetryBiPredicate.java | 6 +- .../observable/ObservableRetryPredicate.java | 6 +- .../observable/ObservableScalarXMap.java | 14 +- .../observable/ObservableSequenceEqual.java | 22 +- .../ObservableSequenceEqualSingle.java | 22 +- .../operators/observable/ObservableSkip.java | 4 +- .../observable/ObservableSkipLast.java | 4 +- .../observable/ObservableSkipWhile.java | 4 +- .../observable/ObservableSubscribeOn.java | 6 +- .../observable/ObservableTakeLastOne.java | 4 +- .../ObservableTakeUntilPredicate.java | 4 +- .../observable/ObservableThrottleLatest.java | 4 +- .../observable/ObservableTimeout.java | 10 +- .../observable/ObservableTimeoutTimed.java | 10 +- .../operators/observable/ObservableTimer.java | 6 +- .../operators/observable/ObservableUsing.java | 10 +- .../ObservableWithLatestFromMany.java | 14 +- .../operators/observable/ObservableZip.java | 6 +- .../internal/operators/single/SingleAmb.java | 22 +- .../operators/single/SingleCache.java | 10 +- .../operators/single/SingleContains.java | 20 +- .../operators/single/SingleCreate.java | 6 +- .../operators/single/SingleDefer.java | 6 +- .../operators/single/SingleDelay.java | 16 +- .../single/SingleDelayWithCompletable.java | 4 +- .../single/SingleDelayWithObservable.java | 4 +- .../single/SingleDelayWithPublisher.java | 4 +- .../single/SingleDelayWithSingle.java | 4 +- .../single/SingleDoAfterSuccess.java | 4 +- .../single/SingleDoAfterTerminate.java | 4 +- .../operators/single/SingleDoFinally.java | 4 +- .../operators/single/SingleDoOnDispose.java | 4 +- .../operators/single/SingleDoOnError.java | 16 +- .../operators/single/SingleDoOnEvent.java | 18 +- .../operators/single/SingleDoOnSubscribe.java | 4 +- .../operators/single/SingleDoOnSuccess.java | 19 +- .../operators/single/SingleEquals.java | 18 +- .../operators/single/SingleError.java | 4 +- .../single/SingleFlatMapCompletable.java | 6 +- .../SingleFlatMapIterableObservable.java | 4 +- .../operators/single/SingleFromPublisher.java | 4 +- .../internal/operators/single/SingleHide.java | 4 +- .../internal/operators/single/SingleJust.java | 6 +- .../internal/operators/single/SingleLift.java | 6 +- .../operators/single/SingleNever.java | 4 +- .../operators/single/SingleObserveOn.java | 4 +- .../operators/single/SingleOnErrorReturn.java | 4 +- .../operators/single/SingleResumeNext.java | 4 +- .../operators/single/SingleSubscribeOn.java | 6 +- .../operators/single/SingleTimeout.java | 6 +- .../operators/single/SingleTimer.java | 6 +- .../operators/single/SingleToObservable.java | 4 +- .../operators/single/SingleUsing.java | 8 +- .../internal/util/NotificationLite.java | 22 +- .../internal/util/QueueDrainHelper.java | 10 +- .../io/reactivex/plugins/RxJavaPlugins.java | 8 +- .../io/reactivex/subjects/AsyncSubject.java | 8 +- .../reactivex/CheckLocalVariablesInTests.java | 85 ++ .../reactivex/ParamValidationCheckerTest.java | 8 +- src/test/java/io/reactivex/TestHelper.java | 80 +- .../completable/CompletableTest.java | 198 +++-- .../reactivex/exceptions/ExceptionsTest.java | 26 +- .../flowable/FlowableCollectTest.java | 6 +- .../flowable/FlowableConcatTests.java | 54 +- .../flowable/FlowableConversionTest.java | 14 +- .../flowable/FlowableCovarianceTest.java | 8 +- .../flowable/FlowableErrorHandlingTests.java | 14 +- .../flowable/FlowableMergeTests.java | 24 +- .../reactivex/flowable/FlowableNullTests.java | 62 +- .../flowable/FlowableReduceTests.java | 8 +- .../flowable/FlowableSubscriberTest.java | 55 +- .../io/reactivex/flowable/FlowableTests.java | 377 ++++----- .../flowable/FlowableThrottleLastTests.java | 14 +- .../FlowableThrottleWithTimeoutTests.java | 14 +- .../observers/DeferredScalarObserverTest.java | 190 +++-- .../observers/FutureObserverTest.java | 128 +-- .../observers/FutureSingleObserverTest.java | 51 +- .../observers/LambdaObserverTest.java | 160 ++-- .../completable/CompletableConcatTest.java | 49 +- .../completable/CompletableCreateTest.java | 115 +-- .../completable/CompletableDoOnTest.java | 8 +- .../completable/CompletableLiftTest.java | 11 +- .../completable/CompletableMergeTest.java | 36 +- .../completable/CompletableTakeUntilTest.java | 24 +- .../completable/CompletableUnsafeTest.java | 19 +- .../completable/CompletableUsingTest.java | 88 +- .../AbstractFlowableWithUpstreamTest.java | 4 +- .../flowable/BlockingFlowableNextTest.java | 14 +- .../BlockingFlowableToFutureTest.java | 8 +- .../BlockingFlowableToIteratorTest.java | 8 +- .../operators/flowable/FlowableAllTest.java | 94 +-- .../operators/flowable/FlowableAmbTest.java | 67 +- .../operators/flowable/FlowableAnyTest.java | 210 ++--- .../flowable/FlowableAsObservableTest.java | 24 +- .../flowable/FlowableBlockingTest.java | 6 +- .../flowable/FlowableBufferTest.java | 487 +++++------ .../operators/flowable/FlowableCacheTest.java | 28 +- .../operators/flowable/FlowableCastTest.java | 24 +- .../flowable/FlowableCombineLatestTest.java | 238 +++--- .../flowable/FlowableConcatMapEagerTest.java | 12 +- .../flowable/FlowableConcatTest.java | 280 +++---- .../FlowableConcatWithCompletableTest.java | 46 +- .../operators/flowable/FlowableCountTest.java | 8 +- .../flowable/FlowableCreateTest.java | 761 ++++++++++-------- .../flowable/FlowableDebounceTest.java | 68 +- .../flowable/FlowableDefaultIfEmptyTest.java | 42 +- .../operators/flowable/FlowableDeferTest.java | 39 +- .../FlowableDelaySubscriptionOtherTest.java | 14 +- .../operators/flowable/FlowableDelayTest.java | 380 ++++----- .../flowable/FlowableDematerializeTest.java | 104 +-- .../flowable/FlowableDetachTest.java | 4 +- .../flowable/FlowableDistinctTest.java | 16 +- .../FlowableDoAfterTerminateTest.java | 40 +- .../flowable/FlowableDoOnEachTest.java | 74 +- .../flowable/FlowableDoOnLifecycleTest.java | 4 +- .../flowable/FlowableDoOnSubscribeTest.java | 26 +- .../flowable/FlowableElementAtTest.java | 24 +- .../flowable/FlowableFilterTest.java | 12 +- .../operators/flowable/FlowableFirstTest.java | 192 ++--- .../FlowableFlatMapCompletableTest.java | 28 +- .../flowable/FlowableFlatMapMaybeTest.java | 8 +- .../flowable/FlowableFlatMapSingleTest.java | 8 +- .../flowable/FlowableFlatMapTest.java | 147 ++-- .../flowable/FlowableFlattenIterableTest.java | 4 +- .../flowable/FlowableFromCallableTest.java | 38 +- .../flowable/FlowableFromIterableTest.java | 58 +- .../flowable/FlowableFromSourceTest.java | 157 ++-- .../flowable/FlowableGroupByTest.java | 69 +- .../flowable/FlowableGroupJoinTest.java | 163 ++-- .../operators/flowable/FlowableHideTest.java | 24 +- .../flowable/FlowableIgnoreElementsTest.java | 8 +- .../operators/flowable/FlowableJoinTest.java | 136 ++-- .../operators/flowable/FlowableLastTest.java | 72 +- .../operators/flowable/FlowableLiftTest.java | 9 +- .../flowable/FlowableMapNotificationTest.java | 8 +- .../operators/flowable/FlowableMapTest.java | 44 +- .../flowable/FlowableMaterializeTest.java | 14 +- .../flowable/FlowableMergeDelayErrorTest.java | 390 ++++----- .../FlowableMergeMaxConcurrentTest.java | 7 - .../operators/flowable/FlowableMergeTest.java | 238 +++--- .../flowable/FlowableObserveOnTest.java | 195 +++-- ...wableOnErrorResumeNextViaFlowableTest.java | 77 +- ...wableOnErrorResumeNextViaFunctionTest.java | 101 ++- .../flowable/FlowableOnErrorReturnTest.java | 48 +- ...eOnExceptionResumeNextViaFlowableTest.java | 126 +-- .../flowable/FlowablePublishFunctionTest.java | 36 +- .../flowable/FlowablePublishTest.java | 114 +-- .../flowable/FlowableRangeLongTest.java | 42 +- .../operators/flowable/FlowableRangeTest.java | 42 +- .../flowable/FlowableReduceTest.java | 52 +- .../flowable/FlowableRefCountTest.java | 299 ++++--- .../flowable/FlowableRepeatTest.java | 72 +- .../flowable/FlowableReplayTest.java | 274 +++---- .../operators/flowable/FlowableRetryTest.java | 278 ++++--- .../FlowableRetryWithPredicateTest.java | 244 +++--- .../flowable/FlowableSampleTest.java | 160 ++-- .../operators/flowable/FlowableScanTest.java | 90 +-- .../flowable/FlowableSequenceEqualTest.java | 126 +-- .../flowable/FlowableSerializeTest.java | 52 +- .../flowable/FlowableSingleTest.java | 222 ++--- .../flowable/FlowableSkipLastTest.java | 91 ++- .../flowable/FlowableSkipLastTimedTest.java | 62 +- .../operators/flowable/FlowableSkipTest.java | 100 +-- .../flowable/FlowableSkipTimedTest.java | 68 +- .../flowable/FlowableSkipUntilTest.java | 68 +- .../flowable/FlowableSkipWhileTest.java | 16 +- .../flowable/FlowableSubscribeOnTest.java | 10 +- .../flowable/FlowableSwitchIfEmptyTest.java | 12 +- .../flowable/FlowableSwitchTest.java | 386 ++++----- .../flowable/FlowableTakeLastOneTest.java | 4 +- .../flowable/FlowableTakeLastTest.java | 69 +- .../flowable/FlowableTakeLastTimedTest.java | 68 +- .../operators/flowable/FlowableTakeTest.java | 146 ++-- .../flowable/FlowableTakeTimedTest.java | 54 +- .../FlowableTakeUntilPredicateTest.java | 90 +-- .../flowable/FlowableTakeUntilTest.java | 14 +- .../flowable/FlowableTakeWhileTest.java | 124 +-- .../flowable/FlowableThrottleFirstTest.java | 92 +-- .../flowable/FlowableTimeIntervalTest.java | 32 +- .../flowable/FlowableTimeoutTests.java | 184 ++--- .../FlowableTimeoutWithSelectorTest.java | 180 +++-- .../operators/flowable/FlowableTimerTest.java | 40 +- .../flowable/FlowableTimestampTest.java | 32 +- .../flowable/FlowableToFutureTest.java | 36 +- .../flowable/FlowableToListTest.java | 87 +- .../operators/flowable/FlowableToMapTest.java | 52 +- .../flowable/FlowableToMultimapTest.java | 68 +- .../flowable/FlowableToSortedListTest.java | 42 +- .../flowable/FlowableUnsubscribeOnTest.java | 22 +- .../operators/flowable/FlowableUsingTest.java | 76 +- .../FlowableWindowWithFlowableTest.java | 242 +++--- .../flowable/FlowableWindowWithSizeTest.java | 26 +- ...lowableWindowWithStartEndFlowableTest.java | 72 +- .../flowable/FlowableWindowWithTimeTest.java | 123 +-- .../flowable/FlowableWithLatestFromTest.java | 34 +- .../flowable/FlowableZipCompletionTest.java | 32 +- .../flowable/FlowableZipIterableTest.java | 148 ++-- .../operators/flowable/FlowableZipTest.java | 370 ++++----- .../maybe/MaybeDelaySubscriptionTest.java | 12 +- .../operators/maybe/MaybeDoOnEventTest.java | 10 +- .../operators/maybe/MaybeUsingTest.java | 6 +- .../mixed/ObservableConcatMapMaybeTest.java | 8 +- .../mixed/ObservableConcatMapSingleTest.java | 8 +- .../ObservableSwitchMapCompletableTest.java | 8 +- .../mixed/ObservableSwitchMapMaybeTest.java | 16 +- .../mixed/ObservableSwitchMapSingleTest.java | 16 +- .../observable/ObservableAnyTest.java | 40 +- .../observable/ObservableBufferTest.java | 64 +- .../ObservableCombineLatestTest.java | 4 +- .../observable/ObservableConcatTest.java | 10 +- .../ObservableConcatWithCompletableTest.java | 8 +- .../ObservableConcatWithMaybeTest.java | 16 +- .../ObservableConcatWithSingleTest.java | 16 +- .../observable/ObservableDebounceTest.java | 8 +- .../observable/ObservableDeferTest.java | 3 +- .../ObservableDistinctUntilChangedTest.java | 14 +- .../observable/ObservableDoOnEachTest.java | 60 +- .../ObservableDoOnSubscribeTest.java | 14 +- .../ObservableFlatMapCompletableTest.java | 20 +- .../observable/ObservableGroupByTest.java | 9 +- .../observable/ObservableMergeTest.java | 38 +- .../ObservableMergeWithMaybeTest.java | 10 +- .../ObservableMergeWithSingleTest.java | 10 +- .../observable/ObservableObserveOnTest.java | 9 +- ...vableOnErrorResumeNextViaFunctionTest.java | 6 +- ...bleOnErrorResumeNextViaObservableTest.java | 3 +- .../ObservableOnErrorReturnTest.java | 9 +- .../observable/ObservablePublishTest.java | 4 +- .../observable/ObservableRefCountTest.java | 28 +- .../observable/ObservableReplayTest.java | 4 +- .../observable/ObservableRetryTest.java | 25 +- .../ObservableRetryWithPredicateTest.java | 12 +- .../observable/ObservableScalarXMapTest.java | 14 +- .../ObservableSequenceEqualTest.java | 4 +- .../observable/ObservableSubscribeOnTest.java | 8 +- .../observable/ObservableSwitchTest.java | 6 +- .../observable/ObservableTakeLastOneTest.java | 30 +- .../observable/ObservableTakeTest.java | 6 +- .../ObservableTimeoutWithSelectorTest.java | 38 +- .../observable/ObservableToListTest.java | 18 +- .../ObservableToSortedListTest.java | 8 +- .../ObservableWindowWithSizeTest.java | 6 +- ...vableWindowWithStartEndObservableTest.java | 10 +- .../operators/single/SingleDelayTest.java | 8 +- .../operators/single/SingleDoOnTest.java | 8 +- .../operators/single/SingleLiftTest.java | 8 +- .../operators/single/SingleMiscTest.java | 6 +- .../subscribers/BoundedSubscriberTest.java | 48 +- .../subscribers/LambdaSubscriberTest.java | 48 +- .../SubscriberResourceWrapperTest.java | 4 +- .../util/HalfSerializerObserverTest.java | 32 +- .../java/io/reactivex/maybe/MaybeTest.java | 4 +- .../observable/ObservableNullTests.java | 2 +- .../observable/ObservableSubscriberTest.java | 2 +- .../reactivex/observable/ObservableTest.java | 26 +- .../reactivex/observers/SafeObserverTest.java | 8 +- .../observers/SerializedObserverTest.java | 6 +- .../reactivex/observers/TestObserverTest.java | 86 +- .../reactivex/plugins/RxJavaPluginsTest.java | 2 +- .../processors/AsyncProcessorTest.java | 88 +- .../processors/BehaviorProcessorTest.java | 194 ++--- .../processors/PublishProcessorTest.java | 108 +-- ...ReplayProcessorBoundedConcurrencyTest.java | 12 +- .../ReplayProcessorConcurrencyTest.java | 12 +- .../processors/ReplayProcessorTest.java | 184 ++--- .../AbstractSchedulerConcurrencyTests.java | 14 +- .../schedulers/AbstractSchedulerTests.java | 34 +- .../schedulers/CachedThreadSchedulerTest.java | 8 +- .../schedulers/ComputationSchedulerTests.java | 16 +- .../schedulers/TrampolineSchedulerTest.java | 12 +- .../io/reactivex/single/SingleNullTests.java | 2 +- .../java/io/reactivex/single/SingleTest.java | 42 +- .../subscribers/SafeSubscriberTest.java | 52 +- .../subscribers/SerializedSubscriberTest.java | 82 +- .../subscribers/TestSubscriberTest.java | 86 +- .../MulticastProcessorRefCountedTckTest.java | 2 +- 384 files changed, 8395 insertions(+), 7778 deletions(-) diff --git a/src/jmh/java/io/reactivex/InputWithIncrementingInteger.java b/src/jmh/java/io/reactivex/InputWithIncrementingInteger.java index 8a784de957..b5ce98e407 100644 --- a/src/jmh/java/io/reactivex/InputWithIncrementingInteger.java +++ b/src/jmh/java/io/reactivex/InputWithIncrementingInteger.java @@ -94,7 +94,7 @@ public void subscribe(Subscriber<? super Integer> s) { } public Iterable<Integer> iterable; - public Flowable<Integer> observable; + public Flowable<Integer> flowable; public Flowable<Integer> firehose; public Blackhole bh; @@ -104,7 +104,7 @@ public void subscribe(Subscriber<? super Integer> s) { public void setup(final Blackhole bh) { this.bh = bh; final int size = getSize(); - observable = Flowable.range(0, size); + flowable = Flowable.range(0, size); firehose = Flowable.unsafeCreate(new IncrementingPublisher(size)); iterable = new IncrementingIterable(size); diff --git a/src/jmh/java/io/reactivex/OperatorFlatMapPerf.java b/src/jmh/java/io/reactivex/OperatorFlatMapPerf.java index c8ab4aacdf..c1f0ddc11a 100644 --- a/src/jmh/java/io/reactivex/OperatorFlatMapPerf.java +++ b/src/jmh/java/io/reactivex/OperatorFlatMapPerf.java @@ -42,7 +42,7 @@ public int getSize() { @Benchmark public void flatMapIntPassthruSync(Input input) throws InterruptedException { - input.observable.flatMap(new Function<Integer, Publisher<Integer>>() { + input.flowable.flatMap(new Function<Integer, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Integer v) { return Flowable.just(v); @@ -53,7 +53,7 @@ public Publisher<Integer> apply(Integer v) { @Benchmark public void flatMapIntPassthruAsync(Input input) throws InterruptedException { PerfSubscriber latchedObserver = input.newLatchedObserver(); - input.observable.flatMap(new Function<Integer, Publisher<Integer>>() { + input.flowable.flatMap(new Function<Integer, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Integer i) { return Flowable.just(i).subscribeOn(Schedulers.computation()); @@ -71,7 +71,7 @@ public void flatMapTwoNestedSync(final Input input) throws InterruptedException Flowable.range(1, 2).flatMap(new Function<Integer, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Integer i) { - return input.observable; + return input.flowable; } }).subscribe(input.newSubscriber()); } diff --git a/src/jmh/java/io/reactivex/OperatorMergePerf.java b/src/jmh/java/io/reactivex/OperatorMergePerf.java index 29de58de2a..97006c163a 100644 --- a/src/jmh/java/io/reactivex/OperatorMergePerf.java +++ b/src/jmh/java/io/reactivex/OperatorMergePerf.java @@ -68,7 +68,7 @@ public Flowable<Integer> apply(Integer i) { @Benchmark public void mergeNSyncStreamsOfN(final InputThousand input) throws InterruptedException { - Flowable<Flowable<Integer>> os = input.observable.map(new Function<Integer, Flowable<Integer>>() { + Flowable<Flowable<Integer>> os = input.flowable.map(new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer i) { return Flowable.range(0, input.size); @@ -85,7 +85,7 @@ public Flowable<Integer> apply(Integer i) { @Benchmark public void mergeNAsyncStreamsOfN(final InputThousand input) throws InterruptedException { - Flowable<Flowable<Integer>> os = input.observable.map(new Function<Integer, Flowable<Integer>>() { + Flowable<Flowable<Integer>> os = input.flowable.map(new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer i) { return Flowable.range(0, input.size).subscribeOn(Schedulers.computation()); diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 8993524b46..9a681d8bc5 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -2155,20 +2155,20 @@ public final Completable hide() { */ @SchedulerSupport(SchedulerSupport.NONE) public final Disposable subscribe() { - EmptyCompletableObserver s = new EmptyCompletableObserver(); - subscribe(s); - return s; + EmptyCompletableObserver observer = new EmptyCompletableObserver(); + subscribe(observer); + return observer; } @SchedulerSupport(SchedulerSupport.NONE) @Override - public final void subscribe(CompletableObserver s) { - ObjectHelper.requireNonNull(s, "s is null"); + public final void subscribe(CompletableObserver observer) { + ObjectHelper.requireNonNull(observer, "s is null"); try { - s = RxJavaPlugins.onSubscribe(this, s); + observer = RxJavaPlugins.onSubscribe(this, observer); - subscribeActual(s); + subscribeActual(observer); } catch (NullPointerException ex) { // NOPMD throw ex; } catch (Throwable ex) { @@ -2184,9 +2184,9 @@ public final void subscribe(CompletableObserver s) { * <p>There is no need to call any of the plugin hooks on the current {@code Completable} instance or * the {@code CompletableObserver}; all hooks and basic safeguards have been * applied by {@link #subscribe(CompletableObserver)} before this method gets called. - * @param s the CompletableObserver instance, never null + * @param observer the CompletableObserver instance, never null */ - protected abstract void subscribeActual(CompletableObserver s); + protected abstract void subscribeActual(CompletableObserver observer); /** * Subscribes a given CompletableObserver (subclass) to this Completable and returns the given @@ -2240,9 +2240,9 @@ public final Disposable subscribe(final Action onComplete, final Consumer<? supe ObjectHelper.requireNonNull(onError, "onError is null"); ObjectHelper.requireNonNull(onComplete, "onComplete is null"); - CallbackCompletableObserver s = new CallbackCompletableObserver(onError, onComplete); - subscribe(s); - return s; + CallbackCompletableObserver observer = new CallbackCompletableObserver(onError, onComplete); + subscribe(observer); + return observer; } /** @@ -2266,9 +2266,9 @@ public final Disposable subscribe(final Action onComplete, final Consumer<? supe public final Disposable subscribe(final Action onComplete) { ObjectHelper.requireNonNull(onComplete, "onComplete is null"); - CallbackCompletableObserver s = new CallbackCompletableObserver(onComplete); - subscribe(s); - return s; + CallbackCompletableObserver observer = new CallbackCompletableObserver(onComplete); + subscribe(observer); + return observer; } /** diff --git a/src/main/java/io/reactivex/FlowableOperator.java b/src/main/java/io/reactivex/FlowableOperator.java index 4211a3ab52..b81a0b6c7e 100644 --- a/src/main/java/io/reactivex/FlowableOperator.java +++ b/src/main/java/io/reactivex/FlowableOperator.java @@ -25,10 +25,10 @@ public interface FlowableOperator<Downstream, Upstream> { /** * Applies a function to the child Subscriber and returns a new parent Subscriber. - * @param observer the child Subscriber instance + * @param subscriber the child Subscriber instance * @return the parent Subscriber instance * @throws Exception on failure */ @NonNull - Subscriber<? super Upstream> apply(@NonNull Subscriber<? super Downstream> observer) throws Exception; + Subscriber<? super Upstream> apply(@NonNull Subscriber<? super Downstream> subscriber) throws Exception; } diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 918bfea14c..4d672cea00 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -4982,9 +4982,9 @@ public final <R> R as(@NonNull ObservableConverter<T, ? extends R> converter) { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final T blockingFirst() { - BlockingFirstObserver<T> s = new BlockingFirstObserver<T>(); - subscribe(s); - T v = s.blockingGet(); + BlockingFirstObserver<T> observer = new BlockingFirstObserver<T>(); + subscribe(observer); + T v = observer.blockingGet(); if (v != null) { return v; } @@ -5010,9 +5010,9 @@ public final T blockingFirst() { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final T blockingFirst(T defaultItem) { - BlockingFirstObserver<T> s = new BlockingFirstObserver<T>(); - subscribe(s); - T v = s.blockingGet(); + BlockingFirstObserver<T> observer = new BlockingFirstObserver<T>(); + subscribe(observer); + T v = observer.blockingGet(); return v != null ? v : defaultItem; } @@ -5119,9 +5119,9 @@ public final Iterable<T> blockingIterable(int bufferSize) { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final T blockingLast() { - BlockingLastObserver<T> s = new BlockingLastObserver<T>(); - subscribe(s); - T v = s.blockingGet(); + BlockingLastObserver<T> observer = new BlockingLastObserver<T>(); + subscribe(observer); + T v = observer.blockingGet(); if (v != null) { return v; } @@ -5151,9 +5151,9 @@ public final T blockingLast() { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final T blockingLast(T defaultItem) { - BlockingLastObserver<T> s = new BlockingLastObserver<T>(); - subscribe(s); - T v = s.blockingGet(); + BlockingLastObserver<T> observer = new BlockingLastObserver<T>(); + subscribe(observer); + T v = observer.blockingGet(); return v != null ? v : defaultItem; } @@ -10998,16 +10998,16 @@ public final Observable<T> retryWhen( * <dt><b>Scheduler:</b></dt> * <dd>{@code safeSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * @param s the incoming Observer instance + * @param observer the incoming Observer instance * @throws NullPointerException if s is null */ @SchedulerSupport(SchedulerSupport.NONE) - public final void safeSubscribe(Observer<? super T> s) { - ObjectHelper.requireNonNull(s, "s is null"); - if (s instanceof SafeObserver) { - subscribe(s); + public final void safeSubscribe(Observer<? super T> observer) { + ObjectHelper.requireNonNull(observer, "s is null"); + if (observer instanceof SafeObserver) { + subscribe(observer); } else { - subscribe(new SafeObserver<T>(s)); + subscribe(new SafeObserver<T>(observer)); } } @@ -14072,19 +14072,19 @@ public final <K, V> Single<Map<K, Collection<V>>> toMultimap( @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> toFlowable(BackpressureStrategy strategy) { - Flowable<T> o = new FlowableFromObservable<T>(this); + Flowable<T> f = new FlowableFromObservable<T>(this); switch (strategy) { case DROP: - return o.onBackpressureDrop(); + return f.onBackpressureDrop(); case LATEST: - return o.onBackpressureLatest(); + return f.onBackpressureLatest(); case MISSING: - return o; + return f; case ERROR: - return RxJavaPlugins.onAssembly(new FlowableOnBackpressureError<T>(o)); + return RxJavaPlugins.onAssembly(new FlowableOnBackpressureError<T>(f)); default: - return o.onBackpressureBuffer(); + return f.onBackpressureBuffer(); } } diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index a42e9eaa5b..17d243f7a1 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -3322,9 +3322,9 @@ public final Disposable subscribe() { public final Disposable subscribe(final BiConsumer<? super T, ? super Throwable> onCallback) { ObjectHelper.requireNonNull(onCallback, "onCallback is null"); - BiConsumerSingleObserver<T> s = new BiConsumerSingleObserver<T>(onCallback); - subscribe(s); - return s; + BiConsumerSingleObserver<T> observer = new BiConsumerSingleObserver<T>(onCallback); + subscribe(observer); + return observer; } /** @@ -3376,22 +3376,22 @@ public final Disposable subscribe(final Consumer<? super T> onSuccess, final Con ObjectHelper.requireNonNull(onSuccess, "onSuccess is null"); ObjectHelper.requireNonNull(onError, "onError is null"); - ConsumerSingleObserver<T> s = new ConsumerSingleObserver<T>(onSuccess, onError); - subscribe(s); - return s; + ConsumerSingleObserver<T> observer = new ConsumerSingleObserver<T>(onSuccess, onError); + subscribe(observer); + return observer; } @SchedulerSupport(SchedulerSupport.NONE) @Override - public final void subscribe(SingleObserver<? super T> subscriber) { - ObjectHelper.requireNonNull(subscriber, "subscriber is null"); + public final void subscribe(SingleObserver<? super T> observer) { + ObjectHelper.requireNonNull(observer, "subscriber is null"); - subscriber = RxJavaPlugins.onSubscribe(this, subscriber); + observer = RxJavaPlugins.onSubscribe(this, observer); - ObjectHelper.requireNonNull(subscriber, "subscriber returned by the RxJavaPlugins hook is null"); + ObjectHelper.requireNonNull(observer, "subscriber returned by the RxJavaPlugins hook is null"); try { - subscribeActual(subscriber); + subscribeActual(observer); } catch (NullPointerException ex) { throw ex; } catch (Throwable ex) { diff --git a/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java b/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java index 4ac0d33dbf..1a00840549 100644 --- a/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java +++ b/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java @@ -48,39 +48,39 @@ public boolean isDisposed() { return this == INSTANCE; } - public static void complete(Observer<?> s) { - s.onSubscribe(INSTANCE); - s.onComplete(); + public static void complete(Observer<?> observer) { + observer.onSubscribe(INSTANCE); + observer.onComplete(); } - public static void complete(MaybeObserver<?> s) { - s.onSubscribe(INSTANCE); - s.onComplete(); + public static void complete(MaybeObserver<?> observer) { + observer.onSubscribe(INSTANCE); + observer.onComplete(); } - public static void error(Throwable e, Observer<?> s) { - s.onSubscribe(INSTANCE); - s.onError(e); + public static void error(Throwable e, Observer<?> observer) { + observer.onSubscribe(INSTANCE); + observer.onError(e); } - public static void complete(CompletableObserver s) { - s.onSubscribe(INSTANCE); - s.onComplete(); + public static void complete(CompletableObserver observer) { + observer.onSubscribe(INSTANCE); + observer.onComplete(); } - public static void error(Throwable e, CompletableObserver s) { - s.onSubscribe(INSTANCE); - s.onError(e); + public static void error(Throwable e, CompletableObserver observer) { + observer.onSubscribe(INSTANCE); + observer.onError(e); } - public static void error(Throwable e, SingleObserver<?> s) { - s.onSubscribe(INSTANCE); - s.onError(e); + public static void error(Throwable e, SingleObserver<?> observer) { + observer.onSubscribe(INSTANCE); + observer.onError(e); } - public static void error(Throwable e, MaybeObserver<?> s) { - s.onSubscribe(INSTANCE); - s.onError(e); + public static void error(Throwable e, MaybeObserver<?> observer) { + observer.onSubscribe(INSTANCE); + observer.onError(e); } diff --git a/src/main/java/io/reactivex/internal/observers/QueueDrainObserver.java b/src/main/java/io/reactivex/internal/observers/QueueDrainObserver.java index d906317a2d..366639340a 100644 --- a/src/main/java/io/reactivex/internal/observers/QueueDrainObserver.java +++ b/src/main/java/io/reactivex/internal/observers/QueueDrainObserver.java @@ -62,11 +62,11 @@ public final boolean fastEnter() { } protected final void fastPathEmit(U value, boolean delayError, Disposable dispose) { - final Observer<? super V> s = actual; + final Observer<? super V> observer = actual; final SimplePlainQueue<U> q = queue; if (wip.get() == 0 && wip.compareAndSet(0, 1)) { - accept(s, value); + accept(observer, value); if (leave(-1) == 0) { return; } @@ -76,7 +76,7 @@ protected final void fastPathEmit(U value, boolean delayError, Disposable dispos return; } } - QueueDrainHelper.drainLoop(q, s, delayError, dispose, this); + QueueDrainHelper.drainLoop(q, observer, delayError, dispose, this); } /** @@ -86,12 +86,12 @@ protected final void fastPathEmit(U value, boolean delayError, Disposable dispos * @param disposable the resource to dispose if the drain terminates */ protected final void fastPathOrderedEmit(U value, boolean delayError, Disposable disposable) { - final Observer<? super V> s = actual; + final Observer<? super V> observer = actual; final SimplePlainQueue<U> q = queue; if (wip.get() == 0 && wip.compareAndSet(0, 1)) { if (q.isEmpty()) { - accept(s, value); + accept(observer, value); if (leave(-1) == 0) { return; } @@ -104,7 +104,7 @@ protected final void fastPathOrderedEmit(U value, boolean delayError, Disposable return; } } - QueueDrainHelper.drainLoop(q, s, delayError, disposable, this); + QueueDrainHelper.drainLoop(q, observer, delayError, disposable, this); } @Override diff --git a/src/main/java/io/reactivex/internal/observers/SubscriberCompletableObserver.java b/src/main/java/io/reactivex/internal/observers/SubscriberCompletableObserver.java index aa0f10c126..425b7c5463 100644 --- a/src/main/java/io/reactivex/internal/observers/SubscriberCompletableObserver.java +++ b/src/main/java/io/reactivex/internal/observers/SubscriberCompletableObserver.java @@ -24,8 +24,8 @@ public final class SubscriberCompletableObserver<T> implements CompletableObserv Disposable d; - public SubscriberCompletableObserver(Subscriber<? super T> observer) { - this.subscriber = observer; + public SubscriberCompletableObserver(Subscriber<? super T> subscriber) { + this.subscriber = subscriber; } @Override diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableAmb.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableAmb.java index 82d0abbcc5..cc603acbdc 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableAmb.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableAmb.java @@ -31,7 +31,7 @@ public CompletableAmb(CompletableSource[] sources, Iterable<? extends Completabl } @Override - public void subscribeActual(final CompletableObserver s) { + public void subscribeActual(final CompletableObserver observer) { CompletableSource[] sources = this.sources; int count = 0; if (sources == null) { @@ -39,7 +39,7 @@ public void subscribeActual(final CompletableObserver s) { try { for (CompletableSource element : sourcesIterable) { if (element == null) { - EmptyDisposable.error(new NullPointerException("One of the sources is null"), s); + EmptyDisposable.error(new NullPointerException("One of the sources is null"), observer); return; } if (count == sources.length) { @@ -51,7 +51,7 @@ public void subscribeActual(final CompletableObserver s) { } } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } } else { @@ -59,11 +59,11 @@ public void subscribeActual(final CompletableObserver s) { } final CompositeDisposable set = new CompositeDisposable(); - s.onSubscribe(set); + observer.onSubscribe(set); final AtomicBoolean once = new AtomicBoolean(); - CompletableObserver inner = new Amb(once, set, s); + CompletableObserver inner = new Amb(once, set, observer); for (int i = 0; i < count; i++) { CompletableSource c = sources[i]; @@ -74,7 +74,7 @@ public void subscribeActual(final CompletableObserver s) { NullPointerException npe = new NullPointerException("One of the sources is null"); if (once.compareAndSet(false, true)) { set.dispose(); - s.onError(npe); + observer.onError(npe); } else { RxJavaPlugins.onError(npe); } @@ -86,26 +86,26 @@ public void subscribeActual(final CompletableObserver s) { } if (count == 0) { - s.onComplete(); + observer.onComplete(); } } static final class Amb implements CompletableObserver { private final AtomicBoolean once; private final CompositeDisposable set; - private final CompletableObserver s; + private final CompletableObserver downstream; - Amb(AtomicBoolean once, CompositeDisposable set, CompletableObserver s) { + Amb(AtomicBoolean once, CompositeDisposable set, CompletableObserver observer) { this.once = once; this.set = set; - this.s = s; + this.downstream = observer; } @Override public void onComplete() { if (once.compareAndSet(false, true)) { set.dispose(); - s.onComplete(); + downstream.onComplete(); } } @@ -113,7 +113,7 @@ public void onComplete() { public void onError(Throwable e) { if (once.compareAndSet(false, true)) { set.dispose(); - s.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java index 9b1652087e..9a333d3dde 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java @@ -44,9 +44,9 @@ public CompletableCache(CompletableSource source) { } @Override - protected void subscribeActual(CompletableObserver s) { - InnerCompletableCache inner = new InnerCompletableCache(s); - s.onSubscribe(inner); + protected void subscribeActual(CompletableObserver observer) { + InnerCompletableCache inner = new InnerCompletableCache(observer); + observer.onSubscribe(inner); if (add(inner)) { if (inner.isDisposed()) { @@ -59,9 +59,9 @@ protected void subscribeActual(CompletableObserver s) { } else { Throwable ex = error; if (ex != null) { - s.onError(ex); + observer.onError(ex); } else { - s.onComplete(); + observer.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcat.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcat.java index fadf4b422e..055ae5086e 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcat.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcat.java @@ -36,8 +36,8 @@ public CompletableConcat(Publisher<? extends CompletableSource> sources, int pre } @Override - public void subscribeActual(CompletableObserver s) { - sources.subscribe(new CompletableConcatSubscriber(s, prefetch)); + public void subscribeActual(CompletableObserver observer) { + sources.subscribe(new CompletableConcatSubscriber(observer, prefetch)); } static final class CompletableConcatSubscriber diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java index 3972a7b31c..f87f2a72ea 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java @@ -27,9 +27,9 @@ public CompletableConcatArray(CompletableSource[] sources) { } @Override - public void subscribeActual(CompletableObserver s) { - ConcatInnerObserver inner = new ConcatInnerObserver(s, sources); - s.onSubscribe(inner.sd); + public void subscribeActual(CompletableObserver observer) { + ConcatInnerObserver inner = new ConcatInnerObserver(observer, sources); + observer.onSubscribe(inner.sd); inner.next(); } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java index 47f4fad3bc..9ca4d919d8 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java @@ -30,7 +30,7 @@ public CompletableConcatIterable(Iterable<? extends CompletableSource> sources) } @Override - public void subscribeActual(CompletableObserver s) { + public void subscribeActual(CompletableObserver observer) { Iterator<? extends CompletableSource> it; @@ -38,12 +38,12 @@ public void subscribeActual(CompletableObserver s) { it = ObjectHelper.requireNonNull(sources.iterator(), "The iterator returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } - ConcatInnerObserver inner = new ConcatInnerObserver(s, it); - s.onSubscribe(inner.sd); + ConcatInnerObserver inner = new ConcatInnerObserver(observer, it); + observer.onSubscribe(inner.sd); inner.next(); } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java index 8e0cc20438..c831d899ae 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java @@ -31,9 +31,9 @@ public CompletableCreate(CompletableOnSubscribe source) { } @Override - protected void subscribeActual(CompletableObserver s) { - Emitter parent = new Emitter(s); - s.onSubscribe(parent); + protected void subscribeActual(CompletableObserver observer) { + Emitter parent = new Emitter(observer); + observer.onSubscribe(parent); try { source.subscribe(parent); diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDefer.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDefer.java index b486a3095f..030ca4fd3d 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDefer.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDefer.java @@ -29,18 +29,18 @@ public CompletableDefer(Callable<? extends CompletableSource> completableSupplie } @Override - protected void subscribeActual(CompletableObserver s) { + protected void subscribeActual(CompletableObserver observer) { CompletableSource c; try { c = ObjectHelper.requireNonNull(completableSupplier.call(), "The completableSupplier returned a null CompletableSource"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } - c.subscribe(s); + c.subscribe(observer); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDelay.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDelay.java index 79b0a49383..a23fd003f1 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDelay.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDelay.java @@ -41,8 +41,8 @@ public CompletableDelay(CompletableSource source, long delay, TimeUnit unit, Sch } @Override - protected void subscribeActual(final CompletableObserver s) { - source.subscribe(new Delay(s, delay, unit, scheduler, delayError)); + protected void subscribeActual(final CompletableObserver observer) { + source.subscribe(new Delay(observer, delay, unit, scheduler, delayError)); } static final class Delay extends AtomicReference<Disposable> diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDisposeOn.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDisposeOn.java index f8e53d3253..df2cfa5e25 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDisposeOn.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDisposeOn.java @@ -30,12 +30,12 @@ public CompletableDisposeOn(CompletableSource source, Scheduler scheduler) { } @Override - protected void subscribeActual(final CompletableObserver s) { - source.subscribe(new CompletableObserverImplementation(s, scheduler)); + protected void subscribeActual(final CompletableObserver observer) { + source.subscribe(new CompletableObserverImplementation(observer, scheduler)); } static final class CompletableObserverImplementation implements CompletableObserver, Disposable, Runnable { - final CompletableObserver s; + final CompletableObserver downstream; final Scheduler scheduler; @@ -43,8 +43,8 @@ static final class CompletableObserverImplementation implements CompletableObser volatile boolean disposed; - CompletableObserverImplementation(CompletableObserver s, Scheduler scheduler) { - this.s = s; + CompletableObserverImplementation(CompletableObserver observer, Scheduler scheduler) { + this.downstream = observer; this.scheduler = scheduler; } @@ -53,7 +53,7 @@ public void onComplete() { if (disposed) { return; } - s.onComplete(); + downstream.onComplete(); } @Override @@ -62,7 +62,7 @@ public void onError(Throwable e) { RxJavaPlugins.onError(e); return; } - s.onError(e); + downstream.onError(e); } @Override @@ -70,7 +70,7 @@ public void onSubscribe(final Disposable d) { if (DisposableHelper.validate(this.d, d)) { this.d = d; - s.onSubscribe(this); + downstream.onSubscribe(this); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java index c1b695220a..d74169d91c 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java @@ -39,8 +39,8 @@ public CompletableDoFinally(CompletableSource source, Action onFinally) { } @Override - protected void subscribeActual(CompletableObserver s) { - source.subscribe(new DoFinallyObserver(s, onFinally)); + protected void subscribeActual(CompletableObserver observer) { + source.subscribe(new DoFinallyObserver(observer, onFinally)); } static final class DoFinallyObserver extends AtomicInteger implements CompletableObserver, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDoOnEvent.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDoOnEvent.java index 19d472af94..3499a553a1 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDoOnEvent.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDoOnEvent.java @@ -31,8 +31,8 @@ public CompletableDoOnEvent(final CompletableSource source, final Consumer<? sup } @Override - protected void subscribeActual(final CompletableObserver s) { - source.subscribe(new DoOnEvent(s)); + protected void subscribeActual(final CompletableObserver observer) { + source.subscribe(new DoOnEvent(observer)); } final class DoOnEvent implements CompletableObserver { diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableEmpty.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableEmpty.java index 13f16b4c3c..dc6b6c5fa2 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableEmpty.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableEmpty.java @@ -23,7 +23,7 @@ private CompletableEmpty() { } @Override - public void subscribeActual(CompletableObserver s) { - EmptyDisposable.complete(s); + public void subscribeActual(CompletableObserver observer) { + EmptyDisposable.complete(observer); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableError.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableError.java index 6d155da1b6..e7d6a23bf5 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableError.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableError.java @@ -25,7 +25,7 @@ public CompletableError(Throwable error) { } @Override - protected void subscribeActual(CompletableObserver s) { - EmptyDisposable.error(error, s); + protected void subscribeActual(CompletableObserver observer) { + EmptyDisposable.error(error, observer); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableErrorSupplier.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableErrorSupplier.java index d8dadfa005..16df486c42 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableErrorSupplier.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableErrorSupplier.java @@ -29,7 +29,7 @@ public CompletableErrorSupplier(Callable<? extends Throwable> errorSupplier) { } @Override - protected void subscribeActual(CompletableObserver s) { + protected void subscribeActual(CompletableObserver observer) { Throwable error; try { @@ -39,7 +39,7 @@ protected void subscribeActual(CompletableObserver s) { error = e; } - EmptyDisposable.error(error, s); + EmptyDisposable.error(error, observer); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromAction.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromAction.java index 1a4652840e..3e49bf0ec6 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromAction.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromAction.java @@ -27,20 +27,20 @@ public CompletableFromAction(Action run) { } @Override - protected void subscribeActual(CompletableObserver s) { + protected void subscribeActual(CompletableObserver observer) { Disposable d = Disposables.empty(); - s.onSubscribe(d); + observer.onSubscribe(d); try { run.run(); } catch (Throwable e) { Exceptions.throwIfFatal(e); if (!d.isDisposed()) { - s.onError(e); + observer.onError(e); } return; } if (!d.isDisposed()) { - s.onComplete(); + observer.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromCallable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromCallable.java index 80bb1a0af0..3dbd3701b5 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromCallable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromCallable.java @@ -28,20 +28,20 @@ public CompletableFromCallable(Callable<?> callable) { } @Override - protected void subscribeActual(CompletableObserver s) { + protected void subscribeActual(CompletableObserver observer) { Disposable d = Disposables.empty(); - s.onSubscribe(d); + observer.onSubscribe(d); try { callable.call(); } catch (Throwable e) { Exceptions.throwIfFatal(e); if (!d.isDisposed()) { - s.onError(e); + observer.onError(e); } return; } if (!d.isDisposed()) { - s.onComplete(); + observer.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromObservable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromObservable.java index 509f173fa4..fdf3523b2f 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromObservable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromObservable.java @@ -25,8 +25,8 @@ public CompletableFromObservable(ObservableSource<T> observable) { } @Override - protected void subscribeActual(final CompletableObserver s) { - observable.subscribe(new CompletableFromObservableObserver<T>(s)); + protected void subscribeActual(final CompletableObserver observer) { + observable.subscribe(new CompletableFromObservableObserver<T>(observer)); } static final class CompletableFromObservableObserver<T> implements Observer<T> { diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromRunnable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromRunnable.java index 789483ab8e..981e6d1f1f 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromRunnable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromRunnable.java @@ -28,20 +28,20 @@ public CompletableFromRunnable(Runnable runnable) { } @Override - protected void subscribeActual(CompletableObserver s) { + protected void subscribeActual(CompletableObserver observer) { Disposable d = Disposables.empty(); - s.onSubscribe(d); + observer.onSubscribe(d); try { runnable.run(); } catch (Throwable e) { Exceptions.throwIfFatal(e); if (!d.isDisposed()) { - s.onError(e); + observer.onError(e); } return; } if (!d.isDisposed()) { - s.onComplete(); + observer.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromSingle.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromSingle.java index 1dab2b98d6..251ae5c8f3 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromSingle.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromSingle.java @@ -25,8 +25,8 @@ public CompletableFromSingle(SingleSource<T> single) { } @Override - protected void subscribeActual(final CompletableObserver s) { - single.subscribe(new CompletableFromSingleObserver<T>(s)); + protected void subscribeActual(final CompletableObserver observer) { + single.subscribe(new CompletableFromSingleObserver<T>(observer)); } static final class CompletableFromSingleObserver<T> implements SingleObserver<T> { diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableLift.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableLift.java index ccc3616811..25a08d5821 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableLift.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableLift.java @@ -29,11 +29,11 @@ public CompletableLift(CompletableSource source, CompletableOperator onLift) { } @Override - protected void subscribeActual(CompletableObserver s) { + protected void subscribeActual(CompletableObserver observer) { try { // TODO plugin wrapping - CompletableObserver sw = onLift.apply(s); + CompletableObserver sw = onLift.apply(observer); source.subscribe(sw); } catch (NullPointerException ex) { // NOPMD diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableMerge.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableMerge.java index fa59a499bd..890e036d74 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableMerge.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableMerge.java @@ -36,8 +36,8 @@ public CompletableMerge(Publisher<? extends CompletableSource> source, int maxCo } @Override - public void subscribeActual(CompletableObserver s) { - CompletableMergeSubscriber parent = new CompletableMergeSubscriber(s, maxConcurrency, delayErrors); + public void subscribeActual(CompletableObserver observer) { + CompletableMergeSubscriber parent = new CompletableMergeSubscriber(observer, maxConcurrency, delayErrors); source.subscribe(parent); } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeArray.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeArray.java index 783788c286..64a5b6e8a4 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeArray.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeArray.java @@ -27,12 +27,12 @@ public CompletableMergeArray(CompletableSource[] sources) { } @Override - public void subscribeActual(final CompletableObserver s) { + public void subscribeActual(final CompletableObserver observer) { final CompositeDisposable set = new CompositeDisposable(); final AtomicBoolean once = new AtomicBoolean(); - InnerCompletableObserver shared = new InnerCompletableObserver(s, once, set, sources.length + 1); - s.onSubscribe(set); + InnerCompletableObserver shared = new InnerCompletableObserver(observer, once, set, sources.length + 1); + observer.onSubscribe(set); for (CompletableSource c : sources) { if (set.isDisposed()) { diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorArray.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorArray.java index c03939f655..733fa88b40 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorArray.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorArray.java @@ -29,13 +29,13 @@ public CompletableMergeDelayErrorArray(CompletableSource[] sources) { } @Override - public void subscribeActual(final CompletableObserver s) { + public void subscribeActual(final CompletableObserver observer) { final CompositeDisposable set = new CompositeDisposable(); final AtomicInteger wip = new AtomicInteger(sources.length + 1); final AtomicThrowable error = new AtomicThrowable(); - s.onSubscribe(set); + observer.onSubscribe(set); for (CompletableSource c : sources) { if (set.isDisposed()) { @@ -49,15 +49,15 @@ public void subscribeActual(final CompletableObserver s) { continue; } - c.subscribe(new MergeInnerCompletableObserver(s, set, error, wip)); + c.subscribe(new MergeInnerCompletableObserver(observer, set, error, wip)); } if (wip.decrementAndGet() == 0) { Throwable ex = error.terminate(); if (ex == null) { - s.onComplete(); + observer.onComplete(); } else { - s.onError(ex); + observer.onError(ex); } } } @@ -69,9 +69,9 @@ static final class MergeInnerCompletableObserver final AtomicThrowable error; final AtomicInteger wip; - MergeInnerCompletableObserver(CompletableObserver s, CompositeDisposable set, AtomicThrowable error, + MergeInnerCompletableObserver(CompletableObserver observer, CompositeDisposable set, AtomicThrowable error, AtomicInteger wip) { - this.actual = s; + this.actual = observer; this.set = set; this.error = error; this.wip = wip; diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorIterable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorIterable.java index 4593f3223e..40c84d1176 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorIterable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorIterable.java @@ -32,10 +32,10 @@ public CompletableMergeDelayErrorIterable(Iterable<? extends CompletableSource> } @Override - public void subscribeActual(final CompletableObserver s) { + public void subscribeActual(final CompletableObserver observer) { final CompositeDisposable set = new CompositeDisposable(); - s.onSubscribe(set); + observer.onSubscribe(set); Iterator<? extends CompletableSource> iterator; @@ -43,7 +43,7 @@ public void subscribeActual(final CompletableObserver s) { iterator = ObjectHelper.requireNonNull(sources.iterator(), "The source iterator returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.onError(e); + observer.onError(e); return; } @@ -89,15 +89,15 @@ public void subscribeActual(final CompletableObserver s) { wip.getAndIncrement(); - c.subscribe(new MergeInnerCompletableObserver(s, set, error, wip)); + c.subscribe(new MergeInnerCompletableObserver(observer, set, error, wip)); } if (wip.decrementAndGet() == 0) { Throwable ex = error.terminate(); if (ex == null) { - s.onComplete(); + observer.onComplete(); } else { - s.onError(ex); + observer.onError(ex); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeIterable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeIterable.java index 32d015a0d4..6c22819e19 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeIterable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeIterable.java @@ -30,10 +30,10 @@ public CompletableMergeIterable(Iterable<? extends CompletableSource> sources) { } @Override - public void subscribeActual(final CompletableObserver s) { + public void subscribeActual(final CompletableObserver observer) { final CompositeDisposable set = new CompositeDisposable(); - s.onSubscribe(set); + observer.onSubscribe(set); Iterator<? extends CompletableSource> iterator; @@ -41,13 +41,13 @@ public void subscribeActual(final CompletableObserver s) { iterator = ObjectHelper.requireNonNull(sources.iterator(), "The source iterator returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.onError(e); + observer.onError(e); return; } final AtomicInteger wip = new AtomicInteger(1); - MergeCompletableObserver shared = new MergeCompletableObserver(s, set, wip); + MergeCompletableObserver shared = new MergeCompletableObserver(observer, set, wip); for (;;) { if (set.isDisposed()) { return; diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableNever.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableNever.java index 5874fda6be..73b52d54d2 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableNever.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableNever.java @@ -23,8 +23,8 @@ private CompletableNever() { } @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(EmptyDisposable.NEVER); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(EmptyDisposable.NEVER); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java index 41f1cfb124..73c86873da 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java @@ -30,8 +30,8 @@ public CompletableObserveOn(CompletableSource source, Scheduler scheduler) { } @Override - protected void subscribeActual(final CompletableObserver s) { - source.subscribe(new ObserveOnCompletableObserver(s, scheduler)); + protected void subscribeActual(final CompletableObserver observer) { + source.subscribe(new ObserveOnCompletableObserver(observer, scheduler)); } static final class ObserveOnCompletableObserver diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableOnErrorComplete.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableOnErrorComplete.java index d4de7495fa..5ff0cc3235 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableOnErrorComplete.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableOnErrorComplete.java @@ -30,22 +30,22 @@ public CompletableOnErrorComplete(CompletableSource source, Predicate<? super Th } @Override - protected void subscribeActual(final CompletableObserver s) { + protected void subscribeActual(final CompletableObserver observer) { - source.subscribe(new OnError(s)); + source.subscribe(new OnError(observer)); } final class OnError implements CompletableObserver { - private final CompletableObserver s; + private final CompletableObserver downstream; - OnError(CompletableObserver s) { - this.s = s; + OnError(CompletableObserver observer) { + this.downstream = observer; } @Override public void onComplete() { - s.onComplete(); + downstream.onComplete(); } @Override @@ -56,20 +56,20 @@ public void onError(Throwable e) { b = predicate.test(e); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.onError(new CompositeException(e, ex)); + downstream.onError(new CompositeException(e, ex)); return; } if (b) { - s.onComplete(); + downstream.onComplete(); } else { - s.onError(e); + downstream.onError(e); } } @Override public void onSubscribe(Disposable d) { - s.onSubscribe(d); + downstream.onSubscribe(d); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java b/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java index 97a4c1b1cb..6584131483 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java @@ -46,9 +46,9 @@ public CompletablePeek(CompletableSource source, Consumer<? super Disposable> on } @Override - protected void subscribeActual(final CompletableObserver s) { + protected void subscribeActual(final CompletableObserver observer) { - source.subscribe(new CompletableObserverImplementation(s)); + source.subscribe(new CompletableObserverImplementation(observer)); } final class CompletableObserverImplementation implements CompletableObserver, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java index 8817843e13..16c46aeb24 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java @@ -34,26 +34,26 @@ public CompletableResumeNext(CompletableSource source, @Override - protected void subscribeActual(final CompletableObserver s) { + protected void subscribeActual(final CompletableObserver observer) { final SequentialDisposable sd = new SequentialDisposable(); - s.onSubscribe(sd); - source.subscribe(new ResumeNext(s, sd)); + observer.onSubscribe(sd); + source.subscribe(new ResumeNext(observer, sd)); } final class ResumeNext implements CompletableObserver { - final CompletableObserver s; + final CompletableObserver downstream; final SequentialDisposable sd; - ResumeNext(CompletableObserver s, SequentialDisposable sd) { - this.s = s; + ResumeNext(CompletableObserver observer, SequentialDisposable sd) { + this.downstream = observer; this.sd = sd; } @Override public void onComplete() { - s.onComplete(); + downstream.onComplete(); } @Override @@ -64,14 +64,14 @@ public void onError(Throwable e) { c = errorMapper.apply(e); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.onError(new CompositeException(ex, e)); + downstream.onError(new CompositeException(ex, e)); return; } if (c == null) { NullPointerException npe = new NullPointerException("The CompletableConsumable returned is null"); npe.initCause(e); - s.onError(npe); + downstream.onError(npe); return; } @@ -87,12 +87,12 @@ final class OnErrorObserver implements CompletableObserver { @Override public void onComplete() { - s.onComplete(); + downstream.onComplete(); } @Override public void onError(Throwable e) { - s.onError(e); + downstream.onError(e); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableSubscribeOn.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableSubscribeOn.java index b749d6f529..d386009f22 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableSubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableSubscribeOn.java @@ -30,10 +30,10 @@ public CompletableSubscribeOn(CompletableSource source, Scheduler scheduler) { } @Override - protected void subscribeActual(final CompletableObserver s) { + protected void subscribeActual(final CompletableObserver observer) { - final SubscribeOnObserver parent = new SubscribeOnObserver(s, source); - s.onSubscribe(parent); + final SubscribeOnObserver parent = new SubscribeOnObserver(observer, source); + observer.onSubscribe(parent); Disposable f = scheduler.scheduleDirect(parent); diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java index 391795846e..7a27b68f9b 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableTakeUntilCompletable.java @@ -38,9 +38,9 @@ public CompletableTakeUntilCompletable(Completable source, } @Override - protected void subscribeActual(CompletableObserver s) { - TakeUntilMainObserver parent = new TakeUntilMainObserver(s); - s.onSubscribe(parent); + protected void subscribeActual(CompletableObserver observer) { + TakeUntilMainObserver parent = new TakeUntilMainObserver(observer); + observer.onSubscribe(parent); other.subscribe(parent.other); source.subscribe(parent); diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableTimeout.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableTimeout.java index 9788e1cf1c..90d36ad103 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableTimeout.java @@ -38,29 +38,29 @@ public CompletableTimeout(CompletableSource source, long timeout, } @Override - public void subscribeActual(final CompletableObserver s) { + public void subscribeActual(final CompletableObserver observer) { final CompositeDisposable set = new CompositeDisposable(); - s.onSubscribe(set); + observer.onSubscribe(set); final AtomicBoolean once = new AtomicBoolean(); - Disposable timer = scheduler.scheduleDirect(new DisposeTask(once, set, s), timeout, unit); + Disposable timer = scheduler.scheduleDirect(new DisposeTask(once, set, observer), timeout, unit); set.add(timer); - source.subscribe(new TimeOutObserver(set, once, s)); + source.subscribe(new TimeOutObserver(set, once, observer)); } static final class TimeOutObserver implements CompletableObserver { private final CompositeDisposable set; private final AtomicBoolean once; - private final CompletableObserver s; + private final CompletableObserver downstream; - TimeOutObserver(CompositeDisposable set, AtomicBoolean once, CompletableObserver s) { + TimeOutObserver(CompositeDisposable set, AtomicBoolean once, CompletableObserver observer) { this.set = set; this.once = once; - this.s = s; + this.downstream = observer; } @Override @@ -72,7 +72,7 @@ public void onSubscribe(Disposable d) { public void onError(Throwable e) { if (once.compareAndSet(false, true)) { set.dispose(); - s.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -82,7 +82,7 @@ public void onError(Throwable e) { public void onComplete() { if (once.compareAndSet(false, true)) { set.dispose(); - s.onComplete(); + downstream.onComplete(); } } @@ -91,12 +91,12 @@ public void onComplete() { final class DisposeTask implements Runnable { private final AtomicBoolean once; final CompositeDisposable set; - final CompletableObserver s; + final CompletableObserver downstream; - DisposeTask(AtomicBoolean once, CompositeDisposable set, CompletableObserver s) { + DisposeTask(AtomicBoolean once, CompositeDisposable set, CompletableObserver observer) { this.once = once; this.set = set; - this.s = s; + this.downstream = observer; } @Override @@ -104,7 +104,7 @@ public void run() { if (once.compareAndSet(false, true)) { set.clear(); if (other == null) { - s.onError(new TimeoutException()); + downstream.onError(new TimeoutException()); } else { other.subscribe(new DisposeObserver()); } @@ -121,13 +121,13 @@ public void onSubscribe(Disposable d) { @Override public void onError(Throwable e) { set.dispose(); - s.onError(e); + downstream.onError(e); } @Override public void onComplete() { set.dispose(); - s.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableTimer.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableTimer.java index 2435365814..5b85346629 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableTimer.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableTimer.java @@ -36,9 +36,9 @@ public CompletableTimer(long delay, TimeUnit unit, Scheduler scheduler) { } @Override - protected void subscribeActual(final CompletableObserver s) { - TimerDisposable parent = new TimerDisposable(s); - s.onSubscribe(parent); + protected void subscribeActual(final CompletableObserver observer) { + TimerDisposable parent = new TimerDisposable(observer); + observer.onSubscribe(parent); parent.setFuture(scheduler.scheduleDirect(parent, delay, unit)); } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableToSingle.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableToSingle.java index bac12bdbd1..e0e5559723 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableToSingle.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableToSingle.java @@ -34,8 +34,8 @@ public CompletableToSingle(CompletableSource source, } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { - source.subscribe(new ToSingle(s)); + protected void subscribeActual(final SingleObserver<? super T> observer) { + source.subscribe(new ToSingle(observer)); } final class ToSingle implements CompletableObserver { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableNext.java b/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableNext.java index 9fd3c09d00..8cd40288e4 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableNext.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableNext.java @@ -48,7 +48,7 @@ public Iterator<T> iterator() { // test needs to access the observer.waiting flag static final class NextIterator<T> implements Iterator<T> { - private final NextSubscriber<T> observer; + private final NextSubscriber<T> subscriber; private final Publisher<? extends T> items; private T next; private boolean hasNext = true; @@ -56,9 +56,9 @@ static final class NextIterator<T> implements Iterator<T> { private Throwable error; private boolean started; - NextIterator(Publisher<? extends T> items, NextSubscriber<T> observer) { + NextIterator(Publisher<? extends T> items, NextSubscriber<T> subscriber) { this.items = items; - this.observer = observer; + this.subscriber = subscriber; } @Override @@ -82,12 +82,12 @@ private boolean moveToNext() { if (!started) { started = true; // if not started, start now - observer.setWaiting(); + subscriber.setWaiting(); Flowable.<T>fromPublisher(items) - .materialize().subscribe(observer); + .materialize().subscribe(subscriber); } - Notification<T> nextNotification = observer.takeNext(); + Notification<T> nextNotification = subscriber.takeNext(); if (nextNotification.isOnNext()) { isNextConsumed = false; next = nextNotification.getValue(); @@ -105,7 +105,7 @@ private boolean moveToNext() { } throw new IllegalStateException("Should not reach here"); } catch (InterruptedException e) { - observer.dispose(); + subscriber.dispose(); error = e; throw ExceptionHelper.wrapOrThrow(e); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java index 9812961382..c3bbc19481 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java @@ -34,8 +34,8 @@ public FlowableAllSingle(Flowable<T> source, Predicate<? super T> predicate) { } @Override - protected void subscribeActual(SingleObserver<? super Boolean> s) { - source.subscribe(new AllSubscriber<T>(s, predicate)); + protected void subscribeActual(SingleObserver<? super Boolean> observer) { + source.subscribe(new AllSubscriber<T>(observer, predicate)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java index 94c0ab9a13..47f2ce4ef2 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java @@ -33,8 +33,8 @@ public FlowableAnySingle(Flowable<T> source, Predicate<? super T> predicate) { } @Override - protected void subscribeActual(SingleObserver<? super Boolean> s) { - source.subscribe(new AnySubscriber<T>(s, predicate)); + protected void subscribeActual(SingleObserver<? super Boolean> observer) { + source.subscribe(new AnySubscriber<T>(observer, predicate)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollectSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollectSingle.java index aaab14bd23..cda031ebbc 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollectSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollectSingle.java @@ -40,16 +40,16 @@ public FlowableCollectSingle(Flowable<T> source, Callable<? extends U> initialSu } @Override - protected void subscribeActual(SingleObserver<? super U> s) { + protected void subscribeActual(SingleObserver<? super U> observer) { U u; try { u = ObjectHelper.requireNonNull(initialSupplier.call(), "The initialSupplier returned a null value"); } catch (Throwable e) { - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } - source.subscribe(new CollectSubscriber<T, U>(s, u, collector)); + source.subscribe(new CollectSubscriber<T, U>(observer, u, collector)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCountSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCountSingle.java index 97c4c08c49..13bf0bd9a8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCountSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCountSingle.java @@ -30,8 +30,8 @@ public FlowableCountSingle(Flowable<T> source) { } @Override - protected void subscribeActual(SingleObserver<? super Long> s) { - source.subscribe(new CountSubscriber(s)); + protected void subscribeActual(SingleObserver<? super Long> observer) { + source.subscribe(new CountSubscriber(observer)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinct.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinct.java index 7072dd3e43..f12b637737 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinct.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinct.java @@ -41,18 +41,18 @@ public FlowableDistinct(Flowable<T> source, Function<? super T, K> keySelector, } @Override - protected void subscribeActual(Subscriber<? super T> observer) { + protected void subscribeActual(Subscriber<? super T> subscriber) { Collection<? super K> collection; try { collection = ObjectHelper.requireNonNull(collectionSupplier.call(), "The collectionSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources."); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - EmptySubscription.error(ex, observer); + EmptySubscription.error(ex, subscriber); return; } - source.subscribe(new DistinctSubscriber<T, K>(observer, keySelector, collection)); + source.subscribe(new DistinctSubscriber<T, K>(subscriber, keySelector, collection)); } static final class DistinctSubscriber<T, K> extends BasicFuseableSubscriber<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtMaybe.java index d8907aa310..5293af4722 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtMaybe.java @@ -32,8 +32,8 @@ public FlowableElementAtMaybe(Flowable<T> source, long index) { } @Override - protected void subscribeActual(MaybeObserver<? super T> s) { - source.subscribe(new ElementAtSubscriber<T>(s, index)); + protected void subscribeActual(MaybeObserver<? super T> observer) { + source.subscribe(new ElementAtSubscriber<T>(observer, index)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtSingle.java index 874f744010..0a08f47fee 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtSingle.java @@ -37,8 +37,8 @@ public FlowableElementAtSingle(Flowable<T> source, long index, T defaultValue) { } @Override - protected void subscribeActual(SingleObserver<? super T> s) { - source.subscribe(new ElementAtSubscriber<T>(s, index, defaultValue)); + protected void subscribeActual(SingleObserver<? super T> observer) { + source.subscribe(new ElementAtSubscriber<T>(observer, index, defaultValue)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletable.java index c1f0a6c1e9..43546d1376 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletable.java @@ -50,8 +50,8 @@ public FlowableFlatMapCompletable(Flowable<T> source, } @Override - protected void subscribeActual(Subscriber<? super T> observer) { - source.subscribe(new FlatMapCompletableMainSubscriber<T>(observer, mapper, delayErrors, maxConcurrency)); + protected void subscribeActual(Subscriber<? super T> subscriber) { + source.subscribe(new FlatMapCompletableMainSubscriber<T>(subscriber, mapper, delayErrors, maxConcurrency)); } static final class FlatMapCompletableMainSubscriber<T> extends BasicIntQueueSubscription<T> @@ -74,10 +74,10 @@ static final class FlatMapCompletableMainSubscriber<T> extends BasicIntQueueSubs volatile boolean cancelled; - FlatMapCompletableMainSubscriber(Subscriber<? super T> observer, + FlatMapCompletableMainSubscriber(Subscriber<? super T> subscriber, Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors, int maxConcurrency) { - this.actual = observer; + this.actual = subscriber; this.mapper = mapper; this.delayErrors = delayErrors; this.errors = new AtomicThrowable(); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java index a62b10b1e2..27f8652ff3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java @@ -40,9 +40,9 @@ public FlowableMergeWithCompletable(Flowable<T> source, CompletableSource other) } @Override - protected void subscribeActual(Subscriber<? super T> observer) { - MergeWithSubscriber<T> parent = new MergeWithSubscriber<T>(observer); - observer.onSubscribe(parent); + protected void subscribeActual(Subscriber<? super T> subscriber) { + MergeWithSubscriber<T> parent = new MergeWithSubscriber<T>(subscriber); + subscriber.onSubscribe(parent); source.subscribe(parent); other.subscribe(parent.otherObserver); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java index 97c81551eb..08430c4a70 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java @@ -43,9 +43,9 @@ public FlowableMergeWithMaybe(Flowable<T> source, MaybeSource<? extends T> other } @Override - protected void subscribeActual(Subscriber<? super T> observer) { - MergeWithObserver<T> parent = new MergeWithObserver<T>(observer); - observer.onSubscribe(parent); + protected void subscribeActual(Subscriber<? super T> subscriber) { + MergeWithObserver<T> parent = new MergeWithObserver<T>(subscriber); + subscriber.onSubscribe(parent); source.subscribe(parent); other.subscribe(parent.otherObserver); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java index 05bf79f5f2..0fee2fa12c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java @@ -43,9 +43,9 @@ public FlowableMergeWithSingle(Flowable<T> source, SingleSource<? extends T> oth } @Override - protected void subscribeActual(Subscriber<? super T> observer) { - MergeWithObserver<T> parent = new MergeWithObserver<T>(observer); - observer.onSubscribe(parent); + protected void subscribeActual(Subscriber<? super T> subscriber) { + MergeWithObserver<T> parent = new MergeWithObserver<T>(subscriber); + subscriber.onSubscribe(parent); source.subscribe(parent); other.subscribe(parent.otherObserver); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java index 64853d362b..7a837f5809 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java @@ -69,8 +69,8 @@ public static <U, R> Flowable<R> multicastSelector( * @return the new ConnectableObservable instance */ public static <T> ConnectableFlowable<T> observeOn(final ConnectableFlowable<T> cf, final Scheduler scheduler) { - final Flowable<T> observable = cf.observeOn(scheduler); - return RxJavaPlugins.onAssembly(new ConnectableFlowableReplay<T>(cf, observable)); + final Flowable<T> flowable = cf.observeOn(scheduler); + return RxJavaPlugins.onAssembly(new ConnectableFlowableReplay<T>(cf, flowable)); } /** @@ -1141,11 +1141,11 @@ public void accept(Disposable r) { static final class ConnectableFlowableReplay<T> extends ConnectableFlowable<T> { private final ConnectableFlowable<T> cf; - private final Flowable<T> observable; + private final Flowable<T> flowable; - ConnectableFlowableReplay(ConnectableFlowable<T> cf, Flowable<T> observable) { + ConnectableFlowableReplay(ConnectableFlowable<T> cf, Flowable<T> flowable) { this.cf = cf; - this.observable = observable; + this.flowable = flowable; } @Override @@ -1155,7 +1155,7 @@ public void connect(Consumer<? super Disposable> connection) { @Override protected void subscribeActual(Subscriber<? super T> s) { - observable.subscribe(s); + flowable.subscribe(s); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java index e9c88c7c7c..cd0d958c49 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java @@ -42,9 +42,9 @@ public FlowableSequenceEqualSingle(Publisher<? extends T> first, Publisher<? ext } @Override - public void subscribeActual(SingleObserver<? super Boolean> s) { - EqualCoordinator<T> parent = new EqualCoordinator<T>(s, prefetch, comparer); - s.onSubscribe(parent); + public void subscribeActual(SingleObserver<? super Boolean> observer) { + EqualCoordinator<T> parent = new EqualCoordinator<T>(observer, prefetch, comparer); + observer.onSubscribe(parent); parent.subscribe(first, second); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java index 28ac5bcda1..4fcc466df0 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java @@ -30,8 +30,8 @@ public FlowableSingleMaybe(Flowable<T> source) { } @Override - protected void subscribeActual(MaybeObserver<? super T> s) { - source.subscribe(new SingleElementSubscriber<T>(s)); + protected void subscribeActual(MaybeObserver<? super T> observer) { + source.subscribe(new SingleElementSubscriber<T>(observer)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java index cb33706362..3ee049ecf2 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java @@ -35,8 +35,8 @@ public FlowableSingleSingle(Flowable<T> source, T defaultValue) { } @Override - protected void subscribeActual(SingleObserver<? super T> s) { - source.subscribe(new SingleElementSubscriber<T>(s, defaultValue)); + protected void subscribeActual(SingleObserver<? super T> observer) { + source.subscribe(new SingleElementSubscriber<T>(observer, defaultValue)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableToListSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableToListSingle.java index 365e9762cd..a0738acf11 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableToListSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableToListSingle.java @@ -45,16 +45,16 @@ public FlowableToListSingle(Flowable<T> source, Callable<U> collectionSupplier) } @Override - protected void subscribeActual(SingleObserver<? super U> s) { + protected void subscribeActual(SingleObserver<? super U> observer) { U coll; try { coll = ObjectHelper.requireNonNull(collectionSupplier.call(), "The collectionSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources."); } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } - source.subscribe(new ToListSubscriber<T, U>(s, coll)); + source.subscribe(new ToListSubscriber<T, U>(observer, coll)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java index e0c42b68ca..4c6de982af 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java @@ -37,9 +37,9 @@ public MaybeCreate(MaybeOnSubscribe<T> source) { } @Override - protected void subscribeActual(MaybeObserver<? super T> s) { - Emitter<T> parent = new Emitter<T>(s); - s.onSubscribe(parent); + protected void subscribeActual(MaybeObserver<? super T> observer) { + Emitter<T> parent = new Emitter<T>(observer); + observer.onSubscribe(parent); try { source.subscribe(parent); diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayWithCompletable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayWithCompletable.java index 37dd45fade..a56f8c9360 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayWithCompletable.java @@ -34,8 +34,8 @@ public MaybeDelayWithCompletable(MaybeSource<T> source, CompletableSource other) } @Override - protected void subscribeActual(MaybeObserver<? super T> subscriber) { - other.subscribe(new OtherObserver<T>(subscriber, source)); + protected void subscribeActual(MaybeObserver<? super T> observer) { + other.subscribe(new OtherObserver<T>(observer, source)); } static final class OtherObserver<T> diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java index 99c77a7b2b..017412ff41 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java @@ -36,8 +36,8 @@ public MaybeDoAfterSuccess(MaybeSource<T> source, Consumer<? super T> onAfterSuc } @Override - protected void subscribeActual(MaybeObserver<? super T> s) { - source.subscribe(new DoAfterObserver<T>(s, onAfterSuccess)); + protected void subscribeActual(MaybeObserver<? super T> observer) { + source.subscribe(new DoAfterObserver<T>(observer, onAfterSuccess)); } static final class DoAfterObserver<T> implements MaybeObserver<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java index 9bba726878..c1db295b50 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java @@ -38,8 +38,8 @@ public MaybeDoFinally(MaybeSource<T> source, Action onFinally) { } @Override - protected void subscribeActual(MaybeObserver<? super T> s) { - source.subscribe(new DoFinallyObserver<T>(s, onFinally)); + protected void subscribeActual(MaybeObserver<? super T> observer) { + source.subscribe(new DoFinallyObserver<T>(observer, onFinally)); } static final class DoFinallyObserver<T> extends AtomicInteger implements MaybeObserver<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapCompletable.java index 6e2c9e1ce6..f0bb42e89d 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapCompletable.java @@ -38,9 +38,9 @@ public MaybeFlatMapCompletable(MaybeSource<T> source, Function<? super T, ? exte } @Override - protected void subscribeActual(CompletableObserver s) { - FlatMapCompletableObserver<T> parent = new FlatMapCompletableObserver<T>(s, mapper); - s.onSubscribe(parent); + protected void subscribeActual(CompletableObserver observer) { + FlatMapCompletableObserver<T> parent = new FlatMapCompletableObserver<T>(observer, mapper); + observer.onSubscribe(parent); source.subscribe(parent); } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java index 23317717cb..1d3ca89756 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java @@ -43,8 +43,8 @@ public MaybeFlatMapIterableObservable(MaybeSource<T> source, } @Override - protected void subscribeActual(Observer<? super R> s) { - source.subscribe(new FlatMapIterableObserver<T, R>(s, mapper)); + protected void subscribeActual(Observer<? super R> observer) { + source.subscribe(new FlatMapIterableObserver<T, R>(observer, mapper)); } static final class FlatMapIterableObserver<T, R> diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java index b0777bf5ac..9b543c6472 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java @@ -39,8 +39,8 @@ public MaybeSource<T> source() { } @Override - protected void subscribeActual(Observer<? super T> s) { - source.subscribe(create(s)); + protected void subscribeActual(Observer<? super T> observer) { + source.subscribe(create(observer)); } /** diff --git a/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java b/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java index 418f1ebbb8..39f1a79a19 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java @@ -39,9 +39,9 @@ public CompletableAndThenObservable(CompletableSource source, } @Override - protected void subscribeActual(Observer<? super R> s) { - AndThenObservableObserver<R> parent = new AndThenObservableObserver<R>(s, other); - s.onSubscribe(parent); + protected void subscribeActual(Observer<? super R> observer) { + AndThenObservableObserver<R> parent = new AndThenObservableObserver<R>(observer, other); + observer.onSubscribe(parent); source.subscribe(parent); } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java index 5e7da33f2e..249d01ef82 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapCompletable.java @@ -57,8 +57,8 @@ public FlowableConcatMapCompletable(Flowable<T> source, } @Override - protected void subscribeActual(CompletableObserver s) { - source.subscribe(new ConcatMapCompletableObserver<T>(s, mapper, errorMode, prefetch)); + protected void subscribeActual(CompletableObserver observer) { + source.subscribe(new ConcatMapCompletableObserver<T>(observer, mapper, errorMode, prefetch)); } static final class ConcatMapCompletableObserver<T> diff --git a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java index 0bcc6041e0..70294ff3d3 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapCompletable.java @@ -51,8 +51,8 @@ public FlowableSwitchMapCompletable(Flowable<T> source, } @Override - protected void subscribeActual(CompletableObserver s) { - source.subscribe(new SwitchMapCompletableObserver<T>(s, mapper, delayErrors)); + protected void subscribeActual(CompletableObserver observer) { + source.subscribe(new SwitchMapCompletableObserver<T>(observer, mapper, delayErrors)); } static final class SwitchMapCompletableObserver<T> implements FlowableSubscriber<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservable.java b/src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservable.java index a15c77cba8..533e00addd 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/MaybeFlatMapObservable.java @@ -43,9 +43,9 @@ public MaybeFlatMapObservable(MaybeSource<T> source, } @Override - protected void subscribeActual(Observer<? super R> s) { - FlatMapObserver<T, R> parent = new FlatMapObserver<T, R>(s, mapper); - s.onSubscribe(parent); + protected void subscribeActual(Observer<? super R> observer) { + FlatMapObserver<T, R> parent = new FlatMapObserver<T, R>(observer, mapper); + observer.onSubscribe(parent); source.subscribe(parent); } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java index 60151de5c0..48a503c13c 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java @@ -54,9 +54,9 @@ public ObservableConcatMapCompletable(Observable<T> source, } @Override - protected void subscribeActual(CompletableObserver s) { - if (!ScalarXMapZHelper.tryAsCompletable(source, mapper, s)) { - source.subscribe(new ConcatMapCompletableObserver<T>(s, mapper, errorMode, prefetch)); + protected void subscribeActual(CompletableObserver observer) { + if (!ScalarXMapZHelper.tryAsCompletable(source, mapper, observer)) { + source.subscribe(new ConcatMapCompletableObserver<T>(observer, mapper, errorMode, prefetch)); } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java index f83388b5b7..1a52327c72 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java @@ -55,9 +55,9 @@ public ObservableConcatMapMaybe(Observable<T> source, } @Override - protected void subscribeActual(Observer<? super R> s) { - if (!ScalarXMapZHelper.tryAsMaybe(source, mapper, s)) { - source.subscribe(new ConcatMapMaybeMainObserver<T, R>(s, mapper, prefetch, errorMode)); + protected void subscribeActual(Observer<? super R> observer) { + if (!ScalarXMapZHelper.tryAsMaybe(source, mapper, observer)) { + source.subscribe(new ConcatMapMaybeMainObserver<T, R>(observer, mapper, prefetch, errorMode)); } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java index faca30b70f..b272f27218 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java @@ -55,9 +55,9 @@ public ObservableConcatMapSingle(Observable<T> source, } @Override - protected void subscribeActual(Observer<? super R> s) { - if (!ScalarXMapZHelper.tryAsSingle(source, mapper, s)) { - source.subscribe(new ConcatMapSingleMainObserver<T, R>(s, mapper, prefetch, errorMode)); + protected void subscribeActual(Observer<? super R> observer) { + if (!ScalarXMapZHelper.tryAsSingle(source, mapper, observer)) { + source.subscribe(new ConcatMapSingleMainObserver<T, R>(observer, mapper, prefetch, errorMode)); } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java index 4482a797c1..7ffe99b707 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java @@ -48,9 +48,9 @@ public ObservableSwitchMapCompletable(Observable<T> source, } @Override - protected void subscribeActual(CompletableObserver s) { - if (!ScalarXMapZHelper.tryAsCompletable(source, mapper, s)) { - source.subscribe(new SwitchMapCompletableObserver<T>(s, mapper, delayErrors)); + protected void subscribeActual(CompletableObserver observer) { + if (!ScalarXMapZHelper.tryAsCompletable(source, mapper, observer)) { + source.subscribe(new SwitchMapCompletableObserver<T>(observer, mapper, delayErrors)); } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java index a4e2586f95..d6e904cec2 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java @@ -50,9 +50,9 @@ public ObservableSwitchMapMaybe(Observable<T> source, } @Override - protected void subscribeActual(Observer<? super R> s) { - if (!ScalarXMapZHelper.tryAsMaybe(source, mapper, s)) { - source.subscribe(new SwitchMapMaybeMainObserver<T, R>(s, mapper, delayErrors)); + protected void subscribeActual(Observer<? super R> observer) { + if (!ScalarXMapZHelper.tryAsMaybe(source, mapper, observer)) { + source.subscribe(new SwitchMapMaybeMainObserver<T, R>(observer, mapper, delayErrors)); } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java index 166dce2b74..f739b10161 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java @@ -50,9 +50,9 @@ public ObservableSwitchMapSingle(Observable<T> source, } @Override - protected void subscribeActual(Observer<? super R> s) { - if (!ScalarXMapZHelper.tryAsSingle(source, mapper, s)) { - source.subscribe(new SwitchMapSingleMainObserver<T, R>(s, mapper, delayErrors)); + protected void subscribeActual(Observer<? super R> observer) { + if (!ScalarXMapZHelper.tryAsSingle(source, mapper, observer)) { + source.subscribe(new SwitchMapSingleMainObserver<T, R>(observer, mapper, delayErrors)); } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservable.java b/src/main/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservable.java index 590a726f89..48d5793185 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/SingleFlatMapObservable.java @@ -43,9 +43,9 @@ public SingleFlatMapObservable(SingleSource<T> source, } @Override - protected void subscribeActual(Observer<? super R> s) { - FlatMapObserver<T, R> parent = new FlatMapObserver<T, R>(s, mapper); - s.onSubscribe(parent); + protected void subscribeActual(Observer<? super R> observer) { + FlatMapObserver<T, R> parent = new FlatMapObserver<T, R>(observer, mapper); + observer.onSubscribe(parent); source.subscribe(parent); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java index 55abe1499b..65e2493f7e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java @@ -32,7 +32,7 @@ public ObservableAmb(ObservableSource<? extends T>[] sources, Iterable<? extends @Override @SuppressWarnings("unchecked") - public void subscribeActual(Observer<? super T> s) { + public void subscribeActual(Observer<? super T> observer) { ObservableSource<? extends T>[] sources = this.sources; int count = 0; if (sources == null) { @@ -40,7 +40,7 @@ public void subscribeActual(Observer<? super T> s) { try { for (ObservableSource<? extends T> p : sourcesIterable) { if (p == null) { - EmptyDisposable.error(new NullPointerException("One of the sources is null"), s); + EmptyDisposable.error(new NullPointerException("One of the sources is null"), observer); return; } if (count == sources.length) { @@ -52,7 +52,7 @@ public void subscribeActual(Observer<? super T> s) { } } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } } else { @@ -60,15 +60,15 @@ public void subscribeActual(Observer<? super T> s) { } if (count == 0) { - EmptyDisposable.complete(s); + EmptyDisposable.complete(observer); return; } else if (count == 1) { - sources[0].subscribe(s); + sources[0].subscribe(observer); return; } - AmbCoordinator<T> ac = new AmbCoordinator<T>(s, count); + AmbCoordinator<T> ac = new AmbCoordinator<T>(observer, count); ac.subscribe(sources); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java index c8c8dd8fa1..d8ed6175f6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java @@ -46,7 +46,7 @@ public ObservableCombineLatest(ObservableSource<? extends T>[] sources, @Override @SuppressWarnings("unchecked") - public void subscribeActual(Observer<? super R> s) { + public void subscribeActual(Observer<? super R> observer) { ObservableSource<? extends T>[] sources = this.sources; int count = 0; if (sources == null) { @@ -64,11 +64,11 @@ public void subscribeActual(Observer<? super R> s) { } if (count == 0) { - EmptyDisposable.complete(s); + EmptyDisposable.complete(observer); return; } - LatestCoordinator<T, R> lc = new LatestCoordinator<T, R>(s, combiner, count, bufferSize, delayError); + LatestCoordinator<T, R> lc = new LatestCoordinator<T, R>(observer, combiner, count, bufferSize, delayError); lc.subscribe(sources); } @@ -136,8 +136,8 @@ public boolean isDisposed() { } void cancelSources() { - for (CombinerObserver<T, R> s : observers) { - s.dispose(); + for (CombinerObserver<T, R> observer : observers) { + observer.dispose(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java index 8e66db0bdc..f719e0a842 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java @@ -41,17 +41,17 @@ public ObservableConcatMap(ObservableSource<T> source, Function<? super T, ? ext this.bufferSize = Math.max(8, bufferSize); } @Override - public void subscribeActual(Observer<? super U> s) { + public void subscribeActual(Observer<? super U> observer) { - if (ObservableScalarXMap.tryScalarXMapSubscribe(source, s, mapper)) { + if (ObservableScalarXMap.tryScalarXMapSubscribe(source, observer, mapper)) { return; } if (delayErrors == ErrorMode.IMMEDIATE) { - SerializedObserver<U> serial = new SerializedObserver<U>(s); + SerializedObserver<U> serial = new SerializedObserver<U>(observer); source.subscribe(new SourceObserver<T, U>(serial, mapper, bufferSize)); } else { - source.subscribe(new ConcatMapDelayErrorObserver<T, U>(s, mapper, bufferSize, delayErrors == ErrorMode.END)); + source.subscribe(new ConcatMapDelayErrorObserver<T, U>(observer, mapper, bufferSize, delayErrors == ErrorMode.END)); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDefer.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDefer.java index 37996e1332..411530c81f 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDefer.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDefer.java @@ -26,16 +26,16 @@ public ObservableDefer(Callable<? extends ObservableSource<? extends T>> supplie this.supplier = supplier; } @Override - public void subscribeActual(Observer<? super T> s) { + public void subscribeActual(Observer<? super T> observer) { ObservableSource<? extends T> pub; try { pub = ObjectHelper.requireNonNull(supplier.call(), "null ObservableSource supplied"); } catch (Throwable t) { Exceptions.throwIfFatal(t); - EmptyDisposable.error(t, s); + EmptyDisposable.error(t, observer); return; } - pub.subscribe(s); + pub.subscribe(observer); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDelay.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDelay.java index adfbbd4b3f..8dff7222eb 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDelay.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDelay.java @@ -38,16 +38,16 @@ public ObservableDelay(ObservableSource<T> source, long delay, TimeUnit unit, Sc @Override @SuppressWarnings("unchecked") public void subscribeActual(Observer<? super T> t) { - Observer<T> s; + Observer<T> observer; if (delayError) { - s = (Observer<T>)t; + observer = (Observer<T>)t; } else { - s = new SerializedObserver<T>(t); + observer = new SerializedObserver<T>(t); } Scheduler.Worker w = scheduler.createWorker(); - source.subscribe(new DelayObserver<T>(s, delay, unit, w, delayError)); + source.subscribe(new DelayObserver<T>(observer, delay, unit, w, delayError)); } static final class DelayObserver<T> implements Observer<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDetach.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDetach.java index 797d06fcd5..b5093e0972 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDetach.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDetach.java @@ -31,8 +31,8 @@ public ObservableDetach(ObservableSource<T> source) { } @Override - protected void subscribeActual(Observer<? super T> s) { - source.subscribe(new DetachObserver<T>(s)); + protected void subscribeActual(Observer<? super T> observer) { + source.subscribe(new DetachObserver<T>(observer)); } static final class DetachObserver<T> implements Observer<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChanged.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChanged.java index e5eb1e7cdf..065d121b0a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChanged.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChanged.java @@ -31,8 +31,8 @@ public ObservableDistinctUntilChanged(ObservableSource<T> source, Function<? sup } @Override - protected void subscribeActual(Observer<? super T> s) { - source.subscribe(new DistinctUntilChangedObserver<T, K>(s, keySelector, comparer)); + protected void subscribeActual(Observer<? super T> observer) { + source.subscribe(new DistinctUntilChangedObserver<T, K>(observer, keySelector, comparer)); } static final class DistinctUntilChangedObserver<T, K> extends BasicFuseableObserver<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java index e1346d2dbe..e2d7760413 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java @@ -34,8 +34,8 @@ public ObservableDoAfterNext(ObservableSource<T> source, Consumer<? super T> onA } @Override - protected void subscribeActual(Observer<? super T> s) { - source.subscribe(new DoAfterObserver<T>(s, onAfterNext)); + protected void subscribeActual(Observer<? super T> observer) { + source.subscribe(new DoAfterObserver<T>(observer, onAfterNext)); } static final class DoAfterObserver<T> extends BasicFuseableObserver<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java index 99720ce5cc..196a8c78e2 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java @@ -39,8 +39,8 @@ public ObservableDoFinally(ObservableSource<T> source, Action onFinally) { } @Override - protected void subscribeActual(Observer<? super T> s) { - source.subscribe(new DoFinallyObserver<T>(s, onFinally)); + protected void subscribeActual(Observer<? super T> observer) { + source.subscribe(new DoFinallyObserver<T>(observer, onFinally)); } static final class DoFinallyObserver<T> extends BasicIntQueueDisposable<T> implements Observer<T> { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableError.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableError.java index 29076de2b4..bc375ddf38 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableError.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableError.java @@ -26,7 +26,7 @@ public ObservableError(Callable<? extends Throwable> errorSupplier) { this.errorSupplier = errorSupplier; } @Override - public void subscribeActual(Observer<? super T> s) { + public void subscribeActual(Observer<? super T> observer) { Throwable error; try { error = ObjectHelper.requireNonNull(errorSupplier.call(), "Callable returned null throwable. Null values are generally not allowed in 2.x operators and sources."); @@ -34,6 +34,6 @@ public void subscribeActual(Observer<? super T> s) { Exceptions.throwIfFatal(t); error = t; } - EmptyDisposable.error(error, s); + EmptyDisposable.error(error, observer); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFilter.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFilter.java index 108c44a88c..cbe8fa3849 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFilter.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFilter.java @@ -26,8 +26,8 @@ public ObservableFilter(ObservableSource<T> source, Predicate<? super T> predica } @Override - public void subscribeActual(Observer<? super T> s) { - source.subscribe(new FilterObserver<T>(s, predicate)); + public void subscribeActual(Observer<? super T> observer) { + source.subscribe(new FilterObserver<T>(observer, predicate)); } static final class FilterObserver<T> extends BasicFuseableObserver<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybe.java index 930f339175..51815b4c1e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybe.java @@ -44,8 +44,8 @@ public ObservableFlatMapMaybe(ObservableSource<T> source, Function<? super T, ? } @Override - protected void subscribeActual(Observer<? super R> s) { - source.subscribe(new FlatMapMaybeObserver<T, R>(s, mapper, delayErrors)); + protected void subscribeActual(Observer<? super R> observer) { + source.subscribe(new FlatMapMaybeObserver<T, R>(observer, mapper, delayErrors)); } static final class FlatMapMaybeObserver<T, R> diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingle.java index 34f298fa2c..4697d8e106 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingle.java @@ -44,8 +44,8 @@ public ObservableFlatMapSingle(ObservableSource<T> source, Function<? super T, ? } @Override - protected void subscribeActual(Observer<? super R> s) { - source.subscribe(new FlatMapSingleObserver<T, R>(s, mapper, delayErrors)); + protected void subscribeActual(Observer<? super R> observer) { + source.subscribe(new FlatMapSingleObserver<T, R>(observer, mapper, delayErrors)); } static final class FlatMapSingleObserver<T, R> diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java index 4ac881ceec..bd12bec41c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java @@ -24,10 +24,10 @@ public ObservableFromArray(T[] array) { this.array = array; } @Override - public void subscribeActual(Observer<? super T> s) { - FromArrayDisposable<T> d = new FromArrayDisposable<T>(s, array); + public void subscribeActual(Observer<? super T> observer) { + FromArrayDisposable<T> d = new FromArrayDisposable<T>(observer, array); - s.onSubscribe(d); + observer.onSubscribe(d); if (d.fusionMode) { return; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromCallable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromCallable.java index aaa3756ec2..214af8f4d7 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromCallable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromCallable.java @@ -31,9 +31,9 @@ public ObservableFromCallable(Callable<? extends T> callable) { this.callable = callable; } @Override - public void subscribeActual(Observer<? super T> s) { - DeferredScalarDisposable<T> d = new DeferredScalarDisposable<T>(s); - s.onSubscribe(d); + public void subscribeActual(Observer<? super T> observer) { + DeferredScalarDisposable<T> d = new DeferredScalarDisposable<T>(observer); + observer.onSubscribe(d); if (d.isDisposed()) { return; } @@ -43,7 +43,7 @@ public void subscribeActual(Observer<? super T> s) { } catch (Throwable e) { Exceptions.throwIfFatal(e); if (!d.isDisposed()) { - s.onError(e); + observer.onError(e); } else { RxJavaPlugins.onError(e); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromFuture.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromFuture.java index 6a58d50680..ec6e90275d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromFuture.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromFuture.java @@ -32,9 +32,9 @@ public ObservableFromFuture(Future<? extends T> future, long timeout, TimeUnit u } @Override - public void subscribeActual(Observer<? super T> s) { - DeferredScalarDisposable<T> d = new DeferredScalarDisposable<T>(s); - s.onSubscribe(d); + public void subscribeActual(Observer<? super T> observer) { + DeferredScalarDisposable<T> d = new DeferredScalarDisposable<T>(observer); + observer.onSubscribe(d); if (!d.isDisposed()) { T v; try { @@ -42,7 +42,7 @@ public void subscribeActual(Observer<? super T> s) { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); if (!d.isDisposed()) { - s.onError(ex); + observer.onError(ex); } return; } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromIterable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromIterable.java index 3a8b7853d5..ae7638e142 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromIterable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromIterable.java @@ -29,13 +29,13 @@ public ObservableFromIterable(Iterable<? extends T> source) { } @Override - public void subscribeActual(Observer<? super T> s) { + public void subscribeActual(Observer<? super T> observer) { Iterator<? extends T> it; try { it = source.iterator(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } boolean hasNext; @@ -43,16 +43,16 @@ public void subscribeActual(Observer<? super T> s) { hasNext = it.hasNext(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } if (!hasNext) { - EmptyDisposable.complete(s); + EmptyDisposable.complete(observer); return; } - FromIterableDisposable<T> d = new FromIterableDisposable<T>(s, it); - s.onSubscribe(d); + FromIterableDisposable<T> d = new FromIterableDisposable<T>(observer, it); + observer.onSubscribe(d); if (!d.fusionMode) { d.run(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java index 063ad6d980..ac33e689ac 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java @@ -35,19 +35,19 @@ public ObservableGenerate(Callable<S> stateSupplier, BiFunction<S, Emitter<T>, S } @Override - public void subscribeActual(Observer<? super T> s) { + public void subscribeActual(Observer<? super T> observer) { S state; try { state = stateSupplier.call(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } - GeneratorDisposable<T, S> gd = new GeneratorDisposable<T, S>(s, generator, disposeState, state); - s.onSubscribe(gd); + GeneratorDisposable<T, S> gd = new GeneratorDisposable<T, S>(observer, generator, disposeState, state); + observer.onSubscribe(gd); gd.run(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupBy.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupBy.java index b2d60f492d..2667401199 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupBy.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupBy.java @@ -247,17 +247,17 @@ public boolean isDisposed() { } @Override - public void subscribe(Observer<? super T> s) { + public void subscribe(Observer<? super T> observer) { if (once.compareAndSet(false, true)) { - s.onSubscribe(this); - actual.lazySet(s); + observer.onSubscribe(this); + actual.lazySet(observer); if (cancelled.get()) { actual.lazySet(null); } else { drain(); } } else { - EmptyDisposable.error(new IllegalStateException("Only one Observer allowed!"), s); + EmptyDisposable.error(new IllegalStateException("Only one Observer allowed!"), observer); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java index a6bf21423f..bf012297cd 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java @@ -56,12 +56,12 @@ public ObservableGroupJoin( } @Override - protected void subscribeActual(Observer<? super R> s) { + protected void subscribeActual(Observer<? super R> observer) { GroupJoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R> parent = - new GroupJoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R>(s, leftEnd, rightEnd, resultSelector); + new GroupJoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R>(observer, leftEnd, rightEnd, resultSelector); - s.onSubscribe(parent); + observer.onSubscribe(parent); LeftRightObserver left = new LeftRightObserver(parent, true); parent.disposables.add(left); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java index 7607b62458..ae5038b525 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java @@ -36,9 +36,9 @@ public ObservableInterval(long initialDelay, long period, TimeUnit unit, Schedul } @Override - public void subscribeActual(Observer<? super Long> s) { - IntervalObserver is = new IntervalObserver(s); - s.onSubscribe(is); + public void subscribeActual(Observer<? super Long> observer) { + IntervalObserver is = new IntervalObserver(observer); + observer.onSubscribe(is); Scheduler sch = scheduler; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java index 3fd5396bfd..9d011b3b6b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java @@ -40,9 +40,9 @@ public ObservableIntervalRange(long start, long end, long initialDelay, long per } @Override - public void subscribeActual(Observer<? super Long> s) { - IntervalRangeObserver is = new IntervalRangeObserver(s, start, end); - s.onSubscribe(is); + public void subscribeActual(Observer<? super Long> observer) { + IntervalRangeObserver is = new IntervalRangeObserver(observer, start, end); + observer.onSubscribe(is); Scheduler sch = scheduler; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java index 2485c1cd2a..5cbde302bb 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java @@ -54,13 +54,13 @@ public ObservableJoin( } @Override - protected void subscribeActual(Observer<? super R> s) { + protected void subscribeActual(Observer<? super R> observer) { JoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R> parent = new JoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R>( - s, leftEnd, rightEnd, resultSelector); + observer, leftEnd, rightEnd, resultSelector); - s.onSubscribe(parent); + observer.onSubscribe(parent); LeftRightObserver left = new LeftRightObserver(parent, true); parent.disposables.add(left); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableJust.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableJust.java index 653fef105b..0ae53fb597 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableJust.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableJust.java @@ -29,9 +29,9 @@ public ObservableJust(final T value) { } @Override - protected void subscribeActual(Observer<? super T> s) { - ScalarDisposable<T> sd = new ScalarDisposable<T>(s, value); - s.onSubscribe(sd); + protected void subscribeActual(Observer<? super T> observer) { + ScalarDisposable<T> sd = new ScalarDisposable<T>(observer, value); + observer.onSubscribe(sd); sd.run(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableLift.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableLift.java index ca9c36a697..8cdd918564 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableLift.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableLift.java @@ -37,10 +37,10 @@ public ObservableLift(ObservableSource<T> source, ObservableOperator<? extends R } @Override - public void subscribeActual(Observer<? super R> s) { - Observer<? super T> observer; + public void subscribeActual(Observer<? super R> observer) { + Observer<? super T> liftedObserver; try { - observer = ObjectHelper.requireNonNull(operator.apply(s), "Operator " + operator + " returned a null Observer"); + liftedObserver = ObjectHelper.requireNonNull(operator.apply(observer), "Operator " + operator + " returned a null Observer"); } catch (NullPointerException e) { // NOPMD throw e; } catch (Throwable e) { @@ -54,6 +54,6 @@ public void subscribeActual(Observer<? super R> s) { throw npe; } - source.subscribe(observer); + source.subscribe(liftedObserver); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java index fd62c1ae60..73b1e0c1db 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java @@ -59,7 +59,7 @@ public ObservableRefCount(ConnectableObservable<T> source, int n, long timeout, } @Override - protected void subscribeActual(Observer<? super T> s) { + protected void subscribeActual(Observer<? super T> observer) { RefConnection conn; @@ -82,7 +82,7 @@ protected void subscribeActual(Observer<? super T> s) { } } - source.subscribe(new RefCountObserver<T>(s, this, conn)); + source.subscribe(new RefCountObserver<T>(observer, this, conn)); if (connect) { source.connect(conn); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java index f3dce65e80..c5ce8d1763 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java @@ -27,11 +27,11 @@ public ObservableRepeat(Observable<T> source, long count) { } @Override - public void subscribeActual(Observer<? super T> s) { + public void subscribeActual(Observer<? super T> observer) { SequentialDisposable sd = new SequentialDisposable(); - s.onSubscribe(sd); + observer.onSubscribe(sd); - RepeatObserver<T> rs = new RepeatObserver<T>(s, count != Long.MAX_VALUE ? count - 1 : Long.MAX_VALUE, sd, source); + RepeatObserver<T> rs = new RepeatObserver<T>(observer, count != Long.MAX_VALUE ? count - 1 : Long.MAX_VALUE, sd, source); rs.subscribeNext(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java index 6f97906ece..595c5e3b03 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java @@ -29,11 +29,11 @@ public ObservableRepeatUntil(Observable<T> source, BooleanSupplier until) { } @Override - public void subscribeActual(Observer<? super T> s) { + public void subscribeActual(Observer<? super T> observer) { SequentialDisposable sd = new SequentialDisposable(); - s.onSubscribe(sd); + observer.onSubscribe(sd); - RepeatUntilObserver<T> rs = new RepeatUntilObserver<T>(s, until, sd, source); + RepeatUntilObserver<T> rs = new RepeatUntilObserver<T>(observer, until, sd, source); rs.subscribeNext(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java index 82cfe538d3..cbf1111400 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java @@ -31,11 +31,11 @@ public ObservableRetryBiPredicate( } @Override - public void subscribeActual(Observer<? super T> s) { + public void subscribeActual(Observer<? super T> observer) { SequentialDisposable sa = new SequentialDisposable(); - s.onSubscribe(sa); + observer.onSubscribe(sa); - RetryBiObserver<T> rs = new RetryBiObserver<T>(s, predicate, sa, source); + RetryBiObserver<T> rs = new RetryBiObserver<T>(observer, predicate, sa, source); rs.subscribeNext(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java index 33a52d84a0..9c22024a7e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java @@ -33,11 +33,11 @@ public ObservableRetryPredicate(Observable<T> source, } @Override - public void subscribeActual(Observer<? super T> s) { + public void subscribeActual(Observer<? super T> observer) { SequentialDisposable sa = new SequentialDisposable(); - s.onSubscribe(sa); + observer.onSubscribe(sa); - RepeatObserver<T> rs = new RepeatObserver<T>(s, count, predicate, sa, source); + RepeatObserver<T> rs = new RepeatObserver<T>(observer, count, predicate, sa, source); rs.subscribeNext(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableScalarXMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableScalarXMap.java index 418e6514f9..d58437900c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableScalarXMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableScalarXMap.java @@ -136,12 +136,12 @@ static final class ScalarXMapObservable<T, R> extends Observable<R> { @SuppressWarnings("unchecked") @Override - public void subscribeActual(Observer<? super R> s) { + public void subscribeActual(Observer<? super R> observer) { ObservableSource<? extends R> other; try { other = ObjectHelper.requireNonNull(mapper.apply(value), "The mapper returned a null ObservableSource"); } catch (Throwable e) { - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } if (other instanceof Callable) { @@ -151,19 +151,19 @@ public void subscribeActual(Observer<? super R> s) { u = ((Callable<R>)other).call(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - EmptyDisposable.error(ex, s); + EmptyDisposable.error(ex, observer); return; } if (u == null) { - EmptyDisposable.complete(s); + EmptyDisposable.complete(observer); return; } - ScalarDisposable<R> sd = new ScalarDisposable<R>(s, u); - s.onSubscribe(sd); + ScalarDisposable<R> sd = new ScalarDisposable<R>(observer, u); + observer.onSubscribe(sd); sd.run(); } else { - other.subscribe(s); + other.subscribe(observer); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqual.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqual.java index c2bf67f605..aab9dcab05 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqual.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqual.java @@ -37,9 +37,9 @@ public ObservableSequenceEqual(ObservableSource<? extends T> first, ObservableSo } @Override - public void subscribeActual(Observer<? super Boolean> s) { - EqualCoordinator<T> ec = new EqualCoordinator<T>(s, bufferSize, first, second, comparer); - s.onSubscribe(ec); + public void subscribeActual(Observer<? super Boolean> observer) { + EqualCoordinator<T> ec = new EqualCoordinator<T>(observer, bufferSize, first, second, comparer); + observer.onSubscribe(ec); ec.subscribe(); } @@ -117,10 +117,10 @@ void drain() { int missed = 1; EqualObserver<T>[] as = observers; - final EqualObserver<T> s1 = as[0]; - final SpscLinkedArrayQueue<T> q1 = s1.queue; - final EqualObserver<T> s2 = as[1]; - final SpscLinkedArrayQueue<T> q2 = s2.queue; + final EqualObserver<T> observer1 = as[0]; + final SpscLinkedArrayQueue<T> q1 = observer1.queue; + final EqualObserver<T> observer2 = as[1]; + final SpscLinkedArrayQueue<T> q2 = observer2.queue; for (;;) { @@ -131,10 +131,10 @@ void drain() { return; } - boolean d1 = s1.done; + boolean d1 = observer1.done; if (d1) { - Throwable e = s1.error; + Throwable e = observer1.error; if (e != null) { cancel(q1, q2); @@ -143,9 +143,9 @@ void drain() { } } - boolean d2 = s2.done; + boolean d2 = observer2.done; if (d2) { - Throwable e = s2.error; + Throwable e = observer2.error; if (e != null) { cancel(q1, q2); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualSingle.java index 8d227e699d..742b7fb39c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualSingle.java @@ -39,9 +39,9 @@ public ObservableSequenceEqualSingle(ObservableSource<? extends T> first, Observ } @Override - public void subscribeActual(SingleObserver<? super Boolean> s) { - EqualCoordinator<T> ec = new EqualCoordinator<T>(s, bufferSize, first, second, comparer); - s.onSubscribe(ec); + public void subscribeActual(SingleObserver<? super Boolean> observer) { + EqualCoordinator<T> ec = new EqualCoordinator<T>(observer, bufferSize, first, second, comparer); + observer.onSubscribe(ec); ec.subscribe(); } @@ -124,10 +124,10 @@ void drain() { int missed = 1; EqualObserver<T>[] as = observers; - final EqualObserver<T> s1 = as[0]; - final SpscLinkedArrayQueue<T> q1 = s1.queue; - final EqualObserver<T> s2 = as[1]; - final SpscLinkedArrayQueue<T> q2 = s2.queue; + final EqualObserver<T> observer1 = as[0]; + final SpscLinkedArrayQueue<T> q1 = observer1.queue; + final EqualObserver<T> observer2 = as[1]; + final SpscLinkedArrayQueue<T> q2 = observer2.queue; for (;;) { @@ -138,10 +138,10 @@ void drain() { return; } - boolean d1 = s1.done; + boolean d1 = observer1.done; if (d1) { - Throwable e = s1.error; + Throwable e = observer1.error; if (e != null) { cancel(q1, q2); @@ -150,9 +150,9 @@ void drain() { } } - boolean d2 = s2.done; + boolean d2 = observer2.done; if (d2) { - Throwable e = s2.error; + Throwable e = observer2.error; if (e != null) { cancel(q1, q2); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java index 944506365a..570c4e8877 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java @@ -25,8 +25,8 @@ public ObservableSkip(ObservableSource<T> source, long n) { } @Override - public void subscribeActual(Observer<? super T> s) { - source.subscribe(new SkipObserver<T>(s, n)); + public void subscribeActual(Observer<? super T> observer) { + source.subscribe(new SkipObserver<T>(observer, n)); } static final class SkipObserver<T> implements Observer<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java index be257cd9c8..f22df6fdf7 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java @@ -28,8 +28,8 @@ public ObservableSkipLast(ObservableSource<T> source, int skip) { } @Override - public void subscribeActual(Observer<? super T> s) { - source.subscribe(new SkipLastObserver<T>(s, skip)); + public void subscribeActual(Observer<? super T> observer) { + source.subscribe(new SkipLastObserver<T>(observer, skip)); } static final class SkipLastObserver<T> extends ArrayDeque<T> implements Observer<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java index a46e27b22e..dfe5fd1d9c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java @@ -27,8 +27,8 @@ public ObservableSkipWhile(ObservableSource<T> source, Predicate<? super T> pred } @Override - public void subscribeActual(Observer<? super T> s) { - source.subscribe(new SkipWhileObserver<T>(s, predicate)); + public void subscribeActual(Observer<? super T> observer) { + source.subscribe(new SkipWhileObserver<T>(observer, predicate)); } static final class SkipWhileObserver<T> implements Observer<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSubscribeOn.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSubscribeOn.java index 57f4666b52..c55a224155 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSubscribeOn.java @@ -28,10 +28,10 @@ public ObservableSubscribeOn(ObservableSource<T> source, Scheduler scheduler) { } @Override - public void subscribeActual(final Observer<? super T> s) { - final SubscribeOnObserver<T> parent = new SubscribeOnObserver<T>(s); + public void subscribeActual(final Observer<? super T> observer) { + final SubscribeOnObserver<T> parent = new SubscribeOnObserver<T>(observer); - s.onSubscribe(parent); + observer.onSubscribe(parent); parent.setDisposable(scheduler.scheduleDirect(new SubscribeTask(parent))); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastOne.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastOne.java index e0c765ec98..04ad923c28 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastOne.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastOne.java @@ -23,8 +23,8 @@ public ObservableTakeLastOne(ObservableSource<T> source) { } @Override - public void subscribeActual(Observer<? super T> s) { - source.subscribe(new TakeLastOneObserver<T>(s)); + public void subscribeActual(Observer<? super T> observer) { + source.subscribe(new TakeLastOneObserver<T>(observer)); } static final class TakeLastOneObserver<T> implements Observer<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicate.java index 8af48da7e0..43cdaf05bd 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicate.java @@ -28,8 +28,8 @@ public ObservableTakeUntilPredicate(ObservableSource<T> source, Predicate<? supe } @Override - public void subscribeActual(Observer<? super T> s) { - source.subscribe(new TakeUntilPredicateObserver<T>(s, predicate)); + public void subscribeActual(Observer<? super T> observer) { + source.subscribe(new TakeUntilPredicateObserver<T>(observer, predicate)); } static final class TakeUntilPredicateObserver<T> implements Observer<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java index 41130d56e2..00dda7ad6b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java @@ -52,8 +52,8 @@ public ObservableThrottleLatest(Observable<T> source, } @Override - protected void subscribeActual(Observer<? super T> s) { - source.subscribe(new ThrottleLatestObserver<T>(s, timeout, unit, scheduler.createWorker(), emitLast)); + protected void subscribeActual(Observer<? super T> observer) { + source.subscribe(new ThrottleLatestObserver<T>(observer, timeout, unit, scheduler.createWorker(), emitLast)); } static final class ThrottleLatestObserver<T> diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java index 5cfcb620ba..eeacf6d555 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java @@ -42,15 +42,15 @@ public ObservableTimeout( } @Override - protected void subscribeActual(Observer<? super T> s) { + protected void subscribeActual(Observer<? super T> observer) { if (other == null) { - TimeoutObserver<T> parent = new TimeoutObserver<T>(s, itemTimeoutIndicator); - s.onSubscribe(parent); + TimeoutObserver<T> parent = new TimeoutObserver<T>(observer, itemTimeoutIndicator); + observer.onSubscribe(parent); parent.startFirstTimeout(firstTimeoutIndicator); source.subscribe(parent); } else { - TimeoutFallbackObserver<T> parent = new TimeoutFallbackObserver<T>(s, itemTimeoutIndicator, other); - s.onSubscribe(parent); + TimeoutFallbackObserver<T> parent = new TimeoutFallbackObserver<T>(observer, itemTimeoutIndicator, other); + observer.onSubscribe(parent); parent.startFirstTimeout(firstTimeoutIndicator); source.subscribe(parent); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java index fdca2d3882..45416b9344 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java @@ -37,15 +37,15 @@ public ObservableTimeoutTimed(Observable<T> source, } @Override - protected void subscribeActual(Observer<? super T> s) { + protected void subscribeActual(Observer<? super T> observer) { if (other == null) { - TimeoutObserver<T> parent = new TimeoutObserver<T>(s, timeout, unit, scheduler.createWorker()); - s.onSubscribe(parent); + TimeoutObserver<T> parent = new TimeoutObserver<T>(observer, timeout, unit, scheduler.createWorker()); + observer.onSubscribe(parent); parent.startTimeout(0L); source.subscribe(parent); } else { - TimeoutFallbackObserver<T> parent = new TimeoutFallbackObserver<T>(s, timeout, unit, scheduler.createWorker(), other); - s.onSubscribe(parent); + TimeoutFallbackObserver<T> parent = new TimeoutFallbackObserver<T>(observer, timeout, unit, scheduler.createWorker(), other); + observer.onSubscribe(parent); parent.startTimeout(0L); source.subscribe(parent); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimer.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimer.java index 1414da06f6..01a6a52743 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimer.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimer.java @@ -31,9 +31,9 @@ public ObservableTimer(long delay, TimeUnit unit, Scheduler scheduler) { } @Override - public void subscribeActual(Observer<? super Long> s) { - TimerObserver ios = new TimerObserver(s); - s.onSubscribe(ios); + public void subscribeActual(Observer<? super Long> observer) { + TimerObserver ios = new TimerObserver(observer); + observer.onSubscribe(ios); Disposable d = scheduler.scheduleDirect(ios, delay, unit); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableUsing.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableUsing.java index e29c3e739e..039da6f67c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableUsing.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableUsing.java @@ -41,14 +41,14 @@ public ObservableUsing(Callable<? extends D> resourceSupplier, } @Override - public void subscribeActual(Observer<? super T> s) { + public void subscribeActual(Observer<? super T> observer) { D resource; try { resource = resourceSupplier.call(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } @@ -61,14 +61,14 @@ public void subscribeActual(Observer<? super T> s) { disposer.accept(resource); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - EmptyDisposable.error(new CompositeException(e, ex), s); + EmptyDisposable.error(new CompositeException(e, ex), observer); return; } - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } - UsingObserver<T, D> us = new UsingObserver<T, D>(s, resource, disposer, eager); + UsingObserver<T, D> us = new UsingObserver<T, D>(observer, resource, disposer, eager); source.subscribe(us); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromMany.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromMany.java index 1578d0e950..b460ad58b1 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromMany.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromMany.java @@ -59,7 +59,7 @@ public ObservableWithLatestFromMany(@NonNull ObservableSource<T> source, @NonNul } @Override - protected void subscribeActual(Observer<? super R> s) { + protected void subscribeActual(Observer<? super R> observer) { ObservableSource<?>[] others = otherArray; int n = 0; if (others == null) { @@ -74,7 +74,7 @@ protected void subscribeActual(Observer<? super R> s) { } } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - EmptyDisposable.error(ex, s); + EmptyDisposable.error(ex, observer); return; } @@ -83,12 +83,12 @@ protected void subscribeActual(Observer<? super R> s) { } if (n == 0) { - new ObservableMap<T, R>(source, new SingletonArrayFunc()).subscribeActual(s); + new ObservableMap<T, R>(source, new SingletonArrayFunc()).subscribeActual(observer); return; } - WithLatestFromObserver<T, R> parent = new WithLatestFromObserver<T, R>(s, combiner, n); - s.onSubscribe(parent); + WithLatestFromObserver<T, R> parent = new WithLatestFromObserver<T, R>(observer, combiner, n); + observer.onSubscribe(parent); parent.subscribe(others, n); source.subscribe(parent); @@ -204,8 +204,8 @@ public boolean isDisposed() { @Override public void dispose() { DisposableHelper.dispose(d); - for (WithLatestInnerObserver s : observers) { - s.dispose(); + for (WithLatestInnerObserver observer : observers) { + observer.dispose(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java index 2227849571..923c1a062d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java @@ -46,7 +46,7 @@ public ObservableZip(ObservableSource<? extends T>[] sources, @Override @SuppressWarnings("unchecked") - public void subscribeActual(Observer<? super R> s) { + public void subscribeActual(Observer<? super R> observer) { ObservableSource<? extends T>[] sources = this.sources; int count = 0; if (sources == null) { @@ -64,11 +64,11 @@ public void subscribeActual(Observer<? super R> s) { } if (count == 0) { - EmptyDisposable.complete(s); + EmptyDisposable.complete(observer); return; } - ZipCoordinator<T, R> zc = new ZipCoordinator<T, R>(s, zipper, count, delayError); + ZipCoordinator<T, R> zc = new ZipCoordinator<T, R>(observer, zipper, count, delayError); zc.subscribe(sources, bufferSize); } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleAmb.java b/src/main/java/io/reactivex/internal/operators/single/SingleAmb.java index d0acba1234..d7508c3a72 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleAmb.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleAmb.java @@ -32,7 +32,7 @@ public SingleAmb(SingleSource<? extends T>[] sources, Iterable<? extends SingleS @Override @SuppressWarnings("unchecked") - protected void subscribeActual(final SingleObserver<? super T> s) { + protected void subscribeActual(final SingleObserver<? super T> observer) { SingleSource<? extends T>[] sources = this.sources; int count = 0; if (sources == null) { @@ -40,7 +40,7 @@ protected void subscribeActual(final SingleObserver<? super T> s) { try { for (SingleSource<? extends T> element : sourcesIterable) { if (element == null) { - EmptyDisposable.error(new NullPointerException("One of the sources is null"), s); + EmptyDisposable.error(new NullPointerException("One of the sources is null"), observer); return; } if (count == sources.length) { @@ -52,7 +52,7 @@ protected void subscribeActual(final SingleObserver<? super T> s) { } } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } } else { @@ -61,8 +61,8 @@ protected void subscribeActual(final SingleObserver<? super T> s) { final CompositeDisposable set = new CompositeDisposable(); - AmbSingleObserver<T> shared = new AmbSingleObserver<T>(s, set); - s.onSubscribe(set); + AmbSingleObserver<T> shared = new AmbSingleObserver<T>(observer, set); + observer.onSubscribe(set); for (int i = 0; i < count; i++) { SingleSource<? extends T> s1 = sources[i]; @@ -74,7 +74,7 @@ protected void subscribeActual(final SingleObserver<? super T> s) { set.dispose(); Throwable e = new NullPointerException("One of the sources is null"); if (shared.compareAndSet(false, true)) { - s.onError(e); + observer.onError(e); } else { RxJavaPlugins.onError(e); } @@ -91,10 +91,10 @@ static final class AmbSingleObserver<T> extends AtomicBoolean implements SingleO final CompositeDisposable set; - final SingleObserver<? super T> s; + final SingleObserver<? super T> downstream; - AmbSingleObserver(SingleObserver<? super T> s, CompositeDisposable set) { - this.s = s; + AmbSingleObserver(SingleObserver<? super T> observer, CompositeDisposable set) { + this.downstream = observer; this.set = set; } @@ -107,7 +107,7 @@ public void onSubscribe(Disposable d) { public void onSuccess(T value) { if (compareAndSet(false, true)) { set.dispose(); - s.onSuccess(value); + downstream.onSuccess(value); } } @@ -115,7 +115,7 @@ public void onSuccess(T value) { public void onError(Throwable e) { if (compareAndSet(false, true)) { set.dispose(); - s.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleCache.java b/src/main/java/io/reactivex/internal/operators/single/SingleCache.java index d658f8cd5a..de237efc84 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleCache.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleCache.java @@ -43,9 +43,9 @@ public SingleCache(SingleSource<? extends T> source) { } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { - CacheDisposable<T> d = new CacheDisposable<T>(s, this); - s.onSubscribe(d); + protected void subscribeActual(final SingleObserver<? super T> observer) { + CacheDisposable<T> d = new CacheDisposable<T>(observer, this); + observer.onSubscribe(d); if (add(d)) { if (d.isDisposed()) { @@ -54,9 +54,9 @@ protected void subscribeActual(final SingleObserver<? super T> s) { } else { Throwable ex = error; if (ex != null) { - s.onError(ex); + observer.onError(ex); } else { - s.onSuccess(value); + observer.onSuccess(value); } return; } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleContains.java b/src/main/java/io/reactivex/internal/operators/single/SingleContains.java index b57d8eefbd..c8fb355f48 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleContains.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleContains.java @@ -33,22 +33,22 @@ public SingleContains(SingleSource<T> source, Object value, BiPredicate<Object, } @Override - protected void subscribeActual(final SingleObserver<? super Boolean> s) { + protected void subscribeActual(final SingleObserver<? super Boolean> observer) { - source.subscribe(new Single(s)); + source.subscribe(new ContainsSingleObserver(observer)); } - final class Single implements SingleObserver<T> { + final class ContainsSingleObserver implements SingleObserver<T> { - private final SingleObserver<? super Boolean> s; + private final SingleObserver<? super Boolean> downstream; - Single(SingleObserver<? super Boolean> s) { - this.s = s; + ContainsSingleObserver(SingleObserver<? super Boolean> observer) { + this.downstream = observer; } @Override public void onSubscribe(Disposable d) { - s.onSubscribe(d); + downstream.onSubscribe(d); } @Override @@ -59,15 +59,15 @@ public void onSuccess(T v) { b = comparer.test(v, value); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.onError(ex); + downstream.onError(ex); return; } - s.onSuccess(b); + downstream.onSuccess(b); } @Override public void onError(Throwable e) { - s.onError(e); + downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java b/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java index 8bb129bda2..fd52840f89 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java @@ -31,9 +31,9 @@ public SingleCreate(SingleOnSubscribe<T> source) { } @Override - protected void subscribeActual(SingleObserver<? super T> s) { - Emitter<T> parent = new Emitter<T>(s); - s.onSubscribe(parent); + protected void subscribeActual(SingleObserver<? super T> observer) { + Emitter<T> parent = new Emitter<T>(observer); + observer.onSubscribe(parent); try { source.subscribe(parent); diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDefer.java b/src/main/java/io/reactivex/internal/operators/single/SingleDefer.java index e3ffe8c0ce..0f7a66dc38 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDefer.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDefer.java @@ -29,18 +29,18 @@ public SingleDefer(Callable<? extends SingleSource<? extends T>> singleSupplier) } @Override - protected void subscribeActual(SingleObserver<? super T> s) { + protected void subscribeActual(SingleObserver<? super T> observer) { SingleSource<? extends T> next; try { next = ObjectHelper.requireNonNull(singleSupplier.call(), "The singleSupplier returned a null SingleSource"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - EmptyDisposable.error(e, s); + EmptyDisposable.error(e, observer); return; } - next.subscribe(s); + next.subscribe(observer); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelay.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelay.java index c72ca988f6..3ea0104a50 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelay.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelay.java @@ -36,20 +36,20 @@ public SingleDelay(SingleSource<? extends T> source, long time, TimeUnit unit, S } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { + protected void subscribeActual(final SingleObserver<? super T> observer) { final SequentialDisposable sd = new SequentialDisposable(); - s.onSubscribe(sd); - source.subscribe(new Delay(sd, s)); + observer.onSubscribe(sd); + source.subscribe(new Delay(sd, observer)); } final class Delay implements SingleObserver<T> { private final SequentialDisposable sd; - final SingleObserver<? super T> s; + final SingleObserver<? super T> downstream; - Delay(SequentialDisposable sd, SingleObserver<? super T> s) { + Delay(SequentialDisposable sd, SingleObserver<? super T> observer) { this.sd = sd; - this.s = s; + this.downstream = observer; } @Override @@ -76,7 +76,7 @@ final class OnSuccess implements Runnable { @Override public void run() { - s.onSuccess(value); + downstream.onSuccess(value); } } @@ -89,7 +89,7 @@ final class OnError implements Runnable { @Override public void run() { - s.onError(e); + downstream.onError(e); } } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java index 9f4845f51c..4307f4197c 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java @@ -32,8 +32,8 @@ public SingleDelayWithCompletable(SingleSource<T> source, CompletableSource othe } @Override - protected void subscribeActual(SingleObserver<? super T> subscriber) { - other.subscribe(new OtherObserver<T>(subscriber, source)); + protected void subscribeActual(SingleObserver<? super T> observer) { + other.subscribe(new OtherObserver<T>(observer, source)); } static final class OtherObserver<T> diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java index 2e1e8fcbfd..d9ec740604 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java @@ -33,8 +33,8 @@ public SingleDelayWithObservable(SingleSource<T> source, ObservableSource<U> oth } @Override - protected void subscribeActual(SingleObserver<? super T> subscriber) { - other.subscribe(new OtherSubscriber<T, U>(subscriber, source)); + protected void subscribeActual(SingleObserver<? super T> observer) { + other.subscribe(new OtherSubscriber<T, U>(observer, source)); } static final class OtherSubscriber<T, U> diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java index 88bd1f8085..0928bab13d 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java @@ -36,8 +36,8 @@ public SingleDelayWithPublisher(SingleSource<T> source, Publisher<U> other) { } @Override - protected void subscribeActual(SingleObserver<? super T> subscriber) { - other.subscribe(new OtherSubscriber<T, U>(subscriber, source)); + protected void subscribeActual(SingleObserver<? super T> observer) { + other.subscribe(new OtherSubscriber<T, U>(observer, source)); } static final class OtherSubscriber<T, U> diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java index b42f678878..3adc4f9333 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java @@ -32,8 +32,8 @@ public SingleDelayWithSingle(SingleSource<T> source, SingleSource<U> other) { } @Override - protected void subscribeActual(SingleObserver<? super T> subscriber) { - other.subscribe(new OtherObserver<T, U>(subscriber, source)); + protected void subscribeActual(SingleObserver<? super T> observer) { + other.subscribe(new OtherObserver<T, U>(observer, source)); } static final class OtherObserver<T, U> diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java index 570def7896..bf2e557c36 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java @@ -38,8 +38,8 @@ public SingleDoAfterSuccess(SingleSource<T> source, Consumer<? super T> onAfterS } @Override - protected void subscribeActual(SingleObserver<? super T> s) { - source.subscribe(new DoAfterObserver<T>(s, onAfterSuccess)); + protected void subscribeActual(SingleObserver<? super T> observer) { + source.subscribe(new DoAfterObserver<T>(observer, onAfterSuccess)); } static final class DoAfterObserver<T> implements SingleObserver<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java index f9d17de184..269902cdc7 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java @@ -40,8 +40,8 @@ public SingleDoAfterTerminate(SingleSource<T> source, Action onAfterTerminate) { } @Override - protected void subscribeActual(SingleObserver<? super T> s) { - source.subscribe(new DoAfterTerminateObserver<T>(s, onAfterTerminate)); + protected void subscribeActual(SingleObserver<? super T> observer) { + source.subscribe(new DoAfterTerminateObserver<T>(observer, onAfterTerminate)); } static final class DoAfterTerminateObserver<T> implements SingleObserver<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java index f575e25b7e..f7e6cc3fee 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java @@ -40,8 +40,8 @@ public SingleDoFinally(SingleSource<T> source, Action onFinally) { } @Override - protected void subscribeActual(SingleObserver<? super T> s) { - source.subscribe(new DoFinallyObserver<T>(s, onFinally)); + protected void subscribeActual(SingleObserver<? super T> observer) { + source.subscribe(new DoFinallyObserver<T>(observer, onFinally)); } static final class DoFinallyObserver<T> extends AtomicInteger implements SingleObserver<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnDispose.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnDispose.java index 0f31f2abc2..8515d99887 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnDispose.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnDispose.java @@ -33,9 +33,9 @@ public SingleDoOnDispose(SingleSource<T> source, Action onDispose) { } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { + protected void subscribeActual(final SingleObserver<? super T> observer) { - source.subscribe(new DoOnDisposeObserver<T>(s, onDispose)); + source.subscribe(new DoOnDisposeObserver<T>(observer, onDispose)); } static final class DoOnDisposeObserver<T> diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnError.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnError.java index bd7bcd0d68..c20eb7fc41 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnError.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnError.java @@ -30,26 +30,26 @@ public SingleDoOnError(SingleSource<T> source, Consumer<? super Throwable> onErr } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { + protected void subscribeActual(final SingleObserver<? super T> observer) { - source.subscribe(new DoOnError(s)); + source.subscribe(new DoOnError(observer)); } final class DoOnError implements SingleObserver<T> { - private final SingleObserver<? super T> s; + private final SingleObserver<? super T> downstream; - DoOnError(SingleObserver<? super T> s) { - this.s = s; + DoOnError(SingleObserver<? super T> observer) { + this.downstream = observer; } @Override public void onSubscribe(Disposable d) { - s.onSubscribe(d); + downstream.onSubscribe(d); } @Override public void onSuccess(T value) { - s.onSuccess(value); + downstream.onSuccess(value); } @Override @@ -60,7 +60,7 @@ public void onError(Throwable e) { Exceptions.throwIfFatal(ex); e = new CompositeException(e, ex); } - s.onError(e); + downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnEvent.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnEvent.java index c262b51ff6..e057642f18 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnEvent.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnEvent.java @@ -32,21 +32,21 @@ public SingleDoOnEvent(SingleSource<T> source, BiConsumer<? super T, ? super Thr } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { + protected void subscribeActual(final SingleObserver<? super T> observer) { - source.subscribe(new DoOnEvent(s)); + source.subscribe(new DoOnEvent(observer)); } final class DoOnEvent implements SingleObserver<T> { - private final SingleObserver<? super T> s; + private final SingleObserver<? super T> downstream; - DoOnEvent(SingleObserver<? super T> s) { - this.s = s; + DoOnEvent(SingleObserver<? super T> observer) { + this.downstream = observer; } @Override public void onSubscribe(Disposable d) { - s.onSubscribe(d); + downstream.onSubscribe(d); } @Override @@ -55,11 +55,11 @@ public void onSuccess(T value) { onEvent.accept(value, null); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.onError(ex); + downstream.onError(ex); return; } - s.onSuccess(value); + downstream.onSuccess(value); } @Override @@ -70,7 +70,7 @@ public void onError(Throwable e) { Exceptions.throwIfFatal(ex); e = new CompositeException(e, ex); } - s.onError(e); + downstream.onError(e); } } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSubscribe.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSubscribe.java index e421a05492..c46c2d819b 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSubscribe.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSubscribe.java @@ -37,8 +37,8 @@ public SingleDoOnSubscribe(SingleSource<T> source, Consumer<? super Disposable> } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { - source.subscribe(new DoOnSubscribeSingleObserver<T>(s, onSubscribe)); + protected void subscribeActual(final SingleObserver<? super T> observer) { + source.subscribe(new DoOnSubscribeSingleObserver<T>(observer, onSubscribe)); } static final class DoOnSubscribeSingleObserver<T> implements SingleObserver<T> { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSuccess.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSuccess.java index 34ee281777..f915c984cd 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSuccess.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSuccess.java @@ -30,21 +30,22 @@ public SingleDoOnSuccess(SingleSource<T> source, Consumer<? super T> onSuccess) } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { + protected void subscribeActual(final SingleObserver<? super T> observer) { - source.subscribe(new DoOnSuccess(s)); + source.subscribe(new DoOnSuccess(observer)); } final class DoOnSuccess implements SingleObserver<T> { - private final SingleObserver<? super T> s; - DoOnSuccess(SingleObserver<? super T> s) { - this.s = s; + final SingleObserver<? super T> downstream; + + DoOnSuccess(SingleObserver<? super T> observer) { + this.downstream = observer; } @Override public void onSubscribe(Disposable d) { - s.onSubscribe(d); + downstream.onSubscribe(d); } @Override @@ -53,15 +54,15 @@ public void onSuccess(T value) { onSuccess.accept(value); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.onError(ex); + downstream.onError(ex); return; } - s.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - s.onError(e); + downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleEquals.java b/src/main/java/io/reactivex/internal/operators/single/SingleEquals.java index 0ed22f4c1b..83c40b1416 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleEquals.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleEquals.java @@ -31,30 +31,30 @@ public SingleEquals(SingleSource<? extends T> first, SingleSource<? extends T> s } @Override - protected void subscribeActual(final SingleObserver<? super Boolean> s) { + protected void subscribeActual(final SingleObserver<? super Boolean> observer) { final AtomicInteger count = new AtomicInteger(); final Object[] values = { null, null }; final CompositeDisposable set = new CompositeDisposable(); - s.onSubscribe(set); + observer.onSubscribe(set); - first.subscribe(new InnerObserver<T>(0, set, values, s, count)); - second.subscribe(new InnerObserver<T>(1, set, values, s, count)); + first.subscribe(new InnerObserver<T>(0, set, values, observer, count)); + second.subscribe(new InnerObserver<T>(1, set, values, observer, count)); } static class InnerObserver<T> implements SingleObserver<T> { final int index; final CompositeDisposable set; final Object[] values; - final SingleObserver<? super Boolean> s; + final SingleObserver<? super Boolean> downstream; final AtomicInteger count; - InnerObserver(int index, CompositeDisposable set, Object[] values, SingleObserver<? super Boolean> s, AtomicInteger count) { + InnerObserver(int index, CompositeDisposable set, Object[] values, SingleObserver<? super Boolean> observer, AtomicInteger count) { this.index = index; this.set = set; this.values = values; - this.s = s; + this.downstream = observer; this.count = count; } @Override @@ -67,7 +67,7 @@ public void onSuccess(T value) { values[index] = value; if (count.incrementAndGet() == 2) { - s.onSuccess(ObjectHelper.equals(values[0], values[1])); + downstream.onSuccess(ObjectHelper.equals(values[0], values[1])); } } @@ -81,7 +81,7 @@ public void onError(Throwable e) { } if (count.compareAndSet(state, 2)) { set.dispose(); - s.onError(e); + downstream.onError(e); return; } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleError.java b/src/main/java/io/reactivex/internal/operators/single/SingleError.java index 689070291f..6a6e1aef5a 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleError.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleError.java @@ -29,7 +29,7 @@ public SingleError(Callable<? extends Throwable> errorSupplier) { } @Override - protected void subscribeActual(SingleObserver<? super T> s) { + protected void subscribeActual(SingleObserver<? super T> observer) { Throwable error; try { @@ -39,7 +39,7 @@ protected void subscribeActual(SingleObserver<? super T> s) { error = e; } - EmptyDisposable.error(error, s); + EmptyDisposable.error(error, observer); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapCompletable.java index 453d8dfeb7..986a831f94 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapCompletable.java @@ -38,9 +38,9 @@ public SingleFlatMapCompletable(SingleSource<T> source, Function<? super T, ? ex } @Override - protected void subscribeActual(CompletableObserver s) { - FlatMapCompletableObserver<T> parent = new FlatMapCompletableObserver<T>(s, mapper); - s.onSubscribe(parent); + protected void subscribeActual(CompletableObserver observer) { + FlatMapCompletableObserver<T> parent = new FlatMapCompletableObserver<T>(observer, mapper); + observer.onSubscribe(parent); source.subscribe(parent); } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java index a4d75e5765..541e5063ed 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java @@ -43,8 +43,8 @@ public SingleFlatMapIterableObservable(SingleSource<T> source, } @Override - protected void subscribeActual(Observer<? super R> s) { - source.subscribe(new FlatMapIterableObserver<T, R>(s, mapper)); + protected void subscribeActual(Observer<? super R> observer) { + source.subscribe(new FlatMapIterableObserver<T, R>(observer, mapper)); } static final class FlatMapIterableObserver<T, R> diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFromPublisher.java b/src/main/java/io/reactivex/internal/operators/single/SingleFromPublisher.java index ecc69b7e92..9543c494c9 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFromPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFromPublisher.java @@ -31,8 +31,8 @@ public SingleFromPublisher(Publisher<? extends T> publisher) { } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { - publisher.subscribe(new ToSingleObserver<T>(s)); + protected void subscribeActual(final SingleObserver<? super T> observer) { + publisher.subscribe(new ToSingleObserver<T>(observer)); } static final class ToSingleObserver<T> implements FlowableSubscriber<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleHide.java b/src/main/java/io/reactivex/internal/operators/single/SingleHide.java index 8415eb76b7..27cf6205b2 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleHide.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleHide.java @@ -26,8 +26,8 @@ public SingleHide(SingleSource<? extends T> source) { } @Override - protected void subscribeActual(SingleObserver<? super T> subscriber) { - source.subscribe(new HideSingleObserver<T>(subscriber)); + protected void subscribeActual(SingleObserver<? super T> observer) { + source.subscribe(new HideSingleObserver<T>(observer)); } static final class HideSingleObserver<T> implements SingleObserver<T>, Disposable { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleJust.java b/src/main/java/io/reactivex/internal/operators/single/SingleJust.java index 63a0c7fdaa..5e3dfdcd61 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleJust.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleJust.java @@ -25,9 +25,9 @@ public SingleJust(T value) { } @Override - protected void subscribeActual(SingleObserver<? super T> s) { - s.onSubscribe(Disposables.disposed()); - s.onSuccess(value); + protected void subscribeActual(SingleObserver<? super T> observer) { + observer.onSubscribe(Disposables.disposed()); + observer.onSuccess(value); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleLift.java b/src/main/java/io/reactivex/internal/operators/single/SingleLift.java index e618020f44..3d55453b8e 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleLift.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleLift.java @@ -30,14 +30,14 @@ public SingleLift(SingleSource<T> source, SingleOperator<? extends R, ? super T> } @Override - protected void subscribeActual(SingleObserver<? super R> s) { + protected void subscribeActual(SingleObserver<? super R> observer) { SingleObserver<? super T> sr; try { - sr = ObjectHelper.requireNonNull(onLift.apply(s), "The onLift returned a null SingleObserver"); + sr = ObjectHelper.requireNonNull(onLift.apply(observer), "The onLift returned a null SingleObserver"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - EmptyDisposable.error(ex, s); + EmptyDisposable.error(ex, observer); return; } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleNever.java b/src/main/java/io/reactivex/internal/operators/single/SingleNever.java index 0c01773724..a3c46ebc99 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleNever.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleNever.java @@ -23,8 +23,8 @@ private SingleNever() { } @Override - protected void subscribeActual(SingleObserver<? super Object> s) { - s.onSubscribe(EmptyDisposable.NEVER); + protected void subscribeActual(SingleObserver<? super Object> observer) { + observer.onSubscribe(EmptyDisposable.NEVER); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleObserveOn.java b/src/main/java/io/reactivex/internal/operators/single/SingleObserveOn.java index 6d9f3f3331..494fa2c896 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleObserveOn.java @@ -31,8 +31,8 @@ public SingleObserveOn(SingleSource<T> source, Scheduler scheduler) { } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { - source.subscribe(new ObserveOnSingleObserver<T>(s, scheduler)); + protected void subscribeActual(final SingleObserver<? super T> observer) { + source.subscribe(new ObserveOnSingleObserver<T>(observer, scheduler)); } static final class ObserveOnSingleObserver<T> extends AtomicReference<Disposable> diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleOnErrorReturn.java b/src/main/java/io/reactivex/internal/operators/single/SingleOnErrorReturn.java index d7f9c4c715..3f1b0588cf 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleOnErrorReturn.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleOnErrorReturn.java @@ -35,9 +35,9 @@ public SingleOnErrorReturn(SingleSource<? extends T> source, @Override - protected void subscribeActual(final SingleObserver<? super T> s) { + protected void subscribeActual(final SingleObserver<? super T> observer) { - source.subscribe(new OnErrorReturn(s)); + source.subscribe(new OnErrorReturn(observer)); } final class OnErrorReturn implements SingleObserver<T> { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleResumeNext.java b/src/main/java/io/reactivex/internal/operators/single/SingleResumeNext.java index 51ab16aca1..42133c05f4 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleResumeNext.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleResumeNext.java @@ -35,8 +35,8 @@ public SingleResumeNext(SingleSource<? extends T> source, } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { - source.subscribe(new ResumeMainSingleObserver<T>(s, nextFunction)); + protected void subscribeActual(final SingleObserver<? super T> observer) { + source.subscribe(new ResumeMainSingleObserver<T>(observer, nextFunction)); } static final class ResumeMainSingleObserver<T> extends AtomicReference<Disposable> diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleSubscribeOn.java b/src/main/java/io/reactivex/internal/operators/single/SingleSubscribeOn.java index 8401704a0a..68299fef2c 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleSubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleSubscribeOn.java @@ -30,9 +30,9 @@ public SingleSubscribeOn(SingleSource<? extends T> source, Scheduler scheduler) } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { - final SubscribeOnObserver<T> parent = new SubscribeOnObserver<T>(s, source); - s.onSubscribe(parent); + protected void subscribeActual(final SingleObserver<? super T> observer) { + final SubscribeOnObserver<T> parent = new SubscribeOnObserver<T>(observer, source); + observer.onSubscribe(parent); Disposable f = scheduler.scheduleDirect(parent); diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java b/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java index 4644f1ce10..575d47732a 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java @@ -43,10 +43,10 @@ public SingleTimeout(SingleSource<T> source, long timeout, TimeUnit unit, Schedu } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { + protected void subscribeActual(final SingleObserver<? super T> observer) { - TimeoutMainObserver<T> parent = new TimeoutMainObserver<T>(s, other); - s.onSubscribe(parent); + TimeoutMainObserver<T> parent = new TimeoutMainObserver<T>(observer, other); + observer.onSubscribe(parent); DisposableHelper.replace(parent.task, scheduler.scheduleDirect(parent, timeout, unit)); diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleTimer.java b/src/main/java/io/reactivex/internal/operators/single/SingleTimer.java index 17267aacd2..638a8894c5 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleTimer.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleTimer.java @@ -36,9 +36,9 @@ public SingleTimer(long delay, TimeUnit unit, Scheduler scheduler) { } @Override - protected void subscribeActual(final SingleObserver<? super Long> s) { - TimerDisposable parent = new TimerDisposable(s); - s.onSubscribe(parent); + protected void subscribeActual(final SingleObserver<? super Long> observer) { + TimerDisposable parent = new TimerDisposable(observer); + observer.onSubscribe(parent); parent.setFuture(scheduler.scheduleDirect(parent, delay, unit)); } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java index 332f910476..56d78e0774 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java @@ -31,8 +31,8 @@ public SingleToObservable(SingleSource<? extends T> source) { } @Override - public void subscribeActual(final Observer<? super T> s) { - source.subscribe(create(s)); + public void subscribeActual(final Observer<? super T> observer) { + source.subscribe(create(observer)); } /** diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleUsing.java b/src/main/java/io/reactivex/internal/operators/single/SingleUsing.java index 8ffec7773c..e2f93a9110 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleUsing.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleUsing.java @@ -42,7 +42,7 @@ public SingleUsing(Callable<U> resourceSupplier, } @Override - protected void subscribeActual(final SingleObserver<? super T> s) { + protected void subscribeActual(final SingleObserver<? super T> observer) { final U resource; // NOPMD @@ -50,7 +50,7 @@ protected void subscribeActual(final SingleObserver<? super T> s) { resource = resourceSupplier.call(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - EmptyDisposable.error(ex, s); + EmptyDisposable.error(ex, observer); return; } @@ -69,7 +69,7 @@ protected void subscribeActual(final SingleObserver<? super T> s) { ex = new CompositeException(ex, exc); } } - EmptyDisposable.error(ex, s); + EmptyDisposable.error(ex, observer); if (!eager) { try { disposer.accept(resource); @@ -81,7 +81,7 @@ protected void subscribeActual(final SingleObserver<? super T> s) { return; } - source.subscribe(new UsingSingleObserver<T, U>(s, resource, eager, disposer)); + source.subscribe(new UsingSingleObserver<T, U>(observer, resource, eager, disposer)); } static final class UsingSingleObserver<T, U> extends diff --git a/src/main/java/io/reactivex/internal/util/NotificationLite.java b/src/main/java/io/reactivex/internal/util/NotificationLite.java index bebc0c342d..68aeb8492e 100644 --- a/src/main/java/io/reactivex/internal/util/NotificationLite.java +++ b/src/main/java/io/reactivex/internal/util/NotificationLite.java @@ -230,20 +230,20 @@ public static <T> boolean accept(Object o, Subscriber<? super T> s) { * <p>Does not check for a subscription notification. * @param <T> the expected value type when unwrapped * @param o the notification object - * @param s the Observer to call methods on + * @param observer the Observer to call methods on * @return true if the notification was a terminal event (i.e., complete or error) */ @SuppressWarnings("unchecked") - public static <T> boolean accept(Object o, Observer<? super T> s) { + public static <T> boolean accept(Object o, Observer<? super T> observer) { if (o == COMPLETE) { - s.onComplete(); + observer.onComplete(); return true; } else if (o instanceof ErrorNotification) { - s.onError(((ErrorNotification)o).e); + observer.onError(((ErrorNotification)o).e); return true; } - s.onNext((T)o); + observer.onNext((T)o); return false; } @@ -277,25 +277,25 @@ public static <T> boolean acceptFull(Object o, Subscriber<? super T> s) { * Calls the appropriate Observer method based on the type of the notification. * @param <T> the expected value type when unwrapped * @param o the notification object - * @param s the subscriber to call methods on + * @param observer the subscriber to call methods on * @return true if the notification was a terminal event (i.e., complete or error) * @see #accept(Object, Observer) */ @SuppressWarnings("unchecked") - public static <T> boolean acceptFull(Object o, Observer<? super T> s) { + public static <T> boolean acceptFull(Object o, Observer<? super T> observer) { if (o == COMPLETE) { - s.onComplete(); + observer.onComplete(); return true; } else if (o instanceof ErrorNotification) { - s.onError(((ErrorNotification)o).e); + observer.onError(((ErrorNotification)o).e); return true; } else if (o instanceof DisposableNotification) { - s.onSubscribe(((DisposableNotification)o).d); + observer.onSubscribe(((DisposableNotification)o).d); return false; } - s.onNext((T)o); + observer.onNext((T)o); return false; } diff --git a/src/main/java/io/reactivex/internal/util/QueueDrainHelper.java b/src/main/java/io/reactivex/internal/util/QueueDrainHelper.java index 25126b3327..ade0d5fa82 100644 --- a/src/main/java/io/reactivex/internal/util/QueueDrainHelper.java +++ b/src/main/java/io/reactivex/internal/util/QueueDrainHelper.java @@ -158,7 +158,7 @@ public static <T, U> void drainLoop(SimplePlainQueue<T> q, Observer<? super U> a } public static <T, U> boolean checkTerminated(boolean d, boolean empty, - Observer<?> s, boolean delayError, SimpleQueue<?> q, Disposable disposable, ObservableQueueDrain<T, U> qd) { + Observer<?> observer, boolean delayError, SimpleQueue<?> q, Disposable disposable, ObservableQueueDrain<T, U> qd) { if (qd.cancelled()) { q.clear(); disposable.dispose(); @@ -173,9 +173,9 @@ public static <T, U> boolean checkTerminated(boolean d, boolean empty, } Throwable err = qd.error(); if (err != null) { - s.onError(err); + observer.onError(err); } else { - s.onComplete(); + observer.onComplete(); } return true; } @@ -186,14 +186,14 @@ public static <T, U> boolean checkTerminated(boolean d, boolean empty, if (disposable != null) { disposable.dispose(); } - s.onError(err); + observer.onError(err); return true; } else if (empty) { if (disposable != null) { disposable.dispose(); } - s.onComplete(); + observer.onComplete(); return true; } } diff --git a/src/main/java/io/reactivex/plugins/RxJavaPlugins.java b/src/main/java/io/reactivex/plugins/RxJavaPlugins.java index 4da3a30122..1d3a810cc5 100644 --- a/src/main/java/io/reactivex/plugins/RxJavaPlugins.java +++ b/src/main/java/io/reactivex/plugins/RxJavaPlugins.java @@ -979,17 +979,17 @@ public static CompletableObserver onSubscribe(@NonNull Completable source, @NonN * Calls the associated hook function. * @param <T> the value type * @param source the hook's input value - * @param subscriber the subscriber + * @param observer the subscriber * @return the value returned by the hook */ @SuppressWarnings({ "rawtypes", "unchecked" }) @NonNull - public static <T> MaybeObserver<? super T> onSubscribe(@NonNull Maybe<T> source, @NonNull MaybeObserver<? super T> subscriber) { + public static <T> MaybeObserver<? super T> onSubscribe(@NonNull Maybe<T> source, @NonNull MaybeObserver<? super T> observer) { BiFunction<? super Maybe, ? super MaybeObserver, ? extends MaybeObserver> f = onMaybeSubscribe; if (f != null) { - return apply(f, source, subscriber); + return apply(f, source, observer); } - return subscriber; + return observer; } /** diff --git a/src/main/java/io/reactivex/subjects/AsyncSubject.java b/src/main/java/io/reactivex/subjects/AsyncSubject.java index 2a99ab03ad..335b183e1a 100644 --- a/src/main/java/io/reactivex/subjects/AsyncSubject.java +++ b/src/main/java/io/reactivex/subjects/AsyncSubject.java @@ -215,9 +215,9 @@ public Throwable getThrowable() { } @Override - protected void subscribeActual(Observer<? super T> s) { - AsyncDisposable<T> as = new AsyncDisposable<T>(s, this); - s.onSubscribe(as); + protected void subscribeActual(Observer<? super T> observer) { + AsyncDisposable<T> as = new AsyncDisposable<T>(observer, this); + observer.onSubscribe(as); if (add(as)) { if (as.isDisposed()) { remove(as); @@ -225,7 +225,7 @@ protected void subscribeActual(Observer<? super T> s) { } else { Throwable ex = error; if (ex != null) { - s.onError(ex); + observer.onError(ex); } else { T v = value; if (v != null) { diff --git a/src/test/java/io/reactivex/CheckLocalVariablesInTests.java b/src/test/java/io/reactivex/CheckLocalVariablesInTests.java index 9139738b9f..864dfe4362 100644 --- a/src/test/java/io/reactivex/CheckLocalVariablesInTests.java +++ b/src/test/java/io/reactivex/CheckLocalVariablesInTests.java @@ -188,4 +188,89 @@ public void completableSourceAsMs() throws Exception { public void observableAsC() throws Exception { findPattern("Observable<.*>\\s+c\\b"); } + + @Test + public void subscriberAsObserver() throws Exception { + findPattern("Subscriber<.*>\\s+observer[0-9]?\\b"); + } + + @Test + public void subscriberAsO() throws Exception { + findPattern("Subscriber<.*>\\s+o[0-9]?\\b"); + } + + @Test + public void singleAsObservable() throws Exception { + findPattern("Single<.*>\\s+observable\\b"); + } + + @Test + public void singleAsFlowable() throws Exception { + findPattern("Single<.*>\\s+flowable\\b"); + } + + @Test + public void observerAsSubscriber() throws Exception { + findPattern("Observer<.*>\\s+subscriber[0-9]?\\b"); + } + + @Test + public void observerAsS() throws Exception { + findPattern("Observer<.*>\\s+s[0-9]?\\b"); + } + + @Test + public void observerNoArgAsSubscriber() throws Exception { + findPattern("Observer\\s+subscriber[0-9]?\\b"); + } + + @Test + public void observerNoArgAsS() throws Exception { + findPattern("Observer\\s+s[0-9]?\\b"); + } + + @Test + public void flowableAsObservable() throws Exception { + findPattern("Flowable<.*>\\s+observable[0-9]?\\b"); + } + + @Test + public void flowableAsO() throws Exception { + findPattern("Flowable<.*>\\s+o[0-9]?\\b"); + } + + @Test + public void flowableNoArgAsO() throws Exception { + findPattern("Flowable\\s+o[0-9]?\\b"); + } + + @Test + public void flowableNoArgAsObservable() throws Exception { + findPattern("Flowable\\s+observable[0-9]?\\b"); + } + + @Test + public void processorAsSubject() throws Exception { + findPattern("Processor<.*>\\s+subject(0-9)?\\b"); + } + + @Test + public void maybeAsObservable() throws Exception { + findPattern("Maybe<.*>\\s+observable\\b"); + } + + @Test + public void maybeAsFlowable() throws Exception { + findPattern("Maybe<.*>\\s+flowable\\b"); + } + + @Test + public void completableAsObservable() throws Exception { + findPattern("Completable\\s+observable\\b"); + } + + @Test + public void completableAsFlowable() throws Exception { + findPattern("Completable\\s+flowable\\b"); + } } diff --git a/src/test/java/io/reactivex/ParamValidationCheckerTest.java b/src/test/java/io/reactivex/ParamValidationCheckerTest.java index 6a3a430c12..45c6dcafbf 100644 --- a/src/test/java/io/reactivex/ParamValidationCheckerTest.java +++ b/src/test/java/io/reactivex/ParamValidationCheckerTest.java @@ -1140,7 +1140,7 @@ public String toString() { static final class NeverObservable extends Observable<Object> { @Override - public void subscribeActual(Observer<? super Object> s) { + public void subscribeActual(Observer<? super Object> observer) { // not invoked, the class is a placeholder default value } @@ -1153,7 +1153,7 @@ public String toString() { static final class NeverSingle extends Single<Object> { @Override - public void subscribeActual(SingleObserver<? super Object> s) { + public void subscribeActual(SingleObserver<? super Object> observer) { // not invoked, the class is a placeholder default value } @@ -1166,7 +1166,7 @@ public String toString() { static final class NeverMaybe extends Maybe<Object> { @Override - public void subscribeActual(MaybeObserver<? super Object> s) { + public void subscribeActual(MaybeObserver<? super Object> observer) { // not invoked, the class is a placeholder default value } @@ -1178,7 +1178,7 @@ public String toString() { static final class NeverCompletable extends Completable { @Override - public void subscribeActual(CompletableObserver s) { + public void subscribeActual(CompletableObserver observer) { // not invoked, the class is a placeholder default value } diff --git a/src/test/java/io/reactivex/TestHelper.java b/src/test/java/io/reactivex/TestHelper.java index 6ac1e5cc75..cba835fcbd 100644 --- a/src/test/java/io/reactivex/TestHelper.java +++ b/src/test/java/io/reactivex/TestHelper.java @@ -556,18 +556,18 @@ public static void doubleOnSubscribe(Subscriber<?> subscriber) { /** * Calls onSubscribe twice and checks if it doesn't affect the first Disposable while * reporting it to plugin error handler. - * @param subscriber the target + * @param observer the target */ - public static void doubleOnSubscribe(Observer<?> subscriber) { + public static void doubleOnSubscribe(Observer<?> observer) { List<Throwable> errors = trackPluginErrors(); try { Disposable d1 = Disposables.empty(); - subscriber.onSubscribe(d1); + observer.onSubscribe(d1); Disposable d2 = Disposables.empty(); - subscriber.onSubscribe(d2); + observer.onSubscribe(d2); assertFalse(d1.isDisposed()); @@ -582,18 +582,18 @@ public static void doubleOnSubscribe(Observer<?> subscriber) { /** * Calls onSubscribe twice and checks if it doesn't affect the first Disposable while * reporting it to plugin error handler. - * @param subscriber the target + * @param observer the target */ - public static void doubleOnSubscribe(SingleObserver<?> subscriber) { + public static void doubleOnSubscribe(SingleObserver<?> observer) { List<Throwable> errors = trackPluginErrors(); try { Disposable d1 = Disposables.empty(); - subscriber.onSubscribe(d1); + observer.onSubscribe(d1); Disposable d2 = Disposables.empty(); - subscriber.onSubscribe(d2); + observer.onSubscribe(d2); assertFalse(d1.isDisposed()); @@ -608,18 +608,18 @@ public static void doubleOnSubscribe(SingleObserver<?> subscriber) { /** * Calls onSubscribe twice and checks if it doesn't affect the first Disposable while * reporting it to plugin error handler. - * @param subscriber the target + * @param observer the target */ - public static void doubleOnSubscribe(CompletableObserver subscriber) { + public static void doubleOnSubscribe(CompletableObserver observer) { List<Throwable> errors = trackPluginErrors(); try { Disposable d1 = Disposables.empty(); - subscriber.onSubscribe(d1); + observer.onSubscribe(d1); Disposable d2 = Disposables.empty(); - subscriber.onSubscribe(d2); + observer.onSubscribe(d2); assertFalse(d1.isDisposed()); @@ -634,18 +634,18 @@ public static void doubleOnSubscribe(CompletableObserver subscriber) { /** * Calls onSubscribe twice and checks if it doesn't affect the first Disposable while * reporting it to plugin error handler. - * @param subscriber the target + * @param observer the target */ - public static void doubleOnSubscribe(MaybeObserver<?> subscriber) { + public static void doubleOnSubscribe(MaybeObserver<?> observer) { List<Throwable> errors = trackPluginErrors(); try { Disposable d1 = Disposables.empty(); - subscriber.onSubscribe(d1); + observer.onSubscribe(d1); Disposable d2 = Disposables.empty(); - subscriber.onSubscribe(d2); + observer.onSubscribe(d2); assertFalse(d1.isDisposed()); @@ -1692,15 +1692,15 @@ public static <T, R> void checkDoubleOnSubscribeFlowableToObservable(Function<Fl Flowable<T> source = new Flowable<T>() { @Override - protected void subscribeActual(Subscriber<? super T> observer) { + protected void subscribeActual(Subscriber<? super T> subscriber) { try { BooleanSubscription d1 = new BooleanSubscription(); - observer.onSubscribe(d1); + subscriber.onSubscribe(d1); BooleanSubscription d2 = new BooleanSubscription(); - observer.onSubscribe(d2); + subscriber.onSubscribe(d2); b[0] = d1.isCancelled(); b[1] = d2.isCancelled(); @@ -1746,15 +1746,15 @@ public static <T, R> void checkDoubleOnSubscribeFlowableToSingle(Function<Flowab Flowable<T> source = new Flowable<T>() { @Override - protected void subscribeActual(Subscriber<? super T> observer) { + protected void subscribeActual(Subscriber<? super T> subscriber) { try { BooleanSubscription d1 = new BooleanSubscription(); - observer.onSubscribe(d1); + subscriber.onSubscribe(d1); BooleanSubscription d2 = new BooleanSubscription(); - observer.onSubscribe(d2); + subscriber.onSubscribe(d2); b[0] = d1.isCancelled(); b[1] = d2.isCancelled(); @@ -1800,15 +1800,15 @@ public static <T, R> void checkDoubleOnSubscribeFlowableToMaybe(Function<Flowabl Flowable<T> source = new Flowable<T>() { @Override - protected void subscribeActual(Subscriber<? super T> observer) { + protected void subscribeActual(Subscriber<? super T> subscriber) { try { BooleanSubscription d1 = new BooleanSubscription(); - observer.onSubscribe(d1); + subscriber.onSubscribe(d1); BooleanSubscription d2 = new BooleanSubscription(); - observer.onSubscribe(d2); + subscriber.onSubscribe(d2); b[0] = d1.isCancelled(); b[1] = d2.isCancelled(); @@ -1853,15 +1853,15 @@ public static <T> void checkDoubleOnSubscribeFlowableToCompletable(Function<Flow Flowable<T> source = new Flowable<T>() { @Override - protected void subscribeActual(Subscriber<? super T> observer) { + protected void subscribeActual(Subscriber<? super T> subscriber) { try { BooleanSubscription d1 = new BooleanSubscription(); - observer.onSubscribe(d1); + subscriber.onSubscribe(d1); BooleanSubscription d2 = new BooleanSubscription(); - observer.onSubscribe(d2); + subscriber.onSubscribe(d2); b[0] = d1.isCancelled(); b[1] = d2.isCancelled(); @@ -2669,24 +2669,24 @@ public static <T> void checkBadSourceFlowable(Function<Flowable<T>, Object> mapp try { Flowable<T> bad = new Flowable<T>() { @Override - protected void subscribeActual(Subscriber<? super T> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super T> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); if (goodValue != null) { - observer.onNext(goodValue); + subscriber.onNext(goodValue); } if (error) { - observer.onError(new TestException("error")); + subscriber.onError(new TestException("error")); } else { - observer.onComplete(); + subscriber.onComplete(); } if (badValue != null) { - observer.onNext(badValue); + subscriber.onNext(badValue); } - observer.onError(new TestException("second")); - observer.onComplete(); + subscriber.onError(new TestException("second")); + subscriber.onComplete(); } }; @@ -2879,8 +2879,8 @@ public boolean isDisposed() { public static <T> Flowable<T> rejectFlowableFusion() { return new Flowable<T>() { @Override - protected void subscribeActual(Subscriber<? super T> observer) { - observer.onSubscribe(new QueueSubscription<T>() { + protected void subscribeActual(Subscriber<? super T> subscriber) { + subscriber.onSubscribe(new QueueSubscription<T>() { @Override public int requestFusion(int mode) { @@ -3042,8 +3042,8 @@ public Observable<T> apply(Observable<T> upstream) { } @Override - protected void subscribeActual(Observer<? super T> s) { - source.subscribe(new StripBoundaryObserver<T>(s)); + protected void subscribeActual(Observer<? super T> observer) { + source.subscribe(new StripBoundaryObserver<T>(observer)); } static final class StripBoundaryObserver<T> implements Observer<T>, QueueDisposable<T> { diff --git a/src/test/java/io/reactivex/completable/CompletableTest.java b/src/test/java/io/reactivex/completable/CompletableTest.java index a595837f29..5dcfa1b531 100644 --- a/src/test/java/io/reactivex/completable/CompletableTest.java +++ b/src/test/java/io/reactivex/completable/CompletableTest.java @@ -106,9 +106,9 @@ static final class NormalCompletable extends AtomicInteger { public final Completable completable = Completable.unsafeCreate(new CompletableSource() { @Override - public void subscribe(CompletableObserver s) { + public void subscribe(CompletableObserver observer) { getAndIncrement(); - EmptyDisposable.complete(s); + EmptyDisposable.complete(observer); } }); @@ -131,9 +131,9 @@ static final class ErrorCompletable extends AtomicInteger { public final Completable completable = Completable.unsafeCreate(new CompletableSource() { @Override - public void subscribe(CompletableObserver s) { + public void subscribe(CompletableObserver observer) { getAndIncrement(); - EmptyDisposable.error(new TestException(), s); + EmptyDisposable.error(new TestException(), observer); } }); @@ -379,7 +379,7 @@ public void createNull() { public void createOnSubscribeThrowsNPE() { Completable c = Completable.unsafeCreate(new CompletableSource() { @Override - public void subscribe(CompletableObserver s) { throw new NullPointerException(); } + public void subscribe(CompletableObserver observer) { throw new NullPointerException(); } }); c.blockingAwait(); @@ -387,10 +387,11 @@ public void createOnSubscribeThrowsNPE() { @Test(timeout = 5000) public void createOnSubscribeThrowsRuntimeException() { + List<Throwable> errors = TestHelper.trackPluginErrors(); try { Completable c = Completable.unsafeCreate(new CompletableSource() { @Override - public void subscribe(CompletableObserver s) { + public void subscribe(CompletableObserver observer) { throw new TestException(); } }); @@ -403,6 +404,10 @@ public void subscribe(CompletableObserver s) { ex.printStackTrace(); Assert.fail("Did not wrap the TestException but it returned: " + ex); } + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); } } @@ -1799,27 +1804,34 @@ public void doOnDisposeNull() { @Test(timeout = 5000) public void doOnDisposeThrows() { - Completable c = normal.completable.doOnDispose(new Action() { - @Override - public void run() { throw new TestException(); } - }); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Completable c = normal.completable.doOnDispose(new Action() { + @Override + public void run() { throw new TestException(); } + }); - c.subscribe(new CompletableObserver() { - @Override - public void onSubscribe(Disposable d) { - d.dispose(); - } + c.subscribe(new CompletableObserver() { + @Override + public void onSubscribe(Disposable d) { + d.dispose(); + } - @Override - public void onError(Throwable e) { - // ignored - } + @Override + public void onError(Throwable e) { + // ignored + } - @Override - public void onComplete() { - // ignored - } - }); + @Override + public void onComplete() { + // ignored + } + }); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test(timeout = 5000) @@ -2453,8 +2465,8 @@ public void run() { }).retryWhen(new Function<Flowable<? extends Throwable>, Publisher<Object>>() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override - public Publisher<Object> apply(Flowable<? extends Throwable> o) { - return (Publisher)o; + public Publisher<Object> apply(Flowable<? extends Throwable> f) { + return (Publisher)f; } }); @@ -2589,13 +2601,20 @@ public void accept(Throwable e) { @Test(timeout = 5000) public void subscribeTwoCallbacksOnErrorThrows() { - error.completable.subscribe(new Action() { - @Override - public void run() { } - }, new Consumer<Throwable>() { - @Override - public void accept(Throwable e) { throw new TestException(); } - }); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + error.completable.subscribe(new Action() { + @Override + public void run() { } + }, new Consumer<Throwable>() { + @Override + public void accept(Throwable e) { throw new TestException(); } + }); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test(timeout = 5000) @@ -2636,16 +2655,23 @@ public void run() { @Test(timeout = 5000) public void subscribeActionError() { - final AtomicBoolean run = new AtomicBoolean(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final AtomicBoolean run = new AtomicBoolean(); - error.completable.subscribe(new Action() { - @Override - public void run() { - run.set(true); - } - }); + error.completable.subscribe(new Action() { + @Override + public void run() { + run.set(true); + } + }); - Assert.assertFalse("Completed", run.get()); + Assert.assertFalse("Completed", run.get()); + + TestHelper.assertError(errors, 0, OnErrorNotImplementedException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test(expected = NullPointerException.class) @@ -2701,9 +2727,9 @@ public void subscribeOnNormal() { Completable c = Completable.unsafeCreate(new CompletableSource() { @Override - public void subscribe(CompletableObserver s) { + public void subscribe(CompletableObserver observer) { name.set(Thread.currentThread().getName()); - EmptyDisposable.complete(s); + EmptyDisposable.complete(observer); } }).subscribeOn(Schedulers.computation()); @@ -2718,9 +2744,9 @@ public void subscribeOnError() { Completable c = Completable.unsafeCreate(new CompletableSource() { @Override - public void subscribe(CompletableObserver s) { + public void subscribe(CompletableObserver observer) { name.set(Thread.currentThread().getName()); - EmptyDisposable.error(new TestException(), s); + EmptyDisposable.error(new TestException(), observer); } }).subscribeOn(Schedulers.computation()); @@ -3468,6 +3494,12 @@ private static void expectUncaughtTestException(Action action) { Thread.UncaughtExceptionHandler originalHandler = Thread.getDefaultUncaughtExceptionHandler(); CapturingUncaughtExceptionHandler handler = new CapturingUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(handler); + RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { + @Override + public void accept(Throwable error) throws Exception { + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), error); + } + }); try { action.run(); assertEquals("Should have received exactly 1 exception", 1, handler.count); @@ -3483,6 +3515,7 @@ private static void expectUncaughtTestException(Action action) { throw ExceptionHelper.wrapOrThrow(ex); } finally { Thread.setDefaultUncaughtExceptionHandler(originalHandler); + RxJavaPlugins.setErrorHandler(null); } } @@ -3576,14 +3609,21 @@ public Completable apply(Integer t) { @Test public void subscribeReportsUnsubscribedOnError() { - PublishSubject<String> stringSubject = PublishSubject.create(); - Completable completable = stringSubject.ignoreElements(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + PublishSubject<String> stringSubject = PublishSubject.create(); + Completable completable = stringSubject.ignoreElements(); - Disposable completableSubscription = completable.subscribe(); + Disposable completableSubscription = completable.subscribe(); - stringSubject.onError(new TestException()); + stringSubject.onError(new TestException()); - assertTrue("Not unsubscribed?", completableSubscription.isDisposed()); + assertTrue("Not unsubscribed?", completableSubscription.isDisposed()); + + TestHelper.assertError(errors, 0, OnErrorNotImplementedException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -3627,18 +3667,25 @@ public void run() { @Test public void subscribeActionReportsUnsubscribedOnError() { - PublishSubject<String> stringSubject = PublishSubject.create(); - Completable completable = stringSubject.ignoreElements(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + PublishSubject<String> stringSubject = PublishSubject.create(); + Completable completable = stringSubject.ignoreElements(); - Disposable completableSubscription = completable.subscribe(new Action() { - @Override - public void run() { - } - }); + Disposable completableSubscription = completable.subscribe(new Action() { + @Override + public void run() { + } + }); - stringSubject.onError(new TestException()); + stringSubject.onError(new TestException()); - assertTrue("Not unsubscribed?", completableSubscription.isDisposed()); + assertTrue("Not unsubscribed?", completableSubscription.isDisposed()); + + TestHelper.assertError(errors, 0, OnErrorNotImplementedException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -3715,9 +3762,9 @@ public void andThenSingleError() { Completable.error(e) .andThen(new Single<String>() { @Override - public void subscribeActual(SingleObserver<? super String> s) { + public void subscribeActual(SingleObserver<? super String> observer) { hasRun.set(true); - s.onSuccess("foo"); + observer.onSuccess("foo"); } }) .toFlowable().subscribe(ts); @@ -4192,8 +4239,8 @@ public void testHookSubscribeStart() throws Exception { TestSubscriber<String> ts = new TestSubscriber<String>(); Completable completable = Completable.unsafeCreate(new CompletableSource() { - @Override public void subscribe(CompletableObserver s) { - s.onComplete(); + @Override public void subscribe(CompletableObserver observer) { + observer.onComplete(); } }); completable.<String>toFlowable().subscribe(ts); @@ -4589,18 +4636,25 @@ public void accept(final Throwable throwable) throws Exception { @Test public void doOnEventError() { - final AtomicInteger atomicInteger = new AtomicInteger(0); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final AtomicInteger atomicInteger = new AtomicInteger(0); - Completable.error(new RuntimeException()).doOnEvent(new Consumer<Throwable>() { - @Override - public void accept(final Throwable throwable) throws Exception { - if (throwable != null) { - atomicInteger.incrementAndGet(); + Completable.error(new RuntimeException()).doOnEvent(new Consumer<Throwable>() { + @Override + public void accept(final Throwable throwable) throws Exception { + if (throwable != null) { + atomicInteger.incrementAndGet(); + } } - } - }).subscribe(); + }).subscribe(); - assertEquals(1, atomicInteger.get()); + assertEquals(1, atomicInteger.get()); + + TestHelper.assertError(errors, 0, OnErrorNotImplementedException.class); + } finally { + RxJavaPlugins.reset(); + } } diff --git a/src/test/java/io/reactivex/exceptions/ExceptionsTest.java b/src/test/java/io/reactivex/exceptions/ExceptionsTest.java index 88a08e8c70..43b316a7f7 100644 --- a/src/test/java/io/reactivex/exceptions/ExceptionsTest.java +++ b/src/test/java/io/reactivex/exceptions/ExceptionsTest.java @@ -318,13 +318,13 @@ public void onNext(Integer integer) { public void testOnErrorExceptionIsThrownFromSubscribe() { Observable.unsafeCreate(new ObservableSource<Integer>() { @Override - public void subscribe(Observer<? super Integer> s1) { + public void subscribe(Observer<? super Integer> observer1) { Observable.unsafeCreate(new ObservableSource<Integer>() { @Override - public void subscribe(Observer<? super Integer> s2) { + public void subscribe(Observer<? super Integer> observer2) { throw new IllegalArgumentException("original exception"); } - }).subscribe(s1); + }).subscribe(observer1); } } ).subscribe(new OnErrorFailedSubscriber()); @@ -335,13 +335,13 @@ public void subscribe(Observer<? super Integer> s2) { public void testOnErrorExceptionIsThrownFromUnsafeSubscribe() { Observable.unsafeCreate(new ObservableSource<Integer>() { @Override - public void subscribe(Observer<? super Integer> s1) { + public void subscribe(Observer<? super Integer> observer1) { Observable.unsafeCreate(new ObservableSource<Integer>() { @Override - public void subscribe(Observer<? super Integer> s2) { + public void subscribe(Observer<? super Integer> observer2) { throw new IllegalArgumentException("original exception"); } - }).subscribe(s1); + }).subscribe(observer1); } } ).subscribe(new OnErrorFailedSubscriber()); @@ -365,13 +365,13 @@ public void accept(Integer integer) { public void testOnErrorExceptionIsThrownFromSingleSubscribe() { Single.unsafeCreate(new SingleSource<Integer>() { @Override - public void subscribe(SingleObserver<? super Integer> s1) { + public void subscribe(SingleObserver<? super Integer> observer1) { Single.unsafeCreate(new SingleSource<Integer>() { @Override - public void subscribe(SingleObserver<? super Integer> s2) { + public void subscribe(SingleObserver<? super Integer> observer2) { throw new IllegalArgumentException("original exception"); } - }).subscribe(s1); + }).subscribe(observer1); } } ).toObservable().subscribe(new OnErrorFailedSubscriber()); @@ -382,10 +382,10 @@ public void subscribe(SingleObserver<? super Integer> s2) { public void testOnErrorExceptionIsThrownFromSingleUnsafeSubscribe() { Single.unsafeCreate(new SingleSource<Integer>() { @Override - public void subscribe(final SingleObserver<? super Integer> s1) { + public void subscribe(final SingleObserver<? super Integer> observer1) { Single.unsafeCreate(new SingleSource<Integer>() { @Override - public void subscribe(SingleObserver<? super Integer> s2) { + public void subscribe(SingleObserver<? super Integer> observer2) { throw new IllegalArgumentException("original exception"); } }).toFlowable().subscribe(new FlowableSubscriber<Integer>() { @@ -401,12 +401,12 @@ public void onComplete() { @Override public void onError(Throwable e) { - s1.onError(e); + observer1.onError(e); } @Override public void onNext(Integer v) { - s1.onSuccess(v); + observer1.onSuccess(v); } }); diff --git a/src/test/java/io/reactivex/flowable/FlowableCollectTest.java b/src/test/java/io/reactivex/flowable/FlowableCollectTest.java index ee88dfac53..09bb562d2b 100644 --- a/src/test/java/io/reactivex/flowable/FlowableCollectTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableCollectTest.java @@ -31,7 +31,7 @@ public final class FlowableCollectTest { @Test public void testCollectToListFlowable() { - Flowable<List<Integer>> o = Flowable.just(1, 2, 3) + Flowable<List<Integer>> f = Flowable.just(1, 2, 3) .collect(new Callable<List<Integer>>() { @Override public List<Integer> call() { @@ -44,7 +44,7 @@ public void accept(List<Integer> list, Integer v) { } }).toFlowable(); - List<Integer> list = o.blockingLast(); + List<Integer> list = f.blockingLast(); assertEquals(3, list.size()); assertEquals(1, list.get(0).intValue()); @@ -52,7 +52,7 @@ public void accept(List<Integer> list, Integer v) { assertEquals(3, list.get(2).intValue()); // test multiple subscribe - List<Integer> list2 = o.blockingLast(); + List<Integer> list2 = f.blockingLast(); assertEquals(3, list2.size()); assertEquals(1, list2.get(0).intValue()); diff --git a/src/test/java/io/reactivex/flowable/FlowableConcatTests.java b/src/test/java/io/reactivex/flowable/FlowableConcatTests.java index 4a689fe5df..3270204055 100644 --- a/src/test/java/io/reactivex/flowable/FlowableConcatTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableConcatTests.java @@ -26,10 +26,10 @@ public class FlowableConcatTests { @Test public void testConcatSimple() { - Flowable<String> o1 = Flowable.just("one", "two"); - Flowable<String> o2 = Flowable.just("three", "four"); + Flowable<String> f1 = Flowable.just("one", "two"); + Flowable<String> f2 = Flowable.just("three", "four"); - List<String> values = Flowable.concat(o1, o2).toList().blockingGet(); + List<String> values = Flowable.concat(f1, f2).toList().blockingGet(); assertEquals("one", values.get(0)); assertEquals("two", values.get(1)); @@ -39,11 +39,11 @@ public void testConcatSimple() { @Test public void testConcatWithFlowableOfFlowable() { - Flowable<String> o1 = Flowable.just("one", "two"); - Flowable<String> o2 = Flowable.just("three", "four"); - Flowable<String> o3 = Flowable.just("five", "six"); + Flowable<String> f1 = Flowable.just("one", "two"); + Flowable<String> f2 = Flowable.just("three", "four"); + Flowable<String> f3 = Flowable.just("five", "six"); - Flowable<Flowable<String>> os = Flowable.just(o1, o2, o3); + Flowable<Flowable<String>> os = Flowable.just(f1, f2, f3); List<String> values = Flowable.concat(os).toList().blockingGet(); @@ -57,12 +57,12 @@ public void testConcatWithFlowableOfFlowable() { @Test public void testConcatWithIterableOfFlowable() { - Flowable<String> o1 = Flowable.just("one", "two"); - Flowable<String> o2 = Flowable.just("three", "four"); - Flowable<String> o3 = Flowable.just("five", "six"); + Flowable<String> f1 = Flowable.just("one", "two"); + Flowable<String> f2 = Flowable.just("three", "four"); + Flowable<String> f3 = Flowable.just("five", "six"); @SuppressWarnings("unchecked") - Iterable<Flowable<String>> is = Arrays.asList(o1, o2, o3); + Iterable<Flowable<String>> is = Arrays.asList(f1, f2, f3); List<String> values = Flowable.concat(Flowable.fromIterable(is)).toList().blockingGet(); @@ -81,10 +81,10 @@ public void testConcatCovariance() { Media media = new Media(); HorrorMovie horrorMovie2 = new HorrorMovie(); - Flowable<Media> o1 = Flowable.<Media> just(horrorMovie1, movie); - Flowable<Media> o2 = Flowable.just(media, horrorMovie2); + Flowable<Media> f1 = Flowable.<Media> just(horrorMovie1, movie); + Flowable<Media> f2 = Flowable.just(media, horrorMovie2); - Flowable<Flowable<Media>> os = Flowable.just(o1, o2); + Flowable<Flowable<Media>> os = Flowable.just(f1, f2); List<Media> values = Flowable.concat(os).toList().blockingGet(); @@ -103,10 +103,10 @@ public void testConcatCovariance2() { Media media2 = new Media(); HorrorMovie horrorMovie2 = new HorrorMovie(); - Flowable<Media> o1 = Flowable.just(horrorMovie1, movie, media1); - Flowable<Media> o2 = Flowable.just(media2, horrorMovie2); + Flowable<Media> f1 = Flowable.just(horrorMovie1, movie, media1); + Flowable<Media> f2 = Flowable.just(media2, horrorMovie2); - Flowable<Flowable<Media>> os = Flowable.just(o1, o2); + Flowable<Flowable<Media>> os = Flowable.just(f1, f2); List<Media> values = Flowable.concat(os).toList().blockingGet(); @@ -125,10 +125,10 @@ public void testConcatCovariance3() { Media media = new Media(); HorrorMovie horrorMovie2 = new HorrorMovie(); - Flowable<Movie> o1 = Flowable.just(horrorMovie1, movie); - Flowable<Media> o2 = Flowable.just(media, horrorMovie2); + Flowable<Movie> f1 = Flowable.just(horrorMovie1, movie); + Flowable<Media> f2 = Flowable.just(media, horrorMovie2); - List<Media> values = Flowable.concat(o1, o2).toList().blockingGet(); + List<Media> values = Flowable.concat(f1, f2).toList().blockingGet(); assertEquals(horrorMovie1, values.get(0)); assertEquals(movie, values.get(1)); @@ -144,19 +144,19 @@ public void testConcatCovariance4() { Media media = new Media(); HorrorMovie horrorMovie2 = new HorrorMovie(); - Flowable<Movie> o1 = Flowable.unsafeCreate(new Publisher<Movie>() { + Flowable<Movie> f1 = Flowable.unsafeCreate(new Publisher<Movie>() { @Override - public void subscribe(Subscriber<? super Movie> o) { - o.onNext(horrorMovie1); - o.onNext(movie); + public void subscribe(Subscriber<? super Movie> subscriber) { + subscriber.onNext(horrorMovie1); + subscriber.onNext(movie); // o.onNext(new Media()); // correctly doesn't compile - o.onComplete(); + subscriber.onComplete(); } }); - Flowable<Media> o2 = Flowable.just(media, horrorMovie2); + Flowable<Media> f2 = Flowable.just(media, horrorMovie2); - List<Media> values = Flowable.concat(o1, o2).toList().blockingGet(); + List<Media> values = Flowable.concat(f1, f2).toList().blockingGet(); assertEquals(horrorMovie1, values.get(0)); assertEquals(movie, values.get(1)); diff --git a/src/test/java/io/reactivex/flowable/FlowableConversionTest.java b/src/test/java/io/reactivex/flowable/FlowableConversionTest.java index 946a3b4742..a7d908111a 100644 --- a/src/test/java/io/reactivex/flowable/FlowableConversionTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableConversionTest.java @@ -115,16 +115,16 @@ public RobotConversionFunc(FlowableOperator<? extends R, ? super T> operator) { public CylonDetectorObservable<R> apply(final Publisher<T> onSubscribe) { return CylonDetectorObservable.create(new Publisher<R>() { @Override - public void subscribe(Subscriber<? super R> o) { + public void subscribe(Subscriber<? super R> subscriber) { try { - Subscriber<? super T> st = operator.apply(o); + Subscriber<? super T> st = operator.apply(subscriber); try { onSubscribe.subscribe(st); } catch (Throwable e) { st.onError(e); } } catch (Throwable e) { - o.onError(e); + subscriber.onError(e); } }}); @@ -147,7 +147,7 @@ public Flowable<T> apply(final Publisher<T> onSubscribe) { @Test public void testConversionBetweenObservableClasses() { - final TestObserver<String> subscriber = new TestObserver<String>(new DefaultObserver<String>() { + final TestObserver<String> to = new TestObserver<String>(new DefaultObserver<String>() { @Override public void onComplete() { @@ -196,10 +196,10 @@ public String apply(String a, String n) { return a + n + "\n"; } }) - .subscribe(subscriber); + .subscribe(to); - subscriber.assertNoErrors(); - subscriber.assertComplete(); + to.assertNoErrors(); + to.assertComplete(); } @Test diff --git a/src/test/java/io/reactivex/flowable/FlowableCovarianceTest.java b/src/test/java/io/reactivex/flowable/FlowableCovarianceTest.java index 80e1785eff..812b747750 100644 --- a/src/test/java/io/reactivex/flowable/FlowableCovarianceTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableCovarianceTest.java @@ -56,12 +56,12 @@ public int compare(Media t1, Media t2) { }; // this one would work without the covariance generics - Flowable<Media> o = Flowable.just(new Movie(), new TVSeason(), new Album()); - o.toSortedList(sortFunction); + Flowable<Media> f = Flowable.just(new Movie(), new TVSeason(), new Album()); + f.toSortedList(sortFunction); // this one would NOT work without the covariance generics - Flowable<Movie> o2 = Flowable.just(new Movie(), new ActionMovie(), new HorrorMovie()); - o2.toSortedList(sortFunction); + Flowable<Movie> f2 = Flowable.just(new Movie(), new ActionMovie(), new HorrorMovie()); + f2.toSortedList(sortFunction); } @Test diff --git a/src/test/java/io/reactivex/flowable/FlowableErrorHandlingTests.java b/src/test/java/io/reactivex/flowable/FlowableErrorHandlingTests.java index 91baaf1b9c..e86aa39266 100644 --- a/src/test/java/io/reactivex/flowable/FlowableErrorHandlingTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableErrorHandlingTests.java @@ -35,8 +35,8 @@ public class FlowableErrorHandlingTests { public void testOnNextError() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> caughtError = new AtomicReference<Throwable>(); - Flowable<Long> o = Flowable.interval(50, TimeUnit.MILLISECONDS); - Subscriber<Long> observer = new DefaultSubscriber<Long>() { + Flowable<Long> f = Flowable.interval(50, TimeUnit.MILLISECONDS); + Subscriber<Long> subscriber = new DefaultSubscriber<Long>() { @Override public void onComplete() { @@ -56,7 +56,7 @@ public void onNext(Long args) { throw new RuntimeException("forced failure"); } }; - o.safeSubscribe(observer); + f.safeSubscribe(subscriber); latch.await(2000, TimeUnit.MILLISECONDS); assertNotNull(caughtError.get()); @@ -71,8 +71,8 @@ public void onNext(Long args) { public void testOnNextErrorAcrossThread() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> caughtError = new AtomicReference<Throwable>(); - Flowable<Long> o = Flowable.interval(50, TimeUnit.MILLISECONDS); - Subscriber<Long> observer = new DefaultSubscriber<Long>() { + Flowable<Long> f = Flowable.interval(50, TimeUnit.MILLISECONDS); + Subscriber<Long> subscriber = new DefaultSubscriber<Long>() { @Override public void onComplete() { @@ -92,8 +92,8 @@ public void onNext(Long args) { throw new RuntimeException("forced failure"); } }; - o.observeOn(Schedulers.newThread()) - .safeSubscribe(observer); + f.observeOn(Schedulers.newThread()) + .safeSubscribe(subscriber); latch.await(2000, TimeUnit.MILLISECONDS); assertNotNull(caughtError.get()); diff --git a/src/test/java/io/reactivex/flowable/FlowableMergeTests.java b/src/test/java/io/reactivex/flowable/FlowableMergeTests.java index 46a0278bec..5c96bcf096 100644 --- a/src/test/java/io/reactivex/flowable/FlowableMergeTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableMergeTests.java @@ -38,10 +38,10 @@ public void testCovarianceOfMerge() { @Test public void testMergeCovariance() { - Flowable<Media> o1 = Flowable.<Media> just(new HorrorMovie(), new Movie()); - Flowable<Media> o2 = Flowable.just(new Media(), new HorrorMovie()); + Flowable<Media> f1 = Flowable.<Media> just(new HorrorMovie(), new Movie()); + Flowable<Media> f2 = Flowable.just(new Media(), new HorrorMovie()); - Flowable<Flowable<Media>> os = Flowable.just(o1, o2); + Flowable<Flowable<Media>> os = Flowable.just(f1, f2); List<Media> values = Flowable.merge(os).toList().blockingGet(); @@ -50,10 +50,10 @@ public void testMergeCovariance() { @Test public void testMergeCovariance2() { - Flowable<Media> o1 = Flowable.just(new HorrorMovie(), new Movie(), new Media()); - Flowable<Media> o2 = Flowable.just(new Media(), new HorrorMovie()); + Flowable<Media> f1 = Flowable.just(new HorrorMovie(), new Movie(), new Media()); + Flowable<Media> f2 = Flowable.just(new Media(), new HorrorMovie()); - Flowable<Flowable<Media>> os = Flowable.just(o1, o2); + Flowable<Flowable<Media>> os = Flowable.just(f1, f2); List<Media> values = Flowable.merge(os).toList().blockingGet(); @@ -62,10 +62,10 @@ public void testMergeCovariance2() { @Test public void testMergeCovariance3() { - Flowable<Movie> o1 = Flowable.just(new HorrorMovie(), new Movie()); - Flowable<Media> o2 = Flowable.just(new Media(), new HorrorMovie()); + Flowable<Movie> f1 = Flowable.just(new HorrorMovie(), new Movie()); + Flowable<Media> f2 = Flowable.just(new Media(), new HorrorMovie()); - List<Media> values = Flowable.merge(o1, o2).toList().blockingGet(); + List<Media> values = Flowable.merge(f1, f2).toList().blockingGet(); assertTrue(values.get(0) instanceof HorrorMovie); assertTrue(values.get(1) instanceof Movie); @@ -76,7 +76,7 @@ public void testMergeCovariance3() { @Test public void testMergeCovariance4() { - Flowable<Movie> o1 = Flowable.defer(new Callable<Publisher<Movie>>() { + Flowable<Movie> f1 = Flowable.defer(new Callable<Publisher<Movie>>() { @Override public Publisher<Movie> call() { return Flowable.just( @@ -86,9 +86,9 @@ public Publisher<Movie> call() { } }); - Flowable<Media> o2 = Flowable.just(new Media(), new HorrorMovie()); + Flowable<Media> f2 = Flowable.just(new Media(), new HorrorMovie()); - List<Media> values = Flowable.merge(o1, o2).toList().blockingGet(); + List<Media> values = Flowable.merge(f1, f2).toList().blockingGet(); assertTrue(values.get(0) instanceof HorrorMovie); assertTrue(values.get(1) instanceof Movie); diff --git a/src/test/java/io/reactivex/flowable/FlowableNullTests.java b/src/test/java/io/reactivex/flowable/FlowableNullTests.java index b5e5301d91..12c7a9b5c1 100644 --- a/src/test/java/io/reactivex/flowable/FlowableNullTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableNullTests.java @@ -1805,7 +1805,7 @@ public void replaySelectorNull() { public void replaySelectorReturnsNull() { just1.replay(new Function<Flowable<Integer>, Publisher<Object>>() { @Override - public Publisher<Object> apply(Flowable<Integer> o) { + public Publisher<Object> apply(Flowable<Integer> f) { return null; } }).blockingSubscribe(); @@ -2738,72 +2738,72 @@ public Object apply(Integer a, Integer b) { @Test(expected = NullPointerException.class) public void asyncSubjectOnNextNull() { - FlowableProcessor<Integer> subject = AsyncProcessor.create(); - subject.onNext(null); - subject.blockingSubscribe(); + FlowableProcessor<Integer> processor = AsyncProcessor.create(); + processor.onNext(null); + processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void asyncSubjectOnErrorNull() { - FlowableProcessor<Integer> subject = AsyncProcessor.create(); - subject.onError(null); - subject.blockingSubscribe(); + FlowableProcessor<Integer> processor = AsyncProcessor.create(); + processor.onError(null); + processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void behaviorSubjectOnNextNull() { - FlowableProcessor<Integer> subject = BehaviorProcessor.create(); - subject.onNext(null); - subject.blockingSubscribe(); + FlowableProcessor<Integer> processor = BehaviorProcessor.create(); + processor.onNext(null); + processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void behaviorSubjectOnErrorNull() { - FlowableProcessor<Integer> subject = BehaviorProcessor.create(); - subject.onError(null); - subject.blockingSubscribe(); + FlowableProcessor<Integer> processor = BehaviorProcessor.create(); + processor.onError(null); + processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void publishSubjectOnNextNull() { - FlowableProcessor<Integer> subject = PublishProcessor.create(); - subject.onNext(null); - subject.blockingSubscribe(); + FlowableProcessor<Integer> processor = PublishProcessor.create(); + processor.onNext(null); + processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void publishSubjectOnErrorNull() { - FlowableProcessor<Integer> subject = PublishProcessor.create(); - subject.onError(null); - subject.blockingSubscribe(); + FlowableProcessor<Integer> processor = PublishProcessor.create(); + processor.onError(null); + processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void replaycSubjectOnNextNull() { - FlowableProcessor<Integer> subject = ReplayProcessor.create(); - subject.onNext(null); - subject.blockingSubscribe(); + FlowableProcessor<Integer> processor = ReplayProcessor.create(); + processor.onNext(null); + processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void replaySubjectOnErrorNull() { - FlowableProcessor<Integer> subject = ReplayProcessor.create(); - subject.onError(null); - subject.blockingSubscribe(); + FlowableProcessor<Integer> processor = ReplayProcessor.create(); + processor.onError(null); + processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void serializedcSubjectOnNextNull() { - FlowableProcessor<Integer> subject = PublishProcessor.<Integer>create().toSerialized(); - subject.onNext(null); - subject.blockingSubscribe(); + FlowableProcessor<Integer> processor = PublishProcessor.<Integer>create().toSerialized(); + processor.onNext(null); + processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void serializedSubjectOnErrorNull() { - FlowableProcessor<Integer> subject = PublishProcessor.<Integer>create().toSerialized(); - subject.onError(null); - subject.blockingSubscribe(); + FlowableProcessor<Integer> processor = PublishProcessor.<Integer>create().toSerialized(); + processor.onError(null); + processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/io/reactivex/flowable/FlowableReduceTests.java b/src/test/java/io/reactivex/flowable/FlowableReduceTests.java index b21821e746..e98c56f0f5 100644 --- a/src/test/java/io/reactivex/flowable/FlowableReduceTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableReduceTests.java @@ -25,8 +25,8 @@ public class FlowableReduceTests { @Test public void reduceIntsFlowable() { - Flowable<Integer> o = Flowable.just(1, 2, 3); - int value = o.reduce(new BiFunction<Integer, Integer, Integer>() { + Flowable<Integer> f = Flowable.just(1, 2, 3); + int value = f.reduce(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) { return t1 + t2; @@ -80,8 +80,8 @@ public Movie apply(Movie t1, Movie t2) { @Test public void reduceInts() { - Flowable<Integer> o = Flowable.just(1, 2, 3); - int value = o.reduce(new BiFunction<Integer, Integer, Integer>() { + Flowable<Integer> f = Flowable.just(1, 2, 3); + int value = f.reduce(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) { return t1 + t2; diff --git a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java index c944d63092..b01c2886ac 100644 --- a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java @@ -602,33 +602,40 @@ public boolean test(Integer v) throws Exception { @Test public void suppressAfterCompleteEvents() { - final TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); - ts.onSubscribe(new BooleanSubscription()); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + ts.onSubscribe(new BooleanSubscription()); + + ForEachWhileSubscriber<Integer> s = new ForEachWhileSubscriber<Integer>(new Predicate<Integer>() { + @Override + public boolean test(Integer v) throws Exception { + ts.onNext(v); + return true; + } + }, new Consumer<Throwable>() { + @Override + public void accept(Throwable e) throws Exception { + ts.onError(e); + } + }, new Action() { + @Override + public void run() throws Exception { + ts.onComplete(); + } + }); - ForEachWhileSubscriber<Integer> s = new ForEachWhileSubscriber<Integer>(new Predicate<Integer>() { - @Override - public boolean test(Integer v) throws Exception { - ts.onNext(v); - return true; - } - }, new Consumer<Throwable>() { - @Override - public void accept(Throwable e) throws Exception { - ts.onError(e); - } - }, new Action() { - @Override - public void run() throws Exception { - ts.onComplete(); - } - }); + s.onComplete(); + s.onNext(1); + s.onError(new TestException()); + s.onComplete(); - s.onComplete(); - s.onNext(1); - s.onError(new TestException()); - s.onComplete(); + ts.assertResult(); - ts.assertResult(); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test diff --git a/src/test/java/io/reactivex/flowable/FlowableTests.java b/src/test/java/io/reactivex/flowable/FlowableTests.java index 84c86a8504..8f45ce3689 100644 --- a/src/test/java/io/reactivex/flowable/FlowableTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableTests.java @@ -27,10 +27,11 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; -import io.reactivex.exceptions.TestException; +import io.reactivex.exceptions.*; import io.reactivex.flowables.ConnectableFlowable; import io.reactivex.functions.*; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.*; import io.reactivex.schedulers.*; import io.reactivex.subscribers.*; @@ -97,24 +98,24 @@ public void fromArityArgs1() { @Test public void testCreate() { - Flowable<String> observable = Flowable.just("one", "two", "three"); + Flowable<String> flowable = Flowable.just("one", "two", "three"); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testCountAFewItemsFlowable() { - Flowable<String> observable = Flowable.just("a", "b", "c", "d"); + Flowable<String> flowable = Flowable.just("a", "b", "c", "d"); - observable.count().toFlowable().subscribe(w); + flowable.count().toFlowable().subscribe(w); // we should be called only once verify(w).onNext(4L); @@ -124,8 +125,8 @@ public void testCountAFewItemsFlowable() { @Test public void testCountZeroItemsFlowable() { - Flowable<String> observable = Flowable.empty(); - observable.count().toFlowable().subscribe(w); + Flowable<String> flowable = Flowable.empty(); + flowable.count().toFlowable().subscribe(w); // we should be called only once verify(w).onNext(0L); verify(w, never()).onError(any(Throwable.class)); @@ -134,14 +135,14 @@ public void testCountZeroItemsFlowable() { @Test public void testCountErrorFlowable() { - Flowable<String> o = Flowable.error(new Callable<Throwable>() { + Flowable<String> f = Flowable.error(new Callable<Throwable>() { @Override public Throwable call() { return new RuntimeException(); } }); - o.count().toFlowable().subscribe(w); + f.count().toFlowable().subscribe(w); verify(w, never()).onNext(anyInt()); verify(w, never()).onComplete(); verify(w, times(1)).onError(any(RuntimeException.class)); @@ -150,9 +151,9 @@ public Throwable call() { @Test public void testCountAFewItems() { - Flowable<String> observable = Flowable.just("a", "b", "c", "d"); + Flowable<String> flowable = Flowable.just("a", "b", "c", "d"); - observable.count().subscribe(wo); + flowable.count().subscribe(wo); // we should be called only once verify(wo).onSuccess(4L); @@ -161,8 +162,8 @@ public void testCountAFewItems() { @Test public void testCountZeroItems() { - Flowable<String> observable = Flowable.empty(); - observable.count().subscribe(wo); + Flowable<String> flowable = Flowable.empty(); + flowable.count().subscribe(wo); // we should be called only once verify(wo).onSuccess(0L); verify(wo, never()).onError(any(Throwable.class)); @@ -170,22 +171,22 @@ public void testCountZeroItems() { @Test public void testCountError() { - Flowable<String> o = Flowable.error(new Callable<Throwable>() { + Flowable<String> f = Flowable.error(new Callable<Throwable>() { @Override public Throwable call() { return new RuntimeException(); } }); - o.count().subscribe(wo); + f.count().subscribe(wo); verify(wo, never()).onSuccess(anyInt()); verify(wo, times(1)).onError(any(RuntimeException.class)); } @Test public void testTakeFirstWithPredicateOfSome() { - Flowable<Integer> observable = Flowable.just(1, 3, 5, 4, 6, 3); - observable.filter(IS_EVEN).take(1).subscribe(w); + Flowable<Integer> flowable = Flowable.just(1, 3, 5, 4, 6, 3); + flowable.filter(IS_EVEN).take(1).subscribe(w); verify(w, times(1)).onNext(anyInt()); verify(w).onNext(4); verify(w, times(1)).onComplete(); @@ -194,8 +195,8 @@ public void testTakeFirstWithPredicateOfSome() { @Test public void testTakeFirstWithPredicateOfNoneMatchingThePredicate() { - Flowable<Integer> observable = Flowable.just(1, 3, 5, 7, 9, 7, 5, 3, 1); - observable.filter(IS_EVEN).take(1).subscribe(w); + Flowable<Integer> flowable = Flowable.just(1, 3, 5, 7, 9, 7, 5, 3, 1); + flowable.filter(IS_EVEN).take(1).subscribe(w); verify(w, never()).onNext(anyInt()); verify(w, times(1)).onComplete(); verify(w, never()).onError(any(Throwable.class)); @@ -203,8 +204,8 @@ public void testTakeFirstWithPredicateOfNoneMatchingThePredicate() { @Test public void testTakeFirstOfSome() { - Flowable<Integer> observable = Flowable.just(1, 2, 3); - observable.take(1).subscribe(w); + Flowable<Integer> flowable = Flowable.just(1, 2, 3); + flowable.take(1).subscribe(w); verify(w, times(1)).onNext(anyInt()); verify(w).onNext(1); verify(w, times(1)).onComplete(); @@ -213,8 +214,8 @@ public void testTakeFirstOfSome() { @Test public void testTakeFirstOfNone() { - Flowable<Integer> observable = Flowable.empty(); - observable.take(1).subscribe(w); + Flowable<Integer> flowable = Flowable.empty(); + flowable.take(1).subscribe(w); verify(w, never()).onNext(anyInt()); verify(w, times(1)).onComplete(); verify(w, never()).onError(any(Throwable.class)); @@ -222,8 +223,8 @@ public void testTakeFirstOfNone() { @Test public void testFirstOfNoneFlowable() { - Flowable<Integer> observable = Flowable.empty(); - observable.firstElement().toFlowable().subscribe(w); + Flowable<Integer> flowable = Flowable.empty(); + flowable.firstElement().toFlowable().subscribe(w); verify(w, never()).onNext(anyInt()); verify(w).onComplete(); verify(w, never()).onError(any(Throwable.class)); @@ -231,8 +232,8 @@ public void testFirstOfNoneFlowable() { @Test public void testFirstWithPredicateOfNoneMatchingThePredicateFlowable() { - Flowable<Integer> observable = Flowable.just(1, 3, 5, 7, 9, 7, 5, 3, 1); - observable.filter(IS_EVEN).firstElement().toFlowable().subscribe(w); + Flowable<Integer> flowable = Flowable.just(1, 3, 5, 7, 9, 7, 5, 3, 1); + flowable.filter(IS_EVEN).firstElement().toFlowable().subscribe(w); verify(w, never()).onNext(anyInt()); verify(w).onComplete(); verify(w, never()).onError(any(Throwable.class)); @@ -240,8 +241,8 @@ public void testFirstWithPredicateOfNoneMatchingThePredicateFlowable() { @Test public void testFirstOfNone() { - Flowable<Integer> observable = Flowable.empty(); - observable.firstElement().subscribe(wm); + Flowable<Integer> flowable = Flowable.empty(); + flowable.firstElement().subscribe(wm); verify(wm, never()).onSuccess(anyInt()); verify(wm).onComplete(); verify(wm, never()).onError(isA(NoSuchElementException.class)); @@ -249,8 +250,8 @@ public void testFirstOfNone() { @Test public void testFirstWithPredicateOfNoneMatchingThePredicate() { - Flowable<Integer> observable = Flowable.just(1, 3, 5, 7, 9, 7, 5, 3, 1); - observable.filter(IS_EVEN).firstElement().subscribe(wm); + Flowable<Integer> flowable = Flowable.just(1, 3, 5, 7, 9, 7, 5, 3, 1); + flowable.filter(IS_EVEN).firstElement().subscribe(wm); verify(wm, never()).onSuccess(anyInt()); verify(wm, times(1)).onComplete(); verify(wm, never()).onError(isA(NoSuchElementException.class)); @@ -258,8 +259,8 @@ public void testFirstWithPredicateOfNoneMatchingThePredicate() { @Test public void testReduce() { - Flowable<Integer> observable = Flowable.just(1, 2, 3, 4); - observable.reduce(new BiFunction<Integer, Integer, Integer>() { + Flowable<Integer> flowable = Flowable.just(1, 2, 3, 4); + flowable.reduce(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) { return t1 + t2; @@ -274,8 +275,8 @@ public Integer apply(Integer t1, Integer t2) { @Test public void testReduceWithEmptyObservable() { - Flowable<Integer> observable = Flowable.range(1, 0); - observable.reduce(new BiFunction<Integer, Integer, Integer>() { + Flowable<Integer> flowable = Flowable.range(1, 0); + flowable.reduce(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) { return t1 + t2; @@ -293,8 +294,8 @@ public Integer apply(Integer t1, Integer t2) { */ @Test public void testReduceWithEmptyObservableAndSeed() { - Flowable<Integer> observable = Flowable.range(1, 0); - int value = observable.reduce(1, new BiFunction<Integer, Integer, Integer>() { + Flowable<Integer> flowable = Flowable.range(1, 0); + int value = flowable.reduce(1, new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) { return t1 + t2; @@ -307,8 +308,8 @@ public Integer apply(Integer t1, Integer t2) { @Test public void testReduceWithInitialValue() { - Flowable<Integer> observable = Flowable.just(1, 2, 3, 4); - observable.reduce(50, new BiFunction<Integer, Integer, Integer>() { + Flowable<Integer> flowable = Flowable.just(1, 2, 3, 4); + flowable.reduce(50, new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) { return t1 + t2; @@ -323,18 +324,19 @@ public Integer apply(Integer t1, Integer t2) { @Ignore("Throwing is not allowed from the unsafeCreate?!") @Test // FIXME throwing is not allowed from the create?! public void testOnSubscribeFails() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); final RuntimeException re = new RuntimeException("bad impl"); - Flowable<String> o = Flowable.unsafeCreate(new Publisher<String>() { + Flowable<String> f = Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> s) { throw re; } }); - o.subscribe(observer); - verify(observer, times(0)).onNext(anyString()); - verify(observer, times(0)).onComplete(); - verify(observer, times(1)).onError(re); + f.subscribe(subscriber); + + verify(subscriber, times(0)).onNext(anyString()); + verify(subscriber, times(0)).onComplete(); + verify(subscriber, times(1)).onError(re); } @Test @@ -342,13 +344,13 @@ public void testMaterializeDematerializeChaining() { Flowable<Integer> obs = Flowable.just(1); Flowable<Integer> chained = obs.materialize().dematerialize(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - chained.subscribe(observer); + chained.subscribe(subscriber); - verify(observer, times(1)).onNext(1); - verify(observer, times(1)).onComplete(); - verify(observer, times(0)).onError(any(Throwable.class)); + verify(subscriber, times(1)).onNext(1); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(0)).onError(any(Throwable.class)); } /** @@ -494,15 +496,15 @@ public void testPublishLast() throws InterruptedException { final AtomicInteger count = new AtomicInteger(); ConnectableFlowable<String> connectable = Flowable.<String>unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); count.incrementAndGet(); new Thread(new Runnable() { @Override public void run() { - observer.onNext("first"); - observer.onNext("last"); - observer.onComplete(); + subscriber.onNext("first"); + subscriber.onNext("last"); + subscriber.onComplete(); } }).start(); } @@ -530,31 +532,31 @@ public void accept(String value) { @Test public void testReplay() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); - ConnectableFlowable<String> o = Flowable.<String>unsafeCreate(new Publisher<String>() { + ConnectableFlowable<String> f = Flowable.<String>unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); - observer.onNext("one"); - observer.onComplete(); + subscriber.onNext("one"); + subscriber.onComplete(); } }).start(); } }).replay(); // we connect immediately and it will emit the value - Disposable s = o.connect(); + Disposable s = f.connect(); try { // we then expect the following 2 subscriptions to get that same value final CountDownLatch latch = new CountDownLatch(2); // subscribe once - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { assertEquals("one", v); @@ -563,7 +565,7 @@ public void accept(String v) { }); // subscribe again - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { assertEquals("one", v); @@ -583,16 +585,16 @@ public void accept(String v) { @Test public void testCache() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); - Flowable<String> o = Flowable.<String>unsafeCreate(new Publisher<String>() { + Flowable<String> f = Flowable.<String>unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); - observer.onNext("one"); - observer.onComplete(); + subscriber.onNext("one"); + subscriber.onComplete(); } }).start(); } @@ -602,7 +604,7 @@ public void run() { final CountDownLatch latch = new CountDownLatch(2); // subscribe once - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { assertEquals("one", v); @@ -611,7 +613,7 @@ public void accept(String v) { }); // subscribe again - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { assertEquals("one", v); @@ -628,16 +630,16 @@ public void accept(String v) { @Test public void testCacheWithCapacity() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); - Flowable<String> o = Flowable.<String>unsafeCreate(new Publisher<String>() { + Flowable<String> f = Flowable.<String>unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); - observer.onNext("one"); - observer.onComplete(); + subscriber.onNext("one"); + subscriber.onComplete(); } }).start(); } @@ -647,7 +649,7 @@ public void run() { final CountDownLatch latch = new CountDownLatch(2); // subscribe once - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { assertEquals("one", v); @@ -656,7 +658,7 @@ public void accept(String v) { }); // subscribe again - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { assertEquals("one", v); @@ -709,13 +711,13 @@ public void testErrorThrownWithoutErrorHandlerAsynchronous() throws InterruptedE final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); Flowable.unsafeCreate(new Publisher<Object>() { @Override - public void subscribe(final Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); new Thread(new Runnable() { @Override public void run() { try { - observer.onError(new Error("failure")); + subscriber.onError(new Error("failure")); } catch (Throwable e) { // without an onError handler it has to just throw on whatever thread invokes it exception.set(e); @@ -768,19 +770,18 @@ public void onNext(String v) { @Test public void testOfType() { - Flowable<String> observable = Flowable.just(1, "abc", false, 2L).ofType(String.class); + Flowable<String> flowable = Flowable.just(1, "abc", false, 2L).ofType(String.class); - Subscriber<Object> observer = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, never()).onNext(1); - verify(observer, times(1)).onNext("abc"); - verify(observer, never()).onNext(false); - verify(observer, never()).onNext(2L); - verify(observer, never()).onError( - any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onNext(1); + verify(subscriber, times(1)).onNext("abc"); + verify(subscriber, never()).onNext(false); + verify(subscriber, never()).onNext(2L); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -791,89 +792,84 @@ public void testOfTypeWithPolymorphism() { l2.add(2); @SuppressWarnings("rawtypes") - Flowable<List> observable = Flowable.<Object> just(l1, l2, "123").ofType(List.class); + Flowable<List> flowable = Flowable.<Object> just(l1, l2, "123").ofType(List.class); - Subscriber<Object> observer = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext(l1); - verify(observer, times(1)).onNext(l2); - verify(observer, never()).onNext("123"); - verify(observer, never()).onError( - any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(l1); + verify(subscriber, times(1)).onNext(l2); + verify(subscriber, never()).onNext("123"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testContainsFlowable() { - Flowable<Boolean> observable = Flowable.just("a", "b", "c").contains("b").toFlowable(); + Flowable<Boolean> flowable = Flowable.just("a", "b", "c").contains("b").toFlowable(); - FlowableSubscriber<Boolean> observer = TestHelper.mockSubscriber(); + FlowableSubscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext(true); - verify(observer, never()).onNext(false); - verify(observer, never()).onError( - any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(true); + verify(subscriber, never()).onNext(false); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testContainsWithInexistenceFlowable() { - Flowable<Boolean> observable = Flowable.just("a", "b").contains("c").toFlowable(); + Flowable<Boolean> flowable = Flowable.just("a", "b").contains("c").toFlowable(); - Subscriber<Object> observer = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext(false); - verify(observer, never()).onNext(true); - verify(observer, never()).onError( - any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(false); + verify(subscriber, never()).onNext(true); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @Ignore("null values are not allowed") public void testContainsWithNullFlowable() { - Flowable<Boolean> observable = Flowable.just("a", "b", null).contains(null).toFlowable(); + Flowable<Boolean> flowable = Flowable.just("a", "b", null).contains(null).toFlowable(); - Subscriber<Object> observer = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext(true); - verify(observer, never()).onNext(false); - verify(observer, never()).onError( - any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(true); + verify(subscriber, never()).onNext(false); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testContainsWithEmptyObservableFlowable() { - Flowable<Boolean> observable = Flowable.<String> empty().contains("a").toFlowable(); + Flowable<Boolean> flowable = Flowable.<String> empty().contains("a").toFlowable(); - FlowableSubscriber<Object> observer = TestHelper.mockSubscriber(); + FlowableSubscriber<Object> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext(false); - verify(observer, never()).onNext(true); - verify(observer, never()).onError( - any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(false); + verify(subscriber, never()).onNext(true); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testContains() { - Single<Boolean> observable = Flowable.just("a", "b", "c").contains("b"); // FIXME nulls not allowed, changed to "c" + Single<Boolean> single = Flowable.just("a", "b", "c").contains("b"); // FIXME nulls not allowed, changed to "c" SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(true); verify(observer, never()).onSuccess(false); @@ -883,11 +879,11 @@ public void testContains() { @Test public void testContainsWithInexistence() { - Single<Boolean> observable = Flowable.just("a", "b").contains("c"); // FIXME null values are not allowed, removed + Single<Boolean> single = Flowable.just("a", "b").contains("c"); // FIXME null values are not allowed, removed SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(false); verify(observer, never()).onSuccess(true); @@ -898,11 +894,11 @@ public void testContainsWithInexistence() { @Test @Ignore("null values are not allowed") public void testContainsWithNull() { - Single<Boolean> observable = Flowable.just("a", "b", null).contains(null); + Single<Boolean> single = Flowable.just("a", "b", null).contains(null); SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(true); verify(observer, never()).onSuccess(false); @@ -912,11 +908,11 @@ public void testContainsWithNull() { @Test public void testContainsWithEmptyObservable() { - Single<Boolean> observable = Flowable.<String> empty().contains("a"); + Single<Boolean> single = Flowable.<String> empty().contains("a"); SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(false); verify(observer, never()).onSuccess(true); @@ -926,24 +922,24 @@ public void testContainsWithEmptyObservable() { @Test public void testIgnoreElementsFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2, 3).ignoreElements().toFlowable(); + Flowable<Integer> flowable = Flowable.just(1, 2, 3).ignoreElements().toFlowable(); - Subscriber<Object> observer = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, never()).onNext(any(Integer.class)); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onNext(any(Integer.class)); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testIgnoreElements() { - Completable observable = Flowable.just(1, 2, 3).ignoreElements(); + Completable completable = Flowable.just(1, 2, 3).ignoreElements(); CompletableObserver observer = TestHelper.mockCompletableObserver(); - observable.subscribe(observer); + completable.subscribe(observer); verify(observer, never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); @@ -952,58 +948,58 @@ public void testIgnoreElements() { @Test public void testJustWithScheduler() { TestScheduler scheduler = new TestScheduler(); - Flowable<Integer> observable = Flowable.fromArray(1, 2).subscribeOn(scheduler); + Flowable<Integer> flowable = Flowable.fromArray(1, 2).subscribeOn(scheduler); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(1); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testStartWithWithScheduler() { TestScheduler scheduler = new TestScheduler(); - Flowable<Integer> observable = Flowable.just(3, 4).startWith(Arrays.asList(1, 2)).subscribeOn(scheduler); + Flowable<Integer> flowable = Flowable.just(3, 4).startWith(Arrays.asList(1, 2)).subscribeOn(scheduler); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(1); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onNext(3); - inOrder.verify(observer, times(1)).onNext(4); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onNext(3); + inOrder.verify(subscriber, times(1)).onNext(4); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testRangeWithScheduler() { TestScheduler scheduler = new TestScheduler(); - Flowable<Integer> observable = Flowable.range(3, 4).subscribeOn(scheduler); + Flowable<Integer> flowable = Flowable.range(3, 4).subscribeOn(scheduler); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(3); - inOrder.verify(observer, times(1)).onNext(4); - inOrder.verify(observer, times(1)).onNext(5); - inOrder.verify(observer, times(1)).onNext(6); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(3); + inOrder.verify(subscriber, times(1)).onNext(4); + inOrder.verify(subscriber, times(1)).onNext(5); + inOrder.verify(subscriber, times(1)).onNext(6); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -1075,18 +1071,25 @@ public String apply(Integer v) { @Test public void testErrorThrownIssue1685() { - FlowableProcessor<Object> subject = ReplayProcessor.create(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + FlowableProcessor<Object> processor = ReplayProcessor.create(); - Flowable.error(new RuntimeException("oops")) - .materialize() - .delay(1, TimeUnit.SECONDS) - .dematerialize() - .subscribe(subject); + Flowable.error(new RuntimeException("oops")) + .materialize() + .delay(1, TimeUnit.SECONDS) + .dematerialize() + .subscribe(processor); - subject.subscribe(); - subject.materialize().blockingFirst(); + processor.subscribe(); + processor.materialize().blockingFirst(); - System.out.println("Done"); + System.out.println("Done"); + + TestHelper.assertError(errors, 0, OnErrorNotImplementedException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test diff --git a/src/test/java/io/reactivex/flowable/FlowableThrottleLastTests.java b/src/test/java/io/reactivex/flowable/FlowableThrottleLastTests.java index 2dfc9d373f..8d249e6c23 100644 --- a/src/test/java/io/reactivex/flowable/FlowableThrottleLastTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableThrottleLastTests.java @@ -29,11 +29,11 @@ public class FlowableThrottleLastTests { @Test public void testThrottle() { - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); TestScheduler s = new TestScheduler(); PublishProcessor<Integer> o = PublishProcessor.create(); - o.throttleLast(500, TimeUnit.MILLISECONDS, s).subscribe(observer); + o.throttleLast(500, TimeUnit.MILLISECONDS, s).subscribe(subscriber); // send events with simulated time increments s.advanceTimeTo(0, TimeUnit.MILLISECONDS); @@ -51,11 +51,11 @@ public void testThrottle() { s.advanceTimeTo(1501, TimeUnit.MILLISECONDS); o.onComplete(); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onNext(2); - inOrder.verify(observer).onNext(6); - inOrder.verify(observer).onNext(7); - inOrder.verify(observer).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(6); + inOrder.verify(subscriber).onNext(7); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); } } diff --git a/src/test/java/io/reactivex/flowable/FlowableThrottleWithTimeoutTests.java b/src/test/java/io/reactivex/flowable/FlowableThrottleWithTimeoutTests.java index 4635332b3c..339d7f4316 100644 --- a/src/test/java/io/reactivex/flowable/FlowableThrottleWithTimeoutTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableThrottleWithTimeoutTests.java @@ -29,12 +29,12 @@ public class FlowableThrottleWithTimeoutTests { @Test public void testThrottle() { - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); TestScheduler s = new TestScheduler(); PublishProcessor<Integer> o = PublishProcessor.create(); o.throttleWithTimeout(500, TimeUnit.MILLISECONDS, s) - .subscribe(observer); + .subscribe(subscriber); // send events with simulated time increments s.advanceTimeTo(0, TimeUnit.MILLISECONDS); @@ -52,11 +52,11 @@ public void testThrottle() { s.advanceTimeTo(1800, TimeUnit.MILLISECONDS); o.onComplete(); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onNext(2); - inOrder.verify(observer).onNext(6); - inOrder.verify(observer).onNext(7); - inOrder.verify(observer).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(6); + inOrder.verify(subscriber).onNext(7); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); } diff --git a/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java b/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java index 75918d345a..07d279d162 100644 --- a/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java @@ -15,13 +15,16 @@ import static org.junit.Assert.*; +import java.util.List; + import org.junit.Test; import io.reactivex.*; import io.reactivex.disposables.*; -import io.reactivex.exceptions.TestException; +import io.reactivex.exceptions.*; import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; +import io.reactivex.plugins.RxJavaPlugins; public class DeferredScalarObserverTest { @@ -44,20 +47,27 @@ public void onNext(Integer value) { @Test public void normal() { - TestObserver<Integer> to = new TestObserver<Integer>(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestObserver<Integer> to = new TestObserver<Integer>(); - TakeFirst source = new TakeFirst(to); + TakeFirst source = new TakeFirst(to); - source.onSubscribe(Disposables.empty()); + source.onSubscribe(Disposables.empty()); - Disposable d = Disposables.empty(); - source.onSubscribe(d); + Disposable d = Disposables.empty(); + source.onSubscribe(d); - assertTrue(d.isDisposed()); + assertTrue(d.isDisposed()); - source.onNext(1); + source.onNext(1); - to.assertResult(1); + to.assertResult(1); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -105,48 +115,62 @@ public void dispose() { @Test public void fused() { - TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.ANY); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.ANY); - TakeFirst source = new TakeFirst(to); + TakeFirst source = new TakeFirst(to); - Disposable d = Disposables.empty(); + Disposable d = Disposables.empty(); - source.onSubscribe(d); + source.onSubscribe(d); - to.assertOf(ObserverFusion.<Integer>assertFuseable()); - to.assertOf(ObserverFusion.<Integer>assertFusionMode(QueueFuseable.ASYNC)); + to.assertOf(ObserverFusion.<Integer>assertFuseable()); + to.assertOf(ObserverFusion.<Integer>assertFusionMode(QueueFuseable.ASYNC)); - source.onNext(1); - source.onNext(1); - source.onError(new TestException()); - source.onComplete(); + source.onNext(1); + source.onNext(1); + source.onError(new TestException()); + source.onComplete(); - assertTrue(d.isDisposed()); + assertTrue(d.isDisposed()); - to.assertResult(1); + to.assertResult(1); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void fusedReject() { - TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.SYNC); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.SYNC); - TakeFirst source = new TakeFirst(to); + TakeFirst source = new TakeFirst(to); - Disposable d = Disposables.empty(); + Disposable d = Disposables.empty(); - source.onSubscribe(d); + source.onSubscribe(d); - to.assertOf(ObserverFusion.<Integer>assertFuseable()); - to.assertOf(ObserverFusion.<Integer>assertFusionMode(QueueFuseable.NONE)); + to.assertOf(ObserverFusion.<Integer>assertFuseable()); + to.assertOf(ObserverFusion.<Integer>assertFusionMode(QueueFuseable.NONE)); - source.onNext(1); - source.onNext(1); - source.onError(new TestException()); - source.onComplete(); + source.onNext(1); + source.onNext(1); + source.onError(new TestException()); + source.onComplete(); - assertTrue(d.isDisposed()); + assertTrue(d.isDisposed()); - to.assertResult(1); + to.assertResult(1); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } static final class TakeLast extends DeferredScalarObserver<Integer, Integer> { @@ -167,74 +191,102 @@ public void onNext(Integer value) { @Test public void nonfusedTerminateMore() { - TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.NONE); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.NONE); - TakeLast source = new TakeLast(to); + TakeLast source = new TakeLast(to); - Disposable d = Disposables.empty(); + Disposable d = Disposables.empty(); - source.onSubscribe(d); + source.onSubscribe(d); - source.onNext(1); - source.onComplete(); - source.onComplete(); - source.onError(new TestException()); + source.onNext(1); + source.onComplete(); + source.onComplete(); + source.onError(new TestException()); - to.assertResult(1); + to.assertResult(1); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void nonfusedError() { - TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.NONE); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.NONE); - TakeLast source = new TakeLast(to); + TakeLast source = new TakeLast(to); - Disposable d = Disposables.empty(); + Disposable d = Disposables.empty(); - source.onSubscribe(d); + source.onSubscribe(d); - source.onNext(1); - source.onError(new TestException()); - source.onError(new TestException()); - source.onComplete(); + source.onNext(1); + source.onError(new TestException()); + source.onError(new TestException("second")); + source.onComplete(); - to.assertFailure(TestException.class); + to.assertFailure(TestException.class); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } } @Test public void fusedTerminateMore() { - TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.ANY); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.ANY); - TakeLast source = new TakeLast(to); + TakeLast source = new TakeLast(to); - Disposable d = Disposables.empty(); + Disposable d = Disposables.empty(); - source.onSubscribe(d); + source.onSubscribe(d); - source.onNext(1); - source.onComplete(); - source.onComplete(); - source.onError(new TestException()); + source.onNext(1); + source.onComplete(); + source.onComplete(); + source.onError(new TestException()); - to.assertResult(1); + to.assertResult(1); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void fusedError() { - TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.ANY); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.ANY); - TakeLast source = new TakeLast(to); + TakeLast source = new TakeLast(to); - Disposable d = Disposables.empty(); + Disposable d = Disposables.empty(); - source.onSubscribe(d); + source.onSubscribe(d); - source.onNext(1); - source.onError(new TestException()); - source.onError(new TestException()); - source.onComplete(); + source.onNext(1); + source.onError(new TestException()); + source.onError(new TestException("second")); + source.onComplete(); - to.assertFailure(TestException.class); + to.assertFailure(TestException.class); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } } @Test diff --git a/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java b/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java index 917a156f14..90fe6c3910 100644 --- a/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java @@ -213,83 +213,115 @@ public void run() { @Test public void onCompleteCancelRace() { - for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final FutureSubscriber<Integer> fo = new FutureSubscriber<Integer>(); - - if (i % 3 == 0) { - fo.onSubscribe(new BooleanSubscription()); - } - - if (i % 2 == 0) { - fo.onNext(1); - } + RxJavaPlugins.setErrorHandler(Functions.emptyConsumer()); + try { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final FutureSubscriber<Integer> fo = new FutureSubscriber<Integer>(); - Runnable r1 = new Runnable() { - @Override - public void run() { - fo.cancel(false); + if (i % 3 == 0) { + fo.onSubscribe(new BooleanSubscription()); } - }; - Runnable r2 = new Runnable() { - @Override - public void run() { - fo.onComplete(); + if (i % 2 == 0) { + fo.onNext(1); } - }; - TestHelper.race(r1, r2); + Runnable r1 = new Runnable() { + @Override + public void run() { + fo.cancel(false); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + fo.onComplete(); + } + }; + + TestHelper.race(r1, r2); + } + } finally { + RxJavaPlugins.reset(); } } @Test public void onErrorOnComplete() throws Exception { - fo.onError(new TestException("One")); - fo.onComplete(); - + List<Throwable> errors = TestHelper.trackPluginErrors(); try { - fo.get(5, TimeUnit.MILLISECONDS); - } catch (ExecutionException ex) { - assertTrue(ex.toString(), ex.getCause() instanceof TestException); - assertEquals("One", ex.getCause().getMessage()); + fo.onError(new TestException("One")); + fo.onComplete(); + + try { + fo.get(5, TimeUnit.MILLISECONDS); + } catch (ExecutionException ex) { + assertTrue(ex.toString(), ex.getCause() instanceof TestException); + assertEquals("One", ex.getCause().getMessage()); + } + + TestHelper.assertUndeliverable(errors, 0, NoSuchElementException.class); + } finally { + RxJavaPlugins.reset(); } } @Test public void onCompleteOnError() throws Exception { - fo.onComplete(); - fo.onError(new TestException("One")); - + List<Throwable> errors = TestHelper.trackPluginErrors(); try { - assertNull(fo.get(5, TimeUnit.MILLISECONDS)); - } catch (ExecutionException ex) { - assertTrue(ex.toString(), ex.getCause() instanceof NoSuchElementException); + fo.onComplete(); + fo.onError(new TestException("One")); + + try { + assertNull(fo.get(5, TimeUnit.MILLISECONDS)); + } catch (ExecutionException ex) { + assertTrue(ex.toString(), ex.getCause() instanceof NoSuchElementException); + } + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); } } @Test public void cancelOnError() throws Exception { - fo.cancel(true); - fo.onError(new TestException("One")); - + List<Throwable> errors = TestHelper.trackPluginErrors(); try { - fo.get(5, TimeUnit.MILLISECONDS); - fail("Should have thrown"); - } catch (CancellationException ex) { - // expected + fo.cancel(true); + fo.onError(new TestException("One")); + + try { + fo.get(5, TimeUnit.MILLISECONDS); + fail("Should have thrown"); + } catch (CancellationException ex) { + // expected + } + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); } } @Test public void cancelOnComplete() throws Exception { - fo.cancel(true); - fo.onComplete(); - + List<Throwable> errors = TestHelper.trackPluginErrors(); try { - fo.get(5, TimeUnit.MILLISECONDS); - fail("Should have thrown"); - } catch (CancellationException ex) { - // expected + fo.cancel(true); + fo.onComplete(); + + try { + fo.get(5, TimeUnit.MILLISECONDS); + fail("Should have thrown"); + } catch (CancellationException ex) { + // expected + } + + TestHelper.assertUndeliverable(errors, 0, NoSuchElementException.class); + } finally { + RxJavaPlugins.reset(); } } diff --git a/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java b/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java index cd52919537..1dc0451434 100644 --- a/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java @@ -22,6 +22,8 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; +import io.reactivex.internal.functions.Functions; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.PublishSubject; public class FutureSingleObserverTest { @@ -156,28 +158,33 @@ public void run() { @Test public void onErrorCancelRace() { - for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishSubject<Integer> ps = PublishSubject.create(); - - final Future<?> f = ps.single(-99).toFuture(); - - final TestException ex = new TestException(); - - Runnable r1 = new Runnable() { - @Override - public void run() { - f.cancel(true); - } - }; - - Runnable r2 = new Runnable() { - @Override - public void run() { - ps.onError(ex); - } - }; - - TestHelper.race(r1, r2); + RxJavaPlugins.setErrorHandler(Functions.emptyConsumer()); + try { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final PublishSubject<Integer> ps = PublishSubject.create(); + + final Future<?> f = ps.single(-99).toFuture(); + + final TestException ex = new TestException(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + f.cancel(true); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ps.onError(ex); + } + }; + + TestHelper.race(r1, r2); + } + } finally { + RxJavaPlugins.reset(); } } } diff --git a/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java b/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java index 94fe4cb4c1..3171f8e8df 100644 --- a/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java @@ -196,92 +196,106 @@ public void accept(Disposable s) throws Exception { @Test public void badSourceOnSubscribe() { - Observable<Integer> source = new Observable<Integer>() { - @Override - public void subscribeActual(Observer<? super Integer> s) { - Disposable s1 = Disposables.empty(); - s.onSubscribe(s1); - Disposable s2 = Disposables.empty(); - s.onSubscribe(s2); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Observable<Integer> source = new Observable<Integer>() { + @Override + public void subscribeActual(Observer<? super Integer> observer) { + Disposable s1 = Disposables.empty(); + observer.onSubscribe(s1); + Disposable s2 = Disposables.empty(); + observer.onSubscribe(s2); - assertFalse(s1.isDisposed()); - assertTrue(s2.isDisposed()); + assertFalse(s1.isDisposed()); + assertTrue(s2.isDisposed()); - s.onNext(1); - s.onComplete(); - } - }; + observer.onNext(1); + observer.onComplete(); + } + }; - final List<Object> received = new ArrayList<Object>(); + final List<Object> received = new ArrayList<Object>(); - LambdaObserver<Object> o = new LambdaObserver<Object>(new Consumer<Object>() { - @Override - public void accept(Object v) throws Exception { - received.add(v); - } - }, - new Consumer<Throwable>() { - @Override - public void accept(Throwable e) throws Exception { - received.add(e); - } - }, new Action() { - @Override - public void run() throws Exception { - received.add(100); - } - }, new Consumer<Disposable>() { - @Override - public void accept(Disposable s) throws Exception { - } - }); + LambdaObserver<Object> o = new LambdaObserver<Object>(new Consumer<Object>() { + @Override + public void accept(Object v) throws Exception { + received.add(v); + } + }, + new Consumer<Throwable>() { + @Override + public void accept(Throwable e) throws Exception { + received.add(e); + } + }, new Action() { + @Override + public void run() throws Exception { + received.add(100); + } + }, new Consumer<Disposable>() { + @Override + public void accept(Disposable s) throws Exception { + } + }); + + source.subscribe(o); - source.subscribe(o); + assertEquals(Arrays.asList(1, 100), received); - assertEquals(Arrays.asList(1, 100), received); + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void badSourceEmitAfterDone() { - Observable<Integer> source = new Observable<Integer>() { - @Override - public void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - - s.onNext(1); - s.onComplete(); - s.onNext(2); - s.onError(new TestException()); - s.onComplete(); - } - }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Observable<Integer> source = new Observable<Integer>() { + @Override + public void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + + observer.onNext(1); + observer.onComplete(); + observer.onNext(2); + observer.onError(new TestException()); + observer.onComplete(); + } + }; - final List<Object> received = new ArrayList<Object>(); + final List<Object> received = new ArrayList<Object>(); - LambdaObserver<Object> o = new LambdaObserver<Object>(new Consumer<Object>() { - @Override - public void accept(Object v) throws Exception { - received.add(v); - } - }, - new Consumer<Throwable>() { - @Override - public void accept(Throwable e) throws Exception { - received.add(e); - } - }, new Action() { - @Override - public void run() throws Exception { - received.add(100); - } - }, new Consumer<Disposable>() { - @Override - public void accept(Disposable s) throws Exception { - } - }); + LambdaObserver<Object> o = new LambdaObserver<Object>(new Consumer<Object>() { + @Override + public void accept(Object v) throws Exception { + received.add(v); + } + }, + new Consumer<Throwable>() { + @Override + public void accept(Throwable e) throws Exception { + received.add(e); + } + }, new Action() { + @Override + public void run() throws Exception { + received.add(100); + } + }, new Consumer<Disposable>() { + @Override + public void accept(Disposable s) throws Exception { + } + }); + + source.subscribe(o); - source.subscribe(o); + assertEquals(Arrays.asList(1, 100), received); - assertEquals(Arrays.asList(1, 100), received); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java index 218180b4a7..47c21fff85 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableConcatTest.java @@ -35,21 +35,28 @@ public class CompletableConcatTest { @Test public void overflowReported() { - Completable.concat( - Flowable.fromPublisher(new Publisher<Completable>() { - @Override - public void subscribe(Subscriber<? super Completable> s) { - s.onSubscribe(new BooleanSubscription()); - s.onNext(Completable.never()); - s.onNext(Completable.never()); - s.onNext(Completable.never()); - s.onNext(Completable.never()); - s.onComplete(); - } - }), 1 - ) - .test() - .assertFailure(MissingBackpressureException.class); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Completable.concat( + Flowable.fromPublisher(new Publisher<Completable>() { + @Override + public void subscribe(Subscriber<? super Completable> s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(Completable.never()); + s.onNext(Completable.never()); + s.onNext(Completable.never()); + s.onNext(Completable.never()); + s.onComplete(); + } + }), 1 + ) + .test() + .assertFailure(MissingBackpressureException.class); + + TestHelper.assertError(errors, 0, MissingBackpressureException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -163,10 +170,10 @@ public void arrayFirstCancels() { Completable.concatArray(new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); to.cancel(); - s.onComplete(); + observer.onComplete(); } }, Completable.complete()) .subscribe(to); @@ -187,10 +194,10 @@ public void iterableFirstCancels() { Completable.concat(Arrays.asList(new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); to.cancel(); - s.onComplete(); + observer.onComplete(); } }, Completable.complete())) .subscribe(to); diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableCreateTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableCreateTest.java index 13b64091fe..33f50adc5b 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableCreateTest.java @@ -35,70 +35,91 @@ public void nullArgument() { @Test public void basic() { - final Disposable d = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); - Completable.create(new CompletableOnSubscribe() { - @Override - public void subscribe(CompletableEmitter e) throws Exception { - e.setDisposable(d); + Completable.create(new CompletableOnSubscribe() { + @Override + public void subscribe(CompletableEmitter e) throws Exception { + e.setDisposable(d); - e.onComplete(); - e.onError(new TestException()); - e.onComplete(); - } - }) - .test() - .assertResult(); + e.onComplete(); + e.onError(new TestException()); + e.onComplete(); + } + }) + .test() + .assertResult(); + + assertTrue(d.isDisposed()); - assertTrue(d.isDisposed()); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicWithCancellable() { - final Disposable d1 = Disposables.empty(); - final Disposable d2 = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d1 = Disposables.empty(); + final Disposable d2 = Disposables.empty(); - Completable.create(new CompletableOnSubscribe() { - @Override - public void subscribe(CompletableEmitter e) throws Exception { - e.setDisposable(d1); - e.setCancellable(new Cancellable() { - @Override - public void cancel() throws Exception { - d2.dispose(); - } - }); + Completable.create(new CompletableOnSubscribe() { + @Override + public void subscribe(CompletableEmitter e) throws Exception { + e.setDisposable(d1); + e.setCancellable(new Cancellable() { + @Override + public void cancel() throws Exception { + d2.dispose(); + } + }); - e.onComplete(); - e.onError(new TestException()); - e.onComplete(); - } - }) - .test() - .assertResult(); + e.onComplete(); + e.onError(new TestException()); + e.onComplete(); + } + }) + .test() + .assertResult(); + + assertTrue(d1.isDisposed()); + assertTrue(d2.isDisposed()); - assertTrue(d1.isDisposed()); - assertTrue(d2.isDisposed()); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicWithError() { - final Disposable d = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); - Completable.create(new CompletableOnSubscribe() { - @Override - public void subscribe(CompletableEmitter e) throws Exception { - e.setDisposable(d); + Completable.create(new CompletableOnSubscribe() { + @Override + public void subscribe(CompletableEmitter e) throws Exception { + e.setDisposable(d); - e.onError(new TestException()); - e.onComplete(); - e.onError(new TestException()); - } - }) - .test() - .assertFailure(TestException.class); + e.onError(new TestException()); + e.onComplete(); + e.onError(new TestException("second")); + } + }) + .test() + .assertFailure(TestException.class); - assertTrue(d.isDisposed()); + assertTrue(d.isDisposed()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } } @Test diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableDoOnTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableDoOnTest.java index b2082c96d5..91f904ce56 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableDoOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableDoOnTest.java @@ -85,10 +85,10 @@ public void onSubscribeCrash() { new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(bs); - s.onError(new TestException("Second")); - s.onComplete(); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(bs); + observer.onError(new TestException("Second")); + observer.onComplete(); } } .doOnSubscribe(new Consumer<Disposable>() { diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableLiftTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableLiftTest.java index 39e7cd1935..da78bc0bcf 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableLiftTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableLiftTest.java @@ -13,16 +13,19 @@ package io.reactivex.internal.operators.completable; -import static org.junit.Assert.*; +import java.util.List; + import org.junit.Test; import io.reactivex.*; import io.reactivex.exceptions.TestException; +import io.reactivex.plugins.RxJavaPlugins; public class CompletableLiftTest { @Test public void callbackThrows() { + List<Throwable> errors = TestHelper.trackPluginErrors(); try { Completable.complete() .lift(new CompletableOperator() { @@ -32,8 +35,10 @@ public CompletableObserver apply(CompletableObserver o) throws Exception { } }) .test(); - } catch (NullPointerException ex) { - assertTrue(ex.toString(), ex.getCause() instanceof TestException); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); } } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeTest.java index d386969ad9..588dda88f9 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableMergeTest.java @@ -46,9 +46,9 @@ public void cancelAfterFirst() { Completable.mergeArray(new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); - s.onComplete(); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); to.cancel(); } }, Completable.complete()) @@ -63,9 +63,9 @@ public void cancelAfterFirstDelayError() { Completable.mergeArrayDelayError(new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); - s.onComplete(); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); to.cancel(); } }, Completable.complete()) @@ -82,10 +82,10 @@ public void onErrorAfterComplete() { Completable.mergeArrayDelayError(Completable.complete(), new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); - s.onComplete(); - co[0] = s; + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); + co[0] = observer; } }) .test() @@ -408,10 +408,10 @@ public void innerDoubleOnError() { final CompletableObserver[] o = { null }; Completable.mergeDelayError(Flowable.just(new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); - s.onError(new TestException("First")); - o[0] = s; + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); + observer.onError(new TestException("First")); + o[0] = observer; } })) .test() @@ -431,13 +431,13 @@ public void innerIsDisposed() { Completable.mergeDelayError(Flowable.just(new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); - assertFalse(((Disposable)s).isDisposed()); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); + assertFalse(((Disposable)observer).isDisposed()); to.dispose(); - assertTrue(((Disposable)s).isDisposed()); + assertTrue(((Disposable)observer).isDisposed()); } })) .subscribe(to); diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableTakeUntilTest.java index 586e0c3207..abf64f32f0 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableTakeUntilTest.java @@ -143,9 +143,9 @@ public void mainErrorLate() { new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); - s.onError(new TestException()); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); + observer.onError(new TestException()); } }.takeUntil(Completable.complete()) .test() @@ -165,9 +165,9 @@ public void mainCompleteLate() { new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); - s.onComplete(); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); } }.takeUntil(Completable.complete()) .test() @@ -190,9 +190,9 @@ public void otherErrorLate() { Completable.complete() .takeUntil(new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); - ref.set(s); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); } }) .test() @@ -217,9 +217,9 @@ public void otherCompleteLate() { Completable.complete() .takeUntil(new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); - ref.set(s); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); + ref.set(observer); } }) .test() diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableUnsafeTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableUnsafeTest.java index ed2ec31e9f..518e81c3a9 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableUnsafeTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableUnsafeTest.java @@ -14,10 +14,14 @@ package io.reactivex.internal.operators.completable; import static org.junit.Assert.*; + +import java.util.List; + import org.junit.Test; import io.reactivex.*; import io.reactivex.disposables.Disposables; +import io.reactivex.plugins.RxJavaPlugins; public class CompletableUnsafeTest { @@ -36,9 +40,9 @@ public void wrapCustomCompletable() { Completable.wrap(new CompletableSource() { @Override - public void subscribe(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); - s.onComplete(); + public void subscribe(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); } }) .test() @@ -49,7 +53,7 @@ public void subscribe(CompletableObserver s) { public void unsafeCreateThrowsNPE() { Completable.unsafeCreate(new CompletableSource() { @Override - public void subscribe(CompletableObserver s) { + public void subscribe(CompletableObserver observer) { throw new NullPointerException(); } }).test(); @@ -57,10 +61,11 @@ public void subscribe(CompletableObserver s) { @Test public void unsafeCreateThrowsIAE() { + List<Throwable> errors = TestHelper.trackPluginErrors(); try { Completable.unsafeCreate(new CompletableSource() { @Override - public void subscribe(CompletableObserver s) { + public void subscribe(CompletableObserver observer) { throw new IllegalArgumentException(); } }).test(); @@ -69,6 +74,10 @@ public void subscribe(CompletableObserver s) { if (!(ex.getCause() instanceof IllegalArgumentException)) { fail(ex.toString() + ": should have thrown NPA(IAE)"); } + + TestHelper.assertError(errors, 0, IllegalArgumentException.class); + } finally { + RxJavaPlugins.reset(); } } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java index 30c1965120..598abdd29c 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java @@ -24,6 +24,7 @@ import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.PublishSubject; @@ -410,14 +411,14 @@ public Object call() throws Exception { public CompletableSource apply(Object v) throws Exception { return Completable.wrap(new CompletableSource() { @Override - public void subscribe(CompletableObserver s) { + public void subscribe(CompletableObserver observer) { Disposable d1 = Disposables.empty(); - s.onSubscribe(d1); + observer.onSubscribe(d1); Disposable d2 = Disposables.empty(); - s.onSubscribe(d2); + observer.onSubscribe(d2); assertFalse(d1.isDisposed()); @@ -482,44 +483,49 @@ public void run() { @Test public void errorDisposeRace() { - for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - - final PublishSubject<Integer> ps = PublishSubject.create(); - - final TestObserver<Void> to = Completable.using(new Callable<Object>() { - @Override - public Object call() throws Exception { - return 1; - } - }, new Function<Object, CompletableSource>() { - @Override - public CompletableSource apply(Object v) throws Exception { - return ps.ignoreElements(); - } - }, new Consumer<Object>() { - @Override - public void accept(Object d) throws Exception { - } - }, true) - .test(); - - final TestException ex = new TestException(); - - Runnable r1 = new Runnable() { - @Override - public void run() { - to.cancel(); - } - }; - - Runnable r2 = new Runnable() { - @Override - public void run() { - ps.onError(ex); - } - }; - - TestHelper.race(r1, r2); + RxJavaPlugins.setErrorHandler(Functions.emptyConsumer()); + try { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final PublishSubject<Integer> ps = PublishSubject.create(); + + final TestObserver<Void> to = Completable.using(new Callable<Object>() { + @Override + public Object call() throws Exception { + return 1; + } + }, new Function<Object, CompletableSource>() { + @Override + public CompletableSource apply(Object v) throws Exception { + return ps.ignoreElements(); + } + }, new Consumer<Object>() { + @Override + public void accept(Object d) throws Exception { + } + }, true) + .test(); + + final TestException ex = new TestException(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ps.onError(ex); + } + }; + + TestHelper.race(r1, r2); + } + } finally { + RxJavaPlugins.reset(); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/AbstractFlowableWithUpstreamTest.java b/src/test/java/io/reactivex/internal/operators/flowable/AbstractFlowableWithUpstreamTest.java index c3ade57ce8..d1d6a0b5d3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/AbstractFlowableWithUpstreamTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/AbstractFlowableWithUpstreamTest.java @@ -26,8 +26,8 @@ public class AbstractFlowableWithUpstreamTest { @SuppressWarnings("unchecked") @Test public void source() { - Flowable<Integer> o = Flowable.just(1); + Flowable<Integer> f = Flowable.just(1); - assertSame(o, ((HasUpstreamPublisher<Integer>)o.map(Functions.<Integer>identity())).source()); + assertSame(f, ((HasUpstreamPublisher<Integer>)f.map(Functions.<Integer>identity())).source()); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableNextTest.java b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableNextTest.java index 356355ab46..32ee150cf3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableNextTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableNextTest.java @@ -241,20 +241,20 @@ public void testNoBufferingOrBlockingOfSequence() throws Throwable { final Flowable<Integer> obs = Flowable.unsafeCreate(new Publisher<Integer>() { @Override - public void subscribe(final Subscriber<? super Integer> o) { - o.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); task.replace(Schedulers.single().scheduleDirect(new Runnable() { @Override public void run() { try { while (running.get() && !task.isDisposed()) { - o.onNext(count.incrementAndGet()); + subscriber.onNext(count.incrementAndGet()); timeHasPassed.countDown(); } - o.onComplete(); + subscriber.onComplete(); } catch (Throwable e) { - o.onError(e); + subscriber.onError(e); } finally { finished.countDown(); } @@ -308,9 +308,9 @@ public void run() { @Test /* (timeout = 8000) */ public void testSingleSourceManyIterators() throws InterruptedException { - Flowable<Long> o = Flowable.interval(250, TimeUnit.MILLISECONDS); + Flowable<Long> f = Flowable.interval(250, TimeUnit.MILLISECONDS); PublishProcessor<Integer> terminal = PublishProcessor.create(); - Flowable<Long> source = o.takeUntil(terminal); + Flowable<Long> source = f.takeUntil(terminal); Iterable<Long> iter = source.blockingNext(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToFutureTest.java b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToFutureTest.java index 87752f2b11..d90b0b2f43 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToFutureTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToFutureTest.java @@ -69,10 +69,10 @@ public void testToFutureWithException() { Flowable<String> obs = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext("one"); - observer.onError(new TestException()); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext("one"); + subscriber.onError(new TestException()); } }); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java index 239aed218d..412d59ac5f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java @@ -51,10 +51,10 @@ public void testToIteratorWithException() { Flowable<String> obs = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext("one"); - observer.onError(new TestException()); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext("one"); + subscriber.onError(new TestException()); } }); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java index 9f578b2d2d..7ab08915d2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java @@ -114,8 +114,8 @@ public boolean test(String s) { @Test public void testFollowingFirst() { - Flowable<Integer> o = Flowable.fromArray(1, 3, 5, 6); - Single<Boolean> allOdd = o.all(new Predicate<Integer>() { + Flowable<Integer> f = Flowable.fromArray(1, 3, 5, 6); + Single<Boolean> allOdd = f.all(new Predicate<Integer>() { @Override public boolean test(Integer i) { return i % 2 == 1; @@ -203,7 +203,7 @@ public boolean test(String v) { public void testAllFlowable() { Flowable<String> obs = Flowable.just("one", "two", "six"); - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); obs.all(new Predicate<String>() { @Override @@ -212,19 +212,19 @@ public boolean test(String s) { } }) .toFlowable() - .subscribe(observer); + .subscribe(subscriber); - verify(observer).onSubscribe((Subscription)any()); - verify(observer).onNext(true); - verify(observer).onComplete(); - verifyNoMoreInteractions(observer); + verify(subscriber).onSubscribe((Subscription)any()); + verify(subscriber).onNext(true); + verify(subscriber).onComplete(); + verifyNoMoreInteractions(subscriber); } @Test public void testNotAllFlowable() { Flowable<String> obs = Flowable.just("one", "two", "three", "six"); - Subscriber <Boolean> observer = TestHelper.mockSubscriber(); + Subscriber <Boolean> subscriber = TestHelper.mockSubscriber(); obs.all(new Predicate<String>() { @Override @@ -233,19 +233,19 @@ public boolean test(String s) { } }) .toFlowable() - .subscribe(observer); + .subscribe(subscriber); - verify(observer).onSubscribe((Subscription)any()); - verify(observer).onNext(false); - verify(observer).onComplete(); - verifyNoMoreInteractions(observer); + verify(subscriber).onSubscribe((Subscription)any()); + verify(subscriber).onNext(false); + verify(subscriber).onComplete(); + verifyNoMoreInteractions(subscriber); } @Test public void testEmptyFlowable() { Flowable<String> obs = Flowable.empty(); - Subscriber <Boolean> observer = TestHelper.mockSubscriber(); + Subscriber <Boolean> subscriber = TestHelper.mockSubscriber(); obs.all(new Predicate<String>() { @Override @@ -254,12 +254,12 @@ public boolean test(String s) { } }) .toFlowable() - .subscribe(observer); + .subscribe(subscriber); - verify(observer).onSubscribe((Subscription)any()); - verify(observer).onNext(true); - verify(observer).onComplete(); - verifyNoMoreInteractions(observer); + verify(subscriber).onSubscribe((Subscription)any()); + verify(subscriber).onNext(true); + verify(subscriber).onComplete(); + verifyNoMoreInteractions(subscriber); } @Test @@ -267,7 +267,7 @@ public void testErrorFlowable() { Throwable error = new Throwable(); Flowable<String> obs = Flowable.error(error); - Subscriber <Boolean> observer = TestHelper.mockSubscriber(); + Subscriber <Boolean> subscriber = TestHelper.mockSubscriber(); obs.all(new Predicate<String>() { @Override @@ -276,17 +276,17 @@ public boolean test(String s) { } }) .toFlowable() - .subscribe(observer); + .subscribe(subscriber); - verify(observer).onSubscribe((Subscription)any()); - verify(observer).onError(error); - verifyNoMoreInteractions(observer); + verify(subscriber).onSubscribe((Subscription)any()); + verify(subscriber).onError(error); + verifyNoMoreInteractions(subscriber); } @Test public void testFollowingFirstFlowable() { - Flowable<Integer> o = Flowable.fromArray(1, 3, 5, 6); - Flowable<Boolean> allOdd = o.all(new Predicate<Integer>() { + Flowable<Integer> f = Flowable.fromArray(1, 3, 5, 6); + Flowable<Boolean> allOdd = f.all(new Predicate<Integer>() { @Override public boolean test(Integer i) { return i % 2 == 1; @@ -391,13 +391,13 @@ public void predicateThrows() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onNext(2); - observer.onError(new TestException()); - observer.onComplete(); + subscriber.onNext(1); + subscriber.onNext(2); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .all(new Predicate<Integer>() { @@ -422,13 +422,13 @@ public void predicateThrowsObservable() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onNext(2); - observer.onError(new TestException()); - observer.onComplete(); + subscriber.onNext(1); + subscriber.onNext(2); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .all(new Predicate<Integer>() { @@ -451,15 +451,15 @@ public boolean test(Integer v) throws Exception { public void badSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(Flowable<Integer> o) throws Exception { - return o.all(Functions.alwaysTrue()); + public Object apply(Flowable<Integer> f) throws Exception { + return f.all(Functions.alwaysTrue()); } }, false, 1, 1, true); TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(Flowable<Integer> o) throws Exception { - return o.all(Functions.alwaysTrue()).toFlowable(); + public Object apply(Flowable<Integer> f) throws Exception { + return f.all(Functions.alwaysTrue()).toFlowable(); } }, false, 1, 1, true); } @@ -468,14 +468,14 @@ public Object apply(Flowable<Integer> o) throws Exception { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<Boolean>>() { @Override - public Publisher<Boolean> apply(Flowable<Object> o) throws Exception { - return o.all(Functions.alwaysTrue()).toFlowable(); + public Publisher<Boolean> apply(Flowable<Object> f) throws Exception { + return f.all(Functions.alwaysTrue()).toFlowable(); } }); TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function<Flowable<Object>, Single<Boolean>>() { @Override - public Single<Boolean> apply(Flowable<Object> o) throws Exception { - return o.all(Functions.alwaysTrue()); + public Single<Boolean> apply(Flowable<Object> f) throws Exception { + return f.all(Functions.alwaysTrue()); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java index 839d04e3e1..9e68ec3948 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java @@ -102,21 +102,20 @@ public void testAmb() { "3", "33", "333", "3333" }, 3000, null); @SuppressWarnings("unchecked") - Flowable<String> o = Flowable.ambArray(flowable1, + Flowable<String> f = Flowable.ambArray(flowable1, flowable2, flowable3); - @SuppressWarnings("unchecked") - DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); - o.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + f.subscribe(subscriber); scheduler.advanceTimeBy(100000, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("2"); - inOrder.verify(observer, times(1)).onNext("22"); - inOrder.verify(observer, times(1)).onNext("222"); - inOrder.verify(observer, times(1)).onNext("2222"); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("2"); + inOrder.verify(subscriber, times(1)).onNext("22"); + inOrder.verify(subscriber, times(1)).onNext("222"); + inOrder.verify(subscriber, times(1)).onNext("2222"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -132,21 +131,20 @@ public void testAmb2() { 3000, new IOException("fake exception")); @SuppressWarnings("unchecked") - Flowable<String> o = Flowable.ambArray(flowable1, + Flowable<String> f = Flowable.ambArray(flowable1, flowable2, flowable3); - @SuppressWarnings("unchecked") - DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); - o.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + f.subscribe(subscriber); scheduler.advanceTimeBy(100000, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("2"); - inOrder.verify(observer, times(1)).onNext("22"); - inOrder.verify(observer, times(1)).onNext("222"); - inOrder.verify(observer, times(1)).onNext("2222"); - inOrder.verify(observer, times(1)).onError(expectedException); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("2"); + inOrder.verify(subscriber, times(1)).onNext("22"); + inOrder.verify(subscriber, times(1)).onNext("222"); + inOrder.verify(subscriber, times(1)).onNext("2222"); + inOrder.verify(subscriber, times(1)).onError(expectedException); inOrder.verifyNoMoreInteractions(); } @@ -160,16 +158,15 @@ public void testAmb3() { "3" }, 3000, null); @SuppressWarnings("unchecked") - Flowable<String> o = Flowable.ambArray(flowable1, + Flowable<String> f = Flowable.ambArray(flowable1, flowable2, flowable3); - @SuppressWarnings("unchecked") - DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); - o.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + f.subscribe(subscriber); scheduler.advanceTimeBy(100000, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -180,7 +177,7 @@ public void testProducerRequestThroughAmb() { ts.request(3); final AtomicLong requested1 = new AtomicLong(); final AtomicLong requested2 = new AtomicLong(); - Flowable<Integer> o1 = Flowable.unsafeCreate(new Publisher<Integer>() { + Flowable<Integer> f1 = Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { @@ -200,7 +197,7 @@ public void cancel() { } }); - Flowable<Integer> o2 = Flowable.unsafeCreate(new Publisher<Integer>() { + Flowable<Integer> f2 = Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { @@ -220,7 +217,7 @@ public void cancel() { } }); - Flowable.ambArray(o1, o2).subscribe(ts); + Flowable.ambArray(f1, f2).subscribe(ts); assertEquals(3, requested1.get()); assertEquals(3, requested2.get()); } @@ -252,13 +249,13 @@ public void accept(Subscription s) { }; //this aync stream should emit first - Flowable<Integer> o1 = Flowable.just(1).doOnSubscribe(incrementer) + Flowable<Integer> f1 = Flowable.just(1).doOnSubscribe(incrementer) .delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation()); //this stream emits second - Flowable<Integer> o2 = Flowable.just(1).doOnSubscribe(incrementer) + Flowable<Integer> f2 = Flowable.just(1).doOnSubscribe(incrementer) .delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation()); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); - Flowable.ambArray(o1, o2).subscribe(ts); + Flowable.ambArray(f1, f2).subscribe(ts); ts.request(1); ts.awaitTerminalEvent(5, TimeUnit.SECONDS); ts.assertNoErrors(); @@ -269,14 +266,14 @@ public void accept(Subscription s) { @Test public void testSecondaryRequestsPropagatedToChildren() throws InterruptedException { //this aync stream should emit first - Flowable<Integer> o1 = Flowable.fromArray(1, 2, 3) + Flowable<Integer> f1 = Flowable.fromArray(1, 2, 3) .delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation()); //this stream emits second - Flowable<Integer> o2 = Flowable.fromArray(4, 5, 6) + Flowable<Integer> f2 = Flowable.fromArray(4, 5, 6) .delay(200, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation()); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(1L); - Flowable.ambArray(o1, o2).subscribe(ts); + Flowable.ambArray(f1, f2).subscribe(ts); // before first emission request 20 more // this request should suffice to emit all ts.request(20); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java index 90d05f7ac1..76bd59591a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java @@ -38,7 +38,7 @@ public class FlowableAnyTest { @Test public void testAnyWithTwoItems() { Flowable<Integer> w = Flowable.just(1, 2); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer v) { return true; @@ -47,7 +47,7 @@ public boolean test(Integer v) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(false); verify(observer, times(1)).onSuccess(true); @@ -57,11 +57,11 @@ public boolean test(Integer v) { @Test public void testIsEmptyWithTwoItems() { Flowable<Integer> w = Flowable.just(1, 2); - Single<Boolean> observable = w.isEmpty(); + Single<Boolean> single = w.isEmpty(); SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(true); verify(observer, times(1)).onSuccess(false); @@ -71,7 +71,7 @@ public void testIsEmptyWithTwoItems() { @Test public void testAnyWithOneItem() { Flowable<Integer> w = Flowable.just(1); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer v) { return true; @@ -80,7 +80,7 @@ public boolean test(Integer v) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(false); verify(observer, times(1)).onSuccess(true); @@ -90,11 +90,11 @@ public boolean test(Integer v) { @Test public void testIsEmptyWithOneItem() { Flowable<Integer> w = Flowable.just(1); - Single<Boolean> observable = w.isEmpty(); + Single<Boolean> single = w.isEmpty(); SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(true); verify(observer, times(1)).onSuccess(false); @@ -104,7 +104,7 @@ public void testIsEmptyWithOneItem() { @Test public void testAnyWithEmpty() { Flowable<Integer> w = Flowable.empty(); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer v) { return true; @@ -113,7 +113,7 @@ public boolean test(Integer v) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(false); verify(observer, never()).onSuccess(true); @@ -123,11 +123,11 @@ public boolean test(Integer v) { @Test public void testIsEmptyWithEmpty() { Flowable<Integer> w = Flowable.empty(); - Single<Boolean> observable = w.isEmpty(); + Single<Boolean> single = w.isEmpty(); SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(true); verify(observer, never()).onSuccess(false); @@ -137,7 +137,7 @@ public void testIsEmptyWithEmpty() { @Test public void testAnyWithPredicate1() { Flowable<Integer> w = Flowable.just(1, 2, 3); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t1) { return t1 < 2; @@ -146,7 +146,7 @@ public boolean test(Integer t1) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(false); verify(observer, times(1)).onSuccess(true); @@ -156,7 +156,7 @@ public boolean test(Integer t1) { @Test public void testExists1() { Flowable<Integer> w = Flowable.just(1, 2, 3); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t1) { return t1 < 2; @@ -165,7 +165,7 @@ public boolean test(Integer t1) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(false); verify(observer, times(1)).onSuccess(true); @@ -175,7 +175,7 @@ public boolean test(Integer t1) { @Test public void testAnyWithPredicate2() { Flowable<Integer> w = Flowable.just(1, 2, 3); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t1) { return t1 < 1; @@ -184,7 +184,7 @@ public boolean test(Integer t1) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(false); verify(observer, never()).onSuccess(true); @@ -195,7 +195,7 @@ public boolean test(Integer t1) { public void testAnyWithEmptyAndPredicate() { // If the source is empty, always output false. Flowable<Integer> w = Flowable.empty(); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t) { return true; @@ -204,7 +204,7 @@ public boolean test(Integer t) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(false); verify(observer, never()).onSuccess(true); @@ -213,8 +213,8 @@ public boolean test(Integer t) { @Test public void testWithFollowingFirst() { - Flowable<Integer> o = Flowable.fromArray(1, 3, 5, 6); - Single<Boolean> anyEven = o.any(new Predicate<Integer>() { + Flowable<Integer> f = Flowable.fromArray(1, 3, 5, 6); + Single<Boolean> anyEven = f.any(new Predicate<Integer>() { @Override public boolean test(Integer i) { return i % 2 == 0; @@ -293,7 +293,7 @@ public boolean test(String v) { @Test public void testAnyWithTwoItemsFlowable() { Flowable<Integer> w = Flowable.just(1, 2); - Flowable<Boolean> observable = w.any(new Predicate<Integer>() { + Flowable<Boolean> flowable = w.any(new Predicate<Integer>() { @Override public boolean test(Integer v) { return true; @@ -302,59 +302,59 @@ public boolean test(Integer v) { .toFlowable() ; - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, never()).onNext(false); - verify(observer, times(1)).onNext(true); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onNext(false); + verify(subscriber, times(1)).onNext(true); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testIsEmptyWithTwoItemsFlowable() { Flowable<Integer> w = Flowable.just(1, 2); - Flowable<Boolean> observable = w.isEmpty().toFlowable(); + Flowable<Boolean> flowable = w.isEmpty().toFlowable(); - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, never()).onNext(true); - verify(observer, times(1)).onNext(false); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onNext(true); + verify(subscriber, times(1)).onNext(false); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testAnyWithOneItemFlowable() { Flowable<Integer> w = Flowable.just(1); - Flowable<Boolean> observable = w.any(new Predicate<Integer>() { + Flowable<Boolean> flowable = w.any(new Predicate<Integer>() { @Override public boolean test(Integer v) { return true; } }).toFlowable(); - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, never()).onNext(false); - verify(observer, times(1)).onNext(true); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onNext(false); + verify(subscriber, times(1)).onNext(true); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testIsEmptyWithOneItemFlowable() { Flowable<Integer> w = Flowable.just(1); - Single<Boolean> observable = w.isEmpty(); + Single<Boolean> single = w.isEmpty(); SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(true); verify(observer, times(1)).onSuccess(false); @@ -364,123 +364,123 @@ public void testIsEmptyWithOneItemFlowable() { @Test public void testAnyWithEmptyFlowable() { Flowable<Integer> w = Flowable.empty(); - Flowable<Boolean> observable = w.any(new Predicate<Integer>() { + Flowable<Boolean> flowable = w.any(new Predicate<Integer>() { @Override public boolean test(Integer v) { return true; } }).toFlowable(); - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext(false); - verify(observer, never()).onNext(true); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(false); + verify(subscriber, never()).onNext(true); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testIsEmptyWithEmptyFlowable() { Flowable<Integer> w = Flowable.empty(); - Flowable<Boolean> observable = w.isEmpty().toFlowable(); + Flowable<Boolean> flowable = w.isEmpty().toFlowable(); - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext(true); - verify(observer, never()).onNext(false); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(true); + verify(subscriber, never()).onNext(false); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testAnyWithPredicate1Flowable() { Flowable<Integer> w = Flowable.just(1, 2, 3); - Flowable<Boolean> observable = w.any(new Predicate<Integer>() { + Flowable<Boolean> flowable = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t1) { return t1 < 2; } }).toFlowable(); - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, never()).onNext(false); - verify(observer, times(1)).onNext(true); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onNext(false); + verify(subscriber, times(1)).onNext(true); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testExists1Flowable() { Flowable<Integer> w = Flowable.just(1, 2, 3); - Flowable<Boolean> observable = w.any(new Predicate<Integer>() { + Flowable<Boolean> flowable = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t1) { return t1 < 2; } }).toFlowable(); - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, never()).onNext(false); - verify(observer, times(1)).onNext(true); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onNext(false); + verify(subscriber, times(1)).onNext(true); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testAnyWithPredicate2Flowable() { Flowable<Integer> w = Flowable.just(1, 2, 3); - Flowable<Boolean> observable = w.any(new Predicate<Integer>() { + Flowable<Boolean> flowable = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t1) { return t1 < 1; } }).toFlowable(); - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext(false); - verify(observer, never()).onNext(true); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(false); + verify(subscriber, never()).onNext(true); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testAnyWithEmptyAndPredicateFlowable() { // If the source is empty, always output false. Flowable<Integer> w = Flowable.empty(); - Flowable<Boolean> observable = w.any(new Predicate<Integer>() { + Flowable<Boolean> flowable = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t) { return true; } }).toFlowable(); - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext(false); - verify(observer, never()).onNext(true); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(false); + verify(subscriber, never()).onNext(true); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testWithFollowingFirstFlowable() { - Flowable<Integer> o = Flowable.fromArray(1, 3, 5, 6); - Flowable<Boolean> anyEven = o.any(new Predicate<Integer>() { + Flowable<Integer> f = Flowable.fromArray(1, 3, 5, 6); + Flowable<Boolean> anyEven = f.any(new Predicate<Integer>() { @Override public boolean test(Integer i) { return i % 2 == 0; @@ -566,15 +566,15 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<Boolean>>() { @Override - public Publisher<Boolean> apply(Flowable<Object> o) throws Exception { - return o.any(Functions.alwaysTrue()).toFlowable(); + public Publisher<Boolean> apply(Flowable<Object> f) throws Exception { + return f.any(Functions.alwaysTrue()).toFlowable(); } }); TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function<Flowable<Object>, Single<Boolean>>() { @Override - public Single<Boolean> apply(Flowable<Object> o) throws Exception { - return o.any(Functions.alwaysTrue()); + public Single<Boolean> apply(Flowable<Object> f) throws Exception { + return f.any(Functions.alwaysTrue()); } }); } @@ -585,13 +585,13 @@ public void predicateThrowsSuppressOthers() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onNext(2); - observer.onError(new IOException()); - observer.onComplete(); + subscriber.onNext(1); + subscriber.onNext(2); + subscriber.onError(new IOException()); + subscriber.onComplete(); } } .any(new Predicate<Integer>() { @@ -616,13 +616,13 @@ public void badSourceSingle() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onError(new TestException("First")); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onError(new TestException("First")); - observer.onNext(1); - observer.onError(new TestException("Second")); - observer.onComplete(); + subscriber.onNext(1); + subscriber.onError(new TestException("Second")); + subscriber.onComplete(); } } .any(Functions.alwaysTrue()) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java index ad90e3a15c..23cf4ecf02 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java @@ -14,15 +14,16 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.assertFalse; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import org.junit.Test; +import org.mockito.Mockito; import org.reactivestreams.Subscriber; import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.processors.PublishProcessor; -import io.reactivex.subscribers.DefaultSubscriber; public class FlowableAsObservableTest { @Test @@ -33,16 +34,16 @@ public void testHiding() { assertFalse(dst instanceof PublishProcessor); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - dst.subscribe(o); + dst.subscribe(subscriber); src.onNext(1); src.onComplete(); - verify(o).onNext(1); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(1); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testHidingError() { @@ -52,15 +53,14 @@ public void testHidingError() { assertFalse(dst instanceof PublishProcessor); - @SuppressWarnings("unchecked") - DefaultSubscriber<Object> o = mock(DefaultSubscriber.class); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - dst.subscribe(o); + dst.subscribe(subscriber); src.onError(new TestException()); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onNext(Mockito.<Integer>any()); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java index 88fa5e11cb..2ed817df9a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java @@ -489,9 +489,9 @@ public void run() { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - s[0] = observer; + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + s[0] = subscriber; } }.blockingSubscribe(ts); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index c8c75031bc..aa8c3ef23c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -42,13 +42,13 @@ public class FlowableBufferTest { - private Subscriber<List<String>> observer; + private Subscriber<List<String>> subscriber; private TestScheduler scheduler; private Scheduler.Worker innerScheduler; @Before public void before() { - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); scheduler = new TestScheduler(); innerScheduler = scheduler.createWorker(); } @@ -58,37 +58,37 @@ public void testComplete() { Flowable<String> source = Flowable.empty(); Flowable<List<String>> buffered = source.buffer(3, 3); - buffered.subscribe(observer); + buffered.subscribe(subscriber); - Mockito.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); - Mockito.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); - Mockito.verify(observer, Mockito.times(1)).onComplete(); + Mockito.verify(subscriber, Mockito.never()).onNext(Mockito.<String>anyList()); + Mockito.verify(subscriber, Mockito.never()).onError(Mockito.any(Throwable.class)); + Mockito.verify(subscriber, Mockito.times(1)).onComplete(); } @Test public void testSkipAndCountOverlappingBuffers() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext("one"); - observer.onNext("two"); - observer.onNext("three"); - observer.onNext("four"); - observer.onNext("five"); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext("one"); + subscriber.onNext("two"); + subscriber.onNext("three"); + subscriber.onNext("four"); + subscriber.onNext("five"); } }); Flowable<List<String>> buffered = source.buffer(3, 1); - buffered.subscribe(observer); + buffered.subscribe(subscriber); - InOrder inOrder = Mockito.inOrder(observer); - inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two", "three")); - inOrder.verify(observer, Mockito.times(1)).onNext(list("two", "three", "four")); - inOrder.verify(observer, Mockito.times(1)).onNext(list("three", "four", "five")); - inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); - inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); - inOrder.verify(observer, Mockito.never()).onComplete(); + InOrder inOrder = Mockito.inOrder(subscriber); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("one", "two", "three")); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("two", "three", "four")); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("three", "four", "five")); + inOrder.verify(subscriber, Mockito.never()).onNext(Mockito.<String>anyList()); + inOrder.verify(subscriber, Mockito.never()).onError(Mockito.any(Throwable.class)); + inOrder.verify(subscriber, Mockito.never()).onComplete(); } @Test @@ -96,14 +96,14 @@ public void testSkipAndCountGaplessBuffers() { Flowable<String> source = Flowable.just("one", "two", "three", "four", "five"); Flowable<List<String>> buffered = source.buffer(3, 3); - buffered.subscribe(observer); + buffered.subscribe(subscriber); - InOrder inOrder = Mockito.inOrder(observer); - inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two", "three")); - inOrder.verify(observer, Mockito.times(1)).onNext(list("four", "five")); - inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); - inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); - inOrder.verify(observer, Mockito.times(1)).onComplete(); + InOrder inOrder = Mockito.inOrder(subscriber); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("one", "two", "three")); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("four", "five")); + inOrder.verify(subscriber, Mockito.never()).onNext(Mockito.<String>anyList()); + inOrder.verify(subscriber, Mockito.never()).onError(Mockito.any(Throwable.class)); + inOrder.verify(subscriber, Mockito.times(1)).onComplete(); } @Test @@ -111,104 +111,104 @@ public void testSkipAndCountBuffersWithGaps() { Flowable<String> source = Flowable.just("one", "two", "three", "four", "five"); Flowable<List<String>> buffered = source.buffer(2, 3); - buffered.subscribe(observer); + buffered.subscribe(subscriber); - InOrder inOrder = Mockito.inOrder(observer); - inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two")); - inOrder.verify(observer, Mockito.times(1)).onNext(list("four", "five")); - inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); - inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); - inOrder.verify(observer, Mockito.times(1)).onComplete(); + InOrder inOrder = Mockito.inOrder(subscriber); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("one", "two")); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("four", "five")); + inOrder.verify(subscriber, Mockito.never()).onNext(Mockito.<String>anyList()); + inOrder.verify(subscriber, Mockito.never()).onError(Mockito.any(Throwable.class)); + inOrder.verify(subscriber, Mockito.times(1)).onComplete(); } @Test public void testTimedAndCount() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, "one", 10); - push(observer, "two", 90); - push(observer, "three", 110); - push(observer, "four", 190); - push(observer, "five", 210); - complete(observer, 250); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, "one", 10); + push(subscriber, "two", 90); + push(subscriber, "three", 110); + push(subscriber, "four", 190); + push(subscriber, "five", 210); + complete(subscriber, 250); } }); Flowable<List<String>> buffered = source.buffer(100, TimeUnit.MILLISECONDS, scheduler, 2); - buffered.subscribe(observer); + buffered.subscribe(subscriber); - InOrder inOrder = Mockito.inOrder(observer); + InOrder inOrder = Mockito.inOrder(subscriber); scheduler.advanceTimeTo(100, TimeUnit.MILLISECONDS); - inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two")); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("one", "two")); scheduler.advanceTimeTo(200, TimeUnit.MILLISECONDS); - inOrder.verify(observer, Mockito.times(1)).onNext(list("three", "four")); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("three", "four")); scheduler.advanceTimeTo(300, TimeUnit.MILLISECONDS); - inOrder.verify(observer, Mockito.times(1)).onNext(list("five")); - inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); - inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); - inOrder.verify(observer, Mockito.times(1)).onComplete(); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("five")); + inOrder.verify(subscriber, Mockito.never()).onNext(Mockito.<String>anyList()); + inOrder.verify(subscriber, Mockito.never()).onError(Mockito.any(Throwable.class)); + inOrder.verify(subscriber, Mockito.times(1)).onComplete(); } @Test public void testTimed() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, "one", 97); - push(observer, "two", 98); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, "one", 97); + push(subscriber, "two", 98); /** * Changed from 100. Because scheduling the cut to 100ms happens before this * Flowable even runs due how lift works, pushing at 100ms would execute after the * buffer cut. */ - push(observer, "three", 99); - push(observer, "four", 101); - push(observer, "five", 102); - complete(observer, 150); + push(subscriber, "three", 99); + push(subscriber, "four", 101); + push(subscriber, "five", 102); + complete(subscriber, 150); } }); Flowable<List<String>> buffered = source.buffer(100, TimeUnit.MILLISECONDS, scheduler); - buffered.subscribe(observer); + buffered.subscribe(subscriber); - InOrder inOrder = Mockito.inOrder(observer); + InOrder inOrder = Mockito.inOrder(subscriber); scheduler.advanceTimeTo(101, TimeUnit.MILLISECONDS); - inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two", "three")); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("one", "two", "three")); scheduler.advanceTimeTo(201, TimeUnit.MILLISECONDS); - inOrder.verify(observer, Mockito.times(1)).onNext(list("four", "five")); - inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); - inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); - inOrder.verify(observer, Mockito.times(1)).onComplete(); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("four", "five")); + inOrder.verify(subscriber, Mockito.never()).onNext(Mockito.<String>anyList()); + inOrder.verify(subscriber, Mockito.never()).onError(Mockito.any(Throwable.class)); + inOrder.verify(subscriber, Mockito.times(1)).onComplete(); } @Test public void testFlowableBasedOpenerAndCloser() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, "one", 10); - push(observer, "two", 60); - push(observer, "three", 110); - push(observer, "four", 160); - push(observer, "five", 210); - complete(observer, 500); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, "one", 10); + push(subscriber, "two", 60); + push(subscriber, "three", 110); + push(subscriber, "four", 160); + push(subscriber, "five", 210); + complete(subscriber, 500); } }); Flowable<Object> openings = Flowable.unsafeCreate(new Publisher<Object>() { @Override - public void subscribe(Subscriber<Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, new Object(), 50); - push(observer, new Object(), 200); - complete(observer, 250); + public void subscribe(Subscriber<Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, new Object(), 50); + push(subscriber, new Object(), 200); + complete(subscriber, 250); } }); @@ -217,39 +217,39 @@ public void subscribe(Subscriber<Object> observer) { public Flowable<Object> apply(Object opening) { return Flowable.unsafeCreate(new Publisher<Object>() { @Override - public void subscribe(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, new Object(), 100); - complete(observer, 101); + public void subscribe(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, new Object(), 100); + complete(subscriber, 101); } }); } }; Flowable<List<String>> buffered = source.buffer(openings, closer); - buffered.subscribe(observer); + buffered.subscribe(subscriber); - InOrder inOrder = Mockito.inOrder(observer); + InOrder inOrder = Mockito.inOrder(subscriber); scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS); - inOrder.verify(observer, Mockito.times(1)).onNext(list("two", "three")); - inOrder.verify(observer, Mockito.times(1)).onNext(list("five")); - inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); - inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); - inOrder.verify(observer, Mockito.times(1)).onComplete(); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("two", "three")); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("five")); + inOrder.verify(subscriber, Mockito.never()).onNext(Mockito.<String>anyList()); + inOrder.verify(subscriber, Mockito.never()).onError(Mockito.any(Throwable.class)); + inOrder.verify(subscriber, Mockito.times(1)).onComplete(); } @Test public void testFlowableBasedCloser() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, "one", 10); - push(observer, "two", 60); - push(observer, "three", 110); - push(observer, "four", 160); - push(observer, "five", 210); - complete(observer, 250); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, "one", 10); + push(subscriber, "two", 60); + push(subscriber, "three", 110); + push(subscriber, "four", 160); + push(subscriber, "five", 210); + complete(subscriber, 250); } }); @@ -258,28 +258,28 @@ public void subscribe(Subscriber<? super String> observer) { public Flowable<Object> call() { return Flowable.unsafeCreate(new Publisher<Object>() { @Override - public void subscribe(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, new Object(), 100); - push(observer, new Object(), 200); - push(observer, new Object(), 300); - complete(observer, 301); + public void subscribe(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, new Object(), 100); + push(subscriber, new Object(), 200); + push(subscriber, new Object(), 300); + complete(subscriber, 301); } }); } }; Flowable<List<String>> buffered = source.buffer(closer); - buffered.subscribe(observer); + buffered.subscribe(subscriber); - InOrder inOrder = Mockito.inOrder(observer); + InOrder inOrder = Mockito.inOrder(subscriber); scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS); - inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two")); - inOrder.verify(observer, Mockito.times(1)).onNext(list("three", "four")); - inOrder.verify(observer, Mockito.times(1)).onNext(list("five")); - inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); - inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); - inOrder.verify(observer, Mockito.times(1)).onComplete(); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("one", "two")); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("three", "four")); + inOrder.verify(subscriber, Mockito.times(1)).onNext(list("five")); + inOrder.verify(subscriber, Mockito.never()).onNext(Mockito.<String>anyList()); + inOrder.verify(subscriber, Mockito.never()).onError(Mockito.any(Throwable.class)); + inOrder.verify(subscriber, Mockito.times(1)).onComplete(); } @Test @@ -324,20 +324,20 @@ private List<String> list(String... args) { return list; } - private <T> void push(final Subscriber<T> observer, final T value, int delay) { + private <T> void push(final Subscriber<T> subscriber, final T value, int delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onNext(value); + subscriber.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } - private void complete(final Subscriber<?> observer, int delay) { + private void complete(final Subscriber<?> subscriber, int delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onComplete(); + subscriber.onComplete(); } }, delay, TimeUnit.MILLISECONDS); } @@ -346,8 +346,8 @@ public void run() { public void testBufferStopsWhenUnsubscribed1() { Flowable<Integer> source = Flowable.never(); - Subscriber<List<Integer>> o = TestHelper.mockSubscriber(); - TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>(o, 0L); + Subscriber<List<Integer>> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>(subscriber, 0L); source.buffer(100, 200, TimeUnit.MILLISECONDS, scheduler) .doOnNext(new Consumer<List<Integer>>() { @@ -358,11 +358,11 @@ public void accept(List<Integer> pv) { }) .subscribe(ts); - InOrder inOrder = Mockito.inOrder(o); + InOrder inOrder = Mockito.inOrder(subscriber); scheduler.advanceTimeBy(1001, TimeUnit.MILLISECONDS); - inOrder.verify(o, times(5)).onNext(Arrays.<Integer> asList()); + inOrder.verify(subscriber, times(5)).onNext(Arrays.<Integer> asList()); ts.dispose(); @@ -376,10 +376,10 @@ public void bufferWithBONormal1() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = Mockito.inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = Mockito.inOrder(subscriber); - source.buffer(boundary).subscribe(o); + source.buffer(boundary).subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -387,23 +387,23 @@ public void bufferWithBONormal1() { boundary.onNext(1); - inOrder.verify(o, times(1)).onNext(Arrays.asList(1, 2, 3)); + inOrder.verify(subscriber, times(1)).onNext(Arrays.asList(1, 2, 3)); source.onNext(4); source.onNext(5); boundary.onNext(2); - inOrder.verify(o, times(1)).onNext(Arrays.asList(4, 5)); + inOrder.verify(subscriber, times(1)).onNext(Arrays.asList(4, 5)); source.onNext(6); boundary.onComplete(); - inOrder.verify(o, times(1)).onNext(Arrays.asList(6)); + inOrder.verify(subscriber, times(1)).onNext(Arrays.asList(6)); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -411,18 +411,18 @@ public void bufferWithBOEmptyLastViaBoundary() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = Mockito.inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = Mockito.inOrder(subscriber); - source.buffer(boundary).subscribe(o); + source.buffer(boundary).subscribe(subscriber); boundary.onComplete(); - inOrder.verify(o, times(1)).onNext(Arrays.asList()); + inOrder.verify(subscriber, times(1)).onNext(Arrays.asList()); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -430,18 +430,18 @@ public void bufferWithBOEmptyLastViaSource() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = Mockito.inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = Mockito.inOrder(subscriber); - source.buffer(boundary).subscribe(o); + source.buffer(boundary).subscribe(subscriber); source.onComplete(); - inOrder.verify(o, times(1)).onNext(Arrays.asList()); + inOrder.verify(subscriber, times(1)).onNext(Arrays.asList()); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -449,19 +449,19 @@ public void bufferWithBOEmptyLastViaBoth() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = Mockito.inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = Mockito.inOrder(subscriber); - source.buffer(boundary).subscribe(o); + source.buffer(boundary).subscribe(subscriber); source.onComplete(); boundary.onComplete(); - inOrder.verify(o, times(1)).onNext(Arrays.asList()); + inOrder.verify(subscriber, times(1)).onNext(Arrays.asList()); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -469,15 +469,15 @@ public void bufferWithBOSourceThrows() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.buffer(boundary).subscribe(o); + source.buffer(boundary).subscribe(subscriber); source.onNext(1); source.onError(new TestException()); - verify(o).onError(any(TestException.class)); - verify(o, never()).onComplete(); - verify(o, never()).onNext(any()); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -485,16 +485,16 @@ public void bufferWithBOBoundaryThrows() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.buffer(boundary).subscribe(o); + source.buffer(boundary).subscribe(subscriber); source.onNext(1); boundary.onError(new TestException()); - verify(o).onError(any(TestException.class)); - verify(o, never()).onComplete(); - verify(o, never()).onNext(any()); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test(timeout = 2000) public void bufferWithSizeTake1() { @@ -502,13 +502,13 @@ public void bufferWithSizeTake1() { Flowable<List<Integer>> result = source.buffer(2).take(1); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(Arrays.asList(1, 1)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1, 1)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) @@ -517,13 +517,13 @@ public void bufferWithSizeSkipTake1() { Flowable<List<Integer>> result = source.buffer(2, 3).take(1); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(Arrays.asList(1, 1)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1, 1)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) public void bufferWithTimeTake1() { @@ -531,15 +531,15 @@ public void bufferWithTimeTake1() { Flowable<List<Long>> result = source.buffer(100, TimeUnit.MILLISECONDS, scheduler).take(1); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); - verify(o).onNext(Arrays.asList(0L, 1L)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(0L, 1L)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) public void bufferWithTimeSkipTake2() { @@ -547,18 +547,19 @@ public void bufferWithTimeSkipTake2() { Flowable<List<Long>> result = source.buffer(100, 60, TimeUnit.MILLISECONDS, scheduler).take(2); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); - inOrder.verify(o).onNext(Arrays.asList(0L, 1L)); - inOrder.verify(o).onNext(Arrays.asList(1L, 2L)); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(Arrays.asList(0L, 1L)); + inOrder.verify(subscriber).onNext(Arrays.asList(1L, 2L)); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } + @Test(timeout = 2000) public void bufferWithBoundaryTake2() { Flowable<Long> boundary = Flowable.interval(60, 60, TimeUnit.MILLISECONDS, scheduler); @@ -566,17 +567,17 @@ public void bufferWithBoundaryTake2() { Flowable<List<Long>> result = source.buffer(boundary).take(2); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); - inOrder.verify(o).onNext(Arrays.asList(0L)); - inOrder.verify(o).onNext(Arrays.asList(1L)); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(Arrays.asList(0L)); + inOrder.verify(subscriber).onNext(Arrays.asList(1L)); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @@ -594,8 +595,8 @@ public Flowable<Long> apply(Long t1) { Flowable<List<Long>> result = source.buffer(start, end).take(2); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); result .doOnNext(new Consumer<List<Long>>() { @@ -604,14 +605,14 @@ public void accept(List<Long> pv) { System.out.println(pv); } }) - .subscribe(o); + .subscribe(subscriber); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); - inOrder.verify(o).onNext(Arrays.asList(1L, 2L, 3L)); - inOrder.verify(o).onNext(Arrays.asList(3L, 4L)); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(Arrays.asList(1L, 2L, 3L)); + inOrder.verify(subscriber).onNext(Arrays.asList(3L, 4L)); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithSizeThrows() { @@ -619,22 +620,22 @@ public void bufferWithSizeThrows() { Flowable<List<Integer>> result = source.buffer(2); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); source.onNext(3); source.onError(new TestException()); - inOrder.verify(o).onNext(Arrays.asList(1, 2)); - inOrder.verify(o).onError(any(TestException.class)); + inOrder.verify(subscriber).onNext(Arrays.asList(1, 2)); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(Arrays.asList(3)); - verify(o, never()).onComplete(); + verify(subscriber, never()).onNext(Arrays.asList(3)); + verify(subscriber, never()).onComplete(); } @@ -644,10 +645,10 @@ public void bufferWithTimeThrows() { Flowable<List<Integer>> result = source.buffer(100, TimeUnit.MILLISECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -656,11 +657,11 @@ public void bufferWithTimeThrows() { source.onError(new TestException()); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - inOrder.verify(o).onNext(Arrays.asList(1, 2)); - inOrder.verify(o).onError(any(TestException.class)); + inOrder.verify(subscriber).onNext(Arrays.asList(1, 2)); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(Arrays.asList(3)); - verify(o, never()).onComplete(); + verify(subscriber, never()).onNext(Arrays.asList(3)); + verify(subscriber, never()).onComplete(); } @@ -670,17 +671,17 @@ public void bufferWithTimeAndSize() { Flowable<List<Long>> result = source.buffer(100, TimeUnit.MILLISECONDS, scheduler, 2).take(3); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); - inOrder.verify(o).onNext(Arrays.asList(0L, 1L)); - inOrder.verify(o).onNext(Arrays.asList(2L)); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(Arrays.asList(0L, 1L)); + inOrder.verify(subscriber).onNext(Arrays.asList(2L)); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithStartEndStartThrows() { @@ -697,18 +698,18 @@ public Flowable<Integer> apply(Integer t1) { Flowable<List<Integer>> result = source.buffer(start, end); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); start.onNext(1); source.onNext(1); source.onNext(2); start.onError(new TestException()); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); } @Test public void bufferWithStartEndEndFunctionThrows() { @@ -725,17 +726,17 @@ public Flowable<Integer> apply(Integer t1) { Flowable<List<Integer>> result = source.buffer(start, end); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); start.onNext(1); source.onNext(1); source.onNext(2); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); } @Test public void bufferWithStartEndEndThrows() { @@ -752,17 +753,17 @@ public Flowable<Integer> apply(Integer t1) { Flowable<List<Integer>> result = source.buffer(start, end); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); start.onNext(1); source.onNext(1); source.onNext(2); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); } @Test @@ -992,22 +993,22 @@ public void onNext(List<Integer> t) { } @Test(timeout = 3000) public void testBufferWithTimeDoesntUnsubscribeDownstream() throws InterruptedException { - final Subscriber<Object> o = TestHelper.mockSubscriber(); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); final CountDownLatch cdl = new CountDownLatch(1); ResourceSubscriber<Object> s = new ResourceSubscriber<Object>() { @Override public void onNext(Object t) { - o.onNext(t); + subscriber.onNext(t); } @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); cdl.countDown(); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); cdl.countDown(); } }; @@ -1016,9 +1017,9 @@ public void onComplete() { cdl.await(); - verify(o).onNext(Arrays.asList(1)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); assertFalse(s.isDisposed()); } @@ -2480,20 +2481,20 @@ public List<Integer> call() throws Exception { public void bufferExactBoundaryBadSource() { Flowable<Integer> pp = new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onComplete(); - observer.onNext(1); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); + subscriber.onNext(1); + subscriber.onComplete(); } }; final AtomicReference<Subscriber<? super Integer>> ref = new AtomicReference<Subscriber<? super Integer>>(); Flowable<Integer> b = new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - ref.set(observer); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + ref.set(subscriber); } }; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java index 2524d5eb28..c26e612e09 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java @@ -84,19 +84,19 @@ public void testColdReplayBackpressure() { @Test public void testCache() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); - Flowable<String> o = Flowable.unsafeCreate(new Publisher<String>() { + Flowable<String> f = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); System.out.println("published observable being executed"); - observer.onNext("one"); - observer.onComplete(); + subscriber.onNext("one"); + subscriber.onComplete(); } }).start(); } @@ -106,7 +106,7 @@ public void run() { final CountDownLatch latch = new CountDownLatch(2); // subscribe once - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { assertEquals("one", v); @@ -116,7 +116,7 @@ public void accept(String v) { }); // subscribe again - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { assertEquals("one", v); @@ -134,10 +134,10 @@ public void accept(String v) { @Test public void testUnsubscribeSource() throws Exception { Action unsubscribe = mock(Action.class); - Flowable<Integer> o = Flowable.just(1).doOnCancel(unsubscribe).cache(); - o.subscribe(); - o.subscribe(); - o.subscribe(); + Flowable<Integer> f = Flowable.just(1).doOnCancel(unsubscribe).cache(); + f.subscribe(); + f.subscribe(); + f.subscribe(); verify(unsubscribe, times(1)).run(); } @@ -305,11 +305,11 @@ public void dispose() { @Test public void disposeOnArrival2() { - Flowable<Integer> o = PublishProcessor.<Integer>create().cache(); + Flowable<Integer> f = PublishProcessor.<Integer>create().cache(); - o.test(); + f.test(); - o.test(0L, true) + f.test(0L, true) .assertEmpty(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCastTest.java index 370f32d18a..4506f67afe 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCastTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCastTest.java @@ -27,30 +27,28 @@ public class FlowableCastTest { @Test public void testCast() { Flowable<?> source = Flowable.just(1, 2); - Flowable<Integer> observable = source.cast(Integer.class); + Flowable<Integer> flowable = source.cast(Integer.class); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext(1); - verify(observer, times(1)).onNext(1); - verify(observer, never()).onError( - any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(1); + verify(subscriber, times(1)).onNext(1); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testCastWithWrongType() { Flowable<?> source = Flowable.just(1, 2); - Flowable<Boolean> observable = source.cast(Boolean.class); + Flowable<Boolean> flowable = source.cast(Boolean.class); - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onError( - any(ClassCastException.class)); + verify(subscriber, times(1)).onError(any(ClassCastException.class)); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java index dd95488500..0599234015 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java @@ -178,16 +178,16 @@ public void testCombineLatest2Types() { BiFunction<String, Integer, String> combineLatestFunction = getConcatStringIntegerCombineLatestFunction(); /* define an Observer to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> w = Flowable.combineLatest(Flowable.just("one", "two"), Flowable.just(2, 3, 4), combineLatestFunction); - w.subscribe(observer); + w.subscribe(subscriber); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("two2"); - verify(observer, times(1)).onNext("two3"); - verify(observer, times(1)).onNext("two4"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("two2"); + verify(subscriber, times(1)).onNext("two3"); + verify(subscriber, times(1)).onNext("two4"); } @Test @@ -195,14 +195,14 @@ public void testCombineLatest3TypesA() { Function3<String, Integer, int[], String> combineLatestFunction = getConcatStringIntegerIntArrayCombineLatestFunction(); /* define an Observer to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> w = Flowable.combineLatest(Flowable.just("one", "two"), Flowable.just(2), Flowable.just(new int[] { 4, 5, 6 }), combineLatestFunction); - w.subscribe(observer); + w.subscribe(subscriber); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("two2[4, 5, 6]"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("two2[4, 5, 6]"); } @Test @@ -210,15 +210,15 @@ public void testCombineLatest3TypesB() { Function3<String, Integer, int[], String> combineLatestFunction = getConcatStringIntegerIntArrayCombineLatestFunction(); /* define an Observer to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> w = Flowable.combineLatest(Flowable.just("one"), Flowable.just(2), Flowable.just(new int[] { 4, 5, 6 }, new int[] { 7, 8 }), combineLatestFunction); - w.subscribe(observer); + w.subscribe(subscriber); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("one2[4, 5, 6]"); - verify(observer, times(1)).onNext("one2[7, 8]"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one2[4, 5, 6]"); + verify(subscriber, times(1)).onNext("one2[7, 8]"); } private Function3<String, String, String, String> getConcat3StringsCombineLatestFunction() { @@ -285,33 +285,33 @@ public void combineSimple() { Flowable<Integer> source = Flowable.combineLatest(a, b, or); - Subscriber<Object> observer = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.subscribe(observer); + source.subscribe(subscriber); a.onNext(1); - inOrder.verify(observer, never()).onNext(any()); + inOrder.verify(subscriber, never()).onNext(any()); a.onNext(2); - inOrder.verify(observer, never()).onNext(any()); + inOrder.verify(subscriber, never()).onNext(any()); b.onNext(0x10); - inOrder.verify(observer, times(1)).onNext(0x12); + inOrder.verify(subscriber, times(1)).onNext(0x12); b.onNext(0x20); - inOrder.verify(observer, times(1)).onNext(0x22); + inOrder.verify(subscriber, times(1)).onNext(0x22); b.onComplete(); - inOrder.verify(observer, never()).onComplete(); + inOrder.verify(subscriber, never()).onComplete(); a.onComplete(); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); a.onNext(3); b.onNext(0x30); @@ -319,7 +319,7 @@ public void combineSimple() { b.onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -329,44 +329,44 @@ public void combineMultipleObservers() { Flowable<Integer> source = Flowable.combineLatest(a, b, or); - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); - Subscriber<Object> observer2 = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber2 = TestHelper.mockSubscriber(); - InOrder inOrder1 = inOrder(observer1); - InOrder inOrder2 = inOrder(observer2); + InOrder inOrder1 = inOrder(subscriber1); + InOrder inOrder2 = inOrder(subscriber2); - source.subscribe(observer1); - source.subscribe(observer2); + source.subscribe(subscriber1); + source.subscribe(subscriber2); a.onNext(1); - inOrder1.verify(observer1, never()).onNext(any()); - inOrder2.verify(observer2, never()).onNext(any()); + inOrder1.verify(subscriber1, never()).onNext(any()); + inOrder2.verify(subscriber2, never()).onNext(any()); a.onNext(2); - inOrder1.verify(observer1, never()).onNext(any()); - inOrder2.verify(observer2, never()).onNext(any()); + inOrder1.verify(subscriber1, never()).onNext(any()); + inOrder2.verify(subscriber2, never()).onNext(any()); b.onNext(0x10); - inOrder1.verify(observer1, times(1)).onNext(0x12); - inOrder2.verify(observer2, times(1)).onNext(0x12); + inOrder1.verify(subscriber1, times(1)).onNext(0x12); + inOrder2.verify(subscriber2, times(1)).onNext(0x12); b.onNext(0x20); - inOrder1.verify(observer1, times(1)).onNext(0x22); - inOrder2.verify(observer2, times(1)).onNext(0x22); + inOrder1.verify(subscriber1, times(1)).onNext(0x22); + inOrder2.verify(subscriber2, times(1)).onNext(0x22); b.onComplete(); - inOrder1.verify(observer1, never()).onComplete(); - inOrder2.verify(observer2, never()).onComplete(); + inOrder1.verify(subscriber1, never()).onComplete(); + inOrder2.verify(subscriber2, never()).onComplete(); a.onComplete(); - inOrder1.verify(observer1, times(1)).onComplete(); - inOrder2.verify(observer2, times(1)).onComplete(); + inOrder1.verify(subscriber1, times(1)).onComplete(); + inOrder2.verify(subscriber2, times(1)).onComplete(); a.onNext(3); b.onNext(0x30); @@ -375,8 +375,8 @@ public void combineMultipleObservers() { inOrder1.verifyNoMoreInteractions(); inOrder2.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); - verify(observer2, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); + verify(subscriber2, never()).onError(any(Throwable.class)); } @Test @@ -386,19 +386,19 @@ public void testFirstNeverProduces() { Flowable<Integer> source = Flowable.combineLatest(a, b, or); - Subscriber<Object> observer = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.subscribe(observer); + source.subscribe(subscriber); b.onNext(0x10); b.onNext(0x20); a.onComplete(); - inOrder.verify(observer, times(1)).onComplete(); - verify(observer, never()).onNext(any()); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -408,10 +408,10 @@ public void testSecondNeverProduces() { Flowable<Integer> source = Flowable.combineLatest(a, b, or); - Subscriber<Object> observer = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.subscribe(observer); + source.subscribe(subscriber); a.onNext(0x1); a.onNext(0x2); @@ -419,9 +419,9 @@ public void testSecondNeverProduces() { b.onComplete(); a.onComplete(); - inOrder.verify(observer, times(1)).onComplete(); - verify(observer, never()).onNext(any()); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } public void test0Sources() { @@ -449,13 +449,13 @@ public List<Object> apply(Object[] args) { Flowable<List<Object>> result = Flowable.combineLatest(sources, func); - Subscriber<List<Object>> o = TestHelper.mockSubscriber(); + Subscriber<List<Object>> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(values); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(values); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } } @@ -480,7 +480,7 @@ public List<Object> apply(Object[] args) { Flowable<List<Object>> result = Flowable.combineLatest(sources, func); - final Subscriber<List<Object>> o = TestHelper.mockSubscriber(); + final Subscriber<List<Object>> subscriber = TestHelper.mockSubscriber(); final CountDownLatch cdl = new CountDownLatch(1); @@ -488,18 +488,18 @@ public List<Object> apply(Object[] args) { @Override public void onNext(List<Object> t) { - o.onNext(t); + subscriber.onNext(t); } @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); cdl.countDown(); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); cdl.countDown(); } }; @@ -508,9 +508,9 @@ public void onComplete() { cdl.await(); - verify(o).onNext(values); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(values); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } } @@ -527,13 +527,13 @@ public List<Integer> apply(Integer t1, Integer t2) { } }); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(Arrays.asList(1, 2)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1, 2)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -550,13 +550,13 @@ public List<Integer> apply(Integer t1, Integer t2, Integer t3) { } }); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(Arrays.asList(1, 2, 3)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1, 2, 3)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -574,13 +574,13 @@ public List<Integer> apply(Integer t1, Integer t2, Integer t3, Integer t4) { } }); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(Arrays.asList(1, 2, 3, 4)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1, 2, 3, 4)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -599,13 +599,13 @@ public List<Integer> apply(Integer t1, Integer t2, Integer t3, Integer t4, Integ } }); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(Arrays.asList(1, 2, 3, 4, 5)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1, 2, 3, 4, 5)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -625,13 +625,13 @@ public List<Integer> apply(Integer t1, Integer t2, Integer t3, Integer t4, Integ } }); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(Arrays.asList(1, 2, 3, 4, 5, 6)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1, 2, 3, 4, 5, 6)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -652,13 +652,13 @@ public List<Integer> apply(Integer t1, Integer t2, Integer t3, Integer t4, Integ } }); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -680,13 +680,13 @@ public List<Integer> apply(Integer t1, Integer t2, Integer t3, Integer t4, Integ } }); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -709,13 +709,13 @@ public List<Integer> apply(Integer t1, Integer t2, Integer t3, Integer t4, Integ } }); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -730,13 +730,13 @@ public Object apply(Object[] args) { }); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onComplete(); - verify(o, never()).onNext(any()); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @@ -808,14 +808,14 @@ public void testCombineLatestRequestOverflow() throws InterruptedException { @SuppressWarnings("unchecked") List<Flowable<Integer>> sources = Arrays.asList(Flowable.fromArray(1, 2, 3, 4), Flowable.fromArray(5,6,7,8)); - Flowable<Integer> o = Flowable.combineLatest(sources,new Function<Object[], Integer>() { + Flowable<Integer> f = Flowable.combineLatest(sources,new Function<Object[], Integer>() { @Override public Integer apply(Object[] args) { return (Integer) args[0]; }}); //should get at least 4 final CountDownLatch latch = new CountDownLatch(4); - o.subscribeOn(Schedulers.computation()).subscribe(new DefaultSubscriber<Integer>() { + f.subscribeOn(Schedulers.computation()).subscribe(new DefaultSubscriber<Integer>() { @Override public void onStart() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java index 90c0c59691..39a9427181 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java @@ -588,11 +588,11 @@ public Flowable<Integer> apply(Integer t) { @Test public void testReentrantWork() { - final PublishProcessor<Integer> subject = PublishProcessor.create(); + final PublishProcessor<Integer> processor = PublishProcessor.create(); final AtomicBoolean once = new AtomicBoolean(); - subject.concatMapEager(new Function<Integer, Flowable<Integer>>() { + processor.concatMapEager(new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer t) { return Flowable.just(t); @@ -602,13 +602,13 @@ public Flowable<Integer> apply(Integer t) { @Override public void accept(Integer t) { if (once.compareAndSet(false, true)) { - subject.onNext(2); + processor.onNext(2); } } }) .subscribe(ts); - subject.onNext(1); + processor.onNext(1); ts.assertNoErrors(); ts.assertNotComplete(); @@ -1051,8 +1051,8 @@ public Flowable<Integer> apply(Integer v) throws Exception { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.concatMapEager(new Function<Object, Flowable<Object>>() { + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.concatMapEager(new Function<Object, Flowable<Object>>() { @Override public Flowable<Object> apply(Object v) throws Exception { return Flowable.just(v); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java index 82c8765f85..7c53083548 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java @@ -41,7 +41,7 @@ public class FlowableConcatTest { @Test public void testConcat() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); final String[] o = { "1", "3", "5", "7" }; final String[] e = { "2", "4", "6" }; @@ -50,14 +50,14 @@ public void testConcat() { final Flowable<String> even = Flowable.fromArray(e); Flowable<String> concat = Flowable.concat(odds, even); - concat.subscribe(observer); + concat.subscribe(subscriber); - verify(observer, times(7)).onNext(anyString()); + verify(subscriber, times(7)).onNext(anyString()); } @Test public void testConcatWithList() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); final String[] o = { "1", "3", "5", "7" }; final String[] e = { "2", "4", "6" }; @@ -68,14 +68,14 @@ public void testConcatWithList() { list.add(odds); list.add(even); Flowable<String> concat = Flowable.concat(Flowable.fromIterable(list)); - concat.subscribe(observer); + concat.subscribe(subscriber); - verify(observer, times(7)).onNext(anyString()); + verify(subscriber, times(7)).onNext(anyString()); } @Test public void testConcatObservableOfObservables() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); final String[] o = { "1", "3", "5", "7" }; final String[] e = { "2", "4", "6" }; @@ -83,23 +83,23 @@ public void testConcatObservableOfObservables() { final Flowable<String> odds = Flowable.fromArray(o); final Flowable<String> even = Flowable.fromArray(e); - Flowable<Flowable<String>> observableOfObservables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { + Flowable<Flowable<String>> flowableOfFlowables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); // simulate what would happen in an observable - observer.onNext(odds); - observer.onNext(even); - observer.onComplete(); + subscriber.onNext(odds); + subscriber.onNext(even); + subscriber.onComplete(); } }); - Flowable<String> concat = Flowable.concat(observableOfObservables); + Flowable<String> concat = Flowable.concat(flowableOfFlowables); - concat.subscribe(observer); + concat.subscribe(subscriber); - verify(observer, times(7)).onNext(anyString()); + verify(subscriber, times(7)).onNext(anyString()); } /** @@ -107,12 +107,12 @@ public void subscribe(Subscriber<? super Flowable<String>> observer) { */ @Test public void testSimpleAsyncConcat() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); TestObservable<String> o1 = new TestObservable<String>("one", "two", "three"); TestObservable<String> o2 = new TestObservable<String>("four", "five", "six"); - Flowable.concat(Flowable.unsafeCreate(o1), Flowable.unsafeCreate(o2)).subscribe(observer); + Flowable.concat(Flowable.unsafeCreate(o1), Flowable.unsafeCreate(o2)).subscribe(subscriber); try { // wait for async observables to complete @@ -122,13 +122,13 @@ public void testSimpleAsyncConcat() { throw new RuntimeException("failed waiting on threads"); } - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("one"); - inOrder.verify(observer, times(1)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - inOrder.verify(observer, times(1)).onNext("four"); - inOrder.verify(observer, times(1)).onNext("five"); - inOrder.verify(observer, times(1)).onNext("six"); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("one"); + inOrder.verify(subscriber, times(1)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + inOrder.verify(subscriber, times(1)).onNext("four"); + inOrder.verify(subscriber, times(1)).onNext("five"); + inOrder.verify(subscriber, times(1)).onNext("six"); } @Test @@ -147,7 +147,7 @@ public void testNestedAsyncConcatLoop() throws Throwable { */ @Test public void testNestedAsyncConcat() throws InterruptedException { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); final TestObservable<String> o1 = new TestObservable<String>("one", "two", "three"); final TestObservable<String> o2 = new TestObservable<String>("four", "five", "six"); @@ -162,9 +162,9 @@ public void testNestedAsyncConcat() throws InterruptedException { Flowable<Flowable<String>> observableOfObservables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(final Subscriber<? super Flowable<String>> observer) { + public void subscribe(final Subscriber<? super Flowable<String>> subscriber) { final Disposable d = Disposables.empty(); - observer.onSubscribe(new Subscription() { + subscriber.onSubscribe(new Subscription() { @Override public void request(long n) { @@ -182,30 +182,30 @@ public void run() { // emit first if (!d.isDisposed()) { System.out.println("Emit o1"); - observer.onNext(Flowable.unsafeCreate(o1)); + subscriber.onNext(Flowable.unsafeCreate(o1)); } // emit second if (!d.isDisposed()) { System.out.println("Emit o2"); - observer.onNext(Flowable.unsafeCreate(o2)); + subscriber.onNext(Flowable.unsafeCreate(o2)); } // wait until sometime later and emit third try { allowThird.await(); } catch (InterruptedException e) { - observer.onError(e); + subscriber.onError(e); } if (!d.isDisposed()) { System.out.println("Emit o3"); - observer.onNext(Flowable.unsafeCreate(o3)); + subscriber.onNext(Flowable.unsafeCreate(o3)); } } catch (Throwable e) { - observer.onError(e); + subscriber.onError(e); } finally { System.out.println("Done parent Flowable"); - observer.onComplete(); + subscriber.onComplete(); parentHasFinished.countDown(); } } @@ -215,7 +215,7 @@ public void run() { } }); - Flowable.concat(observableOfObservables).subscribe(observer); + Flowable.concat(observableOfObservables).subscribe(subscriber); // wait for parent to start parentHasStarted.await(); @@ -230,20 +230,20 @@ public void run() { throw new RuntimeException("failed waiting on threads", e); } - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("one"); - inOrder.verify(observer, times(1)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - inOrder.verify(observer, times(1)).onNext("four"); - inOrder.verify(observer, times(1)).onNext("five"); - inOrder.verify(observer, times(1)).onNext("six"); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("one"); + inOrder.verify(subscriber, times(1)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + inOrder.verify(subscriber, times(1)).onNext("four"); + inOrder.verify(subscriber, times(1)).onNext("five"); + inOrder.verify(subscriber, times(1)).onNext("six"); // we shouldn't have the following 3 yet - inOrder.verify(observer, never()).onNext("seven"); - inOrder.verify(observer, never()).onNext("eight"); - inOrder.verify(observer, never()).onNext("nine"); + inOrder.verify(subscriber, never()).onNext("seven"); + inOrder.verify(subscriber, never()).onNext("eight"); + inOrder.verify(subscriber, never()).onNext("nine"); // we should not be completed yet - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); // now allow the third allowThird.countDown(); @@ -264,17 +264,17 @@ public void run() { throw new RuntimeException("failed waiting on threads", e); } - inOrder.verify(observer, times(1)).onNext("seven"); - inOrder.verify(observer, times(1)).onNext("eight"); - inOrder.verify(observer, times(1)).onNext("nine"); + inOrder.verify(subscriber, times(1)).onNext("seven"); + inOrder.verify(subscriber, times(1)).onNext("eight"); + inOrder.verify(subscriber, times(1)).onNext("nine"); - verify(observer, never()).onError(any(Throwable.class)); - inOrder.verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onComplete(); } @Test public void testBlockedObservableOfObservables() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); final String[] o = { "1", "3", "5", "7" }; final String[] e = { "2", "4", "6" }; @@ -285,7 +285,7 @@ public void testBlockedObservableOfObservables() { @SuppressWarnings("unchecked") TestObservable<Flowable<String>> observableOfObservables = new TestObservable<Flowable<String>>(callOnce, okToContinue, odds, even); Flowable<String> concatF = Flowable.concat(Flowable.unsafeCreate(observableOfObservables)); - concatF.subscribe(observer); + concatF.subscribe(subscriber); try { //Block main thread to allow observables to serve up o1. callOnce.await(); @@ -294,10 +294,10 @@ public void testBlockedObservableOfObservables() { fail(ex.getMessage()); } // The concated observable should have served up all of the odds. - verify(observer, times(1)).onNext("1"); - verify(observer, times(1)).onNext("3"); - verify(observer, times(1)).onNext("5"); - verify(observer, times(1)).onNext("7"); + verify(subscriber, times(1)).onNext("1"); + verify(subscriber, times(1)).onNext("3"); + verify(subscriber, times(1)).onNext("5"); + verify(subscriber, times(1)).onNext("7"); try { // unblock observables so it can serve up o2 and complete @@ -308,9 +308,9 @@ public void testBlockedObservableOfObservables() { fail(ex.getMessage()); } // The concatenated observable should now have served up all the evens. - verify(observer, times(1)).onNext("2"); - verify(observer, times(1)).onNext("4"); - verify(observer, times(1)).onNext("6"); + verify(subscriber, times(1)).onNext("2"); + verify(subscriber, times(1)).onNext("4"); + verify(subscriber, times(1)).onNext("6"); } @Test @@ -319,13 +319,13 @@ public void testConcatConcurrentWithInfinity() { //This observable will send "hello" MAX_VALUE time. final TestObservable<String> w2 = new TestObservable<String>("hello", Integer.MAX_VALUE); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); @SuppressWarnings("unchecked") TestObservable<Flowable<String>> observableOfObservables = new TestObservable<Flowable<String>>(Flowable.unsafeCreate(w1), Flowable.unsafeCreate(w2)); Flowable<String> concatF = Flowable.concat(Flowable.unsafeCreate(observableOfObservables)); - concatF.take(50).subscribe(observer); + concatF.take(50).subscribe(subscriber); //Wait for the thread to start up. try { @@ -335,13 +335,13 @@ public void testConcatConcurrentWithInfinity() { e.printStackTrace(); } - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("one"); - inOrder.verify(observer, times(1)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - inOrder.verify(observer, times(47)).onNext("hello"); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("one"); + inOrder.verify(subscriber, times(1)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + inOrder.verify(subscriber, times(47)).onNext("hello"); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -353,24 +353,24 @@ public void testConcatNonBlockingObservables() { final TestObservable<String> w1 = new TestObservable<String>(null, okToContinueW1, "one", "two", "three"); final TestObservable<String> w2 = new TestObservable<String>(null, okToContinueW2, "four", "five", "six"); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<Flowable<String>> observableOfObservables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); // simulate what would happen in an observable - observer.onNext(Flowable.unsafeCreate(w1)); - observer.onNext(Flowable.unsafeCreate(w2)); - observer.onComplete(); + subscriber.onNext(Flowable.unsafeCreate(w1)); + subscriber.onNext(Flowable.unsafeCreate(w2)); + subscriber.onComplete(); } }); Flowable<String> concat = Flowable.concat(observableOfObservables); - concat.subscribe(observer); + concat.subscribe(subscriber); - verify(observer, times(0)).onComplete(); + verify(subscriber, times(0)).onComplete(); try { // release both threads @@ -383,14 +383,14 @@ public void subscribe(Subscriber<? super Flowable<String>> observer) { e.printStackTrace(); } - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("one"); - inOrder.verify(observer, times(1)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - inOrder.verify(observer, times(1)).onNext("four"); - inOrder.verify(observer, times(1)).onNext("five"); - inOrder.verify(observer, times(1)).onNext("six"); - verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("one"); + inOrder.verify(subscriber, times(1)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + inOrder.verify(subscriber, times(1)).onNext("four"); + inOrder.verify(subscriber, times(1)).onNext("five"); + inOrder.verify(subscriber, times(1)).onNext("six"); + verify(subscriber, times(1)).onComplete(); } @@ -404,8 +404,8 @@ public void testConcatUnsubscribe() { final TestObservable<String> w1 = new TestObservable<String>("one", "two", "three"); final TestObservable<String> w2 = new TestObservable<String>(callOnce, okToContinue, "four", "five", "six"); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer, 0L); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber, 0L); final Flowable<String> concat = Flowable.concat(Flowable.unsafeCreate(w1), Flowable.unsafeCreate(w2)); @@ -425,14 +425,14 @@ public void testConcatUnsubscribe() { fail(e.getMessage()); } - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("one"); - inOrder.verify(observer, times(1)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - inOrder.verify(observer, times(1)).onNext("four"); - inOrder.verify(observer, never()).onNext("five"); - inOrder.verify(observer, never()).onNext("six"); - inOrder.verify(observer, never()).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("one"); + inOrder.verify(subscriber, times(1)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + inOrder.verify(subscriber, times(1)).onNext("four"); + inOrder.verify(subscriber, never()).onNext("five"); + inOrder.verify(subscriber, never()).onNext("six"); + inOrder.verify(subscriber, never()).onComplete(); } @@ -446,8 +446,8 @@ public void testConcatUnsubscribeConcurrent() { final TestObservable<String> w1 = new TestObservable<String>("one", "two", "three"); final TestObservable<String> w2 = new TestObservable<String>(callOnce, okToContinue, "four", "five", "six"); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer, 0L); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber, 0L); @SuppressWarnings("unchecked") TestObservable<Flowable<String>> observableOfObservables = new TestObservable<Flowable<String>>(Flowable.unsafeCreate(w1), Flowable.unsafeCreate(w2)); @@ -470,15 +470,15 @@ public void testConcatUnsubscribeConcurrent() { fail(e.getMessage()); } - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("one"); - inOrder.verify(observer, times(1)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - inOrder.verify(observer, times(1)).onNext("four"); - inOrder.verify(observer, never()).onNext("five"); - inOrder.verify(observer, never()).onNext("six"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("one"); + inOrder.verify(subscriber, times(1)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + inOrder.verify(subscriber, times(1)).onNext("four"); + inOrder.verify(subscriber, never()).onNext("five"); + inOrder.verify(subscriber, never()).onNext("six"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } private static class TestObservable<T> implements Publisher<T> { @@ -526,8 +526,8 @@ public void cancel() { } @Override - public void subscribe(final Subscriber<? super T> observer) { - observer.onSubscribe(s); + public void subscribe(final Subscriber<? super T> subscriber) { + subscriber.onSubscribe(s); t = new Thread(new Runnable() { @Override @@ -535,9 +535,9 @@ public void run() { try { while (count < size && subscribed) { if (null != values) { - observer.onNext(values.get(count)); + subscriber.onNext(values.get(count)); } else { - observer.onNext(seed); + subscriber.onNext(seed); } count++; //Unblock the main thread to call unsubscribe. @@ -550,7 +550,7 @@ public void run() { } } if (subscribed) { - observer.onComplete(); + subscriber.onComplete(); } } catch (InterruptedException e) { e.printStackTrace(); @@ -571,45 +571,45 @@ void waitForThreadDone() throws InterruptedException { @Test public void testMultipleObservers() { - Subscriber<Object> o1 = TestHelper.mockSubscriber(); - Subscriber<Object> o2 = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber2 = TestHelper.mockSubscriber(); TestScheduler s = new TestScheduler(); Flowable<Long> timer = Flowable.interval(500, TimeUnit.MILLISECONDS, s).take(2); - Flowable<Long> o = Flowable.concat(timer, timer); + Flowable<Long> f = Flowable.concat(timer, timer); - o.subscribe(o1); - o.subscribe(o2); + f.subscribe(subscriber1); + f.subscribe(subscriber2); - InOrder inOrder1 = inOrder(o1); - InOrder inOrder2 = inOrder(o2); + InOrder inOrder1 = inOrder(subscriber1); + InOrder inOrder2 = inOrder(subscriber2); s.advanceTimeBy(500, TimeUnit.MILLISECONDS); - inOrder1.verify(o1, times(1)).onNext(0L); - inOrder2.verify(o2, times(1)).onNext(0L); + inOrder1.verify(subscriber1, times(1)).onNext(0L); + inOrder2.verify(subscriber2, times(1)).onNext(0L); s.advanceTimeBy(500, TimeUnit.MILLISECONDS); - inOrder1.verify(o1, times(1)).onNext(1L); - inOrder2.verify(o2, times(1)).onNext(1L); + inOrder1.verify(subscriber1, times(1)).onNext(1L); + inOrder2.verify(subscriber2, times(1)).onNext(1L); s.advanceTimeBy(500, TimeUnit.MILLISECONDS); - inOrder1.verify(o1, times(1)).onNext(0L); - inOrder2.verify(o2, times(1)).onNext(0L); + inOrder1.verify(subscriber1, times(1)).onNext(0L); + inOrder2.verify(subscriber2, times(1)).onNext(0L); s.advanceTimeBy(500, TimeUnit.MILLISECONDS); - inOrder1.verify(o1, times(1)).onNext(1L); - inOrder2.verify(o2, times(1)).onNext(1L); + inOrder1.verify(subscriber1, times(1)).onNext(1L); + inOrder2.verify(subscriber2, times(1)).onNext(1L); - inOrder1.verify(o1, times(1)).onComplete(); - inOrder2.verify(o2, times(1)).onComplete(); + inOrder1.verify(subscriber1, times(1)).onComplete(); + inOrder2.verify(subscriber2, times(1)).onComplete(); - verify(o1, never()).onError(any(Throwable.class)); - verify(o2, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); + verify(subscriber2, never()).onError(any(Throwable.class)); } @Test @@ -705,7 +705,7 @@ public void testInnerBackpressureWithoutAlignedBoundaries() { // https://github.com/ReactiveX/RxJava/issues/1818 @Test public void testConcatWithNonCompliantSourceDoubleOnComplete() { - Flowable<String> o = Flowable.unsafeCreate(new Publisher<String>() { + Flowable<String> f = Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> s) { @@ -718,7 +718,7 @@ public void subscribe(Subscriber<? super String> s) { }); TestSubscriber<String> ts = new TestSubscriber<String>(); - Flowable.concat(o, o).subscribe(ts); + Flowable.concat(f, f).subscribe(ts); ts.awaitTerminalEvent(500, TimeUnit.MILLISECONDS); ts.assertTerminated(); ts.assertNoErrors(); @@ -733,12 +733,12 @@ public void testIssue2890NoStackoverflow() throws InterruptedException { Function<Integer, Flowable<Integer>> func = new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer t) { - Flowable<Integer> observable = Flowable.just(t) + Flowable<Integer> flowable = Flowable.just(t) .subscribeOn(sch) ; - FlowableProcessor<Integer> subject = UnicastProcessor.create(); - observable.subscribe(subject); - return subject; + FlowableProcessor<Integer> processor = UnicastProcessor.create(); + flowable.subscribe(processor); + return processor; } }; @@ -778,10 +778,10 @@ public void onError(Throwable e) { @Test public void testRequestOverflowDoesNotStallStream() { - Flowable<Integer> o1 = Flowable.just(1,2,3); - Flowable<Integer> o2 = Flowable.just(4,5,6); + Flowable<Integer> f1 = Flowable.just(1,2,3); + Flowable<Integer> f2 = Flowable.just(4,5,6); final AtomicBoolean completed = new AtomicBoolean(false); - o1.concatWith(o2).subscribe(new DefaultSubscriber<Integer>() { + f1.concatWith(f2).subscribe(new DefaultSubscriber<Integer>() { @Override public void onComplete() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletableTest.java index d186e2fcd4..681f9d91f3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletableTest.java @@ -15,13 +15,16 @@ import static org.junit.Assert.*; +import java.util.List; + import org.junit.Test; import org.reactivestreams.Subscriber; import io.reactivex.*; -import io.reactivex.exceptions.TestException; +import io.reactivex.exceptions.*; import io.reactivex.functions.Action; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subjects.CompletableSubject; import io.reactivex.subscribers.TestSubscriber; @@ -104,22 +107,29 @@ public void cancelOther() { @Test public void badSource() { - new Flowable<Integer>() { - @Override - protected void subscribeActual(Subscriber<? super Integer> s) { - BooleanSubscription bs1 = new BooleanSubscription(); - s.onSubscribe(bs1); - - BooleanSubscription bs2 = new BooleanSubscription(); - s.onSubscribe(bs2); - - assertFalse(bs1.isCancelled()); - assertTrue(bs2.isCancelled()); - - s.onComplete(); - } - }.concatWith(Completable.complete()) - .test() - .assertResult(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new Flowable<Integer>() { + @Override + protected void subscribeActual(Subscriber<? super Integer> s) { + BooleanSubscription bs1 = new BooleanSubscription(); + s.onSubscribe(bs1); + + BooleanSubscription bs2 = new BooleanSubscription(); + s.onSubscribe(bs2); + + assertFalse(bs1.isCancelled()); + assertTrue(bs2.isCancelled()); + + s.onComplete(); + } + }.concatWith(Completable.complete()) + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + } finally { + RxJavaPlugins.reset(); + } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCountTest.java index a84389310a..e11fb643eb 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCountTest.java @@ -51,15 +51,15 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Long>>() { @Override - public Flowable<Long> apply(Flowable<Object> o) throws Exception { - return o.count().toFlowable(); + public Flowable<Long> apply(Flowable<Object> f) throws Exception { + return f.count().toFlowable(); } }); TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function<Flowable<Object>, SingleSource<Long>>() { @Override - public SingleSource<Long> apply(Flowable<Object> o) throws Exception { - return o.count(); + public SingleSource<Long> apply(Flowable<Object> f) throws Exception { + return f.count(); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java index bbdff04d1c..ba4c9933a9 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java @@ -48,151 +48,189 @@ public void subscribe(FlowableEmitter<Object> s) throws Exception { } @Test public void basic() { - final Disposable d = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); - Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e.setDisposable(d); - - e.onNext(1); - e.onNext(2); - e.onNext(3); - e.onComplete(); - e.onError(new TestException()); - e.onNext(4); - e.onError(new TestException()); - e.onComplete(); - } - }, BackpressureStrategy.BUFFER) - .test() - .assertResult(1, 2, 3); + Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e.setDisposable(d); + + e.onNext(1); + e.onNext(2); + e.onNext(3); + e.onComplete(); + e.onError(new TestException("first")); + e.onNext(4); + e.onError(new TestException("second")); + e.onComplete(); + } + }, BackpressureStrategy.BUFFER) + .test() + .assertResult(1, 2, 3); - assertTrue(d.isDisposed()); + assertTrue(d.isDisposed()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "first"); + TestHelper.assertUndeliverable(errors, 1, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicWithCancellable() { - final Disposable d1 = Disposables.empty(); - final Disposable d2 = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d1 = Disposables.empty(); + final Disposable d2 = Disposables.empty(); - Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e.setDisposable(d1); - e.setCancellable(new Cancellable() { - @Override - public void cancel() throws Exception { - d2.dispose(); - } - }); - - e.onNext(1); - e.onNext(2); - e.onNext(3); - e.onComplete(); - e.onError(new TestException()); - e.onNext(4); - e.onError(new TestException()); - e.onComplete(); - } - }, BackpressureStrategy.BUFFER) - .test() - .assertResult(1, 2, 3); + Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e.setDisposable(d1); + e.setCancellable(new Cancellable() { + @Override + public void cancel() throws Exception { + d2.dispose(); + } + }); + + e.onNext(1); + e.onNext(2); + e.onNext(3); + e.onComplete(); + e.onError(new TestException("first")); + e.onNext(4); + e.onError(new TestException("second")); + e.onComplete(); + } + }, BackpressureStrategy.BUFFER) + .test() + .assertResult(1, 2, 3); + + assertTrue(d1.isDisposed()); + assertTrue(d2.isDisposed()); - assertTrue(d1.isDisposed()); - assertTrue(d2.isDisposed()); + TestHelper.assertUndeliverable(errors, 0, TestException.class, "first"); + TestHelper.assertUndeliverable(errors, 1, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicWithError() { - final Disposable d = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); - Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e.setDisposable(d); - - e.onNext(1); - e.onNext(2); - e.onNext(3); - e.onError(new TestException()); - e.onComplete(); - e.onNext(4); - e.onError(new TestException()); - } - }, BackpressureStrategy.BUFFER) - .test() - .assertFailure(TestException.class, 1, 2, 3); + Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e.setDisposable(d); + + e.onNext(1); + e.onNext(2); + e.onNext(3); + e.onError(new TestException()); + e.onComplete(); + e.onNext(4); + e.onError(new TestException("second")); + } + }, BackpressureStrategy.BUFFER) + .test() + .assertFailure(TestException.class, 1, 2, 3); + + assertTrue(d.isDisposed()); - assertTrue(d.isDisposed()); + TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicSerialized() { - final Disposable d = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); - Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e = e.serialize(); - - e.setDisposable(d); - - e.onNext(1); - e.onNext(2); - e.onNext(3); - e.onComplete(); - e.onError(new TestException()); - e.onNext(4); - e.onError(new TestException()); - e.onComplete(); - } - }, BackpressureStrategy.BUFFER) - .test() - .assertResult(1, 2, 3); + Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e = e.serialize(); + + e.setDisposable(d); + + e.onNext(1); + e.onNext(2); + e.onNext(3); + e.onComplete(); + e.onError(new TestException("first")); + e.onNext(4); + e.onError(new TestException("second")); + e.onComplete(); + } + }, BackpressureStrategy.BUFFER) + .test() + .assertResult(1, 2, 3); + + assertTrue(d.isDisposed()); - assertTrue(d.isDisposed()); + TestHelper.assertUndeliverable(errors, 0, TestException.class, "first"); + TestHelper.assertUndeliverable(errors, 1, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicWithErrorSerialized() { - final Disposable d = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); - Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e = e.serialize(); - - e.setDisposable(d); - - e.onNext(1); - e.onNext(2); - e.onNext(3); - e.onError(new TestException()); - e.onComplete(); - e.onNext(4); - e.onError(new TestException()); - } - }, BackpressureStrategy.BUFFER) - .test() - .assertFailure(TestException.class, 1, 2, 3); + Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e = e.serialize(); + + e.setDisposable(d); - assertTrue(d.isDisposed()); + e.onNext(1); + e.onNext(2); + e.onNext(3); + e.onError(new TestException()); + e.onComplete(); + e.onNext(4); + e.onError(new TestException("second")); + } + }, BackpressureStrategy.BUFFER) + .test() + .assertFailure(TestException.class, 1, 2, 3); + + assertTrue(d.isDisposed()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); + } finally { + RxJavaPlugins.reset(); + } } @Test public void wrap() { Flowable.fromPublisher(new Publisher<Integer>() { @Override - public void subscribe(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onNext(2); - observer.onNext(3); - observer.onNext(4); - observer.onNext(5); - observer.onComplete(); + public void subscribe(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(1); + subscriber.onNext(2); + subscriber.onNext(3); + subscriber.onNext(4); + subscriber.onNext(5); + subscriber.onComplete(); } }) .test() @@ -203,14 +241,14 @@ public void subscribe(Subscriber<? super Integer> observer) { public void unsafe() { Flowable.unsafeCreate(new Publisher<Integer>() { @Override - public void subscribe(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onNext(2); - observer.onNext(3); - observer.onNext(4); - observer.onNext(5); - observer.onComplete(); + public void subscribe(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(1); + subscriber.onNext(2); + subscriber.onNext(3); + subscriber.onNext(4); + subscriber.onNext(5); + subscriber.onComplete(); } }) .test() @@ -224,237 +262,308 @@ public void unsafeWithFlowable() { @Test public void createNullValueBuffer() { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + final Throwable[] error = { null }; + + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, BackpressureStrategy.BUFFER) - .test() - .assertFailure(NullPointerException.class); + }, BackpressureStrategy.BUFFER) + .test() + .assertFailure(NullPointerException.class); + + assertNull(error[0]); - assertNull(error[0]); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void createNullValueLatest() { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, BackpressureStrategy.LATEST) - .test() - .assertFailure(NullPointerException.class); + }, BackpressureStrategy.LATEST) + .test() + .assertFailure(NullPointerException.class); + + assertNull(error[0]); - assertNull(error[0]); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void createNullValueError() { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, BackpressureStrategy.ERROR) - .test() - .assertFailure(NullPointerException.class); + }, BackpressureStrategy.ERROR) + .test() + .assertFailure(NullPointerException.class); + + assertNull(error[0]); - assertNull(error[0]); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void createNullValueDrop() { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, BackpressureStrategy.DROP) - .test() - .assertFailure(NullPointerException.class); + }, BackpressureStrategy.DROP) + .test() + .assertFailure(NullPointerException.class); + + assertNull(error[0]); - assertNull(error[0]); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void createNullValueMissing() { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, BackpressureStrategy.MISSING) - .test() - .assertFailure(NullPointerException.class); + }, BackpressureStrategy.MISSING) + .test() + .assertFailure(NullPointerException.class); - assertNull(error[0]); + assertNull(error[0]); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void createNullValueBufferSerialized() { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e = e.serialize(); - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e = e.serialize(); + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, BackpressureStrategy.BUFFER) - .test() - .assertFailure(NullPointerException.class); + }, BackpressureStrategy.BUFFER) + .test() + .assertFailure(NullPointerException.class); + + assertNull(error[0]); - assertNull(error[0]); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void createNullValueLatestSerialized() { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e = e.serialize(); - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e = e.serialize(); + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, BackpressureStrategy.LATEST) - .test() - .assertFailure(NullPointerException.class); + }, BackpressureStrategy.LATEST) + .test() + .assertFailure(NullPointerException.class); - assertNull(error[0]); + assertNull(error[0]); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void createNullValueErrorSerialized() { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e = e.serialize(); - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e = e.serialize(); + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, BackpressureStrategy.ERROR) - .test() - .assertFailure(NullPointerException.class); + }, BackpressureStrategy.ERROR) + .test() + .assertFailure(NullPointerException.class); + + assertNull(error[0]); - assertNull(error[0]); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void createNullValueDropSerialized() { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e = e.serialize(); - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e = e.serialize(); + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, BackpressureStrategy.DROP) - .test() - .assertFailure(NullPointerException.class); + }, BackpressureStrategy.DROP) + .test() + .assertFailure(NullPointerException.class); - assertNull(error[0]); + assertNull(error[0]); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void createNullValueMissingSerialized() { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e = e.serialize(); - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e = e.serialize(); + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, BackpressureStrategy.MISSING) - .test() - .assertFailure(NullPointerException.class); + }, BackpressureStrategy.MISSING) + .test() + .assertFailure(NullPointerException.class); + + assertNull(error[0]); - assertNull(error[0]); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -630,25 +739,32 @@ public void subscribe(FlowableEmitter<Object> e) throws Exception { @Test public void createNullValue() { for (BackpressureStrategy m : BackpressureStrategy.values()) { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, m) - .test() - .assertFailure(NullPointerException.class); + }, m) + .test() + .assertFailure(NullPointerException.class); - assertNull(error[0]); + assertNull(error[0]); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } } @@ -736,26 +852,33 @@ public void onComplete() { @Test public void createNullValueSerialized() { for (BackpressureStrategy m : BackpressureStrategy.values()) { - final Throwable[] error = { null }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Throwable[] error = { null }; - Flowable.create(new FlowableOnSubscribe<Integer>() { - @Override - public void subscribe(FlowableEmitter<Integer> e) throws Exception { - e = e.serialize(); - try { - e.onNext(null); - e.onNext(1); - e.onError(new TestException()); - e.onComplete(); - } catch (Throwable ex) { - error[0] = ex; + Flowable.create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> e) throws Exception { + e = e.serialize(); + try { + e.onNext(null); + e.onNext(1); + e.onError(new TestException()); + e.onComplete(); + } catch (Throwable ex) { + error[0] = ex; + } } - } - }, m) - .test() - .assertFailure(NullPointerException.class); + }, m) + .test() + .assertFailure(NullPointerException.class); - assertNull(error[0]); + assertNull(error[0]); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java index c152929e1a..40348b0ee6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java @@ -171,10 +171,10 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.debounce(debounceSel).subscribe(o); + source.debounce(debounceSel).subscribe(subscriber); source.onNext(1); debouncer.onNext(1); @@ -188,12 +188,12 @@ public Flowable<Integer> apply(Integer t1) { source.onNext(5); source.onComplete(); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(4); - inOrder.verify(o).onNext(5); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(4); + inOrder.verify(subscriber).onNext(5); + inOrder.verify(subscriber).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -207,15 +207,15 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.debounce(debounceSel).subscribe(o); + source.debounce(debounceSel).subscribe(subscriber); source.onNext(1); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); } @Test @@ -229,32 +229,32 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.debounce(debounceSel).subscribe(o); + source.debounce(debounceSel).subscribe(subscriber); source.onNext(1); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); } @Test public void debounceTimedLastIsNotLost() { PublishProcessor<Integer> source = PublishProcessor.create(); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.debounce(100, TimeUnit.MILLISECONDS, scheduler).subscribe(o); + source.debounce(100, TimeUnit.MILLISECONDS, scheduler).subscribe(subscriber); source.onNext(1); source.onComplete(); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - verify(o).onNext(1); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(1); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void debounceSelectorLastIsNotLost() { @@ -269,18 +269,18 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.debounce(debounceSel).subscribe(o); + source.debounce(debounceSel).subscribe(subscriber); source.onNext(1); source.onComplete(); debouncer.onComplete(); - verify(o).onNext(1); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(1); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -363,8 +363,8 @@ protected void subscribeActual(Subscriber<? super Integer> subscriber) { public void badSourceSelector() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(Flowable<Integer> o) throws Exception { - return o.debounce(new Function<Integer, Flowable<Long>>() { + public Object apply(Flowable<Integer> f) throws Exception { + return f.debounce(new Function<Integer, Flowable<Long>>() { @Override public Flowable<Long> apply(Integer v) throws Exception { return Flowable.timer(1, TimeUnit.SECONDS); @@ -375,11 +375,11 @@ public Flowable<Long> apply(Integer v) throws Exception { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(final Flowable<Integer> o) throws Exception { + public Object apply(final Flowable<Integer> f) throws Exception { return Flowable.just(1).debounce(new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer v) throws Exception { - return o; + return f; } }); } @@ -415,8 +415,8 @@ public void backpressureNoRequestTimed() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.debounce(Functions.justFunction(Flowable.never())); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.debounce(Functions.justFunction(Flowable.never())); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDefaultIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDefaultIfEmptyTest.java index 24b41502e9..fa6b123a15 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDefaultIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDefaultIfEmptyTest.java @@ -27,38 +27,38 @@ public class FlowableDefaultIfEmptyTest { @Test public void testDefaultIfEmpty() { Flowable<Integer> source = Flowable.just(1, 2, 3); - Flowable<Integer> observable = source.defaultIfEmpty(10); + Flowable<Integer> flowable = source.defaultIfEmpty(10); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, never()).onNext(10); - verify(observer).onNext(1); - verify(observer).onNext(2); - verify(observer).onNext(3); - verify(observer).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(10); + verify(subscriber).onNext(1); + verify(subscriber).onNext(2); + verify(subscriber).onNext(3); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testDefaultIfEmptyWithEmpty() { Flowable<Integer> source = Flowable.empty(); - Flowable<Integer> observable = source.defaultIfEmpty(10); + Flowable<Integer> flowable = source.defaultIfEmpty(10); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer).onNext(10); - verify(observer).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(10); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @Ignore("Subscribers should not throw") public void testEmptyButClientThrows() { - final Subscriber<Integer> o = TestHelper.mockSubscriber(); + final Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); Flowable.<Integer>empty().defaultIfEmpty(1).subscribe(new DefaultSubscriber<Integer>() { @Override @@ -68,18 +68,18 @@ public void onNext(Integer t) { @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }); - verify(o).onError(any(TestException.class)); - verify(o, never()).onNext(any(Integer.class)); - verify(o, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any(Integer.class)); + verify(subscriber, never()).onComplete(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDeferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDeferTest.java index 2d3cabc7a9..8d46e9c34e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDeferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDeferTest.java @@ -22,7 +22,6 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; -import io.reactivex.subscribers.DefaultSubscriber; @SuppressWarnings("unchecked") public class FlowableDeferTest { @@ -40,25 +39,25 @@ public void testDefer() throws Throwable { verifyZeroInteractions(factory); - Subscriber<String> firstObserver = TestHelper.mockSubscriber(); - deferred.subscribe(firstObserver); + Subscriber<String> firstSubscriber = TestHelper.mockSubscriber(); + deferred.subscribe(firstSubscriber); verify(factory, times(1)).call(); - verify(firstObserver, times(1)).onNext("one"); - verify(firstObserver, times(1)).onNext("two"); - verify(firstObserver, times(0)).onNext("three"); - verify(firstObserver, times(0)).onNext("four"); - verify(firstObserver, times(1)).onComplete(); + verify(firstSubscriber, times(1)).onNext("one"); + verify(firstSubscriber, times(1)).onNext("two"); + verify(firstSubscriber, times(0)).onNext("three"); + verify(firstSubscriber, times(0)).onNext("four"); + verify(firstSubscriber, times(1)).onComplete(); - Subscriber<String> secondObserver = TestHelper.mockSubscriber(); - deferred.subscribe(secondObserver); + Subscriber<String> secondSubscriber = TestHelper.mockSubscriber(); + deferred.subscribe(secondSubscriber); verify(factory, times(2)).call(); - verify(secondObserver, times(0)).onNext("one"); - verify(secondObserver, times(0)).onNext("two"); - verify(secondObserver, times(1)).onNext("three"); - verify(secondObserver, times(1)).onNext("four"); - verify(secondObserver, times(1)).onComplete(); + verify(secondSubscriber, times(0)).onNext("one"); + verify(secondSubscriber, times(0)).onNext("two"); + verify(secondSubscriber, times(1)).onNext("three"); + verify(secondSubscriber, times(1)).onNext("four"); + verify(secondSubscriber, times(1)).onComplete(); } @@ -70,12 +69,12 @@ public void testDeferFunctionThrows() throws Exception { Flowable<String> result = Flowable.defer(factory); - DefaultSubscriber<String> o = mock(DefaultSubscriber.class); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onError(any(TestException.class)); - verify(o, never()).onNext(any(String.class)); - verify(o, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any(String.class)); + verify(subscriber, never()).onComplete(); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOtherTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOtherTest.java index 9e23acf0ee..e61c3f7905 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOtherTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOtherTest.java @@ -316,8 +316,8 @@ public void otherNull() { public void badSourceOther() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(Flowable<Integer> o) throws Exception { - return Flowable.just(1).delaySubscription(o); + public Object apply(Flowable<Integer> f) throws Exception { + return Flowable.just(1).delaySubscription(f); } }, false, 1, 1, 1); } @@ -327,8 +327,8 @@ public void afterDelayNoInterrupt() { ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); try { for (Scheduler s : new Scheduler[] { Schedulers.single(), Schedulers.computation(), Schedulers.newThread(), Schedulers.io(), Schedulers.from(exec) }) { - final TestSubscriber<Boolean> observer = TestSubscriber.create(); - observer.withTag(s.getClass().getSimpleName()); + final TestSubscriber<Boolean> ts = TestSubscriber.create(); + ts.withTag(s.getClass().getSimpleName()); Flowable.<Boolean>create(new FlowableOnSubscribe<Boolean>() { @Override @@ -338,10 +338,10 @@ public void subscribe(FlowableEmitter<Boolean> emitter) throws Exception { } }, BackpressureStrategy.MISSING) .delaySubscription(100, TimeUnit.MILLISECONDS, s) - .subscribe(observer); + .subscribe(ts); - observer.awaitTerminalEvent(); - observer.assertValue(false); + ts.awaitTerminalEvent(); + ts.assertValue(false); } } finally { exec.shutdown(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java index d86f5f5469..401b9c62b4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java @@ -34,15 +34,15 @@ import io.reactivex.subscribers.*; public class FlowableDelayTest { - private Subscriber<Long> observer; - private Subscriber<Long> observer2; + private Subscriber<Long> subscriber; + private Subscriber<Long> subscriber2; private TestScheduler scheduler; @Before public void before() { - observer = TestHelper.mockSubscriber(); - observer2 = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); + subscriber2 = TestHelper.mockSubscriber(); scheduler = new TestScheduler(); } @@ -51,69 +51,69 @@ public void before() { public void testDelay() { Flowable<Long> source = Flowable.interval(1L, TimeUnit.SECONDS, scheduler).take(3); Flowable<Long> delayed = source.delay(500L, TimeUnit.MILLISECONDS, scheduler); - delayed.subscribe(observer); + delayed.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(1499L, TimeUnit.MILLISECONDS); - verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(1500L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(0L); - inOrder.verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext(0L); + inOrder.verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(2400L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(2500L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(1L); - inOrder.verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext(1L); + inOrder.verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(3400L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(3500L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(2L); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext(2L); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testLongDelay() { Flowable<Long> source = Flowable.interval(1L, TimeUnit.SECONDS, scheduler).take(3); Flowable<Long> delayed = source.delay(5L, TimeUnit.SECONDS, scheduler); - delayed.subscribe(observer); + delayed.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(5999L, TimeUnit.MILLISECONDS); - verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(6000L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(0L); + inOrder.verify(subscriber, times(1)).onNext(0L); scheduler.advanceTimeTo(6999L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyLong()); + inOrder.verify(subscriber, never()).onNext(anyLong()); scheduler.advanceTimeTo(7000L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(1L); + inOrder.verify(subscriber, times(1)).onNext(1L); scheduler.advanceTimeTo(7999L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyLong()); + inOrder.verify(subscriber, never()).onNext(anyLong()); scheduler.advanceTimeTo(8000L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(2L); - inOrder.verify(observer, times(1)).onComplete(); - inOrder.verify(observer, never()).onNext(anyLong()); - inOrder.verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext(2L); + inOrder.verify(subscriber, times(1)).onComplete(); + inOrder.verify(subscriber, never()).onNext(anyLong()); + inOrder.verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -129,103 +129,103 @@ public Long apply(Long value) { } }); Flowable<Long> delayed = source.delay(1L, TimeUnit.SECONDS, scheduler); - delayed.subscribe(observer); + delayed.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(1999L, TimeUnit.MILLISECONDS); - verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(2000L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onError(any(Throwable.class)); - inOrder.verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); + inOrder.verify(subscriber, times(1)).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); scheduler.advanceTimeTo(5000L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyLong()); - inOrder.verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); + inOrder.verify(subscriber, never()).onNext(anyLong()); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); } @Test public void testDelayWithMultipleSubscriptions() { Flowable<Long> source = Flowable.interval(1L, TimeUnit.SECONDS, scheduler).take(3); Flowable<Long> delayed = source.delay(500L, TimeUnit.MILLISECONDS, scheduler); - delayed.subscribe(observer); - delayed.subscribe(observer2); + delayed.subscribe(subscriber); + delayed.subscribe(subscriber2); - InOrder inOrder = inOrder(observer); - InOrder inOrder2 = inOrder(observer2); + InOrder inOrder = inOrder(subscriber); + InOrder inOrder2 = inOrder(subscriber2); scheduler.advanceTimeTo(1499L, TimeUnit.MILLISECONDS); - verify(observer, never()).onNext(anyLong()); - verify(observer2, never()).onNext(anyLong()); + verify(subscriber, never()).onNext(anyLong()); + verify(subscriber2, never()).onNext(anyLong()); scheduler.advanceTimeTo(1500L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(0L); - inOrder2.verify(observer2, times(1)).onNext(0L); + inOrder.verify(subscriber, times(1)).onNext(0L); + inOrder2.verify(subscriber2, times(1)).onNext(0L); scheduler.advanceTimeTo(2499L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyLong()); - inOrder2.verify(observer2, never()).onNext(anyLong()); + inOrder.verify(subscriber, never()).onNext(anyLong()); + inOrder2.verify(subscriber2, never()).onNext(anyLong()); scheduler.advanceTimeTo(2500L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(1L); - inOrder2.verify(observer2, times(1)).onNext(1L); + inOrder.verify(subscriber, times(1)).onNext(1L); + inOrder2.verify(subscriber2, times(1)).onNext(1L); - verify(observer, never()).onComplete(); - verify(observer2, never()).onComplete(); + verify(subscriber, never()).onComplete(); + verify(subscriber2, never()).onComplete(); scheduler.advanceTimeTo(3500L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(2L); - inOrder2.verify(observer2, times(1)).onNext(2L); - inOrder.verify(observer, never()).onNext(anyLong()); - inOrder2.verify(observer2, never()).onNext(anyLong()); - inOrder.verify(observer, times(1)).onComplete(); - inOrder2.verify(observer2, times(1)).onComplete(); - - verify(observer, never()).onError(any(Throwable.class)); - verify(observer2, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext(2L); + inOrder2.verify(subscriber2, times(1)).onNext(2L); + inOrder.verify(subscriber, never()).onNext(anyLong()); + inOrder2.verify(subscriber2, never()).onNext(anyLong()); + inOrder.verify(subscriber, times(1)).onComplete(); + inOrder2.verify(subscriber2, times(1)).onComplete(); + + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber2, never()).onError(any(Throwable.class)); } @Test public void testDelaySubscription() { Flowable<Integer> result = Flowable.just(1, 2, 3).delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); - inOrder.verify(o, never()).onNext(any()); - inOrder.verify(o, never()).onComplete(); + inOrder.verify(subscriber, never()).onNext(any()); + inOrder.verify(subscriber, never()).onComplete(); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - inOrder.verify(o, times(1)).onNext(1); - inOrder.verify(o, times(1)).onNext(2); - inOrder.verify(o, times(1)).onNext(3); - inOrder.verify(o, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onNext(3); + inOrder.verify(subscriber, times(1)).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testDelaySubscriptionCancelBeforeTime() { Flowable<Integer> result = Flowable.just(1, 2, 3).delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); - TestSubscriber<Object> ts = new TestSubscriber<Object>(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<Object> ts = new TestSubscriber<Object>(subscriber); result.subscribe(ts); ts.dispose(); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -245,22 +245,22 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.delay(delayFunc).subscribe(o); + source.delay(delayFunc).subscribe(subscriber); for (int i = 0; i < n; i++) { source.onNext(i); delays.get(i).onNext(i); - inOrder.verify(o).onNext(i); + inOrder.verify(subscriber).onNext(i); } source.onComplete(); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -275,18 +275,18 @@ public Flowable<Integer> apply(Integer t1) { return delay; } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.delay(delayFunc).subscribe(o); + source.delay(delayFunc).subscribe(subscriber); source.onNext(1); delay.onNext(1); delay.onNext(2); - inOrder.verify(o).onNext(1); + inOrder.verify(subscriber).onNext(1); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -301,18 +301,18 @@ public Flowable<Integer> apply(Integer t1) { return delay; } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.delay(delayFunc).subscribe(o); + source.delay(delayFunc).subscribe(subscriber); source.onNext(1); source.onError(new TestException()); delay.onNext(1); - inOrder.verify(o).onError(any(TestException.class)); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -326,16 +326,16 @@ public Flowable<Integer> apply(Integer t1) { throw new TestException(); } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.delay(delayFunc).subscribe(o); + source.delay(delayFunc).subscribe(subscriber); source.onNext(1); - inOrder.verify(o).onError(any(TestException.class)); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -350,17 +350,17 @@ public Flowable<Integer> apply(Integer t1) { return delay; } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.delay(delayFunc).subscribe(o); + source.delay(delayFunc).subscribe(subscriber); source.onNext(1); delay.onError(new TestException()); - inOrder.verify(o).onError(any(TestException.class)); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -375,10 +375,10 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.delay(delay, delayFunc).subscribe(o); + source.delay(delay, delayFunc).subscribe(subscriber); source.onNext(1); delay.onNext(1); @@ -386,10 +386,10 @@ public Flowable<Integer> apply(Integer t1) { source.onNext(2); delay.onNext(2); - inOrder.verify(o).onNext(2); + inOrder.verify(subscriber).onNext(2); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onError(any(Throwable.class)); - verify(o, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); } @Test @@ -410,20 +410,20 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.delay(Flowable.defer(subFunc), delayFunc).subscribe(o); + source.delay(Flowable.defer(subFunc), delayFunc).subscribe(subscriber); source.onNext(1); delay.onNext(1); source.onNext(2); - inOrder.verify(o).onError(any(TestException.class)); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -444,20 +444,20 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.delay(Flowable.defer(subFunc), delayFunc).subscribe(o); + source.delay(Flowable.defer(subFunc), delayFunc).subscribe(subscriber); source.onNext(1); delay.onError(new TestException()); source.onNext(2); - inOrder.verify(o).onError(any(TestException.class)); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -471,18 +471,18 @@ public Flowable<Integer> apply(Integer t1) { return Flowable.empty(); } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.delay(delayFunc).subscribe(o); + source.delay(delayFunc).subscribe(subscriber); source.onNext(1); source.onComplete(); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -504,10 +504,10 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.delay(Flowable.defer(subFunc), delayFunc).subscribe(o); + source.delay(Flowable.defer(subFunc), delayFunc).subscribe(subscriber); source.onNext(1); sdelay.onComplete(); @@ -515,10 +515,10 @@ public Flowable<Integer> apply(Integer t1) { source.onNext(2); delay.onNext(2); - inOrder.verify(o).onNext(2); + inOrder.verify(subscriber).onNext(2); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onError(any(Throwable.class)); - verify(o, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); } @Test @@ -535,40 +535,40 @@ public Flowable<Long> apply(Long t1) { }; Flowable<Long> delayed = source.delay(delayFunc); - delayed.subscribe(observer); + delayed.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(1499L, TimeUnit.MILLISECONDS); - verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(1500L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(0L); - inOrder.verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext(0L); + inOrder.verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(2400L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(2500L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(1L); - inOrder.verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext(1L); + inOrder.verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(3400L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(3500L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(2L); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext(2L); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -589,27 +589,27 @@ public Flowable<Integer> apply(Integer t1) { } }); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); for (int i = 0; i < n; i++) { source.onNext(i); } source.onComplete(); - inOrder.verify(o, never()).onNext(anyInt()); - inOrder.verify(o, never()).onComplete(); + inOrder.verify(subscriber, never()).onNext(anyInt()); + inOrder.verify(subscriber, never()).onComplete(); for (int i = n - 1; i >= 0; i--) { subjects.get(i).onComplete(); - inOrder.verify(o).onNext(i); + inOrder.verify(subscriber).onNext(i); } - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -624,11 +624,11 @@ public void accept(Notification<Integer> t1) { } }); - TestSubscriber<Integer> observer = new TestSubscriber<Integer>(); - delayed.subscribe(observer); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + delayed.subscribe(ts); // all will be delivered after 500ms since range does not delay between them scheduler.advanceTimeBy(500L, TimeUnit.MILLISECONDS); - observer.assertValues(1, 2, 3, 4, 5); + ts.assertValues(1, 2, 3, 4, 5); } @Test @@ -902,16 +902,16 @@ public void delayWithTimeDelayError() throws Exception { public void testDelaySubscriptionDisposeBeforeTime() { Flowable<Integer> result = Flowable.just(1, 2, 3).delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); - TestSubscriber<Object> ts = new TestSubscriber<Object>(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<Object> ts = new TestSubscriber<Object>(subscriber); result.subscribe(ts); ts.dispose(); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -947,15 +947,15 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.delay(1, TimeUnit.SECONDS); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.delay(1, TimeUnit.SECONDS); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.delay(Functions.justFunction(Flowable.never())); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.delay(Functions.justFunction(Flowable.never())); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java index a3ae8aaf49..f83510f830 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java @@ -35,76 +35,76 @@ public void testDematerialize1() { Flowable<Notification<Integer>> notifications = Flowable.just(1, 2).materialize(); Flowable<Integer> dematerialize = notifications.dematerialize(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - dematerialize.subscribe(observer); + dematerialize.subscribe(subscriber); - verify(observer, times(1)).onNext(1); - verify(observer, times(1)).onNext(2); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onNext(1); + verify(subscriber, times(1)).onNext(2); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testDematerialize2() { Throwable exception = new Throwable("test"); - Flowable<Integer> observable = Flowable.error(exception); - Flowable<Integer> dematerialize = observable.materialize().dematerialize(); + Flowable<Integer> flowable = Flowable.error(exception); + Flowable<Integer> dematerialize = flowable.materialize().dematerialize(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - dematerialize.subscribe(observer); + dematerialize.subscribe(subscriber); - verify(observer, times(1)).onError(exception); - verify(observer, times(0)).onComplete(); - verify(observer, times(0)).onNext(any(Integer.class)); + verify(subscriber, times(1)).onError(exception); + verify(subscriber, times(0)).onComplete(); + verify(subscriber, times(0)).onNext(any(Integer.class)); } @Test public void testDematerialize3() { Exception exception = new Exception("test"); - Flowable<Integer> observable = Flowable.error(exception); - Flowable<Integer> dematerialize = observable.materialize().dematerialize(); + Flowable<Integer> flowable = Flowable.error(exception); + Flowable<Integer> dematerialize = flowable.materialize().dematerialize(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - dematerialize.subscribe(observer); + dematerialize.subscribe(subscriber); - verify(observer, times(1)).onError(exception); - verify(observer, times(0)).onComplete(); - verify(observer, times(0)).onNext(any(Integer.class)); + verify(subscriber, times(1)).onError(exception); + verify(subscriber, times(0)).onComplete(); + verify(subscriber, times(0)).onNext(any(Integer.class)); } @Test public void testErrorPassThru() { Exception exception = new Exception("test"); - Flowable<Integer> observable = Flowable.error(exception); - Flowable<Integer> dematerialize = observable.dematerialize(); + Flowable<Integer> flowable = Flowable.error(exception); + Flowable<Integer> dematerialize = flowable.dematerialize(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - dematerialize.subscribe(observer); + dematerialize.subscribe(subscriber); - verify(observer, times(1)).onError(exception); - verify(observer, times(0)).onComplete(); - verify(observer, times(0)).onNext(any(Integer.class)); + verify(subscriber, times(1)).onError(exception); + verify(subscriber, times(0)).onComplete(); + verify(subscriber, times(0)).onNext(any(Integer.class)); } @Test public void testCompletePassThru() { - Flowable<Integer> observable = Flowable.empty(); - Flowable<Integer> dematerialize = observable.dematerialize(); + Flowable<Integer> flowable = Flowable.empty(); + Flowable<Integer> dematerialize = flowable.dematerialize(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - TestSubscriber<Integer> ts = new TestSubscriber<Integer>(observer); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(subscriber); dematerialize.subscribe(ts); System.out.println(ts.errors()); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(0)).onNext(any(Integer.class)); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(0)).onNext(any(Integer.class)); } @Test @@ -113,13 +113,13 @@ public void testHonorsContractWhenCompleted() { Flowable<Integer> result = source.materialize().dematerialize(); - Subscriber<Integer> o = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(1); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(1); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -128,13 +128,13 @@ public void testHonorsContractWhenThrows() { Flowable<Integer> result = source.materialize().dematerialize(); - Subscriber<Integer> o = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); - verify(o, never()).onNext(any(Integer.class)); - verify(o, never()).onComplete(); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any(Integer.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); } @Test @@ -146,8 +146,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.dematerialize(); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.dematerialize(); } }); } @@ -158,12 +158,12 @@ public void eventsAfterDematerializedTerminal() { try { new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext(Notification.createOnComplete()); - observer.onNext(Notification.createOnNext(1)); - observer.onNext(Notification.createOnError(new TestException("First"))); - observer.onError(new TestException("Second")); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(Notification.createOnComplete()); + subscriber.onNext(Notification.createOnNext(1)); + subscriber.onNext(Notification.createOnError(new TestException("First"))); + subscriber.onError(new TestException("Second")); } } .dematerialize() diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java index d2526adbf2..a42c0d889f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java @@ -169,8 +169,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.onTerminateDetach(); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.onTerminateDetach(); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java index 3584224000..fd79f56b9c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java @@ -232,14 +232,14 @@ public void badSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - - observer.onNext(1); - observer.onComplete(); - observer.onNext(2); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + + subscriber.onNext(1); + subscriber.onComplete(); + subscriber.onNext(2); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .distinct() diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoAfterTerminateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoAfterTerminateTest.java index 01704a97b6..c8b327fe04 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoAfterTerminateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoAfterTerminateTest.java @@ -18,6 +18,8 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.*; +import java.util.List; + import org.junit.*; import org.mockito.Mockito; import org.reactivestreams.Subscriber; @@ -25,21 +27,22 @@ import io.reactivex.*; import io.reactivex.functions.Action; import io.reactivex.internal.util.ExceptionHelper; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subscribers.TestSubscriber; public class FlowableDoAfterTerminateTest { private Action aAction0; - private Subscriber<String> observer; + private Subscriber<String> subscriber; @Before public void before() { aAction0 = Mockito.mock(Action.class); - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); } private void checkActionCalled(Flowable<String> input) { - input.doAfterTerminate(aAction0).subscribe(observer); + input.doAfterTerminate(aAction0).subscribe(subscriber); try { verify(aAction0, times(1)).run(); } catch (Throwable ex) { @@ -82,21 +85,28 @@ public void nullFinallyActionShouldBeCheckedASAP() { @Test public void ifFinallyActionThrowsExceptionShouldNotBeSwallowedAndActionShouldBeCalledOnce() throws Exception { - Action finallyAction = Mockito.mock(Action.class); - doThrow(new IllegalStateException()).when(finallyAction).run(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Action finallyAction = Mockito.mock(Action.class); + doThrow(new IllegalStateException()).when(finallyAction).run(); + + TestSubscriber<String> testSubscriber = new TestSubscriber<String>(); - TestSubscriber<String> testSubscriber = new TestSubscriber<String>(); + Flowable + .just("value") + .doAfterTerminate(finallyAction) + .subscribe(testSubscriber); - Flowable - .just("value") - .doAfterTerminate(finallyAction) - .subscribe(testSubscriber); + testSubscriber.assertValue("value"); - testSubscriber.assertValue("value"); + verify(finallyAction).run(); - verify(finallyAction).run(); - // Actual result: - // Not only IllegalStateException was swallowed - // But finallyAction was called twice! + TestHelper.assertError(errors, 0, IllegalStateException.class); + // Actual result: + // Not only IllegalStateException was swallowed + // But finallyAction was called twice! + } finally { + RxJavaPlugins.reset(); + } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java index 225859575e..4a9ac3eca2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java @@ -37,35 +37,35 @@ public class FlowableDoOnEachTest { - Subscriber<String> subscribedObserver; - Subscriber<String> sideEffectObserver; + Subscriber<String> subscribedSubscriber; + Subscriber<String> sideEffectSubscriber; @Before public void before() { - subscribedObserver = TestHelper.mockSubscriber(); - sideEffectObserver = TestHelper.mockSubscriber(); + subscribedSubscriber = TestHelper.mockSubscriber(); + sideEffectSubscriber = TestHelper.mockSubscriber(); } @Test public void testDoOnEach() { Flowable<String> base = Flowable.just("a", "b", "c"); - Flowable<String> doOnEach = base.doOnEach(sideEffectObserver); + Flowable<String> doOnEach = base.doOnEach(sideEffectSubscriber); - doOnEach.subscribe(subscribedObserver); + doOnEach.subscribe(subscribedSubscriber); // ensure the leaf observer is still getting called - verify(subscribedObserver, never()).onError(any(Throwable.class)); - verify(subscribedObserver, times(1)).onNext("a"); - verify(subscribedObserver, times(1)).onNext("b"); - verify(subscribedObserver, times(1)).onNext("c"); - verify(subscribedObserver, times(1)).onComplete(); + verify(subscribedSubscriber, never()).onError(any(Throwable.class)); + verify(subscribedSubscriber, times(1)).onNext("a"); + verify(subscribedSubscriber, times(1)).onNext("b"); + verify(subscribedSubscriber, times(1)).onNext("c"); + verify(subscribedSubscriber, times(1)).onComplete(); // ensure our injected observer is getting called - verify(sideEffectObserver, never()).onError(any(Throwable.class)); - verify(sideEffectObserver, times(1)).onNext("a"); - verify(sideEffectObserver, times(1)).onNext("b"); - verify(sideEffectObserver, times(1)).onNext("c"); - verify(sideEffectObserver, times(1)).onComplete(); + verify(sideEffectSubscriber, never()).onError(any(Throwable.class)); + verify(sideEffectSubscriber, times(1)).onNext("a"); + verify(sideEffectSubscriber, times(1)).onNext("b"); + verify(sideEffectSubscriber, times(1)).onNext("c"); + verify(sideEffectSubscriber, times(1)).onComplete(); } @Test @@ -81,20 +81,20 @@ public String apply(String s) { } }); - Flowable<String> doOnEach = errs.doOnEach(sideEffectObserver); + Flowable<String> doOnEach = errs.doOnEach(sideEffectSubscriber); - doOnEach.subscribe(subscribedObserver); - verify(subscribedObserver, times(1)).onNext("one"); - verify(subscribedObserver, never()).onNext("two"); - verify(subscribedObserver, never()).onNext("three"); - verify(subscribedObserver, never()).onComplete(); - verify(subscribedObserver, times(1)).onError(any(Throwable.class)); + doOnEach.subscribe(subscribedSubscriber); + verify(subscribedSubscriber, times(1)).onNext("one"); + verify(subscribedSubscriber, never()).onNext("two"); + verify(subscribedSubscriber, never()).onNext("three"); + verify(subscribedSubscriber, never()).onComplete(); + verify(subscribedSubscriber, times(1)).onError(any(Throwable.class)); - verify(sideEffectObserver, times(1)).onNext("one"); - verify(sideEffectObserver, never()).onNext("two"); - verify(sideEffectObserver, never()).onNext("three"); - verify(sideEffectObserver, never()).onComplete(); - verify(sideEffectObserver, times(1)).onError(any(Throwable.class)); + verify(sideEffectSubscriber, times(1)).onNext("one"); + verify(sideEffectSubscriber, never()).onNext("two"); + verify(sideEffectSubscriber, never()).onNext("three"); + verify(sideEffectSubscriber, never()).onComplete(); + verify(sideEffectSubscriber, times(1)).onError(any(Throwable.class)); } @Test @@ -109,12 +109,12 @@ public void accept(String s) { } }); - doOnEach.subscribe(subscribedObserver); - verify(subscribedObserver, times(1)).onNext("one"); - verify(subscribedObserver, times(1)).onNext("two"); - verify(subscribedObserver, never()).onNext("three"); - verify(subscribedObserver, never()).onComplete(); - verify(subscribedObserver, times(1)).onError(any(Throwable.class)); + doOnEach.subscribe(subscribedSubscriber); + verify(subscribedSubscriber, times(1)).onNext("one"); + verify(subscribedSubscriber, times(1)).onNext("two"); + verify(subscribedSubscriber, never()).onNext("three"); + verify(subscribedSubscriber, never()).onComplete(); + verify(subscribedSubscriber, times(1)).onError(any(Throwable.class)); } @@ -180,7 +180,7 @@ public void testFatalError() { // public Flowable<?> apply(Integer integer) { // return Flowable.create(new Publisher<Object>() { // @Override -// public void subscribe(Subscriber<Object> o) { +// public void subscribe(Subscriber<Object> subscriber) { // throw new NullPointerException("Test NPE"); // } // }); @@ -728,8 +728,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.doOnEach(new TestSubscriber<Object>()); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.doOnEach(new TestSubscriber<Object>()); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycleTest.java index af309b0e9b..3d23930aaa 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycleTest.java @@ -48,8 +48,8 @@ public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<Object>>() { @Override - public Publisher<Object> apply(Flowable<Object> o) throws Exception { - return o + public Publisher<Object> apply(Flowable<Object> f) throws Exception { + return f .doOnLifecycle(new Consumer<Subscription>() { @Override public void accept(Subscription s) throws Exception { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnSubscribeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnSubscribeTest.java index 339125c7e8..0b75ec3338 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnSubscribeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnSubscribeTest.java @@ -29,23 +29,23 @@ public class FlowableDoOnSubscribeTest { @Test public void testDoOnSubscribe() throws Exception { final AtomicInteger count = new AtomicInteger(); - Flowable<Integer> o = Flowable.just(1).doOnSubscribe(new Consumer<Subscription>() { + Flowable<Integer> f = Flowable.just(1).doOnSubscribe(new Consumer<Subscription>() { @Override public void accept(Subscription s) { count.incrementAndGet(); } }); - o.subscribe(); - o.subscribe(); - o.subscribe(); + f.subscribe(); + f.subscribe(); + f.subscribe(); assertEquals(3, count.get()); } @Test public void testDoOnSubscribe2() throws Exception { final AtomicInteger count = new AtomicInteger(); - Flowable<Integer> o = Flowable.just(1).doOnSubscribe(new Consumer<Subscription>() { + Flowable<Integer> f = Flowable.just(1).doOnSubscribe(new Consumer<Subscription>() { @Override public void accept(Subscription s) { count.incrementAndGet(); @@ -57,7 +57,7 @@ public void accept(Subscription s) { } }); - o.subscribe(); + f.subscribe(); assertEquals(2, count.get()); } @@ -67,7 +67,7 @@ public void testDoOnUnSubscribeWorksWithRefCount() throws Exception { final AtomicInteger countBefore = new AtomicInteger(); final AtomicInteger countAfter = new AtomicInteger(); final AtomicReference<Subscriber<? super Integer>> sref = new AtomicReference<Subscriber<? super Integer>>(); - Flowable<Integer> o = Flowable.unsafeCreate(new Publisher<Integer>() { + Flowable<Integer> f = Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { @@ -89,16 +89,16 @@ public void accept(Subscription s) { } }); - o.subscribe(); - o.subscribe(); - o.subscribe(); + f.subscribe(); + f.subscribe(); + f.subscribe(); assertEquals(1, countBefore.get()); assertEquals(1, onSubscribed.get()); assertEquals(3, countAfter.get()); sref.get().onComplete(); - o.subscribe(); - o.subscribe(); - o.subscribe(); + f.subscribe(); + f.subscribe(); + f.subscribe(); assertEquals(2, countBefore.get()); assertEquals(2, onSubscribed.get()); assertEquals(6, countAfter.get()); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableElementAtTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableElementAtTest.java index 1b795665ad..e8a395fc3b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableElementAtTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableElementAtTest.java @@ -191,22 +191,22 @@ public void elementAtOrErrorIndex1OnEmptySource() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<Object>>() { @Override - public Publisher<Object> apply(Flowable<Object> o) throws Exception { - return o.elementAt(0).toFlowable(); + public Publisher<Object> apply(Flowable<Object> f) throws Exception { + return f.elementAt(0).toFlowable(); } }); TestHelper.checkDoubleOnSubscribeFlowableToMaybe(new Function<Flowable<Object>, Maybe<Object>>() { @Override - public Maybe<Object> apply(Flowable<Object> o) throws Exception { - return o.elementAt(0); + public Maybe<Object> apply(Flowable<Object> f) throws Exception { + return f.elementAt(0); } }); TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function<Flowable<Object>, Single<Object>>() { @Override - public Single<Object> apply(Flowable<Object> o) throws Exception { - return o.elementAt(0, 1); + public Single<Object> apply(Flowable<Object> f) throws Exception { + return f.elementAt(0, 1); } }); } @@ -338,13 +338,13 @@ public void badSource2() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onNext(2); - observer.onError(new TestException()); - observer.onComplete(); + subscriber.onNext(1); + subscriber.onNext(2); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .elementAt(0, 1) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java index 836ead8bca..85093c4576 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java @@ -66,7 +66,7 @@ public boolean test(String t1) { @Test(timeout = 500) public void testWithBackpressure() throws InterruptedException { Flowable<String> w = Flowable.just("one", "two", "three"); - Flowable<String> o = w.filter(new Predicate<String>() { + Flowable<String> f = w.filter(new Predicate<String>() { @Override public boolean test(String t1) { @@ -100,7 +100,7 @@ public void onNext(String t) { // this means it will only request "one" and "two", expecting to receive them before requesting more ts.request(2); - o.subscribe(ts); + f.subscribe(ts); // this will wait forever unless OperatorTake handles the request(n) on filtered items latch.await(); @@ -113,7 +113,7 @@ public void onNext(String t) { @Test(timeout = 500000) public void testWithBackpressure2() throws InterruptedException { Flowable<Integer> w = Flowable.range(1, Flowable.bufferSize() * 2); - Flowable<Integer> o = w.filter(new Predicate<Integer>() { + Flowable<Integer> f = w.filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -146,7 +146,7 @@ public void onNext(Integer t) { // this means it will only request 1 item and expect to receive more ts.request(1); - o.subscribe(ts); + f.subscribe(ts); // this will wait forever unless OperatorTake handles the request(n) on filtered items latch.await(); @@ -555,8 +555,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.filter(Functions.alwaysTrue()); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.filter(Functions.alwaysTrue()); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFirstTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFirstTest.java index 38c5723726..3d4eacd281 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFirstTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFirstTest.java @@ -92,46 +92,46 @@ public void testFirstOrElseWithPredicateOfSomeFlowable() { @Test public void testFirstFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2, 3).firstElement().toFlowable(); + Flowable<Integer> flowable = Flowable.just(1, 2, 3).firstElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(1); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstWithOneElementFlowable() { - Flowable<Integer> observable = Flowable.just(1).firstElement().toFlowable(); + Flowable<Integer> flowable = Flowable.just(1).firstElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(1); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstWithEmptyFlowable() { - Flowable<Integer> observable = Flowable.<Integer> empty().firstElement().toFlowable(); + Flowable<Integer> flowable = Flowable.<Integer> empty().firstElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onComplete(); - inOrder.verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onComplete(); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstWithPredicateFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2, 3, 4, 5, 6) + Flowable<Integer> flowable = Flowable.just(1, 2, 3, 4, 5, 6) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -140,18 +140,18 @@ public boolean test(Integer t1) { }) .firstElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstWithPredicateAndOneElementFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2) + Flowable<Integer> flowable = Flowable.just(1, 2) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -160,18 +160,18 @@ public boolean test(Integer t1) { }) .firstElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstWithPredicateAndEmptyFlowable() { - Flowable<Integer> observable = Flowable.just(1) + Flowable<Integer> flowable = Flowable.just(1) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -180,59 +180,59 @@ public boolean test(Integer t1) { }) .firstElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onComplete(); - inOrder.verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onComplete(); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstOrDefaultFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2, 3) + Flowable<Integer> flowable = Flowable.just(1, 2, 3) .first(4).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(1); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstOrDefaultWithOneElementFlowable() { - Flowable<Integer> observable = Flowable.just(1).first(2).toFlowable(); + Flowable<Integer> flowable = Flowable.just(1).first(2).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(1); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstOrDefaultWithEmptyFlowable() { - Flowable<Integer> observable = Flowable.<Integer> empty() + Flowable<Integer> flowable = Flowable.<Integer> empty() .first(1).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(1); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstOrDefaultWithPredicateFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2, 3, 4, 5, 6) + Flowable<Integer> flowable = Flowable.just(1, 2, 3, 4, 5, 6) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -241,18 +241,18 @@ public boolean test(Integer t1) { }) .first(8).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstOrDefaultWithPredicateAndOneElementFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2) + Flowable<Integer> flowable = Flowable.just(1, 2) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -261,18 +261,18 @@ public boolean test(Integer t1) { }) .first(4).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testFirstOrDefaultWithPredicateAndEmptyFlowable() { - Flowable<Integer> observable = Flowable.just(1) + Flowable<Integer> flowable = Flowable.just(1) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -281,12 +281,12 @@ public boolean test(Integer t1) { }) .first(2).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -332,9 +332,9 @@ public void testFirstOrElseWithPredicateOfSome() { @Test public void testFirst() { - Maybe<Integer> observable = Flowable.just(1, 2, 3).firstElement(); + Maybe<Integer> maybe = Flowable.just(1, 2, 3).firstElement(); - observable.subscribe(wm); + maybe.subscribe(wm); InOrder inOrder = inOrder(wm); inOrder.verify(wm, times(1)).onSuccess(1); @@ -343,9 +343,9 @@ public void testFirst() { @Test public void testFirstWithOneElement() { - Maybe<Integer> observable = Flowable.just(1).firstElement(); + Maybe<Integer> maybe = Flowable.just(1).firstElement(); - observable.subscribe(wm); + maybe.subscribe(wm); InOrder inOrder = inOrder(wm); inOrder.verify(wm, times(1)).onSuccess(1); @@ -354,9 +354,9 @@ public void testFirstWithOneElement() { @Test public void testFirstWithEmpty() { - Maybe<Integer> observable = Flowable.<Integer> empty().firstElement(); + Maybe<Integer> maybe = Flowable.<Integer> empty().firstElement(); - observable.subscribe(wm); + maybe.subscribe(wm); InOrder inOrder = inOrder(wm); inOrder.verify(wm).onComplete(); @@ -366,7 +366,7 @@ public void testFirstWithEmpty() { @Test public void testFirstWithPredicate() { - Maybe<Integer> observable = Flowable.just(1, 2, 3, 4, 5, 6) + Maybe<Integer> maybe = Flowable.just(1, 2, 3, 4, 5, 6) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -375,7 +375,7 @@ public boolean test(Integer t1) { }) .firstElement(); - observable.subscribe(wm); + maybe.subscribe(wm); InOrder inOrder = inOrder(wm); inOrder.verify(wm, times(1)).onSuccess(2); @@ -384,7 +384,7 @@ public boolean test(Integer t1) { @Test public void testFirstWithPredicateAndOneElement() { - Maybe<Integer> observable = Flowable.just(1, 2) + Maybe<Integer> maybe = Flowable.just(1, 2) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -393,7 +393,7 @@ public boolean test(Integer t1) { }) .firstElement(); - observable.subscribe(wm); + maybe.subscribe(wm); InOrder inOrder = inOrder(wm); inOrder.verify(wm, times(1)).onSuccess(2); @@ -402,7 +402,7 @@ public boolean test(Integer t1) { @Test public void testFirstWithPredicateAndEmpty() { - Maybe<Integer> observable = Flowable.just(1) + Maybe<Integer> maybe = Flowable.just(1) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -411,7 +411,7 @@ public boolean test(Integer t1) { }) .firstElement(); - observable.subscribe(wm); + maybe.subscribe(wm); InOrder inOrder = inOrder(wm); inOrder.verify(wm).onComplete(); @@ -421,10 +421,10 @@ public boolean test(Integer t1) { @Test public void testFirstOrDefault() { - Single<Integer> observable = Flowable.just(1, 2, 3) + Single<Integer> single = Flowable.just(1, 2, 3) .first(4); - observable.subscribe(wo); + single.subscribe(wo); InOrder inOrder = inOrder(wo); inOrder.verify(wo, times(1)).onSuccess(1); @@ -433,9 +433,9 @@ public void testFirstOrDefault() { @Test public void testFirstOrDefaultWithOneElement() { - Single<Integer> observable = Flowable.just(1).first(2); + Single<Integer> single = Flowable.just(1).first(2); - observable.subscribe(wo); + single.subscribe(wo); InOrder inOrder = inOrder(wo); inOrder.verify(wo, times(1)).onSuccess(1); @@ -444,10 +444,10 @@ public void testFirstOrDefaultWithOneElement() { @Test public void testFirstOrDefaultWithEmpty() { - Single<Integer> observable = Flowable.<Integer> empty() + Single<Integer> single = Flowable.<Integer> empty() .first(1); - observable.subscribe(wo); + single.subscribe(wo); InOrder inOrder = inOrder(wo); inOrder.verify(wo, times(1)).onSuccess(1); @@ -456,7 +456,7 @@ public void testFirstOrDefaultWithEmpty() { @Test public void testFirstOrDefaultWithPredicate() { - Single<Integer> observable = Flowable.just(1, 2, 3, 4, 5, 6) + Single<Integer> single = Flowable.just(1, 2, 3, 4, 5, 6) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -465,7 +465,7 @@ public boolean test(Integer t1) { }) .first(8); - observable.subscribe(wo); + single.subscribe(wo); InOrder inOrder = inOrder(wo); inOrder.verify(wo, times(1)).onSuccess(2); @@ -474,7 +474,7 @@ public boolean test(Integer t1) { @Test public void testFirstOrDefaultWithPredicateAndOneElement() { - Single<Integer> observable = Flowable.just(1, 2) + Single<Integer> single = Flowable.just(1, 2) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -483,7 +483,7 @@ public boolean test(Integer t1) { }) .first(4); - observable.subscribe(wo); + single.subscribe(wo); InOrder inOrder = inOrder(wo); inOrder.verify(wo, times(1)).onSuccess(2); @@ -492,7 +492,7 @@ public boolean test(Integer t1) { @Test public void testFirstOrDefaultWithPredicateAndEmpty() { - Single<Integer> observable = Flowable.just(1) + Single<Integer> single = Flowable.just(1) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -501,7 +501,7 @@ public boolean test(Integer t1) { }) .first(2); - observable.subscribe(wo); + single.subscribe(wo); InOrder inOrder = inOrder(wo); inOrder.verify(wo, times(1)).onSuccess(2); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java index 3e7ea75c66..c0ddc1f302 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java @@ -399,8 +399,8 @@ public CompletableSource apply(Integer v) throws Exception { public void badSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(Flowable<Integer> o) throws Exception { - return o.flatMapCompletable(new Function<Integer, CompletableSource>() { + public Object apply(Flowable<Integer> f) throws Exception { + return f.flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); @@ -455,14 +455,14 @@ public void innerObserverFlowable() { public CompletableSource apply(Integer v) throws Exception { return new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); - assertFalse(((Disposable)s).isDisposed()); + assertFalse(((Disposable)observer).isDisposed()); - ((Disposable)s).dispose(); + ((Disposable)observer).dispose(); - assertTrue(((Disposable)s).isDisposed()); + assertTrue(((Disposable)observer).isDisposed()); } }; } @@ -475,8 +475,8 @@ protected void subscribeActual(CompletableObserver s) { public void badSourceFlowable() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(Flowable<Integer> o) throws Exception { - return o.flatMapCompletable(new Function<Integer, CompletableSource>() { + public Object apply(Flowable<Integer> f) throws Exception { + return f.flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); @@ -494,14 +494,14 @@ public void innerObserver() { public CompletableSource apply(Integer v) throws Exception { return new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); - assertFalse(((Disposable)s).isDisposed()); + assertFalse(((Disposable)observer).isDisposed()); - ((Disposable)s).dispose(); + ((Disposable)observer).dispose(); - assertTrue(((Disposable)s).isDisposed()); + assertTrue(((Disposable)observer).isDisposed()); } }; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java index cee2e89628..eac6c0503f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java @@ -411,10 +411,10 @@ public void badSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onError(new TestException("First")); - observer.onError(new TestException("Second")); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onError(new TestException("First")); + subscriber.onError(new TestException("Second")); } } .flatMapMaybe(Functions.justFunction(Maybe.just(2))) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java index 78217c9330..381d210070 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java @@ -331,10 +331,10 @@ public void badSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onError(new TestException("First")); - observer.onError(new TestException("Second")); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onError(new TestException("First")); + subscriber.onError(new TestException("Second")); } } .flatMapSingle(Functions.justFunction(Single.just(2))) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index 9b3037a4c2..9cdbfc26af 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -36,7 +36,7 @@ public class FlowableFlatMapTest { @Test public void testNormal() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); final List<Integer> list = Arrays.asList(1, 2, 3); @@ -56,20 +56,20 @@ public Integer apply(Integer t1, Integer t2) { List<Integer> source = Arrays.asList(16, 32, 64); - Flowable.fromIterable(source).flatMapIterable(func, resFunc).subscribe(o); + Flowable.fromIterable(source).flatMapIterable(func, resFunc).subscribe(subscriber); for (Integer s : source) { for (Integer v : list) { - verify(o).onNext(s | v); + verify(subscriber).onNext(s | v); } } - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testCollectionFunctionThrows() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); Function<Integer, List<Integer>> func = new Function<Integer, List<Integer>>() { @Override @@ -87,16 +87,16 @@ public Integer apply(Integer t1, Integer t2) { List<Integer> source = Arrays.asList(16, 32, 64); - Flowable.fromIterable(source).flatMapIterable(func, resFunc).subscribe(o); + Flowable.fromIterable(source).flatMapIterable(func, resFunc).subscribe(subscriber); - verify(o, never()).onComplete(); - verify(o, never()).onNext(any()); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber).onError(any(TestException.class)); } @Test public void testResultFunctionThrows() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); final List<Integer> list = Arrays.asList(1, 2, 3); @@ -116,16 +116,16 @@ public Integer apply(Integer t1, Integer t2) { List<Integer> source = Arrays.asList(16, 32, 64); - Flowable.fromIterable(source).flatMapIterable(func, resFunc).subscribe(o); + Flowable.fromIterable(source).flatMapIterable(func, resFunc).subscribe(subscriber); - verify(o, never()).onComplete(); - verify(o, never()).onNext(any()); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber).onError(any(TestException.class)); } @Test public void testMergeError() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); Function<Integer, Flowable<Integer>> func = new Function<Integer, Flowable<Integer>>() { @Override @@ -143,11 +143,11 @@ public Integer apply(Integer t1, Integer t2) { List<Integer> source = Arrays.asList(16, 32, 64); - Flowable.fromIterable(source).flatMap(func, resFunc).subscribe(o); + Flowable.fromIterable(source).flatMap(func, resFunc).subscribe(subscriber); - verify(o, never()).onComplete(); - verify(o, never()).onNext(any()); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber).onError(any(TestException.class)); } <T, R> Function<T, R> just(final R value) { @@ -178,18 +178,18 @@ public void testFlatMapTransformsNormal() { Flowable<Integer> source = Flowable.fromIterable(Arrays.asList(10, 20, 30)); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.flatMap(just(onNext), just(onError), just0(onComplete)).subscribe(o); + source.flatMap(just(onNext), just(onError), just0(onComplete)).subscribe(subscriber); - verify(o, times(3)).onNext(1); - verify(o, times(3)).onNext(2); - verify(o, times(3)).onNext(3); - verify(o).onNext(4); - verify(o).onComplete(); + verify(subscriber, times(3)).onNext(1); + verify(subscriber, times(3)).onNext(2); + verify(subscriber, times(3)).onNext(3); + verify(subscriber).onNext(4); + verify(subscriber).onComplete(); - verify(o, never()).onNext(5); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(5); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -204,18 +204,18 @@ Flowable.<Integer> error(new RuntimeException("Forced failure!")) ); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.flatMap(just(onNext), just(onError), just0(onComplete)).subscribe(o); + source.flatMap(just(onNext), just(onError), just0(onComplete)).subscribe(subscriber); - verify(o, times(3)).onNext(1); - verify(o, times(3)).onNext(2); - verify(o, times(3)).onNext(3); - verify(o).onNext(5); - verify(o).onComplete(); - verify(o, never()).onNext(4); + verify(subscriber, times(3)).onNext(1); + verify(subscriber, times(3)).onNext(2); + verify(subscriber, times(3)).onNext(3); + verify(subscriber).onNext(5); + verify(subscriber).onComplete(); + verify(subscriber, never()).onNext(4); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } <R> Callable<R> funcThrow0(R r) { @@ -238,18 +238,25 @@ public R apply(T t) { @Test public void testFlatMapTransformsOnNextFuncThrows() { - Flowable<Integer> onComplete = Flowable.fromIterable(Arrays.asList(4)); - Flowable<Integer> onError = Flowable.fromIterable(Arrays.asList(5)); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable<Integer> onComplete = Flowable.fromIterable(Arrays.asList(4)); + Flowable<Integer> onError = Flowable.fromIterable(Arrays.asList(5)); - Flowable<Integer> source = Flowable.fromIterable(Arrays.asList(10, 20, 30)); + Flowable<Integer> source = Flowable.fromIterable(Arrays.asList(10, 20, 30)); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.flatMap(funcThrow(1, onError), just(onError), just0(onComplete)).subscribe(o); + source.flatMap(funcThrow(1, onError), just(onError), just0(onComplete)).subscribe(subscriber); - verify(o).onError(any(TestException.class)); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -260,13 +267,13 @@ public void testFlatMapTransformsOnErrorFuncThrows() { Flowable<Integer> source = Flowable.error(new TestException()); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.flatMap(just(onNext), funcThrow((Throwable) null, onError), just0(onComplete)).subscribe(o); + source.flatMap(just(onNext), funcThrow((Throwable) null, onError), just0(onComplete)).subscribe(subscriber); - verify(o).onError(any(CompositeException.class)); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber).onError(any(CompositeException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -277,13 +284,13 @@ public void testFlatMapTransformsOnCompletedFuncThrows() { Flowable<Integer> source = Flowable.fromIterable(Arrays.<Integer> asList()); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.flatMap(just(onNext), just(onError), funcThrow0(onComplete)).subscribe(o); + source.flatMap(just(onNext), just(onError), funcThrow0(onComplete)).subscribe(subscriber); - verify(o).onError(any(TestException.class)); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -294,13 +301,13 @@ public void testFlatMapTransformsMergeException() { Flowable<Integer> source = Flowable.fromIterable(Arrays.asList(10, 20, 30)); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.flatMap(just(onNext), just(onError), funcThrow0(onComplete)).subscribe(o); + source.flatMap(just(onNext), just(onError), funcThrow0(onComplete)).subscribe(subscriber); - verify(o).onError(any(TestException.class)); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } private static <T> Flowable<T> composer(Flowable<T> source, final AtomicInteger subscriptionCount, final int m) { @@ -411,8 +418,8 @@ public void testFlatMapTransformsMaxConcurrentNormal() { Flowable<Integer> source = Flowable.fromIterable(Arrays.asList(10, 20, 30)); - Subscriber<Object> o = TestHelper.mockSubscriber(); - TestSubscriber<Object> ts = new TestSubscriber<Object>(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<Object> ts = new TestSubscriber<Object>(subscriber); Function<Integer, Flowable<Integer>> just = just(onNext); Function<Throwable, Flowable<Integer>> just2 = just(onError); @@ -423,14 +430,14 @@ public void testFlatMapTransformsMaxConcurrentNormal() { ts.assertNoErrors(); ts.assertTerminated(); - verify(o, times(3)).onNext(1); - verify(o, times(3)).onNext(2); - verify(o, times(3)).onNext(3); - verify(o).onNext(4); - verify(o).onComplete(); + verify(subscriber, times(3)).onNext(1); + verify(subscriber, times(3)).onNext(2); + verify(subscriber, times(3)).onNext(3); + verify(subscriber).onNext(4); + verify(subscriber).onComplete(); - verify(o, never()).onNext(5); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(5); + verify(subscriber, never()).onError(any(Throwable.class)); } @Ignore("Don't care for any reordering") diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java index 8448e1db06..9baf8f2ea7 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java @@ -583,8 +583,8 @@ public Iterable<Integer> apply(Object v) throws Exception { public void badSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(Flowable<Integer> o) throws Exception { - return o.flatMapIterable(new Function<Object, Iterable<Integer>>() { + public Object apply(Flowable<Integer> f) throws Exception { + return f.flatMapIterable(new Function<Object, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Object v) throws Exception { return Arrays.asList(10, 20); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java index bb51c905aa..f3f5e00fa5 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java @@ -58,13 +58,13 @@ public void shouldCallOnNextAndOnCompleted() throws Exception { Flowable<String> fromCallableFlowable = Flowable.fromCallable(func); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - fromCallableFlowable.subscribe(observer); + fromCallableFlowable.subscribe(subscriber); - verify(observer).onNext("test_value"); - verify(observer).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber).onNext("test_value"); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @SuppressWarnings("unchecked") @@ -77,13 +77,13 @@ public void shouldCallOnError() throws Exception { Flowable<Object> fromCallableFlowable = Flowable.fromCallable(func); - Subscriber<Object> observer = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - fromCallableFlowable.subscribe(observer); + fromCallableFlowable.subscribe(subscriber); - verify(observer, never()).onNext(any()); - verify(observer, never()).onComplete(); - verify(observer).onError(throwable); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(throwable); } @SuppressWarnings("unchecked") @@ -114,9 +114,9 @@ public String answer(InvocationOnMock invocation) throws Throwable { Flowable<String> fromCallableFlowable = Flowable.fromCallable(func); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - TestSubscriber<String> outer = new TestSubscriber<String>(observer); + TestSubscriber<String> outer = new TestSubscriber<String>(subscriber); fromCallableFlowable .subscribeOn(Schedulers.computation()) @@ -135,8 +135,8 @@ public String answer(InvocationOnMock invocation) throws Throwable { verify(func).call(); // Observer must not be notified at all - verify(observer).onSubscribe(any(Subscription.class)); - verifyNoMoreInteractions(observer); + verify(subscriber).onSubscribe(any(Subscription.class)); + verifyNoMoreInteractions(subscriber); } @Test @@ -150,13 +150,13 @@ public Object call() throws Exception { } }); - Subscriber<Object> observer = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - fromCallableFlowable.subscribe(observer); + fromCallableFlowable.subscribe(subscriber); - verify(observer).onSubscribe(any(Subscription.class)); - verify(observer).onError(checkedException); - verifyNoMoreInteractions(observer); + verify(subscriber).onSubscribe(any(Subscription.class)); + verify(subscriber).onError(checkedException); + verifyNoMoreInteractions(subscriber); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java index f606ee6eb4..421cd9e4c7 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java @@ -46,15 +46,15 @@ public void testNull() { public void testListIterable() { Flowable<String> flowable = Flowable.fromIterable(Arrays.<String> asList("one", "two", "three")); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - flowable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } /** @@ -90,30 +90,30 @@ public void remove() { }; Flowable<String> flowable = Flowable.fromIterable(it); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - flowable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext("1"); - verify(observer, times(1)).onNext("2"); - verify(observer, times(1)).onNext("3"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("1"); + verify(subscriber, times(1)).onNext("2"); + verify(subscriber, times(1)).onNext("3"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testObservableFromIterable() { Flowable<String> flowable = Flowable.fromIterable(Arrays.<String> asList("one", "two", "three")); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - flowable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -122,14 +122,14 @@ public void testBackpressureViaRequest() { for (int i = 1; i <= Flowable.bufferSize() + 1; i++) { list.add(i); } - Flowable<Integer> o = Flowable.fromIterable(list); + Flowable<Integer> f = Flowable.fromIterable(list); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L); ts.assertNoValues(); ts.request(1); - o.subscribe(ts); + f.subscribe(ts); ts.assertValue(1); ts.request(2); @@ -142,14 +142,14 @@ public void testBackpressureViaRequest() { @Test public void testNoBackpressure() { - Flowable<Integer> o = Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5)); + Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5)); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L); ts.assertNoValues(); ts.request(Long.MAX_VALUE); // infinite - o.subscribe(ts); + f.subscribe(ts); ts.assertValues(1, 2, 3, 4, 5); ts.assertTerminated(); @@ -157,12 +157,12 @@ public void testNoBackpressure() { @Test public void testSubscribeMultipleTimes() { - Flowable<Integer> o = Flowable.fromIterable(Arrays.asList(1, 2, 3)); + Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1, 2, 3)); for (int i = 0; i < 10; i++) { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); - o.subscribe(ts); + f.subscribe(ts); ts.assertValues(1, 2, 3); ts.assertNoErrors(); @@ -172,12 +172,12 @@ public void testSubscribeMultipleTimes() { @Test public void testFromIterableRequestOverflow() throws InterruptedException { - Flowable<Integer> o = Flowable.fromIterable(Arrays.asList(1,2,3,4)); + Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1,2,3,4)); final int expectedCount = 4; final CountDownLatch latch = new CountDownLatch(expectedCount); - o.subscribeOn(Schedulers.computation()) + f.subscribeOn(Schedulers.computation()) .subscribe(new DefaultSubscriber<Integer>() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromSourceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromSourceTest.java index 2aa29ffca8..e1f15bb261 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromSourceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromSourceTest.java @@ -13,12 +13,15 @@ package io.reactivex.internal.operators.flowable; +import java.util.List; + import org.junit.*; import org.reactivestreams.*; import io.reactivex.*; import io.reactivex.exceptions.*; import io.reactivex.functions.Cancellable; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.subscribers.*; @@ -271,82 +274,116 @@ public void unsubscribedMissing() { @Test public void unsubscribedNoCancelBuffer() { - Flowable.create(sourceNoCancel, BackpressureStrategy.BUFFER).subscribe(ts); - ts.cancel(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable.create(sourceNoCancel, BackpressureStrategy.BUFFER).subscribe(ts); + ts.cancel(); - sourceNoCancel.onNext(1); - sourceNoCancel.onNext(2); - sourceNoCancel.onError(new TestException()); + sourceNoCancel.onNext(1); + sourceNoCancel.onNext(2); + sourceNoCancel.onError(new TestException()); - ts.request(1); + ts.request(1); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + ts.assertNoValues(); + ts.assertNoErrors(); + ts.assertNotComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void unsubscribedNoCancelLatest() { - Flowable.create(sourceNoCancel, BackpressureStrategy.LATEST).subscribe(ts); - ts.cancel(); - - sourceNoCancel.onNext(1); - sourceNoCancel.onNext(2); - sourceNoCancel.onError(new TestException()); - - ts.request(1); - - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable.create(sourceNoCancel, BackpressureStrategy.LATEST).subscribe(ts); + ts.cancel(); + + sourceNoCancel.onNext(1); + sourceNoCancel.onNext(2); + sourceNoCancel.onError(new TestException()); + + ts.request(1); + + ts.assertNoValues(); + ts.assertNoErrors(); + ts.assertNotComplete(); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void unsubscribedNoCancelError() { - Flowable.create(sourceNoCancel, BackpressureStrategy.ERROR).subscribe(ts); - ts.cancel(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable.create(sourceNoCancel, BackpressureStrategy.ERROR).subscribe(ts); + ts.cancel(); - sourceNoCancel.onNext(1); - sourceNoCancel.onNext(2); - sourceNoCancel.onError(new TestException()); + sourceNoCancel.onNext(1); + sourceNoCancel.onNext(2); + sourceNoCancel.onError(new TestException()); - ts.request(1); + ts.request(1); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + ts.assertNoValues(); + ts.assertNoErrors(); + ts.assertNotComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void unsubscribedNoCancelDrop() { - Flowable.create(sourceNoCancel, BackpressureStrategy.DROP).subscribe(ts); - ts.cancel(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable.create(sourceNoCancel, BackpressureStrategy.DROP).subscribe(ts); + ts.cancel(); - sourceNoCancel.onNext(1); - sourceNoCancel.onNext(2); - sourceNoCancel.onError(new TestException()); + sourceNoCancel.onNext(1); + sourceNoCancel.onNext(2); + sourceNoCancel.onError(new TestException()); - ts.request(1); + ts.request(1); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + ts.assertNoValues(); + ts.assertNoErrors(); + ts.assertNotComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void unsubscribedNoCancelMissing() { - Flowable.create(sourceNoCancel, BackpressureStrategy.MISSING).subscribe(ts); - ts.cancel(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable.create(sourceNoCancel, BackpressureStrategy.MISSING).subscribe(ts); + ts.cancel(); - sourceNoCancel.onNext(1); - sourceNoCancel.onNext(2); - sourceNoCancel.onError(new TestException()); + sourceNoCancel.onNext(1); + sourceNoCancel.onNext(2); + sourceNoCancel.onError(new TestException()); - ts.request(1); + ts.request(1); - ts.assertNoValues(); - ts.assertNoErrors(); - ts.assertNotComplete(); + ts.assertNoValues(); + ts.assertNoErrors(); + ts.assertNotComplete(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -622,12 +659,12 @@ public void onNext(Integer t) { static final class PublishAsyncEmitter implements FlowableOnSubscribe<Integer>, FlowableSubscriber<Integer> { - final PublishProcessor<Integer> subject; + final PublishProcessor<Integer> processor; FlowableEmitter<Integer> current; PublishAsyncEmitter() { - this.subject = PublishProcessor.create(); + this.processor = PublishProcessor.create(); } long requested() { @@ -658,7 +695,7 @@ public void onNext(Integer v) { }; - subject.subscribe(as); + processor.subscribe(as); t.setCancellable(new Cancellable() { @Override @@ -675,32 +712,32 @@ public void onSubscribe(Subscription s) { @Override public void onNext(Integer t) { - subject.onNext(t); + processor.onNext(t); } @Override public void onError(Throwable e) { - subject.onError(e); + processor.onError(e); } @Override public void onComplete() { - subject.onComplete(); + processor.onComplete(); } } static final class PublishAsyncEmitterNoCancel implements FlowableOnSubscribe<Integer>, FlowableSubscriber<Integer> { - final PublishProcessor<Integer> subject; + final PublishProcessor<Integer> processor; PublishAsyncEmitterNoCancel() { - this.subject = PublishProcessor.create(); + this.processor = PublishProcessor.create(); } @Override public void subscribe(final FlowableEmitter<Integer> t) { - subject.subscribe(new FlowableSubscriber<Integer>() { + processor.subscribe(new FlowableSubscriber<Integer>() { @Override public void onSubscribe(Subscription s) { @@ -732,17 +769,17 @@ public void onSubscribe(Subscription s) { @Override public void onNext(Integer t) { - subject.onNext(t); + processor.onNext(t); } @Override public void onError(Throwable e) { - subject.onError(e); + processor.onError(e); } @Override public void onComplete() { - subject.onComplete(); + processor.onComplete(); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index bc2473d93e..022ab3788f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -102,7 +102,7 @@ public void testEmpty() { @Test public void testError() { Flowable<String> sourceStrings = Flowable.just("one", "two", "three", "four", "five", "six"); - Flowable<String> errorSource = Flowable.error(new RuntimeException("forced failure")); + Flowable<String> errorSource = Flowable.error(new TestException("forced failure")); Flowable<String> source = Flowable.concat(sourceStrings, errorSource); Flowable<GroupedFlowable<Integer, String>> grouped = source.groupBy(length); @@ -114,13 +114,13 @@ public void testError() { grouped.flatMap(new Function<GroupedFlowable<Integer, String>, Flowable<String>>() { @Override - public Flowable<String> apply(final GroupedFlowable<Integer, String> o) { + public Flowable<String> apply(final GroupedFlowable<Integer, String> f) { groupCounter.incrementAndGet(); - return o.map(new Function<String, String>() { + return f.map(new Function<String, String>() { @Override public String apply(String v) { - return "Event => key: " + o.getKey() + " value: " + v; + return "Event => key: " + f.getKey() + " value: " + v; } }); } @@ -133,7 +133,7 @@ public void onComplete() { @Override public void onError(Throwable e) { - e.printStackTrace(); +// e.printStackTrace(); error.set(e); } @@ -148,22 +148,24 @@ public void onNext(String v) { assertEquals(3, groupCounter.get()); assertEquals(6, eventCounter.get()); assertNotNull(error.get()); + assertTrue("" + error.get(), error.get() instanceof TestException); + assertEquals(error.get().getMessage(), "forced failure"); } - private static <K, V> Map<K, Collection<V>> toMap(Flowable<GroupedFlowable<K, V>> observable) { + private static <K, V> Map<K, Collection<V>> toMap(Flowable<GroupedFlowable<K, V>> flowable) { final ConcurrentHashMap<K, Collection<V>> result = new ConcurrentHashMap<K, Collection<V>>(); - observable.blockingForEach(new Consumer<GroupedFlowable<K, V>>() { + flowable.blockingForEach(new Consumer<GroupedFlowable<K, V>>() { @Override - public void accept(final GroupedFlowable<K, V> o) { - result.put(o.getKey(), new ConcurrentLinkedQueue<V>()); - o.subscribe(new Consumer<V>() { + public void accept(final GroupedFlowable<K, V> f) { + result.put(f.getKey(), new ConcurrentLinkedQueue<V>()); + f.subscribe(new Consumer<V>() { @Override public void accept(V v) { - result.get(o.getKey()).add(v); + result.get(f.getKey()).add(v); } }); @@ -191,8 +193,8 @@ public void testGroupedEventStream() throws Throwable { Flowable<Event> es = Flowable.unsafeCreate(new Publisher<Event>() { @Override - public void subscribe(final Subscriber<? super Event> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super Event> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); System.out.println("*** Subscribing to EventStream ***"); subscribeCounter.incrementAndGet(); new Thread(new Runnable() { @@ -203,9 +205,9 @@ public void run() { Event e = new Event(); e.source = i % groupCount; e.message = "Event-" + i; - observer.onNext(e); + subscriber.onNext(e); } - observer.onComplete(); + subscriber.onComplete(); } }).start(); @@ -998,18 +1000,16 @@ public void testGroupByOnAsynchronousSourceAcceptsMultipleSubscriptions() throws Flowable<GroupedFlowable<Boolean, Long>> stream = source.groupBy(IS_EVEN); // create two observers - @SuppressWarnings("unchecked") - DefaultSubscriber<GroupedFlowable<Boolean, Long>> o1 = mock(DefaultSubscriber.class); - @SuppressWarnings("unchecked") - DefaultSubscriber<GroupedFlowable<Boolean, Long>> o2 = mock(DefaultSubscriber.class); + Subscriber<GroupedFlowable<Boolean, Long>> f1 = TestHelper.mockSubscriber(); + Subscriber<GroupedFlowable<Boolean, Long>> f2 = TestHelper.mockSubscriber(); // subscribe with the observers - stream.subscribe(o1); - stream.subscribe(o2); + stream.subscribe(f1); + stream.subscribe(f2); // check that subscriptions were successful - verify(o1, never()).onError(Mockito.<Throwable> any()); - verify(o2, never()).onError(Mockito.<Throwable> any()); + verify(f1, never()).onError(Mockito.<Throwable> any()); + verify(f2, never()).onError(Mockito.<Throwable> any()); } private static Function<Long, Boolean> IS_EVEN = new Function<Long, Boolean>() { @@ -1227,14 +1227,13 @@ public void accept(GroupedFlowable<Integer, Integer> t1) { inner.get().subscribe(); - @SuppressWarnings("unchecked") - DefaultSubscriber<Integer> o2 = mock(DefaultSubscriber.class); + Subscriber<Integer> subscriber2 = TestHelper.mockSubscriber(); - inner.get().subscribe(o2); + inner.get().subscribe(subscriber2); - verify(o2, never()).onComplete(); - verify(o2, never()).onNext(anyInt()); - verify(o2).onError(any(IllegalStateException.class)); + verify(subscriber2, never()).onComplete(); + verify(subscriber2, never()).onNext(anyInt()); + verify(subscriber2).onError(any(IllegalStateException.class)); } @Test @@ -1386,7 +1385,7 @@ public void accept(String s) { @Test public void testGroupByUnsubscribe() { final Subscription s = mock(Subscription.class); - Flowable<Integer> o = Flowable.unsafeCreate( + Flowable<Integer> f = Flowable.unsafeCreate( new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> subscriber) { @@ -1396,7 +1395,7 @@ public void subscribe(Subscriber<? super Integer> subscriber) { ); TestSubscriber<Object> ts = new TestSubscriber<Object>(); - o.groupBy(new Function<Integer, Integer>() { + f.groupBy(new Function<Integer, Integer>() { @Override public Integer apply(Integer integer) { @@ -1427,11 +1426,11 @@ public void onError(Throwable e) { } @Override - public void onNext(GroupedFlowable<Integer, Integer> o) { - if (o.getKey() == 0) { - o.subscribe(inner1); + public void onNext(GroupedFlowable<Integer, Integer> f) { + if (f.getKey() == 0) { + f.subscribe(inner1); } else { - o.subscribe(inner2); + f.subscribe(inner2); } } }); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java index 0d27bc2280..b9e1b4f995 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java @@ -36,7 +36,7 @@ public class FlowableGroupJoinTest { - Subscriber<Object> observer = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); BiFunction<Integer, Integer, Integer> add = new BiFunction<Integer, Integer, Integer>() { @Override @@ -45,20 +45,20 @@ public Integer apply(Integer t1, Integer t2) { } }; - <T> Function<Integer, Flowable<T>> just(final Flowable<T> observable) { + <T> Function<Integer, Flowable<T>> just(final Flowable<T> flowable) { return new Function<Integer, Flowable<T>>() { @Override public Flowable<T> apply(Integer t1) { - return observable; + return flowable; } }; } - <T, R> Function<T, Flowable<R>> just2(final Flowable<R> observable) { + <T, R> Function<T, Flowable<R>> just2(final Flowable<R> flowable) { return new Function<T, Flowable<R>>() { @Override public Flowable<R> apply(T t1) { - return observable; + return flowable; } }; } @@ -90,7 +90,7 @@ public void behaveAsJoin() { just(Flowable.never()), just(Flowable.never()), add2)); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); source1.onNext(2); @@ -103,18 +103,18 @@ public void behaveAsJoin() { source1.onComplete(); source2.onComplete(); - verify(observer, times(1)).onNext(17); - verify(observer, times(1)).onNext(18); - verify(observer, times(1)).onNext(20); - verify(observer, times(1)).onNext(33); - verify(observer, times(1)).onNext(34); - verify(observer, times(1)).onNext(36); - verify(observer, times(1)).onNext(65); - verify(observer, times(1)).onNext(66); - verify(observer, times(1)).onNext(68); - - verify(observer, times(1)).onComplete(); //Never emitted? - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onNext(17); + verify(subscriber, times(1)).onNext(18); + verify(subscriber, times(1)).onNext(20); + verify(subscriber, times(1)).onNext(33); + verify(subscriber, times(1)).onNext(34); + verify(subscriber, times(1)).onNext(36); + verify(subscriber, times(1)).onNext(65); + verify(subscriber, times(1)).onNext(66); + verify(subscriber, times(1)).onNext(68); + + verify(subscriber, times(1)).onComplete(); //Never emitted? + verify(subscriber, never()).onError(any(Throwable.class)); } class Person { @@ -184,19 +184,19 @@ public boolean test(PersonFruit t1) { }).subscribe(new Consumer<PersonFruit>() { @Override public void accept(PersonFruit t1) { - observer.onNext(Arrays.asList(ppf.person.name, t1.fruit)); + subscriber.onNext(Arrays.asList(ppf.person.name, t1.fruit)); } }); } @Override public void onError(Throwable e) { - observer.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - observer.onComplete(); + subscriber.onComplete(); } @Override @@ -207,12 +207,12 @@ public void onSubscribe(Subscription s) { } ); - verify(observer, times(1)).onNext(Arrays.asList("Joe", "Strawberry")); - verify(observer, times(1)).onNext(Arrays.asList("Joe", "Apple")); - verify(observer, times(1)).onNext(Arrays.asList("Charlie", "Peach")); + verify(subscriber, times(1)).onNext(Arrays.asList("Joe", "Strawberry")); + verify(subscriber, times(1)).onNext(Arrays.asList("Joe", "Apple")); + verify(subscriber, times(1)).onNext(Arrays.asList("Charlie", "Peach")); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -224,14 +224,14 @@ public void leftThrows() { just(Flowable.never()), just(Flowable.never()), add2); - m.subscribe(observer); + m.subscribe(subscriber); source2.onNext(1); source1.onError(new RuntimeException("Forced failure")); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -243,14 +243,14 @@ public void rightThrows() { just(Flowable.never()), just(Flowable.never()), add2); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); source2.onError(new RuntimeException("Forced failure")); - verify(observer, times(1)).onNext(any(Flowable.class)); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); + verify(subscriber, times(1)).onNext(any(Flowable.class)); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); } @Test @@ -263,13 +263,13 @@ public void leftDurationThrows() { Flowable<Flowable<Integer>> m = source1.groupJoin(source2, just(duration1), just(Flowable.never()), add2); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -282,13 +282,13 @@ public void rightDurationThrows() { Flowable<Flowable<Integer>> m = source1.groupJoin(source2, just(Flowable.never()), just(duration1), add2); - m.subscribe(observer); + m.subscribe(subscriber); source2.onNext(1); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -306,13 +306,13 @@ public Flowable<Integer> apply(Integer t1) { Flowable<Flowable<Integer>> m = source1.groupJoin(source2, fail, just(Flowable.never()), add2); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -330,13 +330,13 @@ public Flowable<Integer> apply(Integer t1) { Flowable<Flowable<Integer>> m = source1.groupJoin(source2, just(Flowable.never()), fail, add2); - m.subscribe(observer); + m.subscribe(subscriber); source2.onNext(1); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -354,14 +354,14 @@ public Integer apply(Integer t1, Flowable<Integer> t2) { Flowable<Integer> m = source1.groupJoin(source2, just(Flowable.never()), just(Flowable.never()), fail); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); source2.onNext(2); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -478,31 +478,38 @@ public Flowable<Integer> apply(Integer r, Flowable<Integer> l) throws Exception @Test public void innerErrorRight() { - Flowable.just(1) - .groupJoin( - Flowable.just(2), - new Function<Integer, Flowable<Object>>() { - @Override - public Flowable<Object> apply(Integer left) throws Exception { - return Flowable.never(); - } - }, - new Function<Integer, Flowable<Object>>() { - @Override - public Flowable<Object> apply(Integer right) throws Exception { - return Flowable.error(new TestException()); - } - }, - new BiFunction<Integer, Flowable<Integer>, Flowable<Integer>>() { - @Override - public Flowable<Integer> apply(Integer r, Flowable<Integer> l) throws Exception { - return l; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable.just(1) + .groupJoin( + Flowable.just(2), + new Function<Integer, Flowable<Object>>() { + @Override + public Flowable<Object> apply(Integer left) throws Exception { + return Flowable.never(); + } + }, + new Function<Integer, Flowable<Object>>() { + @Override + public Flowable<Object> apply(Integer right) throws Exception { + return Flowable.error(new TestException()); + } + }, + new BiFunction<Integer, Flowable<Integer>, Flowable<Integer>>() { + @Override + public Flowable<Integer> apply(Integer r, Flowable<Integer> l) throws Exception { + return l; + } } - } - ) - .flatMap(Functions.<Flowable<Integer>>identity()) - .test() - .assertFailure(TestException.class); + ) + .flatMap(Functions.<Flowable<Integer>>identity()) + .test() + .assertFailure(TestException.class); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java index df67bccf02..af85b261c6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java @@ -34,16 +34,16 @@ public void testHiding() { assertFalse(dst instanceof PublishProcessor); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - dst.subscribe(o); + dst.subscribe(subscriber); src.onNext(1); src.onComplete(); - verify(o).onNext(1); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(1); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -54,24 +54,24 @@ public void testHidingError() { assertFalse(dst instanceof PublishProcessor); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - dst.subscribe(o); + dst.subscribe(subscriber); src.onError(new TestException()); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) + public Flowable<Object> apply(Flowable<Object> f) throws Exception { - return o.hide(); + return f.hide(); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java index 6d2d42aeaf..8656afde8d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java @@ -330,17 +330,17 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) + public Flowable<Object> apply(Flowable<Object> f) throws Exception { - return o.ignoreElements().toFlowable(); + return f.ignoreElements().toFlowable(); } }); TestHelper.checkDoubleOnSubscribeFlowableToCompletable(new Function<Flowable<Object>, Completable>() { @Override - public Completable apply(Flowable<Object> o) + public Completable apply(Flowable<Object> f) throws Exception { - return o.ignoreElements(); + return f.ignoreElements(); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java index a44b07608f..14a5ec3d59 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java @@ -34,7 +34,7 @@ import io.reactivex.subscribers.TestSubscriber; public class FlowableJoinTest { - Subscriber<Object> observer = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); BiFunction<Integer, Integer, Integer> add = new BiFunction<Integer, Integer, Integer>() { @Override @@ -43,11 +43,11 @@ public Integer apply(Integer t1, Integer t2) { } }; - <T> Function<Integer, Flowable<T>> just(final Flowable<T> observable) { + <T> Function<Integer, Flowable<T>> just(final Flowable<T> flowable) { return new Function<Integer, Flowable<T>>() { @Override public Flowable<T> apply(Integer t1) { - return observable; + return flowable; } }; } @@ -66,7 +66,7 @@ public void normal1() { just(Flowable.never()), just(Flowable.never()), add); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); source1.onNext(2); @@ -79,18 +79,18 @@ public void normal1() { source1.onComplete(); source2.onComplete(); - verify(observer, times(1)).onNext(17); - verify(observer, times(1)).onNext(18); - verify(observer, times(1)).onNext(20); - verify(observer, times(1)).onNext(33); - verify(observer, times(1)).onNext(34); - verify(observer, times(1)).onNext(36); - verify(observer, times(1)).onNext(65); - verify(observer, times(1)).onNext(66); - verify(observer, times(1)).onNext(68); - - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onNext(17); + verify(subscriber, times(1)).onNext(18); + verify(subscriber, times(1)).onNext(20); + verify(subscriber, times(1)).onNext(33); + verify(subscriber, times(1)).onNext(34); + verify(subscriber, times(1)).onNext(36); + verify(subscriber, times(1)).onNext(65); + verify(subscriber, times(1)).onNext(66); + verify(subscriber, times(1)).onNext(68); + + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -103,7 +103,7 @@ public void normal1WithDuration() { Flowable<Integer> m = source1.join(source2, just(duration1), just(Flowable.never()), add); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); source1.onNext(2); @@ -117,13 +117,13 @@ public void normal1WithDuration() { source1.onComplete(); source2.onComplete(); - verify(observer, times(1)).onNext(17); - verify(observer, times(1)).onNext(18); - verify(observer, times(1)).onNext(20); - verify(observer, times(1)).onNext(24); + verify(subscriber, times(1)).onNext(17); + verify(subscriber, times(1)).onNext(18); + verify(subscriber, times(1)).onNext(20); + verify(subscriber, times(1)).onNext(24); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @@ -136,7 +136,7 @@ public void normal2() { just(Flowable.never()), just(Flowable.never()), add); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); source1.onNext(2); @@ -148,15 +148,15 @@ public void normal2() { source2.onComplete(); - verify(observer, times(1)).onNext(17); - verify(observer, times(1)).onNext(18); - verify(observer, times(1)).onNext(33); - verify(observer, times(1)).onNext(34); - verify(observer, times(1)).onNext(65); - verify(observer, times(1)).onNext(66); + verify(subscriber, times(1)).onNext(17); + verify(subscriber, times(1)).onNext(18); + verify(subscriber, times(1)).onNext(33); + verify(subscriber, times(1)).onNext(34); + verify(subscriber, times(1)).onNext(65); + verify(subscriber, times(1)).onNext(66); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -168,14 +168,14 @@ public void leftThrows() { just(Flowable.never()), just(Flowable.never()), add); - m.subscribe(observer); + m.subscribe(subscriber); source2.onNext(1); source1.onError(new RuntimeException("Forced failure")); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -187,14 +187,14 @@ public void rightThrows() { just(Flowable.never()), just(Flowable.never()), add); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); source2.onError(new RuntimeException("Forced failure")); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -207,13 +207,13 @@ public void leftDurationThrows() { Flowable<Integer> m = source1.join(source2, just(duration1), just(Flowable.never()), add); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -226,13 +226,13 @@ public void rightDurationThrows() { Flowable<Integer> m = source1.join(source2, just(Flowable.never()), just(duration1), add); - m.subscribe(observer); + m.subscribe(subscriber); source2.onNext(1); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -250,13 +250,13 @@ public Flowable<Integer> apply(Integer t1) { Flowable<Integer> m = source1.join(source2, fail, just(Flowable.never()), add); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -274,13 +274,13 @@ public Flowable<Integer> apply(Integer t1) { Flowable<Integer> m = source1.join(source2, just(Flowable.never()), fail, add); - m.subscribe(observer); + m.subscribe(subscriber); source2.onNext(1); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -298,14 +298,14 @@ public Integer apply(Integer t1, Integer t2) { Flowable<Integer> m = source1.join(source2, just(Flowable.never()), just(Flowable.never()), fail); - m.subscribe(observer); + m.subscribe(subscriber); source1.onNext(1); source2.onNext(2); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -386,10 +386,10 @@ public void badOuterSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onError(new TestException("First")); - observer.onError(new TestException("Second")); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onError(new TestException("First")); + subscriber.onError(new TestException("Second")); } } .join(Flowable.just(2), @@ -422,10 +422,10 @@ public void badEndSource() { Functions.justFunction(Flowable.never()), Functions.justFunction(new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - o[0] = observer; - observer.onSubscribe(new BooleanSubscription()); - observer.onError(new TestException("First")); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + o[0] = subscriber; + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onError(new TestException("First")); } }), new BiFunction<Integer, Integer, Integer>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableLastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableLastTest.java index 21a0d2935a..517d727903 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableLastTest.java @@ -53,10 +53,10 @@ public void testLastViaFlowable() { @Test public void testLast() { - Maybe<Integer> observable = Flowable.just(1, 2, 3).lastElement(); + Maybe<Integer> maybe = Flowable.just(1, 2, 3).lastElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(3); @@ -66,10 +66,10 @@ public void testLast() { @Test public void testLastWithOneElement() { - Maybe<Integer> observable = Flowable.just(1).lastElement(); + Maybe<Integer> maybe = Flowable.just(1).lastElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(1); @@ -79,10 +79,10 @@ public void testLastWithOneElement() { @Test public void testLastWithEmpty() { - Maybe<Integer> observable = Flowable.<Integer> empty().lastElement(); + Maybe<Integer> maybe = Flowable.<Integer> empty().lastElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer).onComplete(); @@ -92,7 +92,7 @@ public void testLastWithEmpty() { @Test public void testLastWithPredicate() { - Maybe<Integer> observable = Flowable.just(1, 2, 3, 4, 5, 6) + Maybe<Integer> maybe = Flowable.just(1, 2, 3, 4, 5, 6) .filter(new Predicate<Integer>() { @Override @@ -103,7 +103,7 @@ public boolean test(Integer t1) { .lastElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(6); @@ -113,7 +113,7 @@ public boolean test(Integer t1) { @Test public void testLastWithPredicateAndOneElement() { - Maybe<Integer> observable = Flowable.just(1, 2) + Maybe<Integer> maybe = Flowable.just(1, 2) .filter( new Predicate<Integer>() { @@ -125,7 +125,7 @@ public boolean test(Integer t1) { .lastElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(2); @@ -135,7 +135,7 @@ public boolean test(Integer t1) { @Test public void testLastWithPredicateAndEmpty() { - Maybe<Integer> observable = Flowable.just(1) + Maybe<Integer> maybe = Flowable.just(1) .filter( new Predicate<Integer>() { @@ -146,7 +146,7 @@ public boolean test(Integer t1) { }).lastElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer).onComplete(); @@ -156,11 +156,11 @@ public boolean test(Integer t1) { @Test public void testLastOrDefault() { - Single<Integer> observable = Flowable.just(1, 2, 3) + Single<Integer> single = Flowable.just(1, 2, 3) .last(4); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(3); @@ -170,10 +170,10 @@ public void testLastOrDefault() { @Test public void testLastOrDefaultWithOneElement() { - Single<Integer> observable = Flowable.just(1).last(2); + Single<Integer> single = Flowable.just(1).last(2); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(1); @@ -183,11 +183,11 @@ public void testLastOrDefaultWithOneElement() { @Test public void testLastOrDefaultWithEmpty() { - Single<Integer> observable = Flowable.<Integer> empty() + Single<Integer> single = Flowable.<Integer> empty() .last(1); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(1); @@ -197,7 +197,7 @@ public void testLastOrDefaultWithEmpty() { @Test public void testLastOrDefaultWithPredicate() { - Single<Integer> observable = Flowable.just(1, 2, 3, 4, 5, 6) + Single<Integer> single = Flowable.just(1, 2, 3, 4, 5, 6) .filter(new Predicate<Integer>() { @Override @@ -208,7 +208,7 @@ public boolean test(Integer t1) { .last(8); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(6); @@ -218,7 +218,7 @@ public boolean test(Integer t1) { @Test public void testLastOrDefaultWithPredicateAndOneElement() { - Single<Integer> observable = Flowable.just(1, 2) + Single<Integer> single = Flowable.just(1, 2) .filter(new Predicate<Integer>() { @Override @@ -229,7 +229,7 @@ public boolean test(Integer t1) { .last(4); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(2); @@ -239,7 +239,7 @@ public boolean test(Integer t1) { @Test public void testLastOrDefaultWithPredicateAndEmpty() { - Single<Integer> observable = Flowable.just(1) + Single<Integer> single = Flowable.just(1) .filter( new Predicate<Integer>() { @@ -251,7 +251,7 @@ public boolean test(Integer t1) { .last(2); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(2); @@ -312,40 +312,40 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowableToMaybe(new Function<Flowable<Object>, MaybeSource<Object>>() { @Override - public MaybeSource<Object> apply(Flowable<Object> o) throws Exception { - return o.lastElement(); + public MaybeSource<Object> apply(Flowable<Object> f) throws Exception { + return f.lastElement(); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.lastElement().toFlowable(); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.lastElement().toFlowable(); } }); TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function<Flowable<Object>, SingleSource<Object>>() { @Override - public SingleSource<Object> apply(Flowable<Object> o) throws Exception { - return o.lastOrError(); + public SingleSource<Object> apply(Flowable<Object> f) throws Exception { + return f.lastOrError(); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.lastOrError().toFlowable(); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.lastOrError().toFlowable(); } }); TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function<Flowable<Object>, SingleSource<Object>>() { @Override - public SingleSource<Object> apply(Flowable<Object> o) throws Exception { - return o.last(2); + public SingleSource<Object> apply(Flowable<Object> f) throws Exception { + return f.last(2); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.last(2).toFlowable(); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.last(2).toFlowable(); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableLiftTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableLiftTest.java index 84fe5967a7..bb28c6c597 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableLiftTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableLiftTest.java @@ -15,21 +15,25 @@ import static org.junit.Assert.*; +import java.util.List; + import org.junit.Test; import org.reactivestreams.Subscriber; import io.reactivex.*; import io.reactivex.exceptions.TestException; +import io.reactivex.plugins.RxJavaPlugins; public class FlowableLiftTest { @Test public void callbackCrash() { + List<Throwable> errors = TestHelper.trackPluginErrors(); try { Flowable.just(1) .lift(new FlowableOperator<Object, Integer>() { @Override - public Subscriber<? super Integer> apply(Subscriber<? super Object> o) throws Exception { + public Subscriber<? super Integer> apply(Subscriber<? super Object> subscriber) throws Exception { throw new TestException(); } }) @@ -37,6 +41,9 @@ public Subscriber<? super Integer> apply(Subscriber<? super Object> o) throws Ex fail("Should have thrown"); } catch (NullPointerException ex) { assertTrue(ex.toString(), ex.getCause() instanceof TestException); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapNotificationTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapNotificationTest.java index 245fb9b581..1346e7bc50 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapNotificationTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapNotificationTest.java @@ -153,9 +153,9 @@ public void dispose() { TestHelper.checkDisposed(new Flowable<Integer>() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { + protected void subscribeActual(Subscriber<? super Integer> subscriber) { MapNotificationSubscriber mn = new MapNotificationSubscriber( - observer, + subscriber, Functions.justFunction(Flowable.just(1)), Functions.justFunction(Flowable.just(2)), Functions.justCallable(Flowable.just(3)) @@ -169,8 +169,8 @@ protected void subscribeActual(Subscriber<? super Integer> observer) { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Object> o) throws Exception { - return o.flatMap( + public Flowable<Integer> apply(Flowable<Object> f) throws Exception { + return f.flatMap( Functions.justFunction(Flowable.just(1)), Functions.justFunction(Flowable.just(2)), Functions.justCallable(Flowable.just(3)) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java index 20022bf843..9ebc328d56 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java @@ -57,9 +57,9 @@ public void before() { public void testMap() { Map<String, String> m1 = getMap("One"); Map<String, String> m2 = getMap("Two"); - Flowable<Map<String, String>> observable = Flowable.just(m1, m2); + Flowable<Map<String, String>> flowable = Flowable.just(m1, m2); - Flowable<String> m = observable.map(new Function<Map<String, String>, String>() { + Flowable<String> m = flowable.map(new Function<Map<String, String>, String>() { @Override public String apply(Map<String, String> map) { return map.get("firstName"); @@ -120,19 +120,19 @@ public String apply(Map<String, String> map) { public void testMapMany2() { Map<String, String> m1 = getMap("One"); Map<String, String> m2 = getMap("Two"); - Flowable<Map<String, String>> observable1 = Flowable.just(m1, m2); + Flowable<Map<String, String>> flowable1 = Flowable.just(m1, m2); Map<String, String> m3 = getMap("Three"); Map<String, String> m4 = getMap("Four"); - Flowable<Map<String, String>> observable2 = Flowable.just(m3, m4); + Flowable<Map<String, String>> flowable2 = Flowable.just(m3, m4); - Flowable<Flowable<Map<String, String>>> observable = Flowable.just(observable1, observable2); + Flowable<Flowable<Map<String, String>>> f = Flowable.just(flowable1, flowable2); - Flowable<String> m = observable.flatMap(new Function<Flowable<Map<String, String>>, Flowable<String>>() { + Flowable<String> m = f.flatMap(new Function<Flowable<Map<String, String>>, Flowable<String>>() { @Override - public Flowable<String> apply(Flowable<Map<String, String>> o) { - return o.map(new Function<Map<String, String>, String>() { + public Flowable<String> apply(Flowable<Map<String, String>> f) { + return f.map(new Function<Map<String, String>, String>() { @Override public String apply(Map<String, String> map) { @@ -155,12 +155,14 @@ public String apply(Map<String, String> map) { @Test public void testMapWithError() { + final List<Throwable> errors = new ArrayList<Throwable>(); + Flowable<String> w = Flowable.just("one", "fail", "two", "three", "fail"); Flowable<String> m = w.map(new Function<String, String>() { @Override public String apply(String s) { if ("fail".equals(s)) { - throw new RuntimeException("Forced Failure"); + throw new TestException("Forced Failure"); } return s; } @@ -168,7 +170,7 @@ public String apply(String s) { @Override public void accept(Throwable t1) { - t1.printStackTrace(); + errors.add(t1); } }); @@ -178,7 +180,9 @@ public void accept(Throwable t1) { verify(stringSubscriber, never()).onNext("two"); verify(stringSubscriber, never()).onNext("three"); verify(stringSubscriber, never()).onComplete(); - verify(stringSubscriber, times(1)).onError(any(Throwable.class)); + verify(stringSubscriber, times(1)).onError(any(TestException.class)); + + TestHelper.assertError(errors, 0, TestException.class, "Forced Failure"); } @Test(expected = IllegalArgumentException.class) @@ -291,11 +295,11 @@ public void verifyExceptionIsThrownIfThereIsNoExceptionHandler() { // Flowable.OnSubscribe<Object> creator = new Flowable.OnSubscribe<Object>() { // // @Override -// public void call(Subscriber<? super Object> observer) { -// observer.onNext("a"); -// observer.onNext("b"); -// observer.onNext("c"); -// observer.onComplete(); +// public void call(Subscriber<? super Object> subscriber) { +// subscriber.onNext("a"); +// subscriber.onNext("b"); +// subscriber.onNext("c"); +// subscriber.onComplete(); // } // }; // @@ -630,8 +634,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.map(Functions.identity()); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.map(Functions.identity()); } }); } @@ -680,8 +684,8 @@ public void fusedReject() { public void badSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Object>, Object>() { @Override - public Object apply(Flowable<Object> o) throws Exception { - return o.map(Functions.identity()); + public Object apply(Flowable<Object> f) throws Exception { + return f.map(Functions.identity()); } }, false, 1, 1, 1); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMaterializeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMaterializeTest.java index e1d3045ea6..b35006ebbf 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMaterializeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMaterializeTest.java @@ -233,8 +233,8 @@ private static class TestAsyncErrorObservable implements Publisher<String> { volatile Thread t; @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); t = new Thread(new Runnable() { @Override @@ -247,14 +247,14 @@ public void run() { } catch (Throwable e) { } - observer.onError(new NullPointerException()); + subscriber.onError(new NullPointerException()); return; } else { - observer.onNext(s); + subscriber.onNext(s); } } System.out.println("subscription complete"); - observer.onComplete(); + subscriber.onComplete(); } }); @@ -290,8 +290,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Notification<Object>>>() { @Override - public Flowable<Notification<Object>> apply(Flowable<Object> o) throws Exception { - return o.materialize(); + public Flowable<Notification<Object>> apply(Flowable<Object> f) throws Exception { + return f.materialize(); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java index d9be86f909..03300d4dda 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java @@ -34,164 +34,164 @@ public class FlowableMergeDelayErrorTest { - Subscriber<String> stringObserver; + Subscriber<String> stringSubscriber; @Before public void before() { - stringObserver = TestHelper.mockSubscriber(); + stringSubscriber = TestHelper.mockSubscriber(); } @Test public void testErrorDelayed1() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" from the source (and it should never be sent by the source since onError was called - final Flowable<String> o2 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); - - Flowable<String> m = Flowable.mergeDelayError(o1, o2); - m.subscribe(stringObserver); - - verify(stringObserver, times(1)).onError(any(NullPointerException.class)); - verify(stringObserver, never()).onComplete(); - verify(stringObserver, times(1)).onNext("one"); - verify(stringObserver, times(1)).onNext("two"); - verify(stringObserver, times(1)).onNext("three"); - verify(stringObserver, times(1)).onNext("four"); - verify(stringObserver, times(0)).onNext("five"); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" from the source (and it should never be sent by the source since onError was called + final Flowable<String> f2 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); + + Flowable<String> m = Flowable.mergeDelayError(f1, f2); + m.subscribe(stringSubscriber); + + verify(stringSubscriber, times(1)).onError(any(NullPointerException.class)); + verify(stringSubscriber, never()).onComplete(); + verify(stringSubscriber, times(1)).onNext("one"); + verify(stringSubscriber, times(1)).onNext("two"); + verify(stringSubscriber, times(1)).onNext("three"); + verify(stringSubscriber, times(1)).onNext("four"); + verify(stringSubscriber, times(0)).onNext("five"); // despite not expecting it ... we don't do anything to prevent it if the source Flowable keeps sending after onError // inner Flowable errors are considered terminal for that source -// verify(stringObserver, times(1)).onNext("six"); +// verify(stringSubscriber, times(1)).onNext("six"); // inner Flowable errors are considered terminal for that source } @Test public void testErrorDelayed2() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" from the source (and it should never be sent by the source since onError was called - final Flowable<String> o3 = Flowable.unsafeCreate(new TestErrorFlowable("seven", "eight", null)); - final Flowable<String> o4 = Flowable.unsafeCreate(new TestErrorFlowable("nine")); - - Flowable<String> m = Flowable.mergeDelayError(o1, o2, o3, o4); - m.subscribe(stringObserver); - - verify(stringObserver, times(1)).onError(any(CompositeException.class)); - verify(stringObserver, never()).onComplete(); - verify(stringObserver, times(1)).onNext("one"); - verify(stringObserver, times(1)).onNext("two"); - verify(stringObserver, times(1)).onNext("three"); - verify(stringObserver, times(1)).onNext("four"); - verify(stringObserver, times(0)).onNext("five"); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" from the source (and it should never be sent by the source since onError was called + final Flowable<String> f3 = Flowable.unsafeCreate(new TestErrorFlowable("seven", "eight", null)); + final Flowable<String> f4 = Flowable.unsafeCreate(new TestErrorFlowable("nine")); + + Flowable<String> m = Flowable.mergeDelayError(f1, f2, f3, f4); + m.subscribe(stringSubscriber); + + verify(stringSubscriber, times(1)).onError(any(CompositeException.class)); + verify(stringSubscriber, never()).onComplete(); + verify(stringSubscriber, times(1)).onNext("one"); + verify(stringSubscriber, times(1)).onNext("two"); + verify(stringSubscriber, times(1)).onNext("three"); + verify(stringSubscriber, times(1)).onNext("four"); + verify(stringSubscriber, times(0)).onNext("five"); // despite not expecting it ... we don't do anything to prevent it if the source Flowable keeps sending after onError // inner Flowable errors are considered terminal for that source -// verify(stringObserver, times(1)).onNext("six"); - verify(stringObserver, times(1)).onNext("seven"); - verify(stringObserver, times(1)).onNext("eight"); - verify(stringObserver, times(1)).onNext("nine"); +// verify(stringSubscriber, times(1)).onNext("six"); + verify(stringSubscriber, times(1)).onNext("seven"); + verify(stringSubscriber, times(1)).onNext("eight"); + verify(stringSubscriber, times(1)).onNext("nine"); } @Test public void testErrorDelayed3() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestErrorFlowable("four", "five", "six")); - final Flowable<String> o3 = Flowable.unsafeCreate(new TestErrorFlowable("seven", "eight", null)); - final Flowable<String> o4 = Flowable.unsafeCreate(new TestErrorFlowable("nine")); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestErrorFlowable("four", "five", "six")); + final Flowable<String> f3 = Flowable.unsafeCreate(new TestErrorFlowable("seven", "eight", null)); + final Flowable<String> f4 = Flowable.unsafeCreate(new TestErrorFlowable("nine")); - Flowable<String> m = Flowable.mergeDelayError(o1, o2, o3, o4); - m.subscribe(stringObserver); + Flowable<String> m = Flowable.mergeDelayError(f1, f2, f3, f4); + m.subscribe(stringSubscriber); - verify(stringObserver, times(1)).onError(any(NullPointerException.class)); - verify(stringObserver, never()).onComplete(); - verify(stringObserver, times(1)).onNext("one"); - verify(stringObserver, times(1)).onNext("two"); - verify(stringObserver, times(1)).onNext("three"); - verify(stringObserver, times(1)).onNext("four"); - verify(stringObserver, times(1)).onNext("five"); - verify(stringObserver, times(1)).onNext("six"); - verify(stringObserver, times(1)).onNext("seven"); - verify(stringObserver, times(1)).onNext("eight"); - verify(stringObserver, times(1)).onNext("nine"); + verify(stringSubscriber, times(1)).onError(any(NullPointerException.class)); + verify(stringSubscriber, never()).onComplete(); + verify(stringSubscriber, times(1)).onNext("one"); + verify(stringSubscriber, times(1)).onNext("two"); + verify(stringSubscriber, times(1)).onNext("three"); + verify(stringSubscriber, times(1)).onNext("four"); + verify(stringSubscriber, times(1)).onNext("five"); + verify(stringSubscriber, times(1)).onNext("six"); + verify(stringSubscriber, times(1)).onNext("seven"); + verify(stringSubscriber, times(1)).onNext("eight"); + verify(stringSubscriber, times(1)).onNext("nine"); } @Test public void testErrorDelayed4() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestErrorFlowable("four", "five", "six")); - final Flowable<String> o3 = Flowable.unsafeCreate(new TestErrorFlowable("seven", "eight")); - final Flowable<String> o4 = Flowable.unsafeCreate(new TestErrorFlowable("nine", null)); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestErrorFlowable("four", "five", "six")); + final Flowable<String> f3 = Flowable.unsafeCreate(new TestErrorFlowable("seven", "eight")); + final Flowable<String> f4 = Flowable.unsafeCreate(new TestErrorFlowable("nine", null)); - Flowable<String> m = Flowable.mergeDelayError(o1, o2, o3, o4); - m.subscribe(stringObserver); + Flowable<String> m = Flowable.mergeDelayError(f1, f2, f3, f4); + m.subscribe(stringSubscriber); - verify(stringObserver, times(1)).onError(any(NullPointerException.class)); - verify(stringObserver, never()).onComplete(); - verify(stringObserver, times(1)).onNext("one"); - verify(stringObserver, times(1)).onNext("two"); - verify(stringObserver, times(1)).onNext("three"); - verify(stringObserver, times(1)).onNext("four"); - verify(stringObserver, times(1)).onNext("five"); - verify(stringObserver, times(1)).onNext("six"); - verify(stringObserver, times(1)).onNext("seven"); - verify(stringObserver, times(1)).onNext("eight"); - verify(stringObserver, times(1)).onNext("nine"); + verify(stringSubscriber, times(1)).onError(any(NullPointerException.class)); + verify(stringSubscriber, never()).onComplete(); + verify(stringSubscriber, times(1)).onNext("one"); + verify(stringSubscriber, times(1)).onNext("two"); + verify(stringSubscriber, times(1)).onNext("three"); + verify(stringSubscriber, times(1)).onNext("four"); + verify(stringSubscriber, times(1)).onNext("five"); + verify(stringSubscriber, times(1)).onNext("six"); + verify(stringSubscriber, times(1)).onNext("seven"); + verify(stringSubscriber, times(1)).onNext("eight"); + verify(stringSubscriber, times(1)).onNext("nine"); } @Test public void testErrorDelayed4WithThreading() { - final TestAsyncErrorFlowable o1 = new TestAsyncErrorFlowable("one", "two", "three"); - final TestAsyncErrorFlowable o2 = new TestAsyncErrorFlowable("four", "five", "six"); - final TestAsyncErrorFlowable o3 = new TestAsyncErrorFlowable("seven", "eight"); + final TestAsyncErrorFlowable f1 = new TestAsyncErrorFlowable("one", "two", "three"); + final TestAsyncErrorFlowable f2 = new TestAsyncErrorFlowable("four", "five", "six"); + final TestAsyncErrorFlowable f3 = new TestAsyncErrorFlowable("seven", "eight"); // throw the error at the very end so no onComplete will be called after it - final TestAsyncErrorFlowable o4 = new TestAsyncErrorFlowable("nine", null); + final TestAsyncErrorFlowable f4 = new TestAsyncErrorFlowable("nine", null); - Flowable<String> m = Flowable.mergeDelayError(Flowable.unsafeCreate(o1), Flowable.unsafeCreate(o2), Flowable.unsafeCreate(o3), Flowable.unsafeCreate(o4)); - m.subscribe(stringObserver); + Flowable<String> m = Flowable.mergeDelayError(Flowable.unsafeCreate(f1), Flowable.unsafeCreate(f2), Flowable.unsafeCreate(f3), Flowable.unsafeCreate(f4)); + m.subscribe(stringSubscriber); try { - o1.t.join(); - o2.t.join(); - o3.t.join(); - o4.t.join(); + f1.t.join(); + f2.t.join(); + f3.t.join(); + f4.t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } - verify(stringObserver, times(1)).onNext("one"); - verify(stringObserver, times(1)).onNext("two"); - verify(stringObserver, times(1)).onNext("three"); - verify(stringObserver, times(1)).onNext("four"); - verify(stringObserver, times(1)).onNext("five"); - verify(stringObserver, times(1)).onNext("six"); - verify(stringObserver, times(1)).onNext("seven"); - verify(stringObserver, times(1)).onNext("eight"); - verify(stringObserver, times(1)).onNext("nine"); - verify(stringObserver, times(1)).onError(any(NullPointerException.class)); - verify(stringObserver, never()).onComplete(); + verify(stringSubscriber, times(1)).onNext("one"); + verify(stringSubscriber, times(1)).onNext("two"); + verify(stringSubscriber, times(1)).onNext("three"); + verify(stringSubscriber, times(1)).onNext("four"); + verify(stringSubscriber, times(1)).onNext("five"); + verify(stringSubscriber, times(1)).onNext("six"); + verify(stringSubscriber, times(1)).onNext("seven"); + verify(stringSubscriber, times(1)).onNext("eight"); + verify(stringSubscriber, times(1)).onNext("nine"); + verify(stringSubscriber, times(1)).onError(any(NullPointerException.class)); + verify(stringSubscriber, never()).onComplete(); } @Test public void testCompositeErrorDelayed1() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" from the source (and it should never be sent by the source since onError was called - final Flowable<String> o2 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", null)); - - Flowable<String> m = Flowable.mergeDelayError(o1, o2); - m.subscribe(stringObserver); - - verify(stringObserver, times(1)).onError(any(Throwable.class)); - verify(stringObserver, never()).onComplete(); - verify(stringObserver, times(1)).onNext("one"); - verify(stringObserver, times(1)).onNext("two"); - verify(stringObserver, times(0)).onNext("three"); - verify(stringObserver, times(1)).onNext("four"); - verify(stringObserver, times(0)).onNext("five"); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" from the source (and it should never be sent by the source since onError was called + final Flowable<String> f2 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", null)); + + Flowable<String> m = Flowable.mergeDelayError(f1, f2); + m.subscribe(stringSubscriber); + + verify(stringSubscriber, times(1)).onError(any(Throwable.class)); + verify(stringSubscriber, never()).onComplete(); + verify(stringSubscriber, times(1)).onNext("one"); + verify(stringSubscriber, times(1)).onNext("two"); + verify(stringSubscriber, times(0)).onNext("three"); + verify(stringSubscriber, times(1)).onNext("four"); + verify(stringSubscriber, times(0)).onNext("five"); // despite not expecting it ... we don't do anything to prevent it if the source Flowable keeps sending after onError // inner Flowable errors are considered terminal for that source -// verify(stringObserver, times(1)).onNext("six"); +// verify(stringSubscriber, times(1)).onNext("six"); } @Test public void testCompositeErrorDelayed2() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" from the source (and it should never be sent by the source since onError was called - final Flowable<String> o2 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", null)); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" from the source (and it should never be sent by the source since onError was called + final Flowable<String> f2 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", null)); - Flowable<String> m = Flowable.mergeDelayError(o1, o2); + Flowable<String> m = Flowable.mergeDelayError(f1, f2); CaptureObserver w = new CaptureObserver(); m.subscribe(w); @@ -218,84 +218,84 @@ public void testCompositeErrorDelayed2() { @Test public void testMergeFlowableOfFlowables() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); Flowable<Flowable<String>> flowableOfFlowables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); // simulate what would happen in a Flowable - observer.onNext(o1); - observer.onNext(o2); - observer.onComplete(); + subscriber.onNext(f1); + subscriber.onNext(f2); + subscriber.onComplete(); } }); Flowable<String> m = Flowable.mergeDelayError(flowableOfFlowables); - m.subscribe(stringObserver); + m.subscribe(stringSubscriber); - verify(stringObserver, never()).onError(any(Throwable.class)); - verify(stringObserver, times(1)).onComplete(); - verify(stringObserver, times(2)).onNext("hello"); + verify(stringSubscriber, never()).onError(any(Throwable.class)); + verify(stringSubscriber, times(1)).onComplete(); + verify(stringSubscriber, times(2)).onNext("hello"); } @Test public void testMergeArray() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - Flowable<String> m = Flowable.mergeDelayError(o1, o2); - m.subscribe(stringObserver); + Flowable<String> m = Flowable.mergeDelayError(f1, f2); + m.subscribe(stringSubscriber); - verify(stringObserver, never()).onError(any(Throwable.class)); - verify(stringObserver, times(2)).onNext("hello"); - verify(stringObserver, times(1)).onComplete(); + verify(stringSubscriber, never()).onError(any(Throwable.class)); + verify(stringSubscriber, times(2)).onNext("hello"); + verify(stringSubscriber, times(1)).onComplete(); } @Test public void testMergeList() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); List<Flowable<String>> listOfFlowables = new ArrayList<Flowable<String>>(); - listOfFlowables.add(o1); - listOfFlowables.add(o2); + listOfFlowables.add(f1); + listOfFlowables.add(f2); Flowable<String> m = Flowable.mergeDelayError(Flowable.fromIterable(listOfFlowables)); - m.subscribe(stringObserver); + m.subscribe(stringSubscriber); - verify(stringObserver, never()).onError(any(Throwable.class)); - verify(stringObserver, times(1)).onComplete(); - verify(stringObserver, times(2)).onNext("hello"); + verify(stringSubscriber, never()).onError(any(Throwable.class)); + verify(stringSubscriber, times(1)).onComplete(); + verify(stringSubscriber, times(2)).onNext("hello"); } @Test public void testMergeArrayWithThreading() { - final TestASynchronousFlowable o1 = new TestASynchronousFlowable(); - final TestASynchronousFlowable o2 = new TestASynchronousFlowable(); + final TestASynchronousFlowable f1 = new TestASynchronousFlowable(); + final TestASynchronousFlowable f2 = new TestASynchronousFlowable(); - Flowable<String> m = Flowable.mergeDelayError(Flowable.unsafeCreate(o1), Flowable.unsafeCreate(o2)); - m.subscribe(stringObserver); + Flowable<String> m = Flowable.mergeDelayError(Flowable.unsafeCreate(f1), Flowable.unsafeCreate(f2)); + m.subscribe(stringSubscriber); try { - o1.t.join(); - o2.t.join(); + f1.t.join(); + f2.t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } - verify(stringObserver, never()).onError(any(Throwable.class)); - verify(stringObserver, times(2)).onNext("hello"); - verify(stringObserver, times(1)).onComplete(); + verify(stringSubscriber, never()).onError(any(Throwable.class)); + verify(stringSubscriber, times(2)).onNext("hello"); + verify(stringSubscriber, times(1)).onComplete(); } @Test(timeout = 1000L) public void testSynchronousError() { - final Flowable<Flowable<String>> o1 = Flowable.error(new RuntimeException("unit test")); + final Flowable<Flowable<String>> f1 = Flowable.error(new RuntimeException("unit test")); final CountDownLatch latch = new CountDownLatch(1); - Flowable.mergeDelayError(o1).subscribe(new DefaultSubscriber<String>() { + Flowable.mergeDelayError(f1).subscribe(new DefaultSubscriber<String>() { @Override public void onComplete() { fail("Expected onError path"); @@ -322,10 +322,10 @@ public void onNext(String s) { private static class TestSynchronousFlowable implements Publisher<String> { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext("hello"); - observer.onComplete(); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext("hello"); + subscriber.onComplete(); } } @@ -333,14 +333,14 @@ private static class TestASynchronousFlowable implements Publisher<String> { Thread t; @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); t = new Thread(new Runnable() { @Override public void run() { - observer.onNext("hello"); - observer.onComplete(); + subscriber.onNext("hello"); + subscriber.onComplete(); } }); @@ -357,22 +357,22 @@ private static class TestErrorFlowable implements Publisher<String> { } @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); boolean errorThrown = false; for (String s : valuesToReturn) { if (s == null) { System.out.println("throwing exception"); - observer.onError(new NullPointerException()); + subscriber.onError(new NullPointerException()); errorThrown = true; // purposefully not returning here so it will continue calling onNext // so that we also test that we handle bad sequences like this } else { - observer.onNext(s); + subscriber.onNext(s); } } if (!errorThrown) { - observer.onComplete(); + subscriber.onComplete(); } } } @@ -388,8 +388,8 @@ private static class TestAsyncErrorFlowable implements Publisher<String> { Thread t; @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); t = new Thread(new Runnable() { @Override @@ -402,14 +402,14 @@ public void run() { } catch (Throwable e) { } - observer.onError(new NullPointerException()); + subscriber.onError(new NullPointerException()); return; } else { - observer.onNext(s); + subscriber.onNext(s); } } System.out.println("subscription complete"); - observer.onComplete(); + subscriber.onComplete(); } }); @@ -455,8 +455,8 @@ public void subscribe(Subscriber<? super Integer> t1) { Flowable<Integer> result = Flowable.mergeDelayError(source, Flowable.just(2)); - final Subscriber<Integer> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + final Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); result.subscribe(new DefaultSubscriber<Integer>() { int calls; @@ -465,17 +465,17 @@ public void onNext(Integer t) { if (calls++ == 0) { throw new TestException(); } - o.onNext(t); + subscriber.onNext(t); } @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }); @@ -484,12 +484,12 @@ public void onComplete() { * If the child onNext throws, why would we keep accepting values from * other sources? */ - inOrder.verify(o).onNext(2); - inOrder.verify(o, never()).onNext(0); - inOrder.verify(o, never()).onNext(1); - inOrder.verify(o, never()).onNext(anyInt()); - inOrder.verify(o).onError(any(TestException.class)); - verify(o, never()).onComplete(); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber, never()).onNext(0); + inOrder.verify(subscriber, never()).onNext(1); + inOrder.verify(subscriber, never()).onNext(anyInt()); + inOrder.verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); } @Test @@ -509,30 +509,30 @@ public void testErrorInParentFlowable() { @Test public void testErrorInParentFlowableDelayed() throws Exception { for (int i = 0; i < 50; i++) { - final TestASynchronous1sDelayedFlowable o1 = new TestASynchronous1sDelayedFlowable(); - final TestASynchronous1sDelayedFlowable o2 = new TestASynchronous1sDelayedFlowable(); + final TestASynchronous1sDelayedFlowable f1 = new TestASynchronous1sDelayedFlowable(); + final TestASynchronous1sDelayedFlowable f2 = new TestASynchronous1sDelayedFlowable(); Flowable<Flowable<String>> parentFlowable = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override public void subscribe(Subscriber<? super Flowable<String>> op) { op.onSubscribe(new BooleanSubscription()); - op.onNext(Flowable.unsafeCreate(o1)); - op.onNext(Flowable.unsafeCreate(o2)); + op.onNext(Flowable.unsafeCreate(f1)); + op.onNext(Flowable.unsafeCreate(f2)); op.onError(new NullPointerException("throwing exception in parent")); } }); - Subscriber<String> stringObserver = TestHelper.mockSubscriber(); + stringSubscriber = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(stringObserver); + TestSubscriber<String> ts = new TestSubscriber<String>(stringSubscriber); Flowable<String> m = Flowable.mergeDelayError(parentFlowable); m.subscribe(ts); System.out.println("testErrorInParentFlowableDelayed | " + i); ts.awaitTerminalEvent(2000, TimeUnit.MILLISECONDS); ts.assertTerminated(); - verify(stringObserver, times(2)).onNext("hello"); - verify(stringObserver, times(1)).onError(any(NullPointerException.class)); - verify(stringObserver, never()).onComplete(); + verify(stringSubscriber, times(2)).onNext("hello"); + verify(stringSubscriber, times(1)).onError(any(NullPointerException.class)); + verify(stringSubscriber, never()).onComplete(); } } @@ -540,8 +540,8 @@ private static class TestASynchronous1sDelayedFlowable implements Publisher<Stri Thread t; @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); t = new Thread(new Runnable() { @Override @@ -549,10 +549,10 @@ public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { - observer.onError(e); + subscriber.onError(e); } - observer.onNext("hello"); - observer.onComplete(); + subscriber.onNext("hello"); + subscriber.onComplete(); } }); @@ -585,18 +585,18 @@ public void accept(long t1) { // This is pretty much a clone of testMergeList but with the overloaded MergeDelayError for Iterables @Test public void mergeIterable() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); List<Flowable<String>> listOfFlowables = new ArrayList<Flowable<String>>(); - listOfFlowables.add(o1); - listOfFlowables.add(o2); + listOfFlowables.add(f1); + listOfFlowables.add(f2); Flowable<String> m = Flowable.mergeDelayError(listOfFlowables); - m.subscribe(stringObserver); + m.subscribe(stringSubscriber); - verify(stringObserver, never()).onError(any(Throwable.class)); - verify(stringObserver, times(1)).onComplete(); - verify(stringObserver, times(2)).onNext("hello"); + verify(stringSubscriber, never()).onError(any(Throwable.class)); + verify(stringSubscriber, times(1)).onComplete(); + verify(stringSubscriber, times(2)).onNext("hello"); } @SuppressWarnings("unchecked") diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeMaxConcurrentTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeMaxConcurrentTest.java index 0908334c3f..0973027f3b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeMaxConcurrentTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeMaxConcurrentTest.java @@ -30,13 +30,6 @@ public class FlowableMergeMaxConcurrentTest { - Subscriber<String> stringObserver; - - @Before - public void before() { - stringObserver = TestHelper.mockSubscriber(); - } - @Test public void testWhenMaxConcurrentIsOne() { for (int i = 0; i < 100; i++) { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java index 085b9d1720..e66206c865 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java @@ -40,13 +40,13 @@ public class FlowableMergeTest { - Subscriber<String> stringObserver; + Subscriber<String> stringSubscriber; int count; @Before public void before() { - stringObserver = TestHelper.mockSubscriber(); + stringSubscriber = TestHelper.mockSubscriber(); for (Thread t : Thread.getAllStackTraces().keySet()) { if (t.getName().startsWith("RxNewThread")) { @@ -75,56 +75,56 @@ public void after() { @Test public void testMergeFlowableOfFlowables() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); Flowable<Flowable<String>> flowableOfFlowables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); // simulate what would happen in a Flowable - observer.onNext(o1); - observer.onNext(o2); - observer.onComplete(); + subscriber.onNext(f1); + subscriber.onNext(f2); + subscriber.onComplete(); } }); Flowable<String> m = Flowable.merge(flowableOfFlowables); - m.subscribe(stringObserver); + m.subscribe(stringSubscriber); - verify(stringObserver, never()).onError(any(Throwable.class)); - verify(stringObserver, times(1)).onComplete(); - verify(stringObserver, times(2)).onNext("hello"); + verify(stringSubscriber, never()).onError(any(Throwable.class)); + verify(stringSubscriber, times(1)).onComplete(); + verify(stringSubscriber, times(2)).onNext("hello"); } @Test public void testMergeArray() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - Flowable<String> m = Flowable.merge(o1, o2); - m.subscribe(stringObserver); + Flowable<String> m = Flowable.merge(f1, f2); + m.subscribe(stringSubscriber); - verify(stringObserver, never()).onError(any(Throwable.class)); - verify(stringObserver, times(2)).onNext("hello"); - verify(stringObserver, times(1)).onComplete(); + verify(stringSubscriber, never()).onError(any(Throwable.class)); + verify(stringSubscriber, times(2)).onNext("hello"); + verify(stringSubscriber, times(1)).onComplete(); } @Test public void testMergeList() { - final Flowable<String> o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); List<Flowable<String>> listOfFlowables = new ArrayList<Flowable<String>>(); - listOfFlowables.add(o1); - listOfFlowables.add(o2); + listOfFlowables.add(f1); + listOfFlowables.add(f2); Flowable<String> m = Flowable.merge(listOfFlowables); - m.subscribe(stringObserver); + m.subscribe(stringSubscriber); - verify(stringObserver, never()).onError(any(Throwable.class)); - verify(stringObserver, times(1)).onComplete(); - verify(stringObserver, times(2)).onNext("hello"); + verify(stringSubscriber, never()).onError(any(Throwable.class)); + verify(stringSubscriber, times(1)).onComplete(); + verify(stringSubscriber, times(2)).onNext("hello"); } @Test(timeout = 1000) @@ -136,7 +136,7 @@ public void testUnSubscribeFlowableOfFlowables() throws InterruptedException { Flowable<Flowable<Long>> source = Flowable.unsafeCreate(new Publisher<Flowable<Long>>() { @Override - public void subscribe(final Subscriber<? super Flowable<Long>> observer) { + public void subscribe(final Subscriber<? super Flowable<Long>> subscriber) { // verbose on purpose so I can track the inside of it final Subscription s = new Subscription() { @@ -152,7 +152,7 @@ public void cancel() { } }; - observer.onSubscribe(s); + subscriber.onSubscribe(s); new Thread(new Runnable() { @@ -160,10 +160,10 @@ public void cancel() { public void run() { while (!unsubscribed.get()) { - observer.onNext(Flowable.just(1L, 2L)); + subscriber.onNext(Flowable.just(1L, 2L)); } System.out.println("Done looping after unsubscribe: " + unsubscribed.get()); - observer.onComplete(); + subscriber.onComplete(); // mark that the thread is finished latch.countDown(); @@ -197,19 +197,19 @@ public void accept(Long v) { @Test public void testMergeArrayWithThreading() { - final TestASynchronousFlowable o1 = new TestASynchronousFlowable(); - final TestASynchronousFlowable o2 = new TestASynchronousFlowable(); + final TestASynchronousFlowable f1 = new TestASynchronousFlowable(); + final TestASynchronousFlowable f2 = new TestASynchronousFlowable(); - Flowable<String> m = Flowable.merge(Flowable.unsafeCreate(o1), Flowable.unsafeCreate(o2)); - TestSubscriber<String> ts = new TestSubscriber<String>(stringObserver); + Flowable<String> m = Flowable.merge(Flowable.unsafeCreate(f1), Flowable.unsafeCreate(f2)); + TestSubscriber<String> ts = new TestSubscriber<String>(stringSubscriber); m.subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); - verify(stringObserver, never()).onError(any(Throwable.class)); - verify(stringObserver, times(2)).onNext("hello"); - verify(stringObserver, times(1)).onComplete(); + verify(stringSubscriber, never()).onError(any(Throwable.class)); + verify(stringSubscriber, times(2)).onNext("hello"); + verify(stringSubscriber, times(1)).onComplete(); } @Test @@ -222,8 +222,8 @@ public void testSynchronizationOfMultipleSequencesLoop() throws Throwable { @Test public void testSynchronizationOfMultipleSequences() throws Throwable { - final TestASynchronousFlowable o1 = new TestASynchronousFlowable(); - final TestASynchronousFlowable o2 = new TestASynchronousFlowable(); + final TestASynchronousFlowable f1 = new TestASynchronousFlowable(); + final TestASynchronousFlowable f2 = new TestASynchronousFlowable(); // use this latch to cause onNext to wait until we're ready to let it go final CountDownLatch endLatch = new CountDownLatch(1); @@ -233,7 +233,7 @@ public void testSynchronizationOfMultipleSequences() throws Throwable { final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); - Flowable<String> m = Flowable.merge(Flowable.unsafeCreate(o1), Flowable.unsafeCreate(o2)); + Flowable<String> m = Flowable.merge(Flowable.unsafeCreate(f1), Flowable.unsafeCreate(f2)); m.subscribe(new DefaultSubscriber<String>() { @Override @@ -267,8 +267,8 @@ public void onNext(String v) { }); // wait for both Flowables to send (one should be blocked) - o1.onNextBeingSent.await(); - o2.onNextBeingSent.await(); + f1.onNextBeingSent.await(); + f2.onNextBeingSent.await(); // I can't think of a way to know for sure that both threads have or are trying to send onNext // since I can't use a CountDownLatch for "after" onNext since I want to catch during it @@ -295,8 +295,8 @@ public void onNext(String v) { } try { - o1.t.join(); - o2.t.join(); + f1.t.join(); + f2.t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } @@ -311,20 +311,20 @@ public void onNext(String v) { @Test public void testError1() { // we are using synchronous execution to test this exactly rather than non-deterministic concurrent behavior - final Flowable<String> o1 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" - final Flowable<String> o2 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); // we expect to lose all of these since o1 is done first and fails + final Flowable<String> f1 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" + final Flowable<String> f2 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); // we expect to lose all of these since o1 is done first and fails - Flowable<String> m = Flowable.merge(o1, o2); - m.subscribe(stringObserver); + Flowable<String> m = Flowable.merge(f1, f2); + m.subscribe(stringSubscriber); - verify(stringObserver, times(1)).onError(any(NullPointerException.class)); - verify(stringObserver, never()).onComplete(); - verify(stringObserver, times(0)).onNext("one"); - verify(stringObserver, times(0)).onNext("two"); - verify(stringObserver, times(0)).onNext("three"); - verify(stringObserver, times(1)).onNext("four"); - verify(stringObserver, times(0)).onNext("five"); - verify(stringObserver, times(0)).onNext("six"); + verify(stringSubscriber, times(1)).onError(any(NullPointerException.class)); + verify(stringSubscriber, never()).onComplete(); + verify(stringSubscriber, times(0)).onNext("one"); + verify(stringSubscriber, times(0)).onNext("two"); + verify(stringSubscriber, times(0)).onNext("three"); + verify(stringSubscriber, times(1)).onNext("four"); + verify(stringSubscriber, times(0)).onNext("five"); + verify(stringSubscriber, times(0)).onNext("six"); } /** @@ -333,32 +333,32 @@ public void testError1() { @Test public void testError2() { // we are using synchronous execution to test this exactly rather than non-deterministic concurrent behavior - final Flowable<String> o1 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); - final Flowable<String> o2 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" - final Flowable<String> o3 = Flowable.unsafeCreate(new TestErrorFlowable("seven", "eight", null));// we expect to lose all of these since o2 is done first and fails - final Flowable<String> o4 = Flowable.unsafeCreate(new TestErrorFlowable("nine"));// we expect to lose all of these since o2 is done first and fails - - Flowable<String> m = Flowable.merge(o1, o2, o3, o4); - m.subscribe(stringObserver); - - verify(stringObserver, times(1)).onError(any(NullPointerException.class)); - verify(stringObserver, never()).onComplete(); - verify(stringObserver, times(1)).onNext("one"); - verify(stringObserver, times(1)).onNext("two"); - verify(stringObserver, times(1)).onNext("three"); - verify(stringObserver, times(1)).onNext("four"); - verify(stringObserver, times(0)).onNext("five"); - verify(stringObserver, times(0)).onNext("six"); - verify(stringObserver, times(0)).onNext("seven"); - verify(stringObserver, times(0)).onNext("eight"); - verify(stringObserver, times(0)).onNext("nine"); + final Flowable<String> f1 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); + final Flowable<String> f2 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" + final Flowable<String> f3 = Flowable.unsafeCreate(new TestErrorFlowable("seven", "eight", null));// we expect to lose all of these since o2 is done first and fails + final Flowable<String> f4 = Flowable.unsafeCreate(new TestErrorFlowable("nine"));// we expect to lose all of these since o2 is done first and fails + + Flowable<String> m = Flowable.merge(f1, f2, f3, f4); + m.subscribe(stringSubscriber); + + verify(stringSubscriber, times(1)).onError(any(NullPointerException.class)); + verify(stringSubscriber, never()).onComplete(); + verify(stringSubscriber, times(1)).onNext("one"); + verify(stringSubscriber, times(1)).onNext("two"); + verify(stringSubscriber, times(1)).onNext("three"); + verify(stringSubscriber, times(1)).onNext("four"); + verify(stringSubscriber, times(0)).onNext("five"); + verify(stringSubscriber, times(0)).onNext("six"); + verify(stringSubscriber, times(0)).onNext("seven"); + verify(stringSubscriber, times(0)).onNext("eight"); + verify(stringSubscriber, times(0)).onNext("nine"); } @Test @Ignore("Subscribe should not throw") public void testThrownErrorHandling() { TestSubscriber<String> ts = new TestSubscriber<String>(); - Flowable<String> o1 = Flowable.unsafeCreate(new Publisher<String>() { + Flowable<String> f1 = Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> s) { @@ -367,7 +367,7 @@ public void subscribe(Subscriber<? super String> s) { }); - Flowable.merge(o1, o1).subscribe(ts); + Flowable.merge(f1, f1).subscribe(ts); ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); ts.assertTerminated(); System.out.println("Error: " + ts.errors()); @@ -376,10 +376,10 @@ public void subscribe(Subscriber<? super String> s) { private static class TestSynchronousFlowable implements Publisher<String> { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext("hello"); - observer.onComplete(); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext("hello"); + subscriber.onComplete(); } } @@ -388,20 +388,20 @@ private static class TestASynchronousFlowable implements Publisher<String> { final CountDownLatch onNextBeingSent = new CountDownLatch(1); @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); t = new Thread(new Runnable() { @Override public void run() { onNextBeingSent.countDown(); try { - observer.onNext("hello"); + subscriber.onNext("hello"); // I can't use a countDownLatch to prove we are actually sending 'onNext' // since it will block if synchronized and I'll deadlock - observer.onComplete(); + subscriber.onComplete(); } catch (Exception e) { - observer.onError(e); + subscriber.onError(e); } } @@ -419,17 +419,17 @@ private static class TestErrorFlowable implements Publisher<String> { } @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); for (String s : valuesToReturn) { if (s == null) { System.out.println("throwing exception"); - observer.onError(new NullPointerException()); + subscriber.onError(new NullPointerException()); } else { - observer.onNext(s); + subscriber.onNext(s); } } - observer.onComplete(); + subscriber.onComplete(); } } @@ -437,14 +437,14 @@ public void subscribe(Subscriber<? super String> observer) { public void testUnsubscribeAsFlowablesComplete() { TestScheduler scheduler1 = new TestScheduler(); AtomicBoolean os1 = new AtomicBoolean(false); - Flowable<Long> o1 = createFlowableOf5IntervalsOf1SecondIncrementsWithSubscriptionHook(scheduler1, os1); + Flowable<Long> f1 = createFlowableOf5IntervalsOf1SecondIncrementsWithSubscriptionHook(scheduler1, os1); TestScheduler scheduler2 = new TestScheduler(); AtomicBoolean os2 = new AtomicBoolean(false); - Flowable<Long> o2 = createFlowableOf5IntervalsOf1SecondIncrementsWithSubscriptionHook(scheduler2, os2); + Flowable<Long> f2 = createFlowableOf5IntervalsOf1SecondIncrementsWithSubscriptionHook(scheduler2, os2); TestSubscriber<Long> ts = new TestSubscriber<Long>(); - Flowable.merge(o1, o2).subscribe(ts); + Flowable.merge(f1, f2).subscribe(ts); // we haven't incremented time so nothing should be received yet ts.assertNoValues(); @@ -479,14 +479,14 @@ public void testEarlyUnsubscribe() { for (int i = 0; i < 10; i++) { TestScheduler scheduler1 = new TestScheduler(); AtomicBoolean os1 = new AtomicBoolean(false); - Flowable<Long> o1 = createFlowableOf5IntervalsOf1SecondIncrementsWithSubscriptionHook(scheduler1, os1); + Flowable<Long> f1 = createFlowableOf5IntervalsOf1SecondIncrementsWithSubscriptionHook(scheduler1, os1); TestScheduler scheduler2 = new TestScheduler(); AtomicBoolean os2 = new AtomicBoolean(false); - Flowable<Long> o2 = createFlowableOf5IntervalsOf1SecondIncrementsWithSubscriptionHook(scheduler2, os2); + Flowable<Long> f2 = createFlowableOf5IntervalsOf1SecondIncrementsWithSubscriptionHook(scheduler2, os2); TestSubscriber<Long> ts = new TestSubscriber<Long>(); - Flowable.merge(o1, o2).subscribe(ts); + Flowable.merge(f1, f2).subscribe(ts); // we haven't incremented time so nothing should be received yet ts.assertNoValues(); @@ -557,10 +557,10 @@ public void onComplete() { @Test//(timeout = 10000) public void testConcurrency() { - Flowable<Integer> o = Flowable.range(1, 10000).subscribeOn(Schedulers.newThread()); + Flowable<Integer> f = Flowable.range(1, 10000).subscribeOn(Schedulers.newThread()); for (int i = 0; i < 10; i++) { - Flowable<Integer> merge = Flowable.merge(o.onBackpressureBuffer(), o.onBackpressureBuffer(), o.onBackpressureBuffer()); + Flowable<Integer> merge = Flowable.merge(f.onBackpressureBuffer(), f.onBackpressureBuffer(), f.onBackpressureBuffer()); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); merge.subscribe(ts); @@ -577,7 +577,7 @@ public void testConcurrency() { @Test public void testConcurrencyWithSleeping() { - Flowable<Integer> o = Flowable.unsafeCreate(new Publisher<Integer>() { + Flowable<Integer> f = Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(final Subscriber<? super Integer> s) { @@ -613,7 +613,7 @@ public void run() { }); for (int i = 0; i < 10; i++) { - Flowable<Integer> merge = Flowable.merge(o, o, o); + Flowable<Integer> merge = Flowable.merge(f, f, f); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); merge.subscribe(ts); @@ -627,7 +627,7 @@ public void run() { @Test public void testConcurrencyWithBrokenOnCompleteContract() { - Flowable<Integer> o = Flowable.unsafeCreate(new Publisher<Integer>() { + Flowable<Integer> f = Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(final Subscriber<? super Integer> s) { @@ -660,7 +660,7 @@ public void run() { }); for (int i = 0; i < 10; i++) { - Flowable<Integer> merge = Flowable.merge(o.onBackpressureBuffer(), o.onBackpressureBuffer(), o.onBackpressureBuffer()); + Flowable<Integer> merge = Flowable.merge(f.onBackpressureBuffer(), f.onBackpressureBuffer(), f.onBackpressureBuffer()); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); merge.subscribe(ts); @@ -676,9 +676,9 @@ public void run() { @Test public void testBackpressureUpstream() throws InterruptedException { final AtomicInteger generated1 = new AtomicInteger(); - Flowable<Integer> o1 = createInfiniteFlowable(generated1).subscribeOn(Schedulers.computation()); + Flowable<Integer> f1 = createInfiniteFlowable(generated1).subscribeOn(Schedulers.computation()); final AtomicInteger generated2 = new AtomicInteger(); - Flowable<Integer> o2 = createInfiniteFlowable(generated2).subscribeOn(Schedulers.computation()); + Flowable<Integer> f2 = createInfiniteFlowable(generated2).subscribeOn(Schedulers.computation()); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>() { @Override @@ -688,7 +688,7 @@ public void onNext(Integer t) { } }; - Flowable.merge(o1.take(Flowable.bufferSize() * 2), o2.take(Flowable.bufferSize() * 2)).subscribe(testSubscriber); + Flowable.merge(f1.take(Flowable.bufferSize() * 2), f2.take(Flowable.bufferSize() * 2)).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); if (testSubscriber.errors().size() > 0) { testSubscriber.errors().get(0).printStackTrace(); @@ -715,7 +715,7 @@ public void testBackpressureUpstream2InLoop() throws InterruptedException { @Test public void testBackpressureUpstream2() throws InterruptedException { final AtomicInteger generated1 = new AtomicInteger(); - Flowable<Integer> o1 = createInfiniteFlowable(generated1).subscribeOn(Schedulers.computation()); + Flowable<Integer> f1 = createInfiniteFlowable(generated1).subscribeOn(Schedulers.computation()); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>() { @Override @@ -724,7 +724,7 @@ public void onNext(Integer t) { } }; - Flowable.merge(o1.take(Flowable.bufferSize() * 2), Flowable.just(-99)).subscribe(testSubscriber); + Flowable.merge(f1.take(Flowable.bufferSize() * 2), Flowable.just(-99)).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); List<Integer> onNextEvents = testSubscriber.values(); @@ -750,9 +750,9 @@ public void onNext(Integer t) { @Test(timeout = 10000) public void testBackpressureDownstreamWithConcurrentStreams() throws InterruptedException { final AtomicInteger generated1 = new AtomicInteger(); - Flowable<Integer> o1 = createInfiniteFlowable(generated1).subscribeOn(Schedulers.computation()); + Flowable<Integer> f1 = createInfiniteFlowable(generated1).subscribeOn(Schedulers.computation()); final AtomicInteger generated2 = new AtomicInteger(); - Flowable<Integer> o2 = createInfiniteFlowable(generated2).subscribeOn(Schedulers.computation()); + Flowable<Integer> f2 = createInfiniteFlowable(generated2).subscribeOn(Schedulers.computation()); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>() { @Override @@ -770,7 +770,7 @@ public void onNext(Integer t) { } }; - Flowable.merge(o1.take(Flowable.bufferSize() * 2), o2.take(Flowable.bufferSize() * 2)).observeOn(Schedulers.computation()).subscribe(testSubscriber); + Flowable.merge(f1.take(Flowable.bufferSize() * 2), f2.take(Flowable.bufferSize() * 2)).observeOn(Schedulers.computation()).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); if (testSubscriber.errors().size() > 0) { testSubscriber.errors().get(0).printStackTrace(); @@ -787,7 +787,7 @@ public void onNext(Integer t) { @Test public void testBackpressureBothUpstreamAndDownstreamWithSynchronousScalarFlowables() throws InterruptedException { final AtomicInteger generated1 = new AtomicInteger(); - Flowable<Flowable<Integer>> o1 = createInfiniteFlowable(generated1) + Flowable<Flowable<Integer>> f1 = createInfiniteFlowable(generated1) .map(new Function<Integer, Flowable<Integer>>() { @Override @@ -813,7 +813,7 @@ public void onNext(Integer t) { } }; - Flowable.merge(o1).observeOn(Schedulers.computation()).take(Flowable.bufferSize() * 2).subscribe(testSubscriber); + Flowable.merge(f1).observeOn(Schedulers.computation()).take(Flowable.bufferSize() * 2).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); if (testSubscriber.errors().size() > 0) { testSubscriber.errors().get(0).printStackTrace(); @@ -841,7 +841,7 @@ public void onNext(Integer t) { @Test(timeout = 5000) public void testBackpressureBothUpstreamAndDownstreamWithRegularFlowables() throws InterruptedException { final AtomicInteger generated1 = new AtomicInteger(); - Flowable<Flowable<Integer>> o1 = createInfiniteFlowable(generated1).map(new Function<Integer, Flowable<Integer>>() { + Flowable<Flowable<Integer>> f1 = createInfiniteFlowable(generated1).map(new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer t1) { @@ -868,7 +868,7 @@ public void onNext(Integer t) { } }; - Flowable.merge(o1).observeOn(Schedulers.computation()).take(Flowable.bufferSize() * 2).subscribe(testSubscriber); + Flowable.merge(f1).observeOn(Schedulers.computation()).take(Flowable.bufferSize() * 2).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); if (testSubscriber.errors().size() > 0) { testSubscriber.errors().get(0).printStackTrace(); @@ -1269,11 +1269,11 @@ public void run() { @Test public void testMergeRequestOverflow() throws InterruptedException { //do a non-trivial merge so that future optimisations with EMPTY don't invalidate this test - Flowable<Integer> o = Flowable.fromIterable(Arrays.asList(1,2)) + Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1,2)) .mergeWith(Flowable.fromIterable(Arrays.asList(3,4))); final int expectedCount = 4; final CountDownLatch latch = new CountDownLatch(expectedCount); - o.subscribeOn(Schedulers.computation()).subscribe(new DefaultSubscriber<Integer>() { + f.subscribeOn(Schedulers.computation()).subscribe(new DefaultSubscriber<Integer>() { @Override public void onStart() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java index 3344a30a65..10c6f5bd47 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java @@ -46,13 +46,13 @@ public class FlowableObserveOnTest { */ @Test public void testObserveOn() { - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - Flowable.just(1, 2, 3).observeOn(ImmediateThinScheduler.INSTANCE).subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + Flowable.just(1, 2, 3).observeOn(ImmediateThinScheduler.INSTANCE).subscribe(subscriber); - verify(observer, times(1)).onNext(1); - verify(observer, times(1)).onNext(2); - verify(observer, times(1)).onNext(3); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(1); + verify(subscriber, times(1)).onNext(2); + verify(subscriber, times(1)).onNext(3); + verify(subscriber, times(1)).onComplete(); } @Test @@ -61,10 +61,10 @@ public void testOrdering() throws InterruptedException { // FIXME null values not allowed Flowable<String> obs = Flowable.just("one", "null", "two", "three", "four"); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + InOrder inOrder = inOrder(subscriber); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); obs.observeOn(Schedulers.computation()).subscribe(ts); @@ -76,12 +76,12 @@ public void testOrdering() throws InterruptedException { fail("failed with exception"); } - inOrder.verify(observer, times(1)).onNext("one"); - inOrder.verify(observer, times(1)).onNext("null"); - inOrder.verify(observer, times(1)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - inOrder.verify(observer, times(1)).onNext("four"); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("one"); + inOrder.verify(subscriber, times(1)).onNext("null"); + inOrder.verify(subscriber, times(1)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + inOrder.verify(subscriber, times(1)).onNext("four"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -92,7 +92,7 @@ public void testThreadName() throws InterruptedException { // Flowable<String> obs = Flowable.just("one", null, "two", "three", "four"); Flowable<String> obs = Flowable.just("one", "null", "two", "three", "four"); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); final String parentThreadName = Thread.currentThread().getName(); final CountDownLatch completedLatch = new CountDownLatch(1); @@ -127,45 +127,45 @@ public void run() { completedLatch.countDown(); } - }).subscribe(observer); + }).subscribe(subscriber); if (!completedLatch.await(1000, TimeUnit.MILLISECONDS)) { fail("timed out waiting"); } - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(5)).onNext(any(String.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(5)).onNext(any(String.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void observeOnTheSameSchedulerTwice() { Scheduler scheduler = ImmediateThinScheduler.INSTANCE; - Flowable<Integer> o = Flowable.just(1, 2, 3); - Flowable<Integer> o2 = o.observeOn(scheduler); + Flowable<Integer> f = Flowable.just(1, 2, 3); + Flowable<Integer> f2 = f.observeOn(scheduler); - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - Subscriber<Object> observer2 = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber2 = TestHelper.mockSubscriber(); - InOrder inOrder1 = inOrder(observer1); - InOrder inOrder2 = inOrder(observer2); + InOrder inOrder1 = inOrder(subscriber1); + InOrder inOrder2 = inOrder(subscriber2); - o2.subscribe(observer1); - o2.subscribe(observer2); + f2.subscribe(subscriber1); + f2.subscribe(subscriber2); - inOrder1.verify(observer1, times(1)).onNext(1); - inOrder1.verify(observer1, times(1)).onNext(2); - inOrder1.verify(observer1, times(1)).onNext(3); - inOrder1.verify(observer1, times(1)).onComplete(); - verify(observer1, never()).onError(any(Throwable.class)); + inOrder1.verify(subscriber1, times(1)).onNext(1); + inOrder1.verify(subscriber1, times(1)).onNext(2); + inOrder1.verify(subscriber1, times(1)).onNext(3); + inOrder1.verify(subscriber1, times(1)).onComplete(); + verify(subscriber1, never()).onError(any(Throwable.class)); inOrder1.verifyNoMoreInteractions(); - inOrder2.verify(observer2, times(1)).onNext(1); - inOrder2.verify(observer2, times(1)).onNext(2); - inOrder2.verify(observer2, times(1)).onNext(3); - inOrder2.verify(observer2, times(1)).onComplete(); - verify(observer2, never()).onError(any(Throwable.class)); + inOrder2.verify(subscriber2, times(1)).onNext(1); + inOrder2.verify(subscriber2, times(1)).onNext(2); + inOrder2.verify(subscriber2, times(1)).onNext(3); + inOrder2.verify(subscriber2, times(1)).onComplete(); + verify(subscriber2, never()).onError(any(Throwable.class)); inOrder2.verifyNoMoreInteractions(); } @@ -174,34 +174,34 @@ public void observeSameOnMultipleSchedulers() { TestScheduler scheduler1 = new TestScheduler(); TestScheduler scheduler2 = new TestScheduler(); - Flowable<Integer> o = Flowable.just(1, 2, 3); - Flowable<Integer> o1 = o.observeOn(scheduler1); - Flowable<Integer> o2 = o.observeOn(scheduler2); + Flowable<Integer> f = Flowable.just(1, 2, 3); + Flowable<Integer> f1 = f.observeOn(scheduler1); + Flowable<Integer> f2 = f.observeOn(scheduler2); - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - Subscriber<Object> observer2 = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber2 = TestHelper.mockSubscriber(); - InOrder inOrder1 = inOrder(observer1); - InOrder inOrder2 = inOrder(observer2); + InOrder inOrder1 = inOrder(subscriber1); + InOrder inOrder2 = inOrder(subscriber2); - o1.subscribe(observer1); - o2.subscribe(observer2); + f1.subscribe(subscriber1); + f2.subscribe(subscriber2); scheduler1.advanceTimeBy(1, TimeUnit.SECONDS); scheduler2.advanceTimeBy(1, TimeUnit.SECONDS); - inOrder1.verify(observer1, times(1)).onNext(1); - inOrder1.verify(observer1, times(1)).onNext(2); - inOrder1.verify(observer1, times(1)).onNext(3); - inOrder1.verify(observer1, times(1)).onComplete(); - verify(observer1, never()).onError(any(Throwable.class)); + inOrder1.verify(subscriber1, times(1)).onNext(1); + inOrder1.verify(subscriber1, times(1)).onNext(2); + inOrder1.verify(subscriber1, times(1)).onNext(3); + inOrder1.verify(subscriber1, times(1)).onComplete(); + verify(subscriber1, never()).onError(any(Throwable.class)); inOrder1.verifyNoMoreInteractions(); - inOrder2.verify(observer2, times(1)).onNext(1); - inOrder2.verify(observer2, times(1)).onNext(2); - inOrder2.verify(observer2, times(1)).onNext(3); - inOrder2.verify(observer2, times(1)).onComplete(); - verify(observer2, never()).onError(any(Throwable.class)); + inOrder2.verify(subscriber2, times(1)).onNext(1); + inOrder2.verify(subscriber2, times(1)).onNext(2); + inOrder2.verify(subscriber2, times(1)).onNext(3); + inOrder2.verify(subscriber2, times(1)).onComplete(); + verify(subscriber2, never()).onError(any(Throwable.class)); inOrder2.verifyNoMoreInteractions(); } @@ -366,27 +366,26 @@ public void testDelayedErrorDeliveryWhenSafeSubscriberUnsubscribes() { Flowable<Integer> source = Flowable.concat(Flowable.<Integer> error(new TestException()), Flowable.just(1)); - @SuppressWarnings("unchecked") - DefaultSubscriber<Integer> o = mock(DefaultSubscriber.class); - InOrder inOrder = inOrder(o); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.observeOn(testScheduler).subscribe(o); + source.observeOn(testScheduler).subscribe(subscriber); - inOrder.verify(o, never()).onError(any(TestException.class)); + inOrder.verify(subscriber, never()).onError(any(TestException.class)); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); - inOrder.verify(o).onError(any(TestException.class)); - inOrder.verify(o, never()).onNext(anyInt()); - inOrder.verify(o, never()).onComplete(); + inOrder.verify(subscriber).onError(any(TestException.class)); + inOrder.verify(subscriber, never()).onNext(anyInt()); + inOrder.verify(subscriber, never()).onComplete(); } @Test public void testAfterUnsubscribeCalledThenObserverOnNextNeverCalled() { final TestScheduler testScheduler = new TestScheduler(); - final Subscriber<Integer> observer = TestHelper.mockSubscriber(); - TestSubscriber<Integer> ts = new TestSubscriber<Integer>(observer); + final Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(subscriber); Flowable.just(1, 2, 3) .observeOn(testScheduler) @@ -395,11 +394,11 @@ public void testAfterUnsubscribeCalledThenObserverOnNextNeverCalled() { ts.dispose(); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); - final InOrder inOrder = inOrder(observer); + final InOrder inOrder = inOrder(subscriber); - inOrder.verify(observer, never()).onNext(anyInt()); - inOrder.verify(observer, never()).onError(any(Exception.class)); - inOrder.verify(observer, never()).onComplete(); + inOrder.verify(subscriber, never()).onNext(anyInt()); + inOrder.verify(subscriber, never()).onError(any(Exception.class)); + inOrder.verify(subscriber, never()).onComplete(); } @Test @@ -538,13 +537,13 @@ public void testQueueFullEmitsError() { Flowable<Integer> flowable = Flowable.unsafeCreate(new Publisher<Integer>() { @Override - public void subscribe(Subscriber<? super Integer> o) { - o.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); for (int i = 0; i < Flowable.bufferSize() + 10; i++) { - o.onNext(i); + subscriber.onNext(i); } latch.countDown(); - o.onComplete(); + subscriber.onComplete(); } }); @@ -601,7 +600,7 @@ public void testAsyncChild() { @Test public void testOnErrorCutsAheadOfOnNext() { for (int i = 0; i < 50; i++) { - final PublishProcessor<Long> subject = PublishProcessor.create(); + final PublishProcessor<Long> processor = PublishProcessor.create(); final AtomicLong counter = new AtomicLong(); TestSubscriber<Long> ts = new TestSubscriber<Long>(new DefaultSubscriber<Long>() { @@ -626,11 +625,11 @@ public void onNext(Long t) { } }); - subject.observeOn(Schedulers.computation()).subscribe(ts); + processor.observeOn(Schedulers.computation()).subscribe(ts); // this will blow up with backpressure while (counter.get() < 102400) { - subject.onNext(counter.get()); + processor.onNext(counter.get()); counter.incrementAndGet(); } @@ -1151,8 +1150,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.observeOn(new TestScheduler()); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.observeOn(new TestScheduler()); } }); } @@ -1164,12 +1163,12 @@ public void badSource() { TestScheduler scheduler = new TestScheduler(); TestSubscriber<Integer> ts = new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onComplete(); - observer.onNext(1); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); + subscriber.onNext(1); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .observeOn(scheduler) @@ -1344,11 +1343,11 @@ public void onComplete() { public void nonFusedPollThrows() { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); @SuppressWarnings("unchecked") - BaseObserveOnSubscriber<Integer> oo = (BaseObserveOnSubscriber<Integer>)observer; + BaseObserveOnSubscriber<Integer> oo = (BaseObserveOnSubscriber<Integer>)subscriber; oo.sourceMode = QueueFuseable.SYNC; oo.requested.lazySet(1); @@ -1395,11 +1394,11 @@ public void clear() { public void conditionalNonFusedPollThrows() { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); @SuppressWarnings("unchecked") - BaseObserveOnSubscriber<Integer> oo = (BaseObserveOnSubscriber<Integer>)observer; + BaseObserveOnSubscriber<Integer> oo = (BaseObserveOnSubscriber<Integer>)subscriber; oo.sourceMode = QueueFuseable.SYNC; oo.requested.lazySet(1); @@ -1447,11 +1446,11 @@ public void clear() { public void asycFusedPollThrows() { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); @SuppressWarnings("unchecked") - BaseObserveOnSubscriber<Integer> oo = (BaseObserveOnSubscriber<Integer>)observer; + BaseObserveOnSubscriber<Integer> oo = (BaseObserveOnSubscriber<Integer>)subscriber; oo.sourceMode = QueueFuseable.ASYNC; oo.requested.lazySet(1); @@ -1498,11 +1497,11 @@ public void clear() { public void conditionalAsyncFusedPollThrows() { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); @SuppressWarnings("unchecked") - BaseObserveOnSubscriber<Integer> oo = (BaseObserveOnSubscriber<Integer>)observer; + BaseObserveOnSubscriber<Integer> oo = (BaseObserveOnSubscriber<Integer>)subscriber; oo.sourceMode = QueueFuseable.ASYNC; oo.requested.lazySet(1); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java index 86c12e3304..ed8b3b6aba 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java @@ -36,10 +36,10 @@ public void testResumeNext() { TestObservable f = new TestObservable(s, "one", "fail", "two", "three"); Flowable<String> w = Flowable.unsafeCreate(f); Flowable<String> resume = Flowable.just("twoResume", "threeResume"); - Flowable<String> observable = w.onErrorResumeNext(resume); + Flowable<String> flowable = w.onErrorResumeNext(resume); - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); try { f.t.join(); @@ -47,13 +47,13 @@ public void testResumeNext() { fail(e.getMessage()); } - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("one"); - verify(observer, Mockito.never()).onNext("two"); - verify(observer, Mockito.never()).onNext("three"); - verify(observer, times(1)).onNext("twoResume"); - verify(observer, times(1)).onNext("threeResume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, Mockito.never()).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, times(1)).onNext("twoResume"); + verify(subscriber, times(1)).onNext("threeResume"); } @Test @@ -78,11 +78,11 @@ public String apply(String s) { } }); - Flowable<String> observable = w.onErrorResumeNext(resume); + Flowable<String> flowable = w.onErrorResumeNext(resume); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); try { f.t.join(); @@ -90,13 +90,13 @@ public String apply(String s) { fail(e.getMessage()); } - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("one"); - verify(observer, Mockito.never()).onNext("two"); - verify(observer, Mockito.never()).onNext("three"); - verify(observer, times(1)).onNext("twoResume"); - verify(observer, times(1)).onNext("threeResume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, Mockito.never()).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, times(1)).onNext("twoResume"); + verify(subscriber, times(1)).onNext("threeResume"); } @Test @@ -111,14 +111,14 @@ public void subscribe(Subscriber<? super String> t1) { }); Flowable<String> resume = Flowable.just("resume"); - Flowable<String> observable = testObservable.onErrorResumeNext(resume); + Flowable<String> flowable = testObservable.onErrorResumeNext(resume); - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("resume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("resume"); } @Test @@ -133,18 +133,17 @@ public void subscribe(Subscriber<? super String> t1) { }); Flowable<String> resume = Flowable.just("resume"); - Flowable<String> observable = testObservable.subscribeOn(Schedulers.io()).onErrorResumeNext(resume); + Flowable<String> flowable = testObservable.subscribeOn(Schedulers.io()).onErrorResumeNext(resume); - @SuppressWarnings("unchecked") - DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); - TestSubscriber<String> ts = new TestSubscriber<String>(observer, Long.MAX_VALUE); - observable.subscribe(ts); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber, Long.MAX_VALUE); + flowable.subscribe(ts); ts.awaitTerminalEvent(); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("resume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("resume"); } static final class TestObservable implements Publisher<String> { @@ -159,9 +158,9 @@ static final class TestObservable implements Publisher<String> { } @Override - public void subscribe(final Subscriber<? super String> observer) { + public void subscribe(final Subscriber<? super String> subscriber) { System.out.println("TestObservable subscribed to ..."); - observer.onSubscribe(s); + subscriber.onSubscribe(s); t = new Thread(new Runnable() { @Override @@ -173,13 +172,13 @@ public void run() { throw new RuntimeException("Forced Failure"); } System.out.println("TestObservable onNext: " + s); - observer.onNext(s); + subscriber.onNext(s); } System.out.println("TestObservable onComplete"); - observer.onComplete(); + subscriber.onComplete(); } catch (Throwable e) { System.out.println("TestObservable onError: " + e); - observer.onError(e); + subscriber.onError(e); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java index 8d55d06f96..06f10e835d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; @@ -40,12 +41,12 @@ public void testResumeNextWithSynchronousExecution() { Flowable<String> w = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext("one"); - observer.onError(new Throwable("injected failure")); - observer.onNext("two"); - observer.onNext("three"); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext("one"); + subscriber.onError(new Throwable("injected failure")); + subscriber.onNext("two"); + subscriber.onNext("three"); } }); @@ -58,19 +59,19 @@ public Flowable<String> apply(Throwable t1) { } }; - Flowable<String> observable = w.onErrorResumeNext(resume); + Flowable<String> flowable = w.onErrorResumeNext(resume); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("one"); - verify(observer, Mockito.never()).onNext("two"); - verify(observer, Mockito.never()).onNext("three"); - verify(observer, times(1)).onNext("twoResume"); - verify(observer, times(1)).onNext("threeResume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, Mockito.never()).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, times(1)).onNext("twoResume"); + verify(subscriber, times(1)).onNext("threeResume"); assertNotNull(receivedException.get()); } @@ -88,11 +89,11 @@ public Flowable<String> apply(Throwable t1) { } }; - Flowable<String> observable = Flowable.unsafeCreate(w).onErrorResumeNext(resume); + Flowable<String> flowable = Flowable.unsafeCreate(w).onErrorResumeNext(resume); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); try { w.t.join(); @@ -100,13 +101,13 @@ public Flowable<String> apply(Throwable t1) { fail(e.getMessage()); } - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("one"); - verify(observer, Mockito.never()).onNext("two"); - verify(observer, Mockito.never()).onNext("three"); - verify(observer, times(1)).onNext("twoResume"); - verify(observer, times(1)).onNext("threeResume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, Mockito.never()).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, times(1)).onNext("twoResume"); + verify(subscriber, times(1)).onNext("threeResume"); assertNotNull(receivedException.get()); } @@ -125,11 +126,10 @@ public Flowable<String> apply(Throwable t1) { } }; - Flowable<String> observable = Flowable.unsafeCreate(w).onErrorResumeNext(resume); + Flowable<String> flowable = Flowable.unsafeCreate(w).onErrorResumeNext(resume); - @SuppressWarnings("unchecked") - DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); - observable.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); try { w.t.join(); @@ -138,11 +138,11 @@ public Flowable<String> apply(Throwable t1) { } // we should get the "one" value before the error - verify(observer, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("one"); // we should have received an onError call on the Observer since the resume function threw an exception - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, times(0)).onComplete(); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, times(0)).onComplete(); } /** @@ -251,7 +251,7 @@ public String apply(String s) { } }); - Flowable<String> observable = w.onErrorResumeNext(new Function<Throwable, Flowable<String>>() { + Flowable<String> flowable = w.onErrorResumeNext(new Function<Throwable, Flowable<String>>() { @Override public Flowable<String> apply(Throwable t1) { @@ -260,20 +260,19 @@ public Flowable<String> apply(Throwable t1) { }); - @SuppressWarnings("unchecked") - DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer, Long.MAX_VALUE); - observable.subscribe(ts); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber, Long.MAX_VALUE); + flowable.subscribe(ts); ts.awaitTerminalEvent(); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("one"); - verify(observer, Mockito.never()).onNext("two"); - verify(observer, Mockito.never()).onNext("three"); - verify(observer, times(1)).onNext("twoResume"); - verify(observer, times(1)).onNext("threeResume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, Mockito.never()).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, times(1)).onNext("twoResume"); + verify(subscriber, times(1)).onNext("threeResume"); } private static class TestFlowable implements Publisher<String> { @@ -286,9 +285,9 @@ private static class TestFlowable implements Publisher<String> { } @Override - public void subscribe(final Subscriber<? super String> observer) { + public void subscribe(final Subscriber<? super String> subscriber) { System.out.println("TestFlowable subscribed to ..."); - observer.onSubscribe(new BooleanSubscription()); + subscriber.onSubscribe(new BooleanSubscription()); t = new Thread(new Runnable() { @Override @@ -297,11 +296,11 @@ public void run() { System.out.println("running TestFlowable thread"); for (String s : values) { System.out.println("TestFlowable onNext: " + s); - observer.onNext(s); + subscriber.onNext(s); } throw new RuntimeException("Forced Failure"); } catch (Throwable e) { - observer.onError(e); + subscriber.onError(e); } } @@ -382,9 +381,9 @@ public Flowable<Integer> apply(Throwable v) { public void badOtherSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(Flowable<Integer> o) throws Exception { + public Object apply(Flowable<Integer> f) throws Exception { return Flowable.error(new IOException()) - .onErrorResumeNext(Functions.justFunction(o)); + .onErrorResumeNext(Functions.justFunction(f)); } }, false, 1, 1, 1); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java index a22c4055e2..9bcc27d5f3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java @@ -38,7 +38,7 @@ public void testResumeNext() { Flowable<String> w = Flowable.unsafeCreate(f); final AtomicReference<Throwable> capturedException = new AtomicReference<Throwable>(); - Flowable<String> observable = w.onErrorReturn(new Function<Throwable, String>() { + Flowable<String> flowable = w.onErrorReturn(new Function<Throwable, String>() { @Override public String apply(Throwable e) { @@ -48,8 +48,8 @@ public String apply(Throwable e) { }); - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); try { f.t.join(); @@ -57,10 +57,10 @@ public String apply(Throwable e) { fail(e.getMessage()); } - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("failure"); - verify(observer, times(1)).onComplete(); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("failure"); + verify(subscriber, times(1)).onComplete(); assertNotNull(capturedException.get()); } @@ -73,7 +73,7 @@ public void testFunctionThrowsError() { Flowable<String> w = Flowable.unsafeCreate(f); final AtomicReference<Throwable> capturedException = new AtomicReference<Throwable>(); - Flowable<String> observable = w.onErrorReturn(new Function<Throwable, String>() { + Flowable<String> flowable = w.onErrorReturn(new Function<Throwable, String>() { @Override public String apply(Throwable e) { @@ -83,9 +83,8 @@ public String apply(Throwable e) { }); - @SuppressWarnings("unchecked") - DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); - observable.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); try { f.t.join(); @@ -94,11 +93,11 @@ public String apply(Throwable e) { } // we should get the "one" value before the error - verify(observer, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("one"); // we should have received an onError call on the Observer since the resume function threw an exception - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, times(0)).onComplete(); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, times(0)).onComplete(); assertNotNull(capturedException.get()); } @@ -120,7 +119,7 @@ public String apply(String s) { } }); - Flowable<String> observable = w.onErrorReturn(new Function<Throwable, String>() { + Flowable<String> flowable = w.onErrorReturn(new Function<Throwable, String>() { @Override public String apply(Throwable t1) { @@ -129,18 +128,17 @@ public String apply(Throwable t1) { }); - @SuppressWarnings("unchecked") - DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); - TestSubscriber<String> ts = new TestSubscriber<String>(observer, Long.MAX_VALUE); - observable.subscribe(ts); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber, Long.MAX_VALUE); + flowable.subscribe(ts); ts.awaitTerminalEvent(); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("one"); - verify(observer, Mockito.never()).onNext("two"); - verify(observer, Mockito.never()).onNext("three"); - verify(observer, times(1)).onNext("resume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, Mockito.never()).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, times(1)).onNext("resume"); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java index 6c6b8c9962..3da05ffedf 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java @@ -36,10 +36,10 @@ public void testResumeNextWithException() { TestObservable f = new TestObservable("one", "EXCEPTION", "two", "three"); Flowable<String> w = Flowable.unsafeCreate(f); Flowable<String> resume = Flowable.just("twoResume", "threeResume"); - Flowable<String> observable = w.onExceptionResumeNext(resume); + Flowable<String> flowable = w.onExceptionResumeNext(resume); - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); try { f.t.join(); @@ -47,15 +47,15 @@ public void testResumeNextWithException() { fail(e.getMessage()); } - verify(observer).onSubscribe((Subscription)any()); - verify(observer, times(1)).onNext("one"); - verify(observer, Mockito.never()).onNext("two"); - verify(observer, Mockito.never()).onNext("three"); - verify(observer, times(1)).onNext("twoResume"); - verify(observer, times(1)).onNext("threeResume"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verifyNoMoreInteractions(observer); + verify(subscriber).onSubscribe((Subscription)any()); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, Mockito.never()).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, times(1)).onNext("twoResume"); + verify(subscriber, times(1)).onNext("threeResume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verifyNoMoreInteractions(subscriber); } @Test @@ -64,10 +64,10 @@ public void testResumeNextWithRuntimeException() { TestObservable f = new TestObservable("one", "RUNTIMEEXCEPTION", "two", "three"); Flowable<String> w = Flowable.unsafeCreate(f); Flowable<String> resume = Flowable.just("twoResume", "threeResume"); - Flowable<String> observable = w.onExceptionResumeNext(resume); + Flowable<String> flowable = w.onExceptionResumeNext(resume); - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); try { f.t.join(); @@ -75,15 +75,15 @@ public void testResumeNextWithRuntimeException() { fail(e.getMessage()); } - verify(observer).onSubscribe((Subscription)any()); - verify(observer, times(1)).onNext("one"); - verify(observer, Mockito.never()).onNext("two"); - verify(observer, Mockito.never()).onNext("three"); - verify(observer, times(1)).onNext("twoResume"); - verify(observer, times(1)).onNext("threeResume"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verifyNoMoreInteractions(observer); + verify(subscriber).onSubscribe((Subscription)any()); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, Mockito.never()).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, times(1)).onNext("twoResume"); + verify(subscriber, times(1)).onNext("threeResume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verifyNoMoreInteractions(subscriber); } @Test @@ -92,10 +92,10 @@ public void testThrowablePassesThru() { TestObservable f = new TestObservable("one", "THROWABLE", "two", "three"); Flowable<String> w = Flowable.unsafeCreate(f); Flowable<String> resume = Flowable.just("twoResume", "threeResume"); - Flowable<String> observable = w.onExceptionResumeNext(resume); + Flowable<String> flowable = w.onExceptionResumeNext(resume); - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); try { f.t.join(); @@ -103,15 +103,15 @@ public void testThrowablePassesThru() { fail(e.getMessage()); } - verify(observer).onSubscribe((Subscription)any()); - verify(observer, times(1)).onNext("one"); - verify(observer, never()).onNext("two"); - verify(observer, never()).onNext("three"); - verify(observer, never()).onNext("twoResume"); - verify(observer, never()).onNext("threeResume"); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verifyNoMoreInteractions(observer); + verify(subscriber).onSubscribe((Subscription)any()); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onNext("two"); + verify(subscriber, never()).onNext("three"); + verify(subscriber, never()).onNext("twoResume"); + verify(subscriber, never()).onNext("threeResume"); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verifyNoMoreInteractions(subscriber); } @Test @@ -120,10 +120,10 @@ public void testErrorPassesThru() { TestObservable f = new TestObservable("one", "ERROR", "two", "three"); Flowable<String> w = Flowable.unsafeCreate(f); Flowable<String> resume = Flowable.just("twoResume", "threeResume"); - Flowable<String> observable = w.onExceptionResumeNext(resume); + Flowable<String> flowable = w.onExceptionResumeNext(resume); - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); try { f.t.join(); @@ -131,15 +131,15 @@ public void testErrorPassesThru() { fail(e.getMessage()); } - verify(observer).onSubscribe((Subscription)any()); - verify(observer, times(1)).onNext("one"); - verify(observer, never()).onNext("two"); - verify(observer, never()).onNext("three"); - verify(observer, never()).onNext("twoResume"); - verify(observer, never()).onNext("threeResume"); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verifyNoMoreInteractions(observer); + verify(subscriber).onSubscribe((Subscription)any()); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onNext("two"); + verify(subscriber, never()).onNext("three"); + verify(subscriber, never()).onNext("twoResume"); + verify(subscriber, never()).onNext("threeResume"); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verifyNoMoreInteractions(subscriber); } @Test @@ -163,10 +163,10 @@ public String apply(String s) { } }); - Flowable<String> observable = w.onExceptionResumeNext(resume); + Flowable<String> flowable = w.onExceptionResumeNext(resume); - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); try { // if the thread gets started (which it shouldn't if it's working correctly) @@ -177,13 +177,13 @@ public String apply(String s) { fail(e.getMessage()); } - verify(observer, times(1)).onNext("one"); - verify(observer, never()).onNext("two"); - verify(observer, never()).onNext("three"); - verify(observer, times(1)).onNext("twoResume"); - verify(observer, times(1)).onNext("threeResume"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onNext("two"); + verify(subscriber, never()).onNext("three"); + verify(subscriber, times(1)).onNext("twoResume"); + verify(subscriber, times(1)).onNext("threeResume"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @@ -226,8 +226,8 @@ private static class TestObservable implements Publisher<String> { } @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); System.out.println("TestObservable subscribed to ..."); t = new Thread(new Runnable() { @@ -246,13 +246,13 @@ public void run() { throw new Throwable("Forced Throwable"); } System.out.println("TestObservable onNext: " + s); - observer.onNext(s); + subscriber.onNext(s); } System.out.println("TestObservable onComplete"); - observer.onComplete(); + subscriber.onComplete(); } catch (Throwable e) { System.out.println("TestObservable onError: " + e); - observer.onError(e); + subscriber.onError(e); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java index 8dfb7584aa..039114d1c7 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java @@ -41,8 +41,8 @@ public void concatTakeFirstLastCompletes() { Flowable.range(1, 3).publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Integer> o) { - return Flowable.concat(o.take(5), o.takeLast(5)); + public Flowable<Integer> apply(Flowable<Integer> f) { + return Flowable.concat(f.take(5), f.takeLast(5)); } }).subscribe(ts); @@ -57,8 +57,8 @@ public void concatTakeFirstLastBackpressureCompletes() { Flowable.range(1, 6).publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Integer> o) { - return Flowable.concat(o.take(5), o.takeLast(5)); + public Flowable<Integer> apply(Flowable<Integer> f) { + return Flowable.concat(f.take(5), f.takeLast(5)); } }).subscribe(ts); @@ -88,8 +88,8 @@ public void canBeCancelled() { pp.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Integer> o) { - return Flowable.concat(o.take(5), o.takeLast(5)); + public Flowable<Integer> apply(Flowable<Integer> f) { + return Flowable.concat(f.take(5), f.takeLast(5)); } }).subscribe(ts); @@ -124,8 +124,8 @@ public void takeCompletes() { pp.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Integer> o) { - return o.take(1); + public Flowable<Integer> apply(Flowable<Integer> f) { + return f.take(1); } }).subscribe(ts); @@ -155,8 +155,8 @@ public void onStart() { pp.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Integer> o) { - return o.take(1); + public Flowable<Integer> apply(Flowable<Integer> f) { + return f.take(1); } }).subscribe(ts); @@ -171,8 +171,8 @@ public void takeCompletesUnsafe() { pp.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Integer> o) { - return o.take(1); + public Flowable<Integer> apply(Flowable<Integer> f) { + return f.take(1); } }).subscribe(ts); @@ -193,8 +193,8 @@ public void directCompletesUnsafe() { pp.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Integer> o) { - return o; + public Flowable<Integer> apply(Flowable<Integer> f) { + return f; } }).subscribe(ts); @@ -216,8 +216,8 @@ public void overflowMissingBackpressureException() { pp.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Integer> o) { - return o; + public Flowable<Integer> apply(Flowable<Integer> f) { + return f; } }).subscribe(ts); @@ -242,8 +242,8 @@ public void overflowMissingBackpressureExceptionDelayed() { new FlowablePublishMulticast<Integer, Integer>(pp, new Function<Flowable<Integer>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Integer> o) { - return o; + public Flowable<Integer> apply(Flowable<Integer> f) { + return f; } }, Flowable.bufferSize(), true).subscribe(ts); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java index 4c65265cb1..32c906a692 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java @@ -42,18 +42,18 @@ public class FlowablePublishTest { @Test public void testPublish() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); - ConnectableFlowable<String> o = Flowable.unsafeCreate(new Publisher<String>() { + ConnectableFlowable<String> f = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); - observer.onNext("one"); - observer.onComplete(); + subscriber.onNext("one"); + subscriber.onComplete(); } }).start(); } @@ -62,7 +62,7 @@ public void run() { final CountDownLatch latch = new CountDownLatch(2); // subscribe once - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { @@ -72,7 +72,7 @@ public void accept(String v) { }); // subscribe again - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { @@ -81,7 +81,7 @@ public void accept(String v) { } }); - Disposable s = o.connect(); + Disposable s = f.connect(); try { if (!latch.await(1000, TimeUnit.MILLISECONDS)) { fail("subscriptions did not receive values"); @@ -508,9 +508,9 @@ public void testObserveOn() { @Test public void source() { - Flowable<Integer> o = Flowable.never(); + Flowable<Integer> f = Flowable.never(); - assertSame(o, (((HasUpstreamPublisher<?>)o.publish()).source())); + assertSame(f, (((HasUpstreamPublisher<?>)f.publish()).source())); } @Test @@ -651,13 +651,13 @@ public void badSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onComplete(); - observer.onNext(2); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(1); + subscriber.onComplete(); + subscriber.onNext(2); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .publish() @@ -832,47 +832,61 @@ public Object apply(Integer v) throws Exception { @Test public void dryRunCrash() { - final TestSubscriber<Object> ts = new TestSubscriber<Object>(1L) { - @Override - public void onNext(Object t) { - super.onNext(t); - onComplete(); - cancel(); - } - }; + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final TestSubscriber<Object> ts = new TestSubscriber<Object>(1L) { + @Override + public void onNext(Object t) { + super.onNext(t); + onComplete(); + cancel(); + } + }; - Flowable.range(1, 10) - .map(new Function<Integer, Object>() { - @Override - public Object apply(Integer v) throws Exception { - if (v == 2) { - throw new TestException(); + Flowable.range(1, 10) + .map(new Function<Integer, Object>() { + @Override + public Object apply(Integer v) throws Exception { + if (v == 2) { + throw new TestException(); + } + return v; } - return v; - } - }) - .publish() - .autoConnect() - .subscribe(ts); + }) + .publish() + .autoConnect() + .subscribe(ts); - ts - .assertResult(1); + ts + .assertResult(1); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void overflowQueue() { - Flowable.create(new FlowableOnSubscribe<Object>() { - @Override - public void subscribe(FlowableEmitter<Object> s) throws Exception { - for (int i = 0; i < 10; i++) { - s.onNext(i); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable.create(new FlowableOnSubscribe<Object>() { + @Override + public void subscribe(FlowableEmitter<Object> s) throws Exception { + for (int i = 0; i < 10; i++) { + s.onNext(i); + } } - } - }, BackpressureStrategy.MISSING) - .publish(8) - .autoConnect() - .test(0L) - .assertFailure(MissingBackpressureException.class); + }, BackpressureStrategy.MISSING) + .publish(8) + .autoConnect() + .test(0L) + .assertFailure(MissingBackpressureException.class); + + TestHelper.assertError(errors, 0, MissingBackpressureException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java index bf6130b027..f97febd9e2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java @@ -33,21 +33,21 @@ public class FlowableRangeLongTest { @Test public void testRangeStartAt2Count3() { - Subscriber<Long> observer = TestHelper.mockSubscriber(); + Subscriber<Long> subscriber = TestHelper.mockSubscriber(); - Flowable.rangeLong(2, 3).subscribe(observer); + Flowable.rangeLong(2, 3).subscribe(subscriber); - verify(observer, times(1)).onNext(2L); - verify(observer, times(1)).onNext(3L); - verify(observer, times(1)).onNext(4L); - verify(observer, never()).onNext(5L); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(2L); + verify(subscriber, times(1)).onNext(3L); + verify(subscriber, times(1)).onNext(4L); + verify(subscriber, never()).onNext(5L); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testRangeUnsubscribe() { - Subscriber<Long> observer = TestHelper.mockSubscriber(); + Subscriber<Long> subscriber = TestHelper.mockSubscriber(); final AtomicInteger count = new AtomicInteger(); @@ -57,14 +57,14 @@ public void accept(Long t1) { count.incrementAndGet(); } }) - .take(3).subscribe(observer); - - verify(observer, times(1)).onNext(1L); - verify(observer, times(1)).onNext(2L); - verify(observer, times(1)).onNext(3L); - verify(observer, never()).onNext(4L); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + .take(3).subscribe(subscriber); + + verify(subscriber, times(1)).onNext(1L); + verify(subscriber, times(1)).onNext(2L); + verify(subscriber, times(1)).onNext(3L); + verify(subscriber, never()).onNext(4L); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); assertEquals(3, count.get()); } @@ -95,14 +95,14 @@ public void testRangeWithOverflow5() { @Test public void testBackpressureViaRequest() { - Flowable<Long> o = Flowable.rangeLong(1, Flowable.bufferSize()); + Flowable<Long> f = Flowable.rangeLong(1, Flowable.bufferSize()); TestSubscriber<Long> ts = new TestSubscriber<Long>(0L); ts.assertNoValues(); ts.request(1); - o.subscribe(ts); + f.subscribe(ts); ts.assertValue(1L); @@ -123,14 +123,14 @@ public void testNoBackpressure() { list.add(i); } - Flowable<Long> o = Flowable.rangeLong(1, list.size()); + Flowable<Long> f = Flowable.rangeLong(1, list.size()); TestSubscriber<Long> ts = new TestSubscriber<Long>(0L); ts.assertNoValues(); ts.request(Long.MAX_VALUE); // infinite - o.subscribe(ts); + f.subscribe(ts); ts.assertValueSequence(list); ts.assertTerminated(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java index d6e2821d84..36a345c617 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java @@ -33,21 +33,21 @@ public class FlowableRangeTest { @Test public void testRangeStartAt2Count3() { - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - Flowable.range(2, 3).subscribe(observer); + Flowable.range(2, 3).subscribe(subscriber); - verify(observer, times(1)).onNext(2); - verify(observer, times(1)).onNext(3); - verify(observer, times(1)).onNext(4); - verify(observer, never()).onNext(5); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(2); + verify(subscriber, times(1)).onNext(3); + verify(subscriber, times(1)).onNext(4); + verify(subscriber, never()).onNext(5); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testRangeUnsubscribe() { - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); final AtomicInteger count = new AtomicInteger(); @@ -57,14 +57,14 @@ public void accept(Integer t1) { count.incrementAndGet(); } }) - .take(3).subscribe(observer); - - verify(observer, times(1)).onNext(1); - verify(observer, times(1)).onNext(2); - verify(observer, times(1)).onNext(3); - verify(observer, never()).onNext(4); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + .take(3).subscribe(subscriber); + + verify(subscriber, times(1)).onNext(1); + verify(subscriber, times(1)).onNext(2); + verify(subscriber, times(1)).onNext(3); + verify(subscriber, never()).onNext(4); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); assertEquals(3, count.get()); } @@ -95,14 +95,14 @@ public void testRangeWithOverflow5() { @Test public void testBackpressureViaRequest() { - Flowable<Integer> o = Flowable.range(1, Flowable.bufferSize()); + Flowable<Integer> f = Flowable.range(1, Flowable.bufferSize()); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L); ts.assertNoValues(); ts.request(1); - o.subscribe(ts); + f.subscribe(ts); ts.assertValue(1); @@ -123,14 +123,14 @@ public void testNoBackpressure() { list.add(i); } - Flowable<Integer> o = Flowable.range(1, list.size()); + Flowable<Integer> f = Flowable.range(1, list.size()); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L); ts.assertNoValues(); ts.request(Long.MAX_VALUE); // infinite - o.subscribe(ts); + f.subscribe(ts); ts.assertValueSequence(list); ts.assertTerminated(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java index 63e80b3822..12425aed42 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java @@ -34,13 +34,13 @@ import io.reactivex.subscribers.TestSubscriber; public class FlowableReduceTest { - Subscriber<Object> observer; + Subscriber<Object> subscriber; SingleObserver<Object> singleObserver; @Before public void before() { - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); singleObserver = TestHelper.mockSingleObserver(); } @@ -62,11 +62,11 @@ public Integer apply(Integer v) { } }); - result.subscribe(observer); + result.subscribe(subscriber); - verify(observer).onNext(1 + 2 + 3 + 4 + 5); - verify(observer).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(1 + 2 + 3 + 4 + 5); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -80,11 +80,11 @@ public Integer apply(Integer v) { } }); - result.subscribe(observer); + result.subscribe(subscriber); - verify(observer, never()).onNext(any()); - verify(observer, never()).onComplete(); - verify(observer, times(1)).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber, times(1)).onError(any(TestException.class)); } @Test @@ -104,11 +104,11 @@ public Integer apply(Integer v) { } }); - result.subscribe(observer); + result.subscribe(subscriber); - verify(observer, never()).onNext(any()); - verify(observer, never()).onComplete(); - verify(observer, times(1)).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber, times(1)).onError(any(TestException.class)); } @Test @@ -125,11 +125,11 @@ public Integer apply(Integer t1) { Flowable<Integer> result = Flowable.just(1, 2, 3, 4, 5) .reduce(0, sum).toFlowable().map(error); - result.subscribe(observer); + result.subscribe(subscriber); - verify(observer, never()).onNext(any()); - verify(observer, never()).onComplete(); - verify(observer, times(1)).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber, times(1)).onError(any(TestException.class)); } @Test @@ -476,9 +476,9 @@ static String blockingOp(Integer x, Integer y) { public void seedDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function<Flowable<Integer>, SingleSource<Integer>>() { @Override - public SingleSource<Integer> apply(Flowable<Integer> o) + public SingleSource<Integer> apply(Flowable<Integer> f) throws Exception { - return o.reduce(0, new BiFunction<Integer, Integer, Integer>() { + return f.reduce(0, new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer a, Integer b) throws Exception { return a; @@ -504,12 +504,12 @@ public void seedBadSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onComplete(); - observer.onNext(1); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); + subscriber.onNext(1); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .reduce(0, new BiFunction<Integer, Integer, Integer>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index d91f4706d6..acb93684d6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -229,7 +229,7 @@ public void testConnectUnsubscribe() throws InterruptedException { final CountDownLatch unsubscribeLatch = new CountDownLatch(1); final CountDownLatch subscribeLatch = new CountDownLatch(1); - Flowable<Long> o = synchronousInterval() + Flowable<Long> f = synchronousInterval() .doOnSubscribe(new Consumer<Subscription>() { @Override public void accept(Subscription s) { @@ -248,7 +248,7 @@ public void run() { }); TestSubscriber<Long> s = new TestSubscriber<Long>(); - o.publish().refCount().subscribeOn(Schedulers.newThread()).subscribe(s); + f.publish().refCount().subscribeOn(Schedulers.newThread()).subscribe(s); System.out.println("send unsubscribe"); // wait until connected subscribeLatch.await(); @@ -275,7 +275,7 @@ public void testConnectUnsubscribeRaceConditionLoop() throws InterruptedExceptio @Test public void testConnectUnsubscribeRaceCondition() throws InterruptedException { final AtomicInteger subUnsubCount = new AtomicInteger(); - Flowable<Long> o = synchronousInterval() + Flowable<Long> f = synchronousInterval() .doOnCancel(new Action() { @Override public void run() { @@ -294,7 +294,7 @@ public void accept(Subscription s) { TestSubscriber<Long> s = new TestSubscriber<Long>(); - o.publish().refCount().subscribeOn(Schedulers.computation()).subscribe(s); + f.publish().refCount().subscribeOn(Schedulers.computation()).subscribe(s); System.out.println("send unsubscribe"); // now immediately unsubscribe while subscribeOn is racing to subscribe s.dispose(); @@ -347,11 +347,11 @@ public void cancel() { public void onlyFirstShouldSubscribeAndLastUnsubscribe() { final AtomicInteger subscriptionCount = new AtomicInteger(); final AtomicInteger unsubscriptionCount = new AtomicInteger(); - Flowable<Integer> observable = Flowable.unsafeCreate(new Publisher<Integer>() { + Flowable<Integer> flowable = Flowable.unsafeCreate(new Publisher<Integer>() { @Override - public void subscribe(Subscriber<? super Integer> observer) { + public void subscribe(Subscriber<? super Integer> subscriber) { subscriptionCount.incrementAndGet(); - observer.onSubscribe(new Subscription() { + subscriber.onSubscribe(new Subscription() { @Override public void request(long n) { @@ -364,7 +364,7 @@ public void cancel() { }); } }); - Flowable<Integer> refCounted = observable.publish().refCount(); + Flowable<Integer> refCounted = flowable.publish().refCount(); Disposable first = refCounted.subscribe(); assertEquals(1, subscriptionCount.get()); @@ -465,17 +465,17 @@ public void accept(Long t1) { public void testAlreadyUnsubscribedClient() { Subscriber<Integer> done = CancelledSubscriber.INSTANCE; - Subscriber<Integer> o = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); Flowable<Integer> result = Flowable.just(1).publish().refCount(); result.subscribe(done); - result.subscribe(o); + result.subscribe(subscriber); - verify(o).onNext(1); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(1); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -484,12 +484,12 @@ public void testAlreadyUnsubscribedInterleavesWithClient() { Subscriber<Integer> done = CancelledSubscriber.INSTANCE; - Subscriber<Integer> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); Flowable<Integer> result = source.publish().refCount(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); @@ -498,17 +498,17 @@ public void testAlreadyUnsubscribedInterleavesWithClient() { source.onNext(2); source.onComplete(); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testConnectDisconnectConnectAndSubjectState() { - Flowable<Integer> o1 = Flowable.just(10); - Flowable<Integer> o2 = Flowable.just(20); - Flowable<Integer> combined = Flowable.combineLatest(o1, o2, new BiFunction<Integer, Integer, Integer>() { + Flowable<Integer> f1 = Flowable.just(10); + Flowable<Integer> f2 = Flowable.just(20); + Flowable<Integer> combined = Flowable.combineLatest(f1, f2, new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) { return t1 + t2; @@ -533,70 +533,77 @@ public Integer apply(Integer t1, Integer t2) { @Test(timeout = 10000) public void testUpstreamErrorAllowsRetry() throws InterruptedException { - final AtomicInteger intervalSubscribed = new AtomicInteger(); - Flowable<String> interval = - Flowable.interval(200,TimeUnit.MILLISECONDS) - .doOnSubscribe(new Consumer<Subscription>() { - @Override - public void accept(Subscription s) { - System.out.println("Subscribing to interval " + intervalSubscribed.incrementAndGet()); - } - } - ) - .flatMap(new Function<Long, Publisher<String>>() { - @Override - public Publisher<String> apply(Long t1) { - return Flowable.defer(new Callable<Publisher<String>>() { - @Override - public Publisher<String> call() { - return Flowable.<String>error(new Exception("Some exception")); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final AtomicInteger intervalSubscribed = new AtomicInteger(); + Flowable<String> interval = + Flowable.interval(200,TimeUnit.MILLISECONDS) + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription s) { + System.out.println("Subscribing to interval " + intervalSubscribed.incrementAndGet()); } - }); } - }) - .onErrorResumeNext(new Function<Throwable, Publisher<String>>() { - @Override - public Publisher<String> apply(Throwable t1) { - return Flowable.error(t1); - } - }) - .publish() - .refCount(); + ) + .flatMap(new Function<Long, Publisher<String>>() { + @Override + public Publisher<String> apply(Long t1) { + return Flowable.defer(new Callable<Publisher<String>>() { + @Override + public Publisher<String> call() { + return Flowable.<String>error(new TestException("Some exception")); + } + }); + } + }) + .onErrorResumeNext(new Function<Throwable, Publisher<String>>() { + @Override + public Publisher<String> apply(Throwable t1) { + return Flowable.error(t1); + } + }) + .publish() + .refCount(); + + interval + .doOnError(new Consumer<Throwable>() { + @Override + public void accept(Throwable t1) { + System.out.println("Subscriber 1 onError: " + t1); + } + }) + .retry(5) + .subscribe(new Consumer<String>() { + @Override + public void accept(String t1) { + System.out.println("Subscriber 1: " + t1); + } + }); + Thread.sleep(100); + interval + .doOnError(new Consumer<Throwable>() { + @Override + public void accept(Throwable t1) { + System.out.println("Subscriber 2 onError: " + t1); + } + }) + .retry(5) + .subscribe(new Consumer<String>() { + @Override + public void accept(String t1) { + System.out.println("Subscriber 2: " + t1); + } + }); - interval - .doOnError(new Consumer<Throwable>() { - @Override - public void accept(Throwable t1) { - System.out.println("Subscriber 1 onError: " + t1); - } - }) - .retry(5) - .subscribe(new Consumer<String>() { - @Override - public void accept(String t1) { - System.out.println("Subscriber 1: " + t1); - } - }); - Thread.sleep(100); - interval - .doOnError(new Consumer<Throwable>() { - @Override - public void accept(Throwable t1) { - System.out.println("Subscriber 2 onError: " + t1); - } - }) - .retry(5) - .subscribe(new Consumer<String>() { - @Override - public void accept(String t1) { - System.out.println("Subscriber 2: " + t1); - } - }); + Thread.sleep(1300); - Thread.sleep(1300); + System.out.println(intervalSubscribed.get()); + assertEquals(6, intervalSubscribed.get()); - System.out.println(intervalSubscribed.get()); - assertEquals(6, intervalSubscribed.get()); + TestHelper.assertError(errors, 0, OnErrorNotImplementedException.class); + } finally { + RxJavaPlugins.reset(); + } } private enum CancelledSubscriber implements FlowableSubscriber<Integer> { @@ -624,20 +631,20 @@ public void disposed() { @Test public void noOpConnect() { final int[] calls = { 0 }; - Flowable<Integer> o = new ConnectableFlowable<Integer>() { + Flowable<Integer> f = new ConnectableFlowable<Integer>() { @Override public void connect(Consumer<? super Disposable> connection) { calls[0]++; } @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); } }.refCount(); - o.test(); - o.test(); + f.test(); + f.test(); assertEquals(1, calls[0]); } @@ -804,7 +811,7 @@ public void connect(Consumer<? super Disposable> connection) { } @Override - protected void subscribeActual(Subscriber<? super Object> observer) { + protected void subscribeActual(Subscriber<? super Object> subscriber) { throw new TestException("subscribeActual"); } } @@ -831,8 +838,8 @@ public void connect(Consumer<? super Disposable> connection) { } @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); } } @@ -844,21 +851,28 @@ public void connect(Consumer<? super Disposable> connection) { } @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); } } @Test public void badSourceSubscribe() { - BadFlowableSubscribe bo = new BadFlowableSubscribe(); - + List<Throwable> errors = TestHelper.trackPluginErrors(); try { - bo.refCount() - .test(); - fail("Should have thrown"); - } catch (NullPointerException ex) { - assertTrue(ex.getCause() instanceof TestException); + BadFlowableSubscribe bo = new BadFlowableSubscribe(); + + try { + bo.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); } } @@ -877,14 +891,21 @@ public void badSourceDispose() { @Test public void badSourceConnect() { - BadFlowableConnect bf = new BadFlowableConnect(); - + List<Throwable> errors = TestHelper.trackPluginErrors(); try { - bf.refCount() - .test(); - fail("Should have thrown"); - } catch (NullPointerException ex) { - assertTrue(ex.getCause() instanceof TestException); + BadFlowableConnect bf = new BadFlowableConnect(); + + try { + bf.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); } } @@ -902,9 +923,9 @@ public void connect(Consumer<? super Disposable> connection) { } @Override - protected void subscribeActual(Subscriber<? super Object> observer) { + protected void subscribeActual(Subscriber<? super Object> subscriber) { if (++count == 1) { - observer.onSubscribe(new BooleanSubscription()); + subscriber.onSubscribe(new BooleanSubscription()); } else { throw new TestException("subscribeActual"); } @@ -913,15 +934,22 @@ protected void subscribeActual(Subscriber<? super Object> observer) { @Test public void badSourceSubscribe2() { - BadFlowableSubscribe2 bf = new BadFlowableSubscribe2(); - - Flowable<Object> o = bf.refCount(); - o.test(); + List<Throwable> errors = TestHelper.trackPluginErrors(); try { - o.test(); - fail("Should have thrown"); - } catch (NullPointerException ex) { - assertTrue(ex.getCause() instanceof TestException); + BadFlowableSubscribe2 bf = new BadFlowableSubscribe2(); + + Flowable<Object> f = bf.refCount(); + f.test(); + try { + f.test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); } } @@ -938,9 +966,9 @@ public void connect(Consumer<? super Disposable> connection) { } @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); } @Override @@ -956,14 +984,21 @@ public boolean isDisposed() { @Test public void badSourceCompleteDisconnect() { - BadFlowableConnect2 bf = new BadFlowableConnect2(); - + List<Throwable> errors = TestHelper.trackPluginErrors(); try { - bf.refCount() - .test(); - fail("Should have thrown"); - } catch (NullPointerException ex) { - assertTrue(ex.getCause() instanceof TestException); + BadFlowableConnect2 bf = new BadFlowableConnect2(); + + try { + bf.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); } } @@ -1181,12 +1216,12 @@ public void connect(Consumer<? super Disposable> connection) { } @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onSubscribe(new BooleanSubscription()); - observer.onComplete(); - observer.onComplete(); - observer.onError(new TestException()); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); + subscriber.onComplete(); + subscriber.onError(new TestException()); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java index b74221fdea..82cec69233 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java @@ -42,9 +42,9 @@ public void testRepetition() { int value = Flowable.unsafeCreate(new Publisher<Integer>() { @Override - public void subscribe(final Subscriber<? super Integer> o) { - o.onNext(count.incrementAndGet()); - o.onComplete(); + public void subscribe(final Subscriber<? super Integer> subscriber) { + subscriber.onNext(count.incrementAndGet()); + subscriber.onComplete(); } }).repeat().subscribeOn(Schedulers.computation()) .take(num).blockingLast(); @@ -100,58 +100,58 @@ public Integer apply(Integer t1) { @Test(timeout = 2000) public void testRepeatAndTake() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - Flowable.just(1).repeat().take(10).subscribe(o); + Flowable.just(1).repeat().take(10).subscribe(subscriber); - verify(o, times(10)).onNext(1); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, times(10)).onNext(1); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) public void testRepeatLimited() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - Flowable.just(1).repeat(10).subscribe(o); + Flowable.just(1).repeat(10).subscribe(subscriber); - verify(o, times(10)).onNext(1); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, times(10)).onNext(1); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) public void testRepeatError() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - Flowable.error(new TestException()).repeat(10).subscribe(o); + Flowable.error(new TestException()).repeat(10).subscribe(subscriber); - verify(o).onError(any(TestException.class)); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test(timeout = 2000) public void testRepeatZero() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - Flowable.just(1).repeat(0).subscribe(o); + Flowable.just(1).repeat(0).subscribe(subscriber); - verify(o).onComplete(); - verify(o, never()).onNext(any()); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) public void testRepeatOne() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - Flowable.just(1).repeat(1).subscribe(o); + Flowable.just(1).repeat(1).subscribe(subscriber); - verify(o).onComplete(); - verify(o, times(1)).onNext(any()); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onComplete(); + verify(subscriber, times(1)).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } /** Issue #2587. */ @@ -216,8 +216,8 @@ public void repeatWhenDefaultScheduler() { Flowable.just(1).repeatWhen((Function)new Function<Flowable, Flowable>() { @Override - public Flowable apply(Flowable o) { - return o.take(2); + public Flowable apply(Flowable f) { + return f.take(2); } }).subscribe(ts); @@ -235,8 +235,8 @@ public void repeatWhenTrampolineScheduler() { Flowable.just(1).subscribeOn(Schedulers.trampoline()) .repeatWhen((Function)new Function<Flowable, Flowable>() { @Override - public Flowable apply(Flowable o) { - return o.take(2); + public Flowable apply(Flowable f) { + return f.take(2); } }).subscribe(ts); @@ -323,7 +323,7 @@ public boolean getAsBoolean() throws Exception { @Test public void shouldDisposeInnerObservable() { - final PublishProcessor<Object> subject = PublishProcessor.create(); + final PublishProcessor<Object> processor = PublishProcessor.create(); final Disposable disposable = Flowable.just("Leak") .repeatWhen(new Function<Flowable<Object>, Flowable<Object>>() { @Override @@ -331,16 +331,16 @@ public Flowable<Object> apply(Flowable<Object> completions) throws Exception { return completions.switchMap(new Function<Object, Flowable<Object>>() { @Override public Flowable<Object> apply(Object ignore) throws Exception { - return subject; + return processor; } }); } }) .subscribe(); - assertTrue(subject.hasSubscribers()); + assertTrue(processor.hasSubscribers()); disposable.dispose(); - assertFalse(subject.hasSubscribers()); + assertFalse(processor.hasSubscribers()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index 5941a8f4e2..137565dae4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -50,40 +50,40 @@ public void testBufferedReplay() { cf.connect(); { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - cf.subscribe(observer1); + cf.subscribe(subscriber1); source.onNext(1); source.onNext(2); source.onNext(3); - inOrder.verify(observer1, times(1)).onNext(1); - inOrder.verify(observer1, times(1)).onNext(2); - inOrder.verify(observer1, times(1)).onNext(3); + inOrder.verify(subscriber1, times(1)).onNext(1); + inOrder.verify(subscriber1, times(1)).onNext(2); + inOrder.verify(subscriber1, times(1)).onNext(3); source.onNext(4); source.onComplete(); - inOrder.verify(observer1, times(1)).onNext(4); - inOrder.verify(observer1, times(1)).onComplete(); + inOrder.verify(subscriber1, times(1)).onNext(4); + inOrder.verify(subscriber1, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - cf.subscribe(observer1); + cf.subscribe(subscriber1); - inOrder.verify(observer1, times(1)).onNext(2); - inOrder.verify(observer1, times(1)).onNext(3); - inOrder.verify(observer1, times(1)).onNext(4); - inOrder.verify(observer1, times(1)).onComplete(); + inOrder.verify(subscriber1, times(1)).onNext(2); + inOrder.verify(subscriber1, times(1)).onNext(3); + inOrder.verify(subscriber1, times(1)).onNext(4); + inOrder.verify(subscriber1, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } } @@ -95,10 +95,10 @@ public void testBufferedWindowReplay() { cf.connect(); { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - cf.subscribe(observer1); + cf.subscribe(subscriber1); source.onNext(1); scheduler.advanceTimeBy(10, TimeUnit.MILLISECONDS); @@ -107,33 +107,33 @@ public void testBufferedWindowReplay() { source.onNext(3); scheduler.advanceTimeBy(10, TimeUnit.MILLISECONDS); - inOrder.verify(observer1, times(1)).onNext(1); - inOrder.verify(observer1, times(1)).onNext(2); - inOrder.verify(observer1, times(1)).onNext(3); + inOrder.verify(subscriber1, times(1)).onNext(1); + inOrder.verify(subscriber1, times(1)).onNext(2); + inOrder.verify(subscriber1, times(1)).onNext(3); source.onNext(4); source.onNext(5); scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); - inOrder.verify(observer1, times(1)).onNext(4); + inOrder.verify(subscriber1, times(1)).onNext(4); - inOrder.verify(observer1, times(1)).onNext(5); + inOrder.verify(subscriber1, times(1)).onNext(5); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - cf.subscribe(observer1); + cf.subscribe(subscriber1); - inOrder.verify(observer1, times(1)).onNext(4); - inOrder.verify(observer1, times(1)).onNext(5); + inOrder.verify(subscriber1, times(1)).onNext(4); + inOrder.verify(subscriber1, times(1)).onNext(5); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } } @@ -147,10 +147,10 @@ public void testWindowedReplay() { cf.connect(); { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - cf.subscribe(observer1); + cf.subscribe(subscriber1); source.onNext(1); scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); @@ -161,25 +161,25 @@ public void testWindowedReplay() { source.onComplete(); scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); - inOrder.verify(observer1, times(1)).onNext(1); - inOrder.verify(observer1, times(1)).onNext(2); - inOrder.verify(observer1, times(1)).onNext(3); + inOrder.verify(subscriber1, times(1)).onNext(1); + inOrder.verify(subscriber1, times(1)).onNext(2); + inOrder.verify(subscriber1, times(1)).onNext(3); - inOrder.verify(observer1, times(1)).onComplete(); + inOrder.verify(subscriber1, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - cf.subscribe(observer1); - inOrder.verify(observer1, never()).onNext(3); + cf.subscribe(subscriber1); + inOrder.verify(subscriber1, never()).onNext(3); - inOrder.verify(observer1, times(1)).onComplete(); + inOrder.verify(subscriber1, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } } @@ -208,37 +208,37 @@ public Flowable<Integer> apply(Flowable<Integer> t1) { Flowable<Integer> co = source.replay(selector); { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - co.subscribe(observer1); + co.subscribe(subscriber1); source.onNext(1); source.onNext(2); source.onNext(3); - inOrder.verify(observer1, times(1)).onNext(2); - inOrder.verify(observer1, times(1)).onNext(4); - inOrder.verify(observer1, times(1)).onNext(6); + inOrder.verify(subscriber1, times(1)).onNext(2); + inOrder.verify(subscriber1, times(1)).onNext(4); + inOrder.verify(subscriber1, times(1)).onNext(6); source.onNext(4); source.onComplete(); - inOrder.verify(observer1, times(1)).onNext(8); - inOrder.verify(observer1, times(1)).onComplete(); + inOrder.verify(subscriber1, times(1)).onNext(8); + inOrder.verify(subscriber1, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - co.subscribe(observer1); + co.subscribe(subscriber1); - inOrder.verify(observer1, times(1)).onComplete(); + inOrder.verify(subscriber1, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } @@ -270,37 +270,37 @@ public Flowable<Integer> apply(Flowable<Integer> t1) { Flowable<Integer> co = source.replay(selector, 3); { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - co.subscribe(observer1); + co.subscribe(subscriber1); source.onNext(1); source.onNext(2); source.onNext(3); - inOrder.verify(observer1, times(1)).onNext(2); - inOrder.verify(observer1, times(1)).onNext(4); - inOrder.verify(observer1, times(1)).onNext(6); + inOrder.verify(subscriber1, times(1)).onNext(2); + inOrder.verify(subscriber1, times(1)).onNext(4); + inOrder.verify(subscriber1, times(1)).onNext(6); source.onNext(4); source.onComplete(); - inOrder.verify(observer1, times(1)).onNext(8); - inOrder.verify(observer1, times(1)).onComplete(); + inOrder.verify(subscriber1, times(1)).onNext(8); + inOrder.verify(subscriber1, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - co.subscribe(observer1); + co.subscribe(subscriber1); - inOrder.verify(observer1, times(1)).onComplete(); + inOrder.verify(subscriber1, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } } @@ -332,10 +332,10 @@ public Flowable<Integer> apply(Flowable<Integer> t1) { Flowable<Integer> co = source.replay(selector, 100, TimeUnit.MILLISECONDS, scheduler); { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - co.subscribe(observer1); + co.subscribe(subscriber1); source.onNext(1); scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); @@ -346,24 +346,24 @@ public Flowable<Integer> apply(Flowable<Integer> t1) { source.onComplete(); scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); - inOrder.verify(observer1, times(1)).onNext(2); - inOrder.verify(observer1, times(1)).onNext(4); - inOrder.verify(observer1, times(1)).onNext(6); + inOrder.verify(subscriber1, times(1)).onNext(2); + inOrder.verify(subscriber1, times(1)).onNext(4); + inOrder.verify(subscriber1, times(1)).onNext(6); - inOrder.verify(observer1, times(1)).onComplete(); + inOrder.verify(subscriber1, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - co.subscribe(observer1); + co.subscribe(subscriber1); - inOrder.verify(observer1, times(1)).onComplete(); + inOrder.verify(subscriber1, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onError(any(Throwable.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); } } @@ -375,41 +375,41 @@ public void testBufferedReplayError() { cf.connect(); { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - cf.subscribe(observer1); + cf.subscribe(subscriber1); source.onNext(1); source.onNext(2); source.onNext(3); - inOrder.verify(observer1, times(1)).onNext(1); - inOrder.verify(observer1, times(1)).onNext(2); - inOrder.verify(observer1, times(1)).onNext(3); + inOrder.verify(subscriber1, times(1)).onNext(1); + inOrder.verify(subscriber1, times(1)).onNext(2); + inOrder.verify(subscriber1, times(1)).onNext(3); source.onNext(4); source.onError(new RuntimeException("Forced failure")); - inOrder.verify(observer1, times(1)).onNext(4); - inOrder.verify(observer1, times(1)).onError(any(RuntimeException.class)); + inOrder.verify(subscriber1, times(1)).onNext(4); + inOrder.verify(subscriber1, times(1)).onError(any(RuntimeException.class)); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onComplete(); + verify(subscriber1, never()).onComplete(); } { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - cf.subscribe(observer1); + cf.subscribe(subscriber1); - inOrder.verify(observer1, times(1)).onNext(2); - inOrder.verify(observer1, times(1)).onNext(3); - inOrder.verify(observer1, times(1)).onNext(4); - inOrder.verify(observer1, times(1)).onError(any(RuntimeException.class)); + inOrder.verify(subscriber1, times(1)).onNext(2); + inOrder.verify(subscriber1, times(1)).onNext(3); + inOrder.verify(subscriber1, times(1)).onNext(4); + inOrder.verify(subscriber1, times(1)).onError(any(RuntimeException.class)); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onComplete(); + verify(subscriber1, never()).onComplete(); } } @@ -423,10 +423,10 @@ public void testWindowedReplayError() { cf.connect(); { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - cf.subscribe(observer1); + cf.subscribe(subscriber1); source.onNext(1); scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); @@ -437,25 +437,25 @@ public void testWindowedReplayError() { source.onError(new RuntimeException("Forced failure")); scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); - inOrder.verify(observer1, times(1)).onNext(1); - inOrder.verify(observer1, times(1)).onNext(2); - inOrder.verify(observer1, times(1)).onNext(3); + inOrder.verify(subscriber1, times(1)).onNext(1); + inOrder.verify(subscriber1, times(1)).onNext(2); + inOrder.verify(subscriber1, times(1)).onNext(3); - inOrder.verify(observer1, times(1)).onError(any(RuntimeException.class)); + inOrder.verify(subscriber1, times(1)).onError(any(RuntimeException.class)); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onComplete(); + verify(subscriber1, never()).onComplete(); } { - Subscriber<Object> observer1 = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer1); + Subscriber<Object> subscriber1 = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber1); - cf.subscribe(observer1); - inOrder.verify(observer1, never()).onNext(3); + cf.subscribe(subscriber1); + inOrder.verify(subscriber1, never()).onNext(3); - inOrder.verify(observer1, times(1)).onError(any(RuntimeException.class)); + inOrder.verify(subscriber1, times(1)).onError(any(RuntimeException.class)); inOrder.verifyNoMoreInteractions(); - verify(observer1, never()).onComplete(); + verify(subscriber1, never()).onComplete(); } } @@ -474,8 +474,8 @@ public void accept(Integer v) { Flowable<Integer> result = source.replay( new Function<Flowable<Integer>, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Flowable<Integer> o) { - return o.take(2); + public Flowable<Integer> apply(Flowable<Integer> f) { + return f.take(2); } }); @@ -900,19 +900,19 @@ public void testColdReplayBackpressure() { @Test public void testCache() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); - Flowable<String> o = Flowable.unsafeCreate(new Publisher<String>() { + Flowable<String> f = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); System.out.println("published observable being executed"); - observer.onNext("one"); - observer.onComplete(); + subscriber.onNext("one"); + subscriber.onComplete(); } }).start(); } @@ -922,7 +922,7 @@ public void run() { final CountDownLatch latch = new CountDownLatch(2); // subscribe once - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { @@ -933,7 +933,7 @@ public void accept(String v) { }); // subscribe again - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String v) { @@ -952,10 +952,10 @@ public void accept(String v) { @Test public void testUnsubscribeSource() throws Exception { Action unsubscribe = mock(Action.class); - Flowable<Integer> o = Flowable.just(1).doOnCancel(unsubscribe).cache(); - o.subscribe(); - o.subscribe(); - o.subscribe(); + Flowable<Integer> f = Flowable.just(1).doOnCancel(unsubscribe).cache(); + f.subscribe(); + f.subscribe(); + f.subscribe(); verify(unsubscribe, times(1)).run(); } @@ -1425,12 +1425,12 @@ public void badSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onError(new TestException("First")); - observer.onNext(1); - observer.onError(new TestException("Second")); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onError(new TestException("First")); + subscriber.onNext(1); + subscriber.onError(new TestException("Second")); + subscriber.onComplete(); } }.replay() .autoConnect() diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java index 062470229d..e7a2bb8eaa 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java @@ -111,29 +111,29 @@ public static class Tuple { @Test public void testRetryIndefinitely() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); int numRetries = 20; Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); - origin.retry().subscribe(new TestSubscriber<String>(observer)); + origin.retry().subscribe(new TestSubscriber<String>(subscriber)); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // should show 3 attempts - inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); + inOrder.verify(subscriber, times(numRetries + 1)).onNext("beginningEveryTime"); // should have no errors - inOrder.verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); // should have a single success - inOrder.verify(observer, times(1)).onNext("onSuccessOnly"); + inOrder.verify(subscriber, times(1)).onNext("onSuccessOnly"); // should have a single successful onComplete - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testSchedulingNotificationHandler() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); int numRetries = 2; Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); - TestSubscriber<String> subscriber = new TestSubscriber<String>(observer); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); origin.retryWhen(new Function<Flowable<? extends Throwable>, Flowable<Object>>() { @Override public Flowable<Object> apply(Flowable<? extends Throwable> t1) { @@ -151,24 +151,24 @@ public void accept(Throwable e) { e.printStackTrace(); } }) - .subscribe(subscriber); + .subscribe(ts); - subscriber.awaitTerminalEvent(); - InOrder inOrder = inOrder(observer); + ts.awaitTerminalEvent(); + InOrder inOrder = inOrder(subscriber); // should show 3 attempts - inOrder.verify(observer, times(1 + numRetries)).onNext("beginningEveryTime"); + inOrder.verify(subscriber, times(1 + numRetries)).onNext("beginningEveryTime"); // should have no errors - inOrder.verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); // should have a single success - inOrder.verify(observer, times(1)).onNext("onSuccessOnly"); + inOrder.verify(subscriber, times(1)).onNext("onSuccessOnly"); // should have a single successful onComplete - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testOnNextFromNotificationHandler() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); int numRetries = 2; Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); origin.retryWhen(new Function<Flowable<? extends Throwable>, Flowable<Object>>() { @@ -182,58 +182,58 @@ public Integer apply(Throwable t1) { } }).startWith(0).cast(Object.class); } - }).subscribe(observer); + }).subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // should show 3 attempts - inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); + inOrder.verify(subscriber, times(numRetries + 1)).onNext("beginningEveryTime"); // should have no errors - inOrder.verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); // should have a single success - inOrder.verify(observer, times(1)).onNext("onSuccessOnly"); + inOrder.verify(subscriber, times(1)).onNext("onSuccessOnly"); // should have a single successful onComplete - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testOnCompletedFromNotificationHandler() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(1)); - TestSubscriber<String> subscriber = new TestSubscriber<String>(observer); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); origin.retryWhen(new Function<Flowable<? extends Throwable>, Flowable<Object>>() { @Override public Flowable<Object> apply(Flowable<? extends Throwable> t1) { return Flowable.empty(); } - }).subscribe(subscriber); + }).subscribe(ts); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onSubscribe((Subscription)notNull()); - inOrder.verify(observer, never()).onNext("beginningEveryTime"); - inOrder.verify(observer, never()).onNext("onSuccessOnly"); - inOrder.verify(observer, times(1)).onComplete(); - inOrder.verify(observer, never()).onError(any(Exception.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onSubscribe((Subscription)notNull()); + inOrder.verify(subscriber, never()).onNext("beginningEveryTime"); + inOrder.verify(subscriber, never()).onNext("onSuccessOnly"); + inOrder.verify(subscriber, times(1)).onComplete(); + inOrder.verify(subscriber, never()).onError(any(Exception.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testOnErrorFromNotificationHandler() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(2)); origin.retryWhen(new Function<Flowable<? extends Throwable>, Flowable<Object>>() { @Override public Flowable<Object> apply(Flowable<? extends Throwable> t1) { return Flowable.error(new RuntimeException()); } - }).subscribe(observer); - - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onSubscribe((Subscription)notNull()); - inOrder.verify(observer, never()).onNext("beginningEveryTime"); - inOrder.verify(observer, never()).onNext("onSuccessOnly"); - inOrder.verify(observer, never()).onComplete(); - inOrder.verify(observer, times(1)).onError(any(RuntimeException.class)); + }).subscribe(subscriber); + + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onSubscribe((Subscription)notNull()); + inOrder.verify(subscriber, never()).onNext("beginningEveryTime"); + inOrder.verify(subscriber, never()).onNext("onSuccessOnly"); + inOrder.verify(subscriber, never()).onComplete(); + inOrder.verify(subscriber, times(1)).onError(any(RuntimeException.class)); inOrder.verifyNoMoreInteractions(); } @@ -270,71 +270,71 @@ public Object apply(Throwable o, Integer integer) { @Test public void testOriginFails() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(1)); - origin.subscribe(observer); + origin.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("beginningEveryTime"); - inOrder.verify(observer, times(1)).onError(any(RuntimeException.class)); - inOrder.verify(observer, never()).onNext("onSuccessOnly"); - inOrder.verify(observer, never()).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("beginningEveryTime"); + inOrder.verify(subscriber, times(1)).onError(any(RuntimeException.class)); + inOrder.verify(subscriber, never()).onNext("onSuccessOnly"); + inOrder.verify(subscriber, never()).onComplete(); } @Test public void testRetryFail() { int numRetries = 1; int numFailures = 2; - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numFailures)); - origin.retry(numRetries).subscribe(observer); + origin.retry(numRetries).subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // should show 2 attempts (first time fail, second time (1st retry) fail) - inOrder.verify(observer, times(1 + numRetries)).onNext("beginningEveryTime"); + inOrder.verify(subscriber, times(1 + numRetries)).onNext("beginningEveryTime"); // should only retry once, fail again and emit onError - inOrder.verify(observer, times(1)).onError(any(RuntimeException.class)); + inOrder.verify(subscriber, times(1)).onError(any(RuntimeException.class)); // no success - inOrder.verify(observer, never()).onNext("onSuccessOnly"); - inOrder.verify(observer, never()).onComplete(); + inOrder.verify(subscriber, never()).onNext("onSuccessOnly"); + inOrder.verify(subscriber, never()).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testRetrySuccess() { int numFailures = 1; - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numFailures)); - origin.retry(3).subscribe(observer); + origin.retry(3).subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // should show 3 attempts - inOrder.verify(observer, times(1 + numFailures)).onNext("beginningEveryTime"); + inOrder.verify(subscriber, times(1 + numFailures)).onNext("beginningEveryTime"); // should have no errors - inOrder.verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); // should have a single success - inOrder.verify(observer, times(1)).onNext("onSuccessOnly"); + inOrder.verify(subscriber, times(1)).onNext("onSuccessOnly"); // should have a single successful onComplete - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testInfiniteRetry() { int numFailures = 20; - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numFailures)); - origin.retry().subscribe(observer); + origin.retry().subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // should show 3 attempts - inOrder.verify(observer, times(1 + numFailures)).onNext("beginningEveryTime"); + inOrder.verify(subscriber, times(1 + numFailures)).onNext("beginningEveryTime"); // should have no errors - inOrder.verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); // should have a single success - inOrder.verify(observer, times(1)).onNext("onSuccessOnly"); + inOrder.verify(subscriber, times(1)).onNext("onSuccessOnly"); // should have a single successful onComplete - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -356,8 +356,8 @@ public void testRetrySubscribesAgainAfterError() throws Exception { doThrow(new RuntimeException()).when(throwException).accept(Mockito.anyInt()); // create a retrying observable based on a PublishProcessor - PublishProcessor<Integer> subject = PublishProcessor.create(); - subject + PublishProcessor<Integer> processor = PublishProcessor.create(); + processor // record item .doOnNext(record) // throw a RuntimeException @@ -369,13 +369,13 @@ public void testRetrySubscribesAgainAfterError() throws Exception { inOrder.verifyNoMoreInteractions(); - subject.onNext(1); + processor.onNext(1); inOrder.verify(record).accept(1); - subject.onNext(2); + processor.onNext(2); inOrder.verify(record).accept(2); - subject.onNext(3); + processor.onNext(3); inOrder.verify(record).accept(3); inOrder.verifyNoMoreInteractions(); @@ -391,8 +391,8 @@ public static class FuncWithErrors implements Publisher<String> { } @Override - public void subscribe(final Subscriber<? super String> o) { - o.onSubscribe(new Subscription() { + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new Subscription() { final AtomicLong req = new AtomicLong(); // 0 = not set, 1 = fast path, 2 = backpressure final AtomicInteger path = new AtomicInteger(0); @@ -401,30 +401,30 @@ public void subscribe(final Subscriber<? super String> o) { @Override public void request(long n) { if (n == Long.MAX_VALUE && path.compareAndSet(0, 1)) { - o.onNext("beginningEveryTime"); + subscriber.onNext("beginningEveryTime"); int i = count.getAndIncrement(); if (i < numFailures) { - o.onError(new RuntimeException("forced failure: " + (i + 1))); + subscriber.onError(new RuntimeException("forced failure: " + (i + 1))); } else { - o.onNext("onSuccessOnly"); - o.onComplete(); + subscriber.onNext("onSuccessOnly"); + subscriber.onComplete(); } return; } if (n > 0 && req.getAndAdd(n) == 0 && (path.get() == 2 || path.compareAndSet(0, 2)) && !done) { int i = count.getAndIncrement(); if (i < numFailures) { - o.onNext("beginningEveryTime"); - o.onError(new RuntimeException("forced failure: " + (i + 1))); + subscriber.onNext("beginningEveryTime"); + subscriber.onError(new RuntimeException("forced failure: " + (i + 1))); done = true; } else { do { if (i == numFailures) { - o.onNext("beginningEveryTime"); + subscriber.onNext("beginningEveryTime"); } else if (i > numFailures) { - o.onNext("onSuccessOnly"); - o.onComplete(); + subscriber.onNext("onSuccessOnly"); + subscriber.onComplete(); done = true; break; } @@ -444,17 +444,17 @@ public void cancel() { @Test public void testUnsubscribeFromRetry() { - PublishProcessor<Integer> subject = PublishProcessor.create(); + PublishProcessor<Integer> processor = PublishProcessor.create(); final AtomicInteger count = new AtomicInteger(0); - Disposable sub = subject.retry().subscribe(new Consumer<Integer>() { + Disposable sub = processor.retry().subscribe(new Consumer<Integer>() { @Override public void accept(Integer n) { count.incrementAndGet(); } }); - subject.onNext(1); + processor.onNext(1); sub.dispose(); - subject.onNext(2); + processor.onNext(2); assertEquals(1, count.get()); } @@ -614,7 +614,7 @@ public void run() { } /** Observer for listener on seperate thread. */ - static final class AsyncObserver<T> extends DefaultSubscriber<T> { + static final class AsyncSubscriber<T> extends DefaultSubscriber<T> { protected CountDownLatch latch = new CountDownLatch(1); @@ -624,7 +624,7 @@ static final class AsyncObserver<T> extends DefaultSubscriber<T> { * Wrap existing Observer. * @param target the target subscriber */ - AsyncObserver(Subscriber<T> target) { + AsyncSubscriber(Subscriber<T> target) { this.target = target; } @@ -660,23 +660,22 @@ public void onNext(T v) { @Test(timeout = 10000) public void testUnsubscribeAfterError() { - @SuppressWarnings("unchecked") - DefaultSubscriber<Long> observer = mock(DefaultSubscriber.class); + Subscriber<Long> subscriber = TestHelper.mockSubscriber(); // Flowable that always fails after 100ms SlowFlowable so = new SlowFlowable(100, 0); - Flowable<Long> o = Flowable.unsafeCreate(so).retry(5); + Flowable<Long> f = Flowable.unsafeCreate(so).retry(5); - AsyncObserver<Long> async = new AsyncObserver<Long>(observer); + AsyncSubscriber<Long> async = new AsyncSubscriber<Long>(subscriber); - o.subscribe(async); + f.subscribe(async); async.await(); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // Should fail once - inOrder.verify(observer, times(1)).onError(any(Throwable.class)); - inOrder.verify(observer, never()).onComplete(); + inOrder.verify(subscriber, times(1)).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onComplete(); assertEquals("Start 6 threads, retry 5 then fail on 6", 6, so.efforts.get()); assertEquals("Only 1 active subscription", 1, so.maxActive.get()); @@ -685,25 +684,24 @@ public void testUnsubscribeAfterError() { @Test//(timeout = 10000) public void testTimeoutWithRetry() { - @SuppressWarnings("unchecked") - DefaultSubscriber<Long> observer = mock(DefaultSubscriber.class); + Subscriber<Long> subscriber = TestHelper.mockSubscriber(); // Flowable that sends every 100ms (timeout fails instead) - SlowFlowable so = new SlowFlowable(100, 10); - Flowable<Long> o = Flowable.unsafeCreate(so).timeout(80, TimeUnit.MILLISECONDS).retry(5); + SlowFlowable sf = new SlowFlowable(100, 10); + Flowable<Long> f = Flowable.unsafeCreate(sf).timeout(80, TimeUnit.MILLISECONDS).retry(5); - AsyncObserver<Long> async = new AsyncObserver<Long>(observer); + AsyncSubscriber<Long> async = new AsyncSubscriber<Long>(subscriber); - o.subscribe(async); + f.subscribe(async); async.await(); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // Should fail once - inOrder.verify(observer, times(1)).onError(any(Throwable.class)); - inOrder.verify(observer, never()).onComplete(); + inOrder.verify(subscriber, times(1)).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onComplete(); - assertEquals("Start 6 threads, retry 5 then fail on 6", 6, so.efforts.get()); + assertEquals("Start 6 threads, retry 5 then fail on 6", 6, sf.efforts.get()); } @Test//(timeout = 15000) @@ -712,21 +710,21 @@ public void testRetryWithBackpressure() throws InterruptedException { for (int j = 0;j < NUM_LOOPS; j++) { final int numRetries = Flowable.bufferSize() * 2; for (int i = 0; i < 400; i++) { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); origin.retry().observeOn(Schedulers.computation()).subscribe(ts); ts.awaitTerminalEvent(5, TimeUnit.SECONDS); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // should have no errors - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); // should show numRetries attempts - inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); + inOrder.verify(subscriber, times(numRetries + 1)).onNext("beginningEveryTime"); // should have a single success - inOrder.verify(observer, times(1)).onNext("onSuccessOnly"); + inOrder.verify(subscriber, times(1)).onNext("onSuccessOnly"); // should have a single successful onComplete - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } } @@ -833,7 +831,7 @@ static <T> StringBuilder sequenceFrequency(Iterable<T> it) { } @Test//(timeout = 3000) public void testIssue1900() throws InterruptedException { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); final int NUM_MSG = 1034; final AtomicInteger count = new AtomicInteger(); @@ -858,34 +856,34 @@ public Flowable<String> apply(GroupedFlowable<String, String> t1) { return t1.take(1); } }) - .subscribe(new TestSubscriber<String>(observer)); + .subscribe(new TestSubscriber<String>(subscriber)); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // should show 3 attempts - inOrder.verify(observer, times(NUM_MSG)).onNext(any(java.lang.String.class)); + inOrder.verify(subscriber, times(NUM_MSG)).onNext(any(java.lang.String.class)); // // should have no errors - inOrder.verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); // should have a single success //inOrder.verify(observer, times(1)).onNext("onSuccessOnly"); // should have a single successful onComplete - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test//(timeout = 3000) public void testIssue1900SourceNotSupportingBackpressure() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); final int NUM_MSG = 1034; final AtomicInteger count = new AtomicInteger(); Flowable<String> origin = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> o) { - o.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); for (int i = 0; i < NUM_MSG; i++) { - o.onNext("msg:" + count.incrementAndGet()); + subscriber.onNext("msg:" + count.incrementAndGet()); } - o.onComplete(); + subscriber.onComplete(); } }); @@ -902,17 +900,17 @@ public Flowable<String> apply(GroupedFlowable<String, String> t1) { return t1.take(1); } }) - .subscribe(new TestSubscriber<String>(observer)); + .subscribe(new TestSubscriber<String>(subscriber)); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // should show 3 attempts - inOrder.verify(observer, times(NUM_MSG)).onNext(any(java.lang.String.class)); + inOrder.verify(subscriber, times(NUM_MSG)).onNext(any(java.lang.String.class)); // // should have no errors - inOrder.verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); // should have a single success //inOrder.verify(observer, times(1)).onNext("onSuccessOnly"); // should have a single successful onComplete - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -925,8 +923,8 @@ public void retryWhenDefaultScheduler() { .concatWith(Flowable.<Integer>error(new TestException())) .retryWhen((Function)new Function<Flowable, Flowable>() { @Override - public Flowable apply(Flowable o) { - return o.take(2); + public Flowable apply(Flowable f) { + return f.take(2); } }).subscribe(ts); @@ -946,8 +944,8 @@ public void retryWhenTrampolineScheduler() { .subscribeOn(Schedulers.trampoline()) .retryWhen((Function)new Function<Flowable, Flowable>() { @Override - public Flowable apply(Flowable o) { - return o.take(2); + public Flowable apply(Flowable f) { + return f.take(2); } }).subscribe(ts); @@ -1002,7 +1000,7 @@ public boolean getAsBoolean() throws Exception { @Test public void shouldDisposeInnerObservable() { - final PublishProcessor<Object> subject = PublishProcessor.create(); + final PublishProcessor<Object> processor = PublishProcessor.create(); final Disposable disposable = Flowable.error(new RuntimeException("Leak")) .retryWhen(new Function<Flowable<Throwable>, Flowable<Object>>() { @Override @@ -1010,15 +1008,15 @@ public Flowable<Object> apply(Flowable<Throwable> errors) throws Exception { return errors.switchMap(new Function<Throwable, Flowable<Object>>() { @Override public Flowable<Object> apply(Throwable ignore) throws Exception { - return subject; + return processor; } }); } }) .subscribe(); - assertTrue(subject.hasSubscribers()); + assertTrue(processor.hasSubscribers()); disposable.dispose(); - assertFalse(subject.hasSubscribers()); + assertFalse(processor.hasSubscribers()); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java index 72a9f518ce..1f9f8c0736 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java @@ -32,6 +32,7 @@ import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.subscribers.*; @@ -58,16 +59,16 @@ public boolean test(Integer t1, Throwable t2) { public void testWithNothingToRetry() { Flowable<Integer> source = Flowable.range(0, 3); - Subscriber<Integer> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.retry(retryTwice).subscribe(o); + source.retry(retryTwice).subscribe(subscriber); - inOrder.verify(o).onNext(0); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(0); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testRetryTwice() { @@ -89,20 +90,19 @@ public void subscribe(Subscriber<? super Integer> t1) { } }); - @SuppressWarnings("unchecked") - DefaultSubscriber<Integer> o = mock(DefaultSubscriber.class); - InOrder inOrder = inOrder(o); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.retry(retryTwice).subscribe(o); + source.retry(retryTwice).subscribe(subscriber); - inOrder.verify(o).onNext(0); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(0); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onNext(3); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(0); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(0); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(3); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -117,20 +117,19 @@ public void subscribe(Subscriber<? super Integer> t1) { } }); - @SuppressWarnings("unchecked") - DefaultSubscriber<Integer> o = mock(DefaultSubscriber.class); - InOrder inOrder = inOrder(o); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.retry(retryTwice).subscribe(o); + source.retry(retryTwice).subscribe(subscriber); - inOrder.verify(o).onNext(0); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(0); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(0); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onError(any(TestException.class)); - verify(o, never()).onComplete(); + inOrder.verify(subscriber).onNext(0); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(0); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(0); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); } @Test @@ -153,20 +152,19 @@ public void subscribe(Subscriber<? super Integer> t1) { } }); - @SuppressWarnings("unchecked") - DefaultSubscriber<Integer> o = mock(DefaultSubscriber.class); - InOrder inOrder = inOrder(o); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.retry(retryOnTestException).subscribe(o); + source.retry(retryOnTestException).subscribe(subscriber); - inOrder.verify(o).onNext(0); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(0); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onNext(3); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(0); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(0); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(3); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testRetryOnSpecificExceptionAndNotOther() { @@ -190,60 +188,59 @@ public void subscribe(Subscriber<? super Integer> t1) { } }); - @SuppressWarnings("unchecked") - DefaultSubscriber<Integer> o = mock(DefaultSubscriber.class); - InOrder inOrder = inOrder(o); - - source.retry(retryOnTestException).subscribe(o); - - inOrder.verify(o).onNext(0); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(0); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onNext(3); - inOrder.verify(o).onError(te); - verify(o, never()).onError(ioe); - verify(o, never()).onComplete(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); + + source.retry(retryOnTestException).subscribe(subscriber); + + inOrder.verify(subscriber).onNext(0); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(0); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(3); + inOrder.verify(subscriber).onError(te); + verify(subscriber, never()).onError(ioe); + verify(subscriber, never()).onComplete(); } @Test public void testUnsubscribeFromRetry() { - PublishProcessor<Integer> subject = PublishProcessor.create(); + PublishProcessor<Integer> processor = PublishProcessor.create(); final AtomicInteger count = new AtomicInteger(0); - Disposable sub = subject.retry(retryTwice).subscribe(new Consumer<Integer>() { + Disposable sub = processor.retry(retryTwice).subscribe(new Consumer<Integer>() { @Override public void accept(Integer n) { count.incrementAndGet(); } }); - subject.onNext(1); + processor.onNext(1); sub.dispose(); - subject.onNext(2); + processor.onNext(2); assertEquals(1, count.get()); } @Test(timeout = 10000) public void testUnsubscribeAfterError() { - Subscriber<Long> observer = TestHelper.mockSubscriber(); + Subscriber<Long> subscriber = TestHelper.mockSubscriber(); // Flowable that always fails after 100ms FlowableRetryTest.SlowFlowable so = new FlowableRetryTest.SlowFlowable(100, 0); - Flowable<Long> o = Flowable + Flowable<Long> f = Flowable .unsafeCreate(so) .retry(retry5); - FlowableRetryTest.AsyncObserver<Long> async = new FlowableRetryTest.AsyncObserver<Long>(observer); + FlowableRetryTest.AsyncSubscriber<Long> async = new FlowableRetryTest.AsyncSubscriber<Long>(subscriber); - o.subscribe(async); + f.subscribe(async); async.await(); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // Should fail once - inOrder.verify(observer, times(1)).onError(any(Throwable.class)); - inOrder.verify(observer, never()).onComplete(); + inOrder.verify(subscriber, times(1)).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onComplete(); assertEquals("Start 6 threads, retry 5 then fail on 6", 6, so.efforts.get()); assertEquals("Only 1 active subscription", 1, so.maxActive.get()); @@ -252,25 +249,25 @@ public void testUnsubscribeAfterError() { @Test(timeout = 10000) public void testTimeoutWithRetry() { - Subscriber<Long> observer = TestHelper.mockSubscriber(); + Subscriber<Long> subscriber = TestHelper.mockSubscriber(); // Flowable that sends every 100ms (timeout fails instead) FlowableRetryTest.SlowFlowable so = new FlowableRetryTest.SlowFlowable(100, 10); - Flowable<Long> o = Flowable + Flowable<Long> f = Flowable .unsafeCreate(so) .timeout(80, TimeUnit.MILLISECONDS) .retry(retry5); - FlowableRetryTest.AsyncObserver<Long> async = new FlowableRetryTest.AsyncObserver<Long>(observer); + FlowableRetryTest.AsyncSubscriber<Long> async = new FlowableRetryTest.AsyncSubscriber<Long>(subscriber); - o.subscribe(async); + f.subscribe(async); async.await(); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); // Should fail once - inOrder.verify(observer, times(1)).onError(any(Throwable.class)); - inOrder.verify(observer, never()).onComplete(); + inOrder.verify(subscriber, times(1)).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onComplete(); assertEquals("Start 6 threads, retry 5 then fail on 6", 6, so.efforts.get()); } @@ -418,30 +415,34 @@ public void dontRetry() { @Test public void retryDisposeRace() { - for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor<Integer> pp = PublishProcessor.create(); - - final TestSubscriber<Integer> ts = pp.retry(Functions.alwaysTrue()).test(); + final TestException ex = new TestException(); + RxJavaPlugins.setErrorHandler(Functions.emptyConsumer()); + try { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final PublishProcessor<Integer> pp = PublishProcessor.create(); - final TestException ex = new TestException(); + final TestSubscriber<Integer> ts = pp.retry(Functions.alwaysTrue()).test(); - Runnable r1 = new Runnable() { - @Override - public void run() { - pp.onError(ex); - } - }; + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onError(ex); + } + }; - Runnable r2 = new Runnable() { - @Override - public void run() { - ts.cancel(); - } - }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; - TestHelper.race(r1, r2); + TestHelper.race(r1, r2); - ts.assertEmpty(); + ts.assertEmpty(); + } + } finally { + RxJavaPlugins.reset(); } } @@ -466,35 +467,40 @@ public boolean test(Integer n, Throwable e) throws Exception { @Test public void retryBiPredicateDisposeRace() { - for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final PublishProcessor<Integer> pp = PublishProcessor.create(); + RxJavaPlugins.setErrorHandler(Functions.emptyConsumer()); + try { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final PublishProcessor<Integer> pp = PublishProcessor.create(); - final TestSubscriber<Integer> ts = pp.retry(new BiPredicate<Object, Object>() { - @Override - public boolean test(Object t1, Object t2) throws Exception { - return true; - } - }).test(); + final TestSubscriber<Integer> ts = pp.retry(new BiPredicate<Object, Object>() { + @Override + public boolean test(Object t1, Object t2) throws Exception { + return true; + } + }).test(); - final TestException ex = new TestException(); + final TestException ex = new TestException(); - Runnable r1 = new Runnable() { - @Override - public void run() { - pp.onError(ex); - } - }; + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onError(ex); + } + }; - Runnable r2 = new Runnable() { - @Override - public void run() { - ts.cancel(); - } - }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; - TestHelper.race(r1, r2); + TestHelper.race(r1, r2); - ts.assertEmpty(); + ts.assertEmpty(); + } + } finally { + RxJavaPlugins.reset(); } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java index f168dc1891..12e354cda2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java @@ -33,78 +33,78 @@ public class FlowableSampleTest { private TestScheduler scheduler; private Scheduler.Worker innerScheduler; - private Subscriber<Long> observer; - private Subscriber<Object> observer2; + private Subscriber<Long> subscriber; + private Subscriber<Object> subscriber2; @Before // due to mocking public void before() { scheduler = new TestScheduler(); innerScheduler = scheduler.createWorker(); - observer = TestHelper.mockSubscriber(); - observer2 = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); + subscriber2 = TestHelper.mockSubscriber(); } @Test public void testSample() { Flowable<Long> source = Flowable.unsafeCreate(new Publisher<Long>() { @Override - public void subscribe(final Subscriber<? super Long> observer1) { - observer1.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super Long> subscriber1) { + subscriber1.onSubscribe(new BooleanSubscription()); innerScheduler.schedule(new Runnable() { @Override public void run() { - observer1.onNext(1L); + subscriber1.onNext(1L); } }, 1, TimeUnit.SECONDS); innerScheduler.schedule(new Runnable() { @Override public void run() { - observer1.onNext(2L); + subscriber1.onNext(2L); } }, 2, TimeUnit.SECONDS); innerScheduler.schedule(new Runnable() { @Override public void run() { - observer1.onComplete(); + subscriber1.onComplete(); } }, 3, TimeUnit.SECONDS); } }); Flowable<Long> sampled = source.sample(400L, TimeUnit.MILLISECONDS, scheduler); - sampled.subscribe(observer); + sampled.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(800L, TimeUnit.MILLISECONDS); - verify(observer, never()).onNext(any(Long.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any(Long.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(1200L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext(1L); - verify(observer, never()).onNext(2L); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext(1L); + verify(subscriber, never()).onNext(2L); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(1600L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(1L); - verify(observer, never()).onNext(2L); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(1L); + verify(subscriber, never()).onNext(2L); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(2000L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(1L); - inOrder.verify(observer, times(1)).onNext(2L); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(1L); + inOrder.verify(subscriber, times(1)).onNext(2L); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(3000L, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(1L); - inOrder.verify(observer, never()).onNext(2L); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(1L); + inOrder.verify(subscriber, never()).onNext(2L); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -113,7 +113,7 @@ public void sampleWithSamplerNormal() { PublishProcessor<Integer> sampler = PublishProcessor.create(); Flowable<Integer> m = source.sample(sampler); - m.subscribe(observer2); + m.subscribe(subscriber2); source.onNext(1); source.onNext(2); @@ -124,13 +124,13 @@ public void sampleWithSamplerNormal() { source.onComplete(); sampler.onNext(3); - InOrder inOrder = inOrder(observer2); - inOrder.verify(observer2, never()).onNext(1); - inOrder.verify(observer2, times(1)).onNext(2); - inOrder.verify(observer2, never()).onNext(3); - inOrder.verify(observer2, times(1)).onNext(4); - inOrder.verify(observer2, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber2); + inOrder.verify(subscriber2, never()).onNext(1); + inOrder.verify(subscriber2, times(1)).onNext(2); + inOrder.verify(subscriber2, never()).onNext(3); + inOrder.verify(subscriber2, times(1)).onNext(4); + inOrder.verify(subscriber2, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -139,7 +139,7 @@ public void sampleWithSamplerNoDuplicates() { PublishProcessor<Integer> sampler = PublishProcessor.create(); Flowable<Integer> m = source.sample(sampler); - m.subscribe(observer2); + m.subscribe(subscriber2); source.onNext(1); source.onNext(2); @@ -154,13 +154,13 @@ public void sampleWithSamplerNoDuplicates() { source.onComplete(); sampler.onNext(3); - InOrder inOrder = inOrder(observer2); - inOrder.verify(observer2, never()).onNext(1); - inOrder.verify(observer2, times(1)).onNext(2); - inOrder.verify(observer2, never()).onNext(3); - inOrder.verify(observer2, times(1)).onNext(4); - inOrder.verify(observer2, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber2); + inOrder.verify(subscriber2, never()).onNext(1); + inOrder.verify(subscriber2, times(1)).onNext(2); + inOrder.verify(subscriber2, never()).onNext(3); + inOrder.verify(subscriber2, times(1)).onNext(4); + inOrder.verify(subscriber2, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -169,7 +169,7 @@ public void sampleWithSamplerTerminatingEarly() { PublishProcessor<Integer> sampler = PublishProcessor.create(); Flowable<Integer> m = source.sample(sampler); - m.subscribe(observer2); + m.subscribe(subscriber2); source.onNext(1); source.onNext(2); @@ -179,12 +179,12 @@ public void sampleWithSamplerTerminatingEarly() { source.onNext(3); source.onNext(4); - InOrder inOrder = inOrder(observer2); - inOrder.verify(observer2, never()).onNext(1); - inOrder.verify(observer2, times(1)).onNext(2); - inOrder.verify(observer2, times(1)).onComplete(); - inOrder.verify(observer2, never()).onNext(any()); - verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber2); + inOrder.verify(subscriber2, never()).onNext(1); + inOrder.verify(subscriber2, times(1)).onNext(2); + inOrder.verify(subscriber2, times(1)).onComplete(); + inOrder.verify(subscriber2, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -193,7 +193,7 @@ public void sampleWithSamplerEmitAndTerminate() { PublishProcessor<Integer> sampler = PublishProcessor.create(); Flowable<Integer> m = source.sample(sampler); - m.subscribe(observer2); + m.subscribe(subscriber2); source.onNext(1); source.onNext(2); @@ -203,13 +203,13 @@ public void sampleWithSamplerEmitAndTerminate() { sampler.onNext(2); sampler.onComplete(); - InOrder inOrder = inOrder(observer2); - inOrder.verify(observer2, never()).onNext(1); - inOrder.verify(observer2, times(1)).onNext(2); - inOrder.verify(observer2, never()).onNext(3); - inOrder.verify(observer2, times(1)).onComplete(); - inOrder.verify(observer2, never()).onNext(any()); - verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber2); + inOrder.verify(subscriber2, never()).onNext(1); + inOrder.verify(subscriber2, times(1)).onNext(2); + inOrder.verify(subscriber2, never()).onNext(3); + inOrder.verify(subscriber2, times(1)).onComplete(); + inOrder.verify(subscriber2, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -218,15 +218,15 @@ public void sampleWithSamplerEmptySource() { PublishProcessor<Integer> sampler = PublishProcessor.create(); Flowable<Integer> m = source.sample(sampler); - m.subscribe(observer2); + m.subscribe(subscriber2); source.onComplete(); sampler.onNext(1); - InOrder inOrder = inOrder(observer2); - inOrder.verify(observer2, times(1)).onComplete(); - verify(observer2, never()).onNext(any()); - verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber2); + inOrder.verify(subscriber2, times(1)).onComplete(); + verify(subscriber2, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -235,16 +235,16 @@ public void sampleWithSamplerSourceThrows() { PublishProcessor<Integer> sampler = PublishProcessor.create(); Flowable<Integer> m = source.sample(sampler); - m.subscribe(observer2); + m.subscribe(subscriber2); source.onNext(1); source.onError(new RuntimeException("Forced failure!")); sampler.onNext(1); - InOrder inOrder = inOrder(observer2); - inOrder.verify(observer2, times(1)).onError(any(Throwable.class)); - verify(observer2, never()).onNext(any()); - verify(observer, never()).onComplete(); + InOrder inOrder = inOrder(subscriber2); + inOrder.verify(subscriber2, times(1)).onError(any(Throwable.class)); + verify(subscriber2, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -253,22 +253,22 @@ public void sampleWithSamplerThrows() { PublishProcessor<Integer> sampler = PublishProcessor.create(); Flowable<Integer> m = source.sample(sampler); - m.subscribe(observer2); + m.subscribe(subscriber2); source.onNext(1); sampler.onNext(1); sampler.onError(new RuntimeException("Forced failure!")); - InOrder inOrder = inOrder(observer2); - inOrder.verify(observer2, times(1)).onNext(1); - inOrder.verify(observer2, times(1)).onError(any(RuntimeException.class)); - verify(observer, never()).onComplete(); + InOrder inOrder = inOrder(subscriber2); + inOrder.verify(subscriber2, times(1)).onNext(1); + inOrder.verify(subscriber2, times(1)).onError(any(RuntimeException.class)); + verify(subscriber, never()).onComplete(); } @Test public void testSampleUnsubscribe() { final Subscription s = mock(Subscription.class); - Flowable<Integer> o = Flowable.unsafeCreate( + Flowable<Integer> f = Flowable.unsafeCreate( new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> subscriber) { @@ -276,7 +276,7 @@ public void subscribe(Subscriber<? super Integer> subscriber) { } } ); - o.throttleLast(1, TimeUnit.MILLISECONDS).subscribe().dispose(); + f.throttleLast(1, TimeUnit.MILLISECONDS).subscribe().dispose(); verify(s).cancel(); } @@ -450,9 +450,9 @@ public void run() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) + public Flowable<Object> apply(Flowable<Object> f) throws Exception { - return o.sample(1, TimeUnit.SECONDS); + return f.sample(1, TimeUnit.SECONDS); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java index a01495295e..d12476cf4e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java @@ -37,11 +37,11 @@ public class FlowableScanTest { @Test public void testScanIntegersWithInitialValue() { - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable<Integer> observable = Flowable.just(1, 2, 3); + Flowable<Integer> flowable = Flowable.just(1, 2, 3); - Flowable<String> m = observable.scan("", new BiFunction<String, Integer, String>() { + Flowable<String> m = flowable.scan("", new BiFunction<String, Integer, String>() { @Override public String apply(String s, Integer n) { @@ -49,25 +49,25 @@ public String apply(String s, Integer n) { } }); - m.subscribe(observer); + m.subscribe(subscriber); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onNext(""); - verify(observer, times(1)).onNext("1"); - verify(observer, times(1)).onNext("12"); - verify(observer, times(1)).onNext("123"); - verify(observer, times(4)).onNext(anyString()); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onNext(""); + verify(subscriber, times(1)).onNext("1"); + verify(subscriber, times(1)).onNext("12"); + verify(subscriber, times(1)).onNext("123"); + verify(subscriber, times(4)).onNext(anyString()); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testScanIntegersWithoutInitialValue() { - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - Flowable<Integer> observable = Flowable.just(1, 2, 3); + Flowable<Integer> flowable = Flowable.just(1, 2, 3); - Flowable<Integer> m = observable.scan(new BiFunction<Integer, Integer, Integer>() { + Flowable<Integer> m = flowable.scan(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) { @@ -75,25 +75,25 @@ public Integer apply(Integer t1, Integer t2) { } }); - m.subscribe(observer); + m.subscribe(subscriber); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onNext(0); - verify(observer, times(1)).onNext(1); - verify(observer, times(1)).onNext(3); - verify(observer, times(1)).onNext(6); - verify(observer, times(3)).onNext(anyInt()); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(0); + verify(subscriber, times(1)).onNext(1); + verify(subscriber, times(1)).onNext(3); + verify(subscriber, times(1)).onNext(6); + verify(subscriber, times(3)).onNext(anyInt()); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testScanIntegersWithoutInitialValueAndOnlyOneValue() { - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - Flowable<Integer> observable = Flowable.just(1); + Flowable<Integer> flowable = Flowable.just(1); - Flowable<Integer> m = observable.scan(new BiFunction<Integer, Integer, Integer>() { + Flowable<Integer> m = flowable.scan(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) { @@ -101,14 +101,14 @@ public Integer apply(Integer t1, Integer t2) { } }); - m.subscribe(observer); + m.subscribe(subscriber); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onNext(0); - verify(observer, times(1)).onNext(1); - verify(observer, times(1)).onNext(anyInt()); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(0); + verify(subscriber, times(1)).onNext(1); + verify(subscriber, times(1)).onNext(anyInt()); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -283,7 +283,7 @@ public void accept(List<Integer> list, Integer t2) { */ @Test public void testSeedFactoryFlowable() { - Flowable<List<Integer>> o = Flowable.range(1, 10) + Flowable<List<Integer>> f = Flowable.range(1, 10) .collect(new Callable<List<Integer>>() { @Override @@ -300,13 +300,13 @@ public void accept(List<Integer> list, Integer t2) { }).toFlowable().takeLast(1); - assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), o.blockingSingle()); - assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), o.blockingSingle()); + assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), f.blockingSingle()); + assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), f.blockingSingle()); } @Test public void testScanWithRequestOne() { - Flowable<Integer> o = Flowable.just(1, 2).scan(0, new BiFunction<Integer, Integer, Integer>() { + Flowable<Integer> f = Flowable.just(1, 2).scan(0, new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) { @@ -315,7 +315,7 @@ public Integer apply(Integer t1, Integer t2) { }).take(1); TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>(); - o.subscribe(subscriber); + f.subscribe(subscriber); subscriber.assertValue(0); subscriber.assertTerminated(); subscriber.assertNoErrors(); @@ -324,7 +324,7 @@ public Integer apply(Integer t1, Integer t2) { @Test public void testScanShouldNotRequestZero() { final AtomicReference<Subscription> producer = new AtomicReference<Subscription>(); - Flowable<Integer> o = Flowable.unsafeCreate(new Publisher<Integer>() { + Flowable<Integer> f = Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(final Subscriber<? super Integer> subscriber) { Subscription p = spy(new Subscription() { @@ -356,7 +356,7 @@ public Integer apply(Integer t1, Integer t2) { }); - o.subscribe(new TestSubscriber<Integer>(1L) { + f.subscribe(new TestSubscriber<Integer>(1L) { @Override public void onNext(Integer integer) { @@ -427,8 +427,8 @@ public Integer apply(Integer a, Integer b) throws Exception { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.scan(new BiFunction<Object, Object, Object>() { + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.scan(new BiFunction<Object, Object, Object>() { @Override public Object apply(Object a, Object b) throws Exception { return a; @@ -439,8 +439,8 @@ public Object apply(Object a, Object b) throws Exception { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.scan(0, new BiFunction<Object, Object, Object>() { + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.scan(0, new BiFunction<Object, Object, Object>() { @Override public Object apply(Object a, Object b) throws Exception { return a; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java index a71e68f696..4ee2fad368 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java @@ -37,98 +37,98 @@ public class FlowableSequenceEqualTest { @Test public void test1Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.just("one", "two", "three"), Flowable.just("one", "two", "three")).toFlowable(); - verifyResult(observable, true); + verifyResult(flowable, true); } @Test public void test2Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.just("one", "two", "three"), Flowable.just("one", "two", "three", "four")).toFlowable(); - verifyResult(observable, false); + verifyResult(flowable, false); } @Test public void test3Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.just("one", "two", "three", "four"), Flowable.just("one", "two", "three")).toFlowable(); - verifyResult(observable, false); + verifyResult(flowable, false); } @Test public void testWithError1Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.concat(Flowable.just("one"), Flowable.<String> error(new TestException())), Flowable.just("one", "two", "three")).toFlowable(); - verifyError(observable); + verifyError(flowable); } @Test public void testWithError2Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.just("one", "two", "three"), Flowable.concat(Flowable.just("one"), Flowable.<String> error(new TestException()))).toFlowable(); - verifyError(observable); + verifyError(flowable); } @Test public void testWithError3Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.concat(Flowable.just("one"), Flowable.<String> error(new TestException())), Flowable.concat(Flowable.just("one"), Flowable.<String> error(new TestException()))).toFlowable(); - verifyError(observable); + verifyError(flowable); } @Test public void testWithEmpty1Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.<String> empty(), Flowable.just("one", "two", "three")).toFlowable(); - verifyResult(observable, false); + verifyResult(flowable, false); } @Test public void testWithEmpty2Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.just("one", "two", "three"), Flowable.<String> empty()).toFlowable(); - verifyResult(observable, false); + verifyResult(flowable, false); } @Test public void testWithEmpty3Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.<String> empty(), Flowable.<String> empty()).toFlowable(); - verifyResult(observable, true); + verifyResult(flowable, true); } @Test @Ignore("Null values not allowed") public void testWithNull1Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.just((String) null), Flowable.just("one")).toFlowable(); - verifyResult(observable, false); + verifyResult(flowable, false); } @Test @Ignore("Null values not allowed") public void testWithNull2Flowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.just((String) null), Flowable.just((String) null)).toFlowable(); - verifyResult(observable, true); + verifyResult(flowable, true); } @Test public void testWithEqualityErrorFlowable() { - Flowable<Boolean> observable = Flowable.sequenceEqual( + Flowable<Boolean> flowable = Flowable.sequenceEqual( Flowable.just("one"), Flowable.just("one"), new BiPredicate<String, String>() { @Override @@ -136,103 +136,103 @@ public boolean test(String t1, String t2) { throw new TestException(); } }).toFlowable(); - verifyError(observable); + verifyError(flowable); } @Test public void test1() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.just("one", "two", "three"), Flowable.just("one", "two", "three")); - verifyResult(observable, true); + verifyResult(single, true); } @Test public void test2() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.just("one", "two", "three"), Flowable.just("one", "two", "three", "four")); - verifyResult(observable, false); + verifyResult(single, false); } @Test public void test3() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.just("one", "two", "three", "four"), Flowable.just("one", "two", "three")); - verifyResult(observable, false); + verifyResult(single, false); } @Test public void testWithError1() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.concat(Flowable.just("one"), Flowable.<String> error(new TestException())), Flowable.just("one", "two", "three")); - verifyError(observable); + verifyError(single); } @Test public void testWithError2() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.just("one", "two", "three"), Flowable.concat(Flowable.just("one"), Flowable.<String> error(new TestException()))); - verifyError(observable); + verifyError(single); } @Test public void testWithError3() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.concat(Flowable.just("one"), Flowable.<String> error(new TestException())), Flowable.concat(Flowable.just("one"), Flowable.<String> error(new TestException()))); - verifyError(observable); + verifyError(single); } @Test public void testWithEmpty1() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.<String> empty(), Flowable.just("one", "two", "three")); - verifyResult(observable, false); + verifyResult(single, false); } @Test public void testWithEmpty2() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.just("one", "two", "three"), Flowable.<String> empty()); - verifyResult(observable, false); + verifyResult(single, false); } @Test public void testWithEmpty3() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.<String> empty(), Flowable.<String> empty()); - verifyResult(observable, true); + verifyResult(single, true); } @Test @Ignore("Null values not allowed") public void testWithNull1() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.just((String) null), Flowable.just("one")); - verifyResult(observable, false); + verifyResult(single, false); } @Test @Ignore("Null values not allowed") public void testWithNull2() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.just((String) null), Flowable.just((String) null)); - verifyResult(observable, true); + verifyResult(single, true); } @Test public void testWithEqualityError() { - Single<Boolean> observable = Flowable.sequenceEqual( + Single<Boolean> single = Flowable.sequenceEqual( Flowable.just("one"), Flowable.just("one"), new BiPredicate<String, String>() { @Override @@ -240,42 +240,42 @@ public boolean test(String t1, String t2) { throw new TestException(); } }); - verifyError(observable); + verifyError(single); } - private void verifyResult(Flowable<Boolean> observable, boolean result) { - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); + private void verifyResult(Flowable<Boolean> flowable, boolean result) { + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); - observable.subscribe(observer); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(result); - inOrder.verify(observer).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(result); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); } - private void verifyResult(Single<Boolean> observable, boolean result) { + private void verifyResult(Single<Boolean> single, boolean result) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(result); inOrder.verifyNoMoreInteractions(); } - private void verifyError(Flowable<Boolean> observable) { - Subscriber<Boolean> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + private void verifyError(Flowable<Boolean> flowable) { + Subscriber<Boolean> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onError(isA(TestException.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onError(isA(TestException.class)); inOrder.verifyNoMoreInteractions(); } - private void verifyError(Single<Boolean> observable) { + private void verifyError(Single<Boolean> single) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError(isA(TestException.class)); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSerializeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSerializeTest.java index 8fe8431271..6094955e83 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSerializeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSerializeTest.java @@ -28,11 +28,11 @@ public class FlowableSerializeTest { - Subscriber<String> observer; + Subscriber<String> subscriber; @Before public void before() { - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); } @Test @@ -40,14 +40,14 @@ public void testSingleThreadedBasic() { TestSingleThreadedObservable onSubscribe = new TestSingleThreadedObservable("one", "two", "three"); Flowable<String> w = Flowable.unsafeCreate(onSubscribe); - w.serialize().subscribe(observer); + w.serialize().subscribe(subscriber); onSubscribe.waitToFinish(); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); // non-deterministic because unsubscribe happens after 'waitToFinish' releases // so commenting out for now as this is not a critical thing to test here // verify(s, times(1)).unsubscribe(); @@ -144,18 +144,18 @@ public void testMultiThreadedWithNPEinMiddle() { */ static class OnNextThread implements Runnable { - private final DefaultSubscriber<String> observer; + private final DefaultSubscriber<String> subscriber; private final int numStringsToSend; - OnNextThread(DefaultSubscriber<String> observer, int numStringsToSend) { - this.observer = observer; + OnNextThread(DefaultSubscriber<String> subscriber, int numStringsToSend) { + this.subscriber = subscriber; this.numStringsToSend = numStringsToSend; } @Override public void run() { for (int i = 0; i < numStringsToSend; i++) { - observer.onNext("aString"); + subscriber.onNext("aString"); } } } @@ -165,12 +165,12 @@ public void run() { */ static class CompletionThread implements Runnable { - private final DefaultSubscriber<String> observer; + private final DefaultSubscriber<String> subscriber; private final TestConcurrencyobserverEvent event; private final Future<?>[] waitOnThese; - CompletionThread(DefaultSubscriber<String> observer, TestConcurrencyobserverEvent event, Future<?>... waitOnThese) { - this.observer = observer; + CompletionThread(DefaultSubscriber<String> subscriber, TestConcurrencyobserverEvent event, Future<?>... waitOnThese) { + this.subscriber = subscriber; this.event = event; this.waitOnThese = waitOnThese; } @@ -190,9 +190,9 @@ public void run() { /* send the event */ if (event == TestConcurrencyobserverEvent.onError) { - observer.onError(new RuntimeException("mocked exception")); + subscriber.onError(new RuntimeException("mocked exception")); } else if (event == TestConcurrencyobserverEvent.onComplete) { - observer.onComplete(); + subscriber.onComplete(); } else { throw new IllegalArgumentException("Expecting either onError or onComplete"); @@ -218,8 +218,8 @@ private static class TestSingleThreadedObservable implements Publisher<String> { } @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); System.out.println("TestSingleThreadedObservable subscribed to ..."); t = new Thread(new Runnable() { @@ -229,9 +229,9 @@ public void run() { System.out.println("running TestSingleThreadedObservable thread"); for (String s : values) { System.out.println("TestSingleThreadedObservable onNext: " + s); - observer.onNext(s); + subscriber.onNext(s); } - observer.onComplete(); + subscriber.onComplete(); } catch (Throwable e) { throw new RuntimeException(e); } @@ -269,8 +269,8 @@ private static class TestMultiThreadedObservable implements Publisher<String> { } @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); System.out.println("TestMultiThreadedObservable subscribed to ..."); final NullPointerException npe = new NullPointerException(); t = new Thread(new Runnable() { @@ -299,7 +299,7 @@ public void run() { } System.out.println("TestMultiThreadedObservable onNext: " + s); } - observer.onNext(s); + subscriber.onNext(s); // capture 'maxThreads' int concurrentThreads = threadsRunning.get(); int maxThreads = maxConcurrentThreads.get(); @@ -307,7 +307,7 @@ public void run() { maxConcurrentThreads.compareAndSet(maxThreads, concurrentThreads); } } catch (Throwable e) { - observer.onError(e); + subscriber.onError(e); } finally { threadsRunning.decrementAndGet(); } @@ -327,7 +327,7 @@ public void run() { } catch (InterruptedException e) { throw new RuntimeException(e); } - observer.onComplete(); + subscriber.onComplete(); } }); System.out.println("starting TestMultiThreadedObservable thread"); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java index 8be75e36e1..88cb84d40d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java @@ -34,40 +34,40 @@ public class FlowableSingleTest { @Test public void testSingleFlowable() { - Flowable<Integer> observable = Flowable.just(1).singleElement().toFlowable(); + Flowable<Integer> flowable = Flowable.just(1).singleElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(1); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleWithTooManyElementsFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2).singleElement().toFlowable(); + Flowable<Integer> flowable = Flowable.just(1, 2).singleElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onError( + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onError( isA(IllegalArgumentException.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleWithEmptyFlowable() { - Flowable<Integer> observable = Flowable.<Integer> empty().singleElement().toFlowable(); + Flowable<Integer> flowable = Flowable.<Integer> empty().singleElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onComplete(); - inOrder.verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onComplete(); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); inOrder.verifyNoMoreInteractions(); } @@ -195,7 +195,7 @@ public void onNext(Integer t) { @Test public void testSingleWithPredicateFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2) + Flowable<Integer> flowable = Flowable.just(1, 2) .filter( new Predicate<Integer>() { @@ -206,18 +206,18 @@ public boolean test(Integer t1) { }) .singleElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleWithPredicateAndTooManyElementsFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2, 3, 4) + Flowable<Integer> flowable = Flowable.just(1, 2, 3, 4) .filter( new Predicate<Integer>() { @@ -228,18 +228,18 @@ public boolean test(Integer t1) { }) .singleElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onError( + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onError( isA(IllegalArgumentException.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleWithPredicateAndEmptyFlowable() { - Flowable<Integer> observable = Flowable.just(1) + Flowable<Integer> flowable = Flowable.just(1) .filter( new Predicate<Integer>() { @@ -249,58 +249,58 @@ public boolean test(Integer t1) { } }) .singleElement().toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onComplete(); - inOrder.verify(observer, never()).onError(any(Throwable.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onComplete(); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleOrDefaultFlowable() { - Flowable<Integer> observable = Flowable.just(1).single(2).toFlowable(); + Flowable<Integer> flowable = Flowable.just(1).single(2).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(1); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleOrDefaultWithTooManyElementsFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2).single(3).toFlowable(); + Flowable<Integer> flowable = Flowable.just(1, 2).single(3).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onError( + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onError( isA(IllegalArgumentException.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleOrDefaultWithEmptyFlowable() { - Flowable<Integer> observable = Flowable.<Integer> empty() + Flowable<Integer> flowable = Flowable.<Integer> empty() .single(1).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(1); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(1); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleOrDefaultWithPredicateFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2) + Flowable<Integer> flowable = Flowable.just(1, 2) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -309,18 +309,18 @@ public boolean test(Integer t1) { }) .single(4).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleOrDefaultWithPredicateAndTooManyElementsFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2, 3, 4) + Flowable<Integer> flowable = Flowable.just(1, 2, 3, 4) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -329,18 +329,18 @@ public boolean test(Integer t1) { }) .single(6).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onError( + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onError( isA(IllegalArgumentException.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleOrDefaultWithPredicateAndEmptyFlowable() { - Flowable<Integer> observable = Flowable.just(1) + Flowable<Integer> flowable = Flowable.just(1) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -349,18 +349,18 @@ public boolean test(Integer t1) { }) .single(2).toFlowable(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testSingleWithBackpressureFlowable() { - Flowable<Integer> observable = Flowable.just(1, 2).singleElement().toFlowable(); + Flowable<Integer> flowable = Flowable.just(1, 2).singleElement().toFlowable(); Subscriber<Integer> subscriber = spy(new DefaultSubscriber<Integer>() { @@ -384,7 +384,7 @@ public void onNext(Integer integer) { request(1); } }); - observable.subscribe(subscriber); + flowable.subscribe(subscriber); InOrder inOrder = inOrder(subscriber); inOrder.verify(subscriber, times(1)).onError(isA(IllegalArgumentException.class)); @@ -393,10 +393,10 @@ public void onNext(Integer integer) { @Test public void testSingle() { - Maybe<Integer> observable = Flowable.just(1).singleElement(); + Maybe<Integer> maybe = Flowable.just(1).singleElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(1); @@ -405,10 +405,10 @@ public void testSingle() { @Test public void testSingleWithTooManyElements() { - Maybe<Integer> observable = Flowable.just(1, 2).singleElement(); + Maybe<Integer> maybe = Flowable.just(1, 2).singleElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError( @@ -418,10 +418,10 @@ public void testSingleWithTooManyElements() { @Test public void testSingleWithEmpty() { - Maybe<Integer> observable = Flowable.<Integer> empty().singleElement(); + Maybe<Integer> maybe = Flowable.<Integer> empty().singleElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer).onComplete(); @@ -476,7 +476,7 @@ public void accept(long n) { @Test public void testSingleWithPredicate() { - Maybe<Integer> observable = Flowable.just(1, 2) + Maybe<Integer> maybe = Flowable.just(1, 2) .filter( new Predicate<Integer>() { @@ -488,7 +488,7 @@ public boolean test(Integer t1) { .singleElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(2); @@ -497,7 +497,7 @@ public boolean test(Integer t1) { @Test public void testSingleWithPredicateAndTooManyElements() { - Maybe<Integer> observable = Flowable.just(1, 2, 3, 4) + Maybe<Integer> maybe = Flowable.just(1, 2, 3, 4) .filter( new Predicate<Integer>() { @@ -509,7 +509,7 @@ public boolean test(Integer t1) { .singleElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError( @@ -519,7 +519,7 @@ public boolean test(Integer t1) { @Test public void testSingleWithPredicateAndEmpty() { - Maybe<Integer> observable = Flowable.just(1) + Maybe<Integer> maybe = Flowable.just(1) .filter( new Predicate<Integer>() { @@ -531,7 +531,7 @@ public boolean test(Integer t1) { .singleElement(); MaybeObserver<Integer> observer = TestHelper.mockMaybeObserver(); - observable.subscribe(observer); + maybe.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer).onComplete(); @@ -541,10 +541,10 @@ public boolean test(Integer t1) { @Test public void testSingleOrDefault() { - Single<Integer> observable = Flowable.just(1).single(2); + Single<Integer> single = Flowable.just(1).single(2); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(1); @@ -553,10 +553,10 @@ public void testSingleOrDefault() { @Test public void testSingleOrDefaultWithTooManyElements() { - Single<Integer> observable = Flowable.just(1, 2).single(3); + Single<Integer> single = Flowable.just(1, 2).single(3); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError( @@ -566,11 +566,11 @@ public void testSingleOrDefaultWithTooManyElements() { @Test public void testSingleOrDefaultWithEmpty() { - Single<Integer> observable = Flowable.<Integer> empty() + Single<Integer> single = Flowable.<Integer> empty() .single(1); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(1); @@ -579,7 +579,7 @@ public void testSingleOrDefaultWithEmpty() { @Test public void testSingleOrDefaultWithPredicate() { - Single<Integer> observable = Flowable.just(1, 2) + Single<Integer> single = Flowable.just(1, 2) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -589,7 +589,7 @@ public boolean test(Integer t1) { .single(4); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(2); @@ -598,7 +598,7 @@ public boolean test(Integer t1) { @Test public void testSingleOrDefaultWithPredicateAndTooManyElements() { - Single<Integer> observable = Flowable.just(1, 2, 3, 4) + Single<Integer> single = Flowable.just(1, 2, 3, 4) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -608,7 +608,7 @@ public boolean test(Integer t1) { .single(6); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError( @@ -618,7 +618,7 @@ public boolean test(Integer t1) { @Test public void testSingleOrDefaultWithPredicateAndEmpty() { - Single<Integer> observable = Flowable.just(1) + Single<Integer> single = Flowable.just(1) .filter(new Predicate<Integer>() { @Override public boolean test(Integer t1) { @@ -628,7 +628,7 @@ public boolean test(Integer t1) { .single(2); SingleObserver<Integer> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(2); @@ -715,9 +715,9 @@ public void singleElementOperatorDoNotSwallowExceptionWhenDone() { }); Flowable.unsafeCreate(new Publisher<Integer>() { - @Override public void subscribe(final Subscriber<? super Integer> observer) { - observer.onComplete(); - observer.onError(exception); + @Override public void subscribe(final Subscriber<? super Integer> subscriber) { + subscriber.onComplete(); + subscriber.onError(exception); } }).singleElement().test().assertComplete(); @@ -731,22 +731,22 @@ public void singleElementOperatorDoNotSwallowExceptionWhenDone() { public void badSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Object>, Object>() { @Override - public Object apply(Flowable<Object> o) throws Exception { - return o.singleOrError(); + public Object apply(Flowable<Object> f) throws Exception { + return f.singleOrError(); } }, false, 1, 1, 1); TestHelper.checkBadSourceFlowable(new Function<Flowable<Object>, Object>() { @Override - public Object apply(Flowable<Object> o) throws Exception { - return o.singleElement(); + public Object apply(Flowable<Object> f) throws Exception { + return f.singleElement(); } }, false, 1, 1, 1); TestHelper.checkBadSourceFlowable(new Function<Flowable<Object>, Object>() { @Override - public Object apply(Flowable<Object> o) throws Exception { - return o.singleOrError().toFlowable(); + public Object apply(Flowable<Object> f) throws Exception { + return f.singleOrError().toFlowable(); } }, false, 1, 1, 1); } @@ -755,29 +755,29 @@ public Object apply(Flowable<Object> o) throws Exception { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function<Flowable<Object>, SingleSource<Object>>() { @Override - public SingleSource<Object> apply(Flowable<Object> o) throws Exception { - return o.singleOrError(); + public SingleSource<Object> apply(Flowable<Object> f) throws Exception { + return f.singleOrError(); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.singleOrError().toFlowable(); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.singleOrError().toFlowable(); } }); TestHelper.checkDoubleOnSubscribeFlowableToMaybe(new Function<Flowable<Object>, MaybeSource<Object>>() { @Override - public MaybeSource<Object> apply(Flowable<Object> o) throws Exception { - return o.singleElement(); + public MaybeSource<Object> apply(Flowable<Object> f) throws Exception { + return f.singleElement(); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.singleElement().toFlowable(); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.singleElement().toFlowable(); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTest.java index 9918af965d..11680a0927 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTest.java @@ -32,72 +32,77 @@ public class FlowableSkipLastTest { @Test public void testSkipLastEmpty() { - Flowable<String> observable = Flowable.<String> empty().skipLast(2); + Flowable<String> flowable = Flowable.<String> empty().skipLast(2); - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); - verify(observer, never()).onNext(any(String.class)); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); + + verify(subscriber, never()).onNext(any(String.class)); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testSkipLast1() { - Flowable<String> observable = Flowable.fromIterable(Arrays.asList("one", "two", "three")).skipLast(2); - - Subscriber<String> observer = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer); - observable.subscribe(observer); - inOrder.verify(observer, never()).onNext("two"); - inOrder.verify(observer, never()).onNext("three"); - verify(observer, times(1)).onNext("one"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Flowable<String> flowable = Flowable.fromIterable(Arrays.asList("one", "two", "three")).skipLast(2); + + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); + flowable.subscribe(subscriber); + + inOrder.verify(subscriber, never()).onNext("two"); + inOrder.verify(subscriber, never()).onNext("three"); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testSkipLast2() { - Flowable<String> observable = Flowable.fromIterable(Arrays.asList("one", "two")).skipLast(2); + Flowable<String> flowable = Flowable.fromIterable(Arrays.asList("one", "two")).skipLast(2); + + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); - verify(observer, never()).onNext(any(String.class)); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onNext(any(String.class)); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testSkipLastWithZeroCount() { Flowable<String> w = Flowable.just("one", "two"); - Flowable<String> observable = w.skipLast(0); - - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Flowable<String> flowable = w.skipLast(0); + + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); + + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @Ignore("Null values not allowed") public void testSkipLastWithNull() { - Flowable<String> observable = Flowable.fromIterable(Arrays.asList("one", null, "two")).skipLast(1); - - Subscriber<String> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext(null); - verify(observer, never()).onNext("two"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Flowable<String> flowable = Flowable.fromIterable(Arrays.asList("one", null, "two")).skipLast(1); + + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); + + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext(null); + verify(subscriber, never()).onNext("two"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testSkipLastWithBackpressure() { - Flowable<Integer> o = Flowable.range(0, Flowable.bufferSize() * 2).skipLast(Flowable.bufferSize() + 10); + Flowable<Integer> f = Flowable.range(0, Flowable.bufferSize() * 2).skipLast(Flowable.bufferSize() + 10); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); - o.observeOn(Schedulers.computation()).subscribe(ts); + f.observeOn(Schedulers.computation()).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); assertEquals((Flowable.bufferSize()) - 10, ts.valueCount()); @@ -126,9 +131,9 @@ public void error() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) + public Flowable<Object> apply(Flowable<Object> f) throws Exception { - return o.skipLast(1); + return f.skipLast(1); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java index f82e172f23..d24a84b4b6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java @@ -40,9 +40,9 @@ public void testSkipLastTimed() { // FIXME the timeunit now matters due to rounding Flowable<Integer> result = source.skipLast(1000, TimeUnit.MILLISECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -57,17 +57,17 @@ public void testSkipLastTimed() { scheduler.advanceTimeBy(950, TimeUnit.MILLISECONDS); source.onComplete(); - InOrder inOrder = inOrder(o); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onNext(3); - inOrder.verify(o, never()).onNext(4); - inOrder.verify(o, never()).onNext(5); - inOrder.verify(o, never()).onNext(6); - inOrder.verify(o).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(3); + inOrder.verify(subscriber, never()).onNext(4); + inOrder.verify(subscriber, never()).onNext(5); + inOrder.verify(subscriber, never()).onNext(6); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -78,9 +78,9 @@ public void testSkipLastTimedErrorBeforeTime() { Flowable<Integer> result = source.skipLast(1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -89,10 +89,10 @@ public void testSkipLastTimedErrorBeforeTime() { scheduler.advanceTimeBy(1050, TimeUnit.MILLISECONDS); - verify(o).onError(any(TestException.class)); + verify(subscriber).onError(any(TestException.class)); - verify(o, never()).onComplete(); - verify(o, never()).onNext(any()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any()); } @Test @@ -103,9 +103,9 @@ public void testSkipLastTimedCompleteBeforeTime() { Flowable<Integer> result = source.skipLast(1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -115,12 +115,12 @@ public void testSkipLastTimedCompleteBeforeTime() { source.onComplete(); - InOrder inOrder = inOrder(o); - inOrder.verify(o).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(any()); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -131,9 +131,9 @@ public void testSkipLastTimedWhenAllElementsAreValid() { Flowable<Integer> result = source.skipLast(1, TimeUnit.MILLISECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -143,11 +143,11 @@ public void testSkipLastTimedWhenAllElementsAreValid() { source.onComplete(); - InOrder inOrder = inOrder(o); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onNext(3); - inOrder.verify(o).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(3); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -187,8 +187,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.skipLast(1, TimeUnit.DAYS); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.skipLast(1, TimeUnit.DAYS); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java index 7597e23f69..25d902310b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java @@ -34,13 +34,13 @@ public void testSkipNegativeElements() { Flowable<String> skip = Flowable.just("one", "two", "three").skip(-99); - Subscriber<String> observer = TestHelper.mockSubscriber(); - skip.subscribe(observer); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + skip.subscribe(subscriber); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -48,13 +48,13 @@ public void testSkipZeroElements() { Flowable<String> skip = Flowable.just("one", "two", "three").skip(0); - Subscriber<String> observer = TestHelper.mockSubscriber(); - skip.subscribe(observer); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + skip.subscribe(subscriber); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -62,13 +62,13 @@ public void testSkipOneElement() { Flowable<String> skip = Flowable.just("one", "two", "three").skip(1); - Subscriber<String> observer = TestHelper.mockSubscriber(); - skip.subscribe(observer); - verify(observer, never()).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + skip.subscribe(subscriber); + verify(subscriber, never()).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -76,13 +76,13 @@ public void testSkipTwoElements() { Flowable<String> skip = Flowable.just("one", "two", "three").skip(2); - Subscriber<String> observer = TestHelper.mockSubscriber(); - skip.subscribe(observer); - verify(observer, never()).onNext("one"); - verify(observer, never()).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + skip.subscribe(subscriber); + verify(subscriber, never()).onNext("one"); + verify(subscriber, never()).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -91,11 +91,11 @@ public void testSkipEmptyStream() { Flowable<String> w = Flowable.empty(); Flowable<String> skip = w.skip(1); - Subscriber<String> observer = TestHelper.mockSubscriber(); - skip.subscribe(observer); - verify(observer, never()).onNext(any(String.class)); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + skip.subscribe(subscriber); + verify(subscriber, never()).onNext(any(String.class)); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -104,19 +104,19 @@ public void testSkipMultipleObservers() { Flowable<String> skip = Flowable.just("one", "two", "three") .skip(2); - Subscriber<String> observer1 = TestHelper.mockSubscriber(); - skip.subscribe(observer1); + Subscriber<String> subscriber1 = TestHelper.mockSubscriber(); + skip.subscribe(subscriber1); - Subscriber<String> observer2 = TestHelper.mockSubscriber(); - skip.subscribe(observer2); + Subscriber<String> subscriber2 = TestHelper.mockSubscriber(); + skip.subscribe(subscriber2); - verify(observer1, times(1)).onNext(any(String.class)); - verify(observer1, never()).onError(any(Throwable.class)); - verify(observer1, times(1)).onComplete(); + verify(subscriber1, times(1)).onNext(any(String.class)); + verify(subscriber1, never()).onError(any(Throwable.class)); + verify(subscriber1, times(1)).onComplete(); - verify(observer2, times(1)).onNext(any(String.class)); - verify(observer2, never()).onError(any(Throwable.class)); - verify(observer2, times(1)).onComplete(); + verify(subscriber2, times(1)).onNext(any(String.class)); + verify(subscriber2, never()).onError(any(Throwable.class)); + verify(subscriber2, times(1)).onComplete(); } @Test @@ -129,12 +129,12 @@ public void testSkipError() { Flowable<String> skip = Flowable.concat(ok, error).skip(100); - Subscriber<String> observer = TestHelper.mockSubscriber(); - skip.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + skip.subscribe(subscriber); - verify(observer, never()).onNext(any(String.class)); - verify(observer, times(1)).onError(e); - verify(observer, never()).onComplete(); + verify(subscriber, never()).onNext(any(String.class)); + verify(subscriber, times(1)).onError(e); + verify(subscriber, never()).onComplete(); } @@ -179,9 +179,9 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) + public Flowable<Object> apply(Flowable<Object> f) throws Exception { - return o.skip(1); + return f.skip(1); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTimedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTimedTest.java index 1869d74e66..0033cb4559 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTimedTest.java @@ -36,9 +36,9 @@ public void testSkipTimed() { Flowable<Integer> result = source.skip(1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -52,17 +52,17 @@ public void testSkipTimed() { source.onComplete(); - InOrder inOrder = inOrder(o); + InOrder inOrder = inOrder(subscriber); - inOrder.verify(o, never()).onNext(1); - inOrder.verify(o, never()).onNext(2); - inOrder.verify(o, never()).onNext(3); - inOrder.verify(o).onNext(4); - inOrder.verify(o).onNext(5); - inOrder.verify(o).onNext(6); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber, never()).onNext(1); + inOrder.verify(subscriber, never()).onNext(2); + inOrder.verify(subscriber, never()).onNext(3); + inOrder.verify(subscriber).onNext(4); + inOrder.verify(subscriber).onNext(5); + inOrder.verify(subscriber).onNext(6); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -73,9 +73,9 @@ public void testSkipTimedFinishBeforeTime() { Flowable<Integer> result = source.skip(1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -84,12 +84,12 @@ public void testSkipTimedFinishBeforeTime() { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - InOrder inOrder = inOrder(o); + InOrder inOrder = inOrder(subscriber); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(any()); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -100,9 +100,9 @@ public void testSkipTimedErrorBeforeTime() { Flowable<Integer> result = source.skip(1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -111,12 +111,12 @@ public void testSkipTimedErrorBeforeTime() { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - InOrder inOrder = inOrder(o); + InOrder inOrder = inOrder(subscriber); - inOrder.verify(o).onError(any(TestException.class)); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -127,9 +127,9 @@ public void testSkipTimedErrorAfterTime() { Flowable<Integer> result = source.skip(1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -143,17 +143,17 @@ public void testSkipTimedErrorAfterTime() { source.onError(new TestException()); - InOrder inOrder = inOrder(o); + InOrder inOrder = inOrder(subscriber); - inOrder.verify(o, never()).onNext(1); - inOrder.verify(o, never()).onNext(2); - inOrder.verify(o, never()).onNext(3); - inOrder.verify(o).onNext(4); - inOrder.verify(o).onNext(5); - inOrder.verify(o).onNext(6); - inOrder.verify(o).onError(any(TestException.class)); + inOrder.verify(subscriber, never()).onNext(1); + inOrder.verify(subscriber, never()).onNext(2); + inOrder.verify(subscriber, never()).onNext(3); + inOrder.verify(subscriber).onNext(4); + inOrder.verify(subscriber).onNext(5); + inOrder.verify(subscriber).onNext(6); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onComplete(); + verify(subscriber, never()).onComplete(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipUntilTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipUntilTest.java index 00386c8a7f..a770b8520b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipUntilTest.java @@ -23,11 +23,11 @@ import io.reactivex.processors.PublishProcessor; public class FlowableSkipUntilTest { - Subscriber<Object> observer; + Subscriber<Object> subscriber; @Before public void before() { - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); } @Test @@ -36,7 +36,7 @@ public void normal1() { PublishProcessor<Integer> other = PublishProcessor.create(); Flowable<Integer> m = source.skipUntil(other); - m.subscribe(observer); + m.subscribe(subscriber); source.onNext(0); source.onNext(1); @@ -48,11 +48,11 @@ public void normal1() { source.onNext(4); source.onComplete(); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onNext(2); - verify(observer, times(1)).onNext(3); - verify(observer, times(1)).onNext(4); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onNext(2); + verify(subscriber, times(1)).onNext(3); + verify(subscriber, times(1)).onNext(4); + verify(subscriber, times(1)).onComplete(); } @Test @@ -61,7 +61,7 @@ public void otherNeverFires() { Flowable<Integer> m = source.skipUntil(Flowable.never()); - m.subscribe(observer); + m.subscribe(subscriber); source.onNext(0); source.onNext(1); @@ -70,9 +70,9 @@ public void otherNeverFires() { source.onNext(4); source.onComplete(); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onNext(any()); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, times(1)).onComplete(); } @Test @@ -81,11 +81,11 @@ public void otherEmpty() { Flowable<Integer> m = source.skipUntil(Flowable.empty()); - m.subscribe(observer); + m.subscribe(subscriber); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onNext(any()); - verify(observer, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -94,7 +94,7 @@ public void otherFiresAndCompletes() { PublishProcessor<Integer> other = PublishProcessor.create(); Flowable<Integer> m = source.skipUntil(other); - m.subscribe(observer); + m.subscribe(subscriber); source.onNext(0); source.onNext(1); @@ -107,11 +107,11 @@ public void otherFiresAndCompletes() { source.onNext(4); source.onComplete(); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onNext(2); - verify(observer, times(1)).onNext(3); - verify(observer, times(1)).onNext(4); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onNext(2); + verify(subscriber, times(1)).onNext(3); + verify(subscriber, times(1)).onNext(4); + verify(subscriber, times(1)).onComplete(); } @Test @@ -120,7 +120,7 @@ public void sourceThrows() { PublishProcessor<Integer> other = PublishProcessor.create(); Flowable<Integer> m = source.skipUntil(other); - m.subscribe(observer); + m.subscribe(subscriber); source.onNext(0); source.onNext(1); @@ -131,9 +131,9 @@ public void sourceThrows() { source.onNext(2); source.onError(new RuntimeException("Forced failure")); - verify(observer, times(1)).onNext(2); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); + verify(subscriber, times(1)).onNext(2); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); } @Test @@ -142,16 +142,16 @@ public void otherThrowsImmediately() { PublishProcessor<Integer> other = PublishProcessor.create(); Flowable<Integer> m = source.skipUntil(other); - m.subscribe(observer); + m.subscribe(subscriber); source.onNext(0); source.onNext(1); other.onError(new RuntimeException("Forced failure")); - verify(observer, never()).onNext(any()); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); } @Test @@ -163,15 +163,15 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.skipUntil(Flowable.never()); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.skipUntil(Flowable.never()); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return Flowable.never().skipUntil(o); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return Flowable.never().skipUntil(f); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipWhileTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipWhileTest.java index d098675349..b9574cd8ef 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipWhileTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipWhileTest.java @@ -121,16 +121,16 @@ public void testSkipManySubscribers() { Flowable<Integer> src = Flowable.range(1, 10).skipWhile(LESS_THAN_FIVE); int n = 5; for (int i = 0; i < n; i++) { - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - src.subscribe(o); + src.subscribe(subscriber); for (int j = 5; j < 10; j++) { - inOrder.verify(o).onNext(j); + inOrder.verify(subscriber).onNext(j); } - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } } @@ -143,8 +143,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.skipWhile(Functions.alwaysFalse()); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.skipWhile(Functions.alwaysFalse()); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOnTest.java index 0214825887..6b1b24b78e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOnTest.java @@ -40,7 +40,7 @@ public void testIssue813() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch doneLatch = new CountDownLatch(1); - TestSubscriber<Integer> observer = new TestSubscriber<Integer>(); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Flowable .unsafeCreate(new Publisher<Integer>() { @@ -64,16 +64,16 @@ public void subscribe( doneLatch.countDown(); } } - }).subscribeOn(Schedulers.computation()).subscribe(observer); + }).subscribeOn(Schedulers.computation()).subscribe(ts); // wait for scheduling scheduled.await(); // trigger unsubscribe - observer.dispose(); + ts.dispose(); latch.countDown(); doneLatch.await(); - observer.assertNoErrors(); - observer.assertComplete(); + ts.assertNoErrors(); + ts.assertComplete(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java index 1607a4b524..6c7cc67603 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java @@ -35,7 +35,7 @@ public class FlowableSwitchIfEmptyTest { @Test public void testSwitchWhenNotEmpty() throws Exception { final AtomicBoolean subscribed = new AtomicBoolean(false); - final Flowable<Integer> observable = Flowable.just(4) + final Flowable<Integer> flowable = Flowable.just(4) .switchIfEmpty(Flowable.just(2) .doOnSubscribe(new Consumer<Subscription>() { @Override @@ -44,16 +44,16 @@ public void accept(Subscription s) { } })); - assertEquals(4, observable.blockingSingle().intValue()); + assertEquals(4, flowable.blockingSingle().intValue()); assertFalse(subscribed.get()); } @Test public void testSwitchWhenEmpty() throws Exception { - final Flowable<Integer> observable = Flowable.<Integer>empty() + final Flowable<Integer> flowable = Flowable.<Integer>empty() .switchIfEmpty(Flowable.fromIterable(Arrays.asList(42))); - assertEquals(42, observable.blockingSingle().intValue()); + assertEquals(42, flowable.blockingSingle().intValue()); } @Test @@ -80,8 +80,8 @@ public void cancel() { } }); - final Flowable<Long> observable = Flowable.<Long>empty().switchIfEmpty(withProducer); - assertEquals(42, observable.blockingSingle().intValue()); + final Flowable<Long> flowable = Flowable.<Long>empty().switchIfEmpty(withProducer); + assertEquals(42, flowable.blockingSingle().intValue()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java index 28f599e487..1878d133a4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java @@ -40,290 +40,290 @@ public class FlowableSwitchTest { private TestScheduler scheduler; private Scheduler.Worker innerScheduler; - private Subscriber<String> observer; + private Subscriber<String> subscriber; @Before public void before() { scheduler = new TestScheduler(); innerScheduler = scheduler.createWorker(); - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); } @Test public void testSwitchWhenOuterCompleteBeforeInner() { Flowable<Flowable<String>> source = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 50, Flowable.unsafeCreate(new Publisher<String>() { + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 50, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 70, "one"); - publishNext(observer, 100, "two"); - publishCompleted(observer, 200); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 70, "one"); + publishNext(subscriber, 100, "two"); + publishCompleted(subscriber, 200); } })); - publishCompleted(observer, 60); + publishCompleted(subscriber, 60); } }); Flowable<String> sampled = Flowable.switchOnNext(source); - sampled.subscribe(observer); + sampled.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(350, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(2)).onNext(anyString()); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(2)).onNext(anyString()); + inOrder.verify(subscriber, times(1)).onComplete(); } @Test public void testSwitchWhenInnerCompleteBeforeOuter() { Flowable<Flowable<String>> source = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 10, Flowable.unsafeCreate(new Publisher<String>() { + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 10, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 0, "one"); - publishNext(observer, 10, "two"); - publishCompleted(observer, 20); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 0, "one"); + publishNext(subscriber, 10, "two"); + publishCompleted(subscriber, 20); } })); - publishNext(observer, 100, Flowable.unsafeCreate(new Publisher<String>() { + publishNext(subscriber, 100, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 0, "three"); - publishNext(observer, 10, "four"); - publishCompleted(observer, 20); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 0, "three"); + publishNext(subscriber, 10, "four"); + publishCompleted(subscriber, 20); } })); - publishCompleted(observer, 200); + publishCompleted(subscriber, 200); } }); Flowable<String> sampled = Flowable.switchOnNext(source); - sampled.subscribe(observer); + sampled.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(150, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onComplete(); - inOrder.verify(observer, times(1)).onNext("one"); - inOrder.verify(observer, times(1)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - inOrder.verify(observer, times(1)).onNext("four"); + inOrder.verify(subscriber, never()).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("one"); + inOrder.verify(subscriber, times(1)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + inOrder.verify(subscriber, times(1)).onNext("four"); scheduler.advanceTimeTo(250, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyString()); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, never()).onNext(anyString()); + inOrder.verify(subscriber, times(1)).onComplete(); } @Test public void testSwitchWithComplete() { Flowable<Flowable<String>> source = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 50, Flowable.unsafeCreate(new Publisher<String>() { + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 50, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 60, "one"); - publishNext(observer, 100, "two"); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 60, "one"); + publishNext(subscriber, 100, "two"); } })); - publishNext(observer, 200, Flowable.unsafeCreate(new Publisher<String>() { + publishNext(subscriber, 200, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 0, "three"); - publishNext(observer, 100, "four"); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 0, "three"); + publishNext(subscriber, 100, "four"); } })); - publishCompleted(observer, 250); + publishCompleted(subscriber, 250); } }); Flowable<String> sampled = Flowable.switchOnNext(source); - sampled.subscribe(observer); + sampled.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(90, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyString()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(anyString()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(125, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("one"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(175, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("two"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("two"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(225, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("three"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(350, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("four"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("four"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testSwitchWithError() { Flowable<Flowable<String>> source = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 50, Flowable.unsafeCreate(new Publisher<String>() { + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 50, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 50, "one"); - publishNext(observer, 100, "two"); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 50, "one"); + publishNext(subscriber, 100, "two"); } })); - publishNext(observer, 200, Flowable.unsafeCreate(new Publisher<String>() { + publishNext(subscriber, 200, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 0, "three"); - publishNext(observer, 100, "four"); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 0, "three"); + publishNext(subscriber, 100, "four"); } })); - publishError(observer, 250, new TestException()); + publishError(subscriber, 250, new TestException()); } }); Flowable<String> sampled = Flowable.switchOnNext(source); - sampled.subscribe(observer); + sampled.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(90, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyString()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(anyString()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(125, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("one"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(175, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("two"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("two"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(225, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("three"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(350, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyString()); - verify(observer, never()).onComplete(); - verify(observer, times(1)).onError(any(TestException.class)); + inOrder.verify(subscriber, never()).onNext(anyString()); + verify(subscriber, never()).onComplete(); + verify(subscriber, times(1)).onError(any(TestException.class)); } @Test public void testSwitchWithSubsequenceComplete() { Flowable<Flowable<String>> source = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 50, Flowable.unsafeCreate(new Publisher<String>() { + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 50, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 50, "one"); - publishNext(observer, 100, "two"); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 50, "one"); + publishNext(subscriber, 100, "two"); } })); - publishNext(observer, 130, Flowable.unsafeCreate(new Publisher<String>() { + publishNext(subscriber, 130, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishCompleted(observer, 0); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishCompleted(subscriber, 0); } })); - publishNext(observer, 150, Flowable.unsafeCreate(new Publisher<String>() { + publishNext(subscriber, 150, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 50, "three"); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 50, "three"); } })); } }); Flowable<String> sampled = Flowable.switchOnNext(source); - sampled.subscribe(observer); + sampled.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(90, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyString()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(anyString()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(125, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("one"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(250, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("three"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testSwitchWithSubsequenceError() { Flowable<Flowable<String>> source = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 50, Flowable.unsafeCreate(new Publisher<String>() { + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 50, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 50, "one"); - publishNext(observer, 100, "two"); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 50, "one"); + publishNext(subscriber, 100, "two"); } })); - publishNext(observer, 130, Flowable.unsafeCreate(new Publisher<String>() { + publishNext(subscriber, 130, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishError(observer, 0, new TestException()); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishError(subscriber, 0, new TestException()); } })); - publishNext(observer, 150, Flowable.unsafeCreate(new Publisher<String>() { + publishNext(subscriber, 150, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 50, "three"); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 50, "three"); } })); @@ -331,49 +331,49 @@ public void subscribe(Subscriber<? super String> observer) { }); Flowable<String> sampled = Flowable.switchOnNext(source); - sampled.subscribe(observer); + sampled.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(90, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext(anyString()); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onNext(anyString()); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(125, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("one"); - verify(observer, never()).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); scheduler.advanceTimeTo(250, TimeUnit.MILLISECONDS); - inOrder.verify(observer, never()).onNext("three"); - verify(observer, never()).onComplete(); - verify(observer, times(1)).onError(any(TestException.class)); + inOrder.verify(subscriber, never()).onNext("three"); + verify(subscriber, never()).onComplete(); + verify(subscriber, times(1)).onError(any(TestException.class)); } - private <T> void publishCompleted(final Subscriber<T> observer, long delay) { + private <T> void publishCompleted(final Subscriber<T> subscriber, long delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onComplete(); + subscriber.onComplete(); } }, delay, TimeUnit.MILLISECONDS); } - private <T> void publishError(final Subscriber<T> observer, long delay, final Throwable error) { + private <T> void publishError(final Subscriber<T> subscriber, long delay, final Throwable error) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onError(error); + subscriber.onError(error); } }, delay, TimeUnit.MILLISECONDS); } - private <T> void publishNext(final Subscriber<T> observer, long delay, final T value) { + private <T> void publishNext(final Subscriber<T> subscriber, long delay, final T value) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onNext(value); + subscriber.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } @@ -383,45 +383,45 @@ public void testSwitchIssue737() { // https://github.com/ReactiveX/RxJava/issues/737 Flowable<Flowable<String>> source = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override - public void subscribe(Subscriber<? super Flowable<String>> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 0, Flowable.unsafeCreate(new Publisher<String>() { + public void subscribe(Subscriber<? super Flowable<String>> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 0, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 10, "1-one"); - publishNext(observer, 20, "1-two"); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 10, "1-one"); + publishNext(subscriber, 20, "1-two"); // The following events will be ignored - publishNext(observer, 30, "1-three"); - publishCompleted(observer, 40); + publishNext(subscriber, 30, "1-three"); + publishCompleted(subscriber, 40); } })); - publishNext(observer, 25, Flowable.unsafeCreate(new Publisher<String>() { + publishNext(subscriber, 25, Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 10, "2-one"); - publishNext(observer, 20, "2-two"); - publishNext(observer, 30, "2-three"); - publishCompleted(observer, 40); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 10, "2-one"); + publishNext(subscriber, 20, "2-two"); + publishNext(subscriber, 30, "2-three"); + publishCompleted(subscriber, 40); } })); - publishCompleted(observer, 30); + publishCompleted(subscriber, 30); } }); Flowable<String> sampled = Flowable.switchOnNext(source); - sampled.subscribe(observer); + sampled.subscribe(subscriber); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("1-one"); - inOrder.verify(observer, times(1)).onNext("1-two"); - inOrder.verify(observer, times(1)).onNext("2-one"); - inOrder.verify(observer, times(1)).onNext("2-two"); - inOrder.verify(observer, times(1)).onNext("2-three"); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("1-one"); + inOrder.verify(subscriber, times(1)).onNext("1-two"); + inOrder.verify(subscriber, times(1)).onNext("2-one"); + inOrder.verify(subscriber, times(1)).onNext("2-two"); + inOrder.verify(subscriber, times(1)).onNext("2-three"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -965,11 +965,11 @@ public void badMainSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onComplete(); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .switchMap(Functions.justFunction(Flowable.never())) @@ -1005,12 +1005,12 @@ public void badInnerSource() { Flowable.just(1).hide() .switchMap(Functions.justFunction(new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onError(new TestException()); - observer.onComplete(); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onError(new TestException()); + subscriber.onComplete(); + subscriber.onError(new TestException()); + subscriber.onComplete(); } })) .test() diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOneTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOneTest.java index 2d31e46223..5da9f37c50 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOneTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOneTest.java @@ -118,7 +118,9 @@ public void requestMore(long n) { @Override public void onStart() { - request(initialRequest); + if (initialRequest > 0) { + request(initialRequest); + } } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java index 9ae4bfd380..3277d5f831 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java @@ -37,11 +37,12 @@ public void testTakeLastEmpty() { Flowable<String> w = Flowable.empty(); Flowable<String> take = w.takeLast(2); - Subscriber<String> observer = TestHelper.mockSubscriber(); - take.subscribe(observer); - verify(observer, never()).onNext(any(String.class)); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + take.subscribe(subscriber); + + verify(subscriber, never()).onNext(any(String.class)); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -49,14 +50,15 @@ public void testTakeLast1() { Flowable<String> w = Flowable.just("one", "two", "three"); Flowable<String> take = w.takeLast(2); - Subscriber<String> observer = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(observer); - take.subscribe(observer); - inOrder.verify(observer, times(1)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - verify(observer, never()).onNext("one"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); + take.subscribe(subscriber); + + inOrder.verify(subscriber, times(1)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onNext("one"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -64,11 +66,12 @@ public void testTakeLast2() { Flowable<String> w = Flowable.just("one"); Flowable<String> take = w.takeLast(10); - Subscriber<String> observer = TestHelper.mockSubscriber(); - take.subscribe(observer); - verify(observer, times(1)).onNext("one"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + take.subscribe(subscriber); + + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -76,11 +79,12 @@ public void testTakeLastWithZeroCount() { Flowable<String> w = Flowable.just("one"); Flowable<String> take = w.takeLast(0); - Subscriber<String> observer = TestHelper.mockSubscriber(); - take.subscribe(observer); - verify(observer, never()).onNext("one"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + take.subscribe(subscriber); + + verify(subscriber, never()).onNext("one"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -89,13 +93,14 @@ public void testTakeLastWithNull() { Flowable<String> w = Flowable.just("one", null, "three"); Flowable<String> take = w.takeLast(2); - Subscriber<String> observer = TestHelper.mockSubscriber(); - take.subscribe(observer); - verify(observer, never()).onNext("one"); - verify(observer, times(1)).onNext(null); - verify(observer, times(1)).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + take.subscribe(subscriber); + + verify(subscriber, never()).onNext("one"); + verify(subscriber, times(1)).onNext(null); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test(expected = IndexOutOfBoundsException.class) @@ -328,8 +333,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.takeLast(5); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.takeLast(5); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java index a0bce236de..4864cac7f6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java @@ -44,11 +44,11 @@ public void takeLastTimed() { // FIXME time unit now matters! Flowable<Object> result = source.takeLast(1000, TimeUnit.MILLISECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); // T: 0ms scheduler.advanceTimeBy(250, TimeUnit.MILLISECONDS); @@ -62,13 +62,13 @@ public void takeLastTimed() { scheduler.advanceTimeBy(250, TimeUnit.MILLISECONDS); source.onComplete(); // T: 1250ms - inOrder.verify(o, times(1)).onNext(2); - inOrder.verify(o, times(1)).onNext(3); - inOrder.verify(o, times(1)).onNext(4); - inOrder.verify(o, times(1)).onNext(5); - inOrder.verify(o, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onNext(3); + inOrder.verify(subscriber, times(1)).onNext(4); + inOrder.verify(subscriber, times(1)).onNext(5); + inOrder.verify(subscriber, times(1)).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -80,11 +80,11 @@ public void takeLastTimedDelayCompletion() { // FIXME time unit now matters Flowable<Object> result = source.takeLast(1000, TimeUnit.MILLISECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); // T: 0ms scheduler.advanceTimeBy(250, TimeUnit.MILLISECONDS); @@ -98,10 +98,10 @@ public void takeLastTimedDelayCompletion() { scheduler.advanceTimeBy(1250, TimeUnit.MILLISECONDS); source.onComplete(); // T: 2250ms - inOrder.verify(o, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); - verify(o, never()).onNext(any()); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -113,11 +113,11 @@ public void takeLastTimedWithCapacity() { // FIXME time unit now matters! Flowable<Object> result = source.takeLast(2, 1000, TimeUnit.MILLISECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); // T: 0ms scheduler.advanceTimeBy(250, TimeUnit.MILLISECONDS); @@ -131,11 +131,11 @@ public void takeLastTimedWithCapacity() { scheduler.advanceTimeBy(250, TimeUnit.MILLISECONDS); source.onComplete(); // T: 1250ms - inOrder.verify(o, times(1)).onNext(4); - inOrder.verify(o, times(1)).onNext(5); - inOrder.verify(o, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext(4); + inOrder.verify(subscriber, times(1)).onNext(5); + inOrder.verify(subscriber, times(1)).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -146,11 +146,11 @@ public void takeLastTimedThrowingSource() { Flowable<Object> result = source.takeLast(1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); // T: 0ms scheduler.advanceTimeBy(250, TimeUnit.MILLISECONDS); @@ -164,10 +164,10 @@ public void takeLastTimedThrowingSource() { scheduler.advanceTimeBy(250, TimeUnit.MILLISECONDS); source.onError(new TestException()); // T: 1250ms - inOrder.verify(o, times(1)).onError(any(TestException.class)); + inOrder.verify(subscriber, times(1)).onError(any(TestException.class)); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @Test @@ -178,11 +178,11 @@ public void takeLastTimedWithZeroCapacity() { Flowable<Object> result = source.takeLast(0, 1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + InOrder inOrder = inOrder(subscriber); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); // T: 0ms scheduler.advanceTimeBy(250, TimeUnit.MILLISECONDS); @@ -196,10 +196,10 @@ public void takeLastTimedWithZeroCapacity() { scheduler.advanceTimeBy(250, TimeUnit.MILLISECONDS); source.onComplete(); // T: 1250ms - inOrder.verify(o, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); - verify(o, never()).onNext(any()); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java index 345282bfbd..5510b534ea 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java @@ -41,13 +41,14 @@ public void testTake1() { Flowable<String> w = Flowable.fromIterable(Arrays.asList("one", "two", "three")); Flowable<String> take = w.take(2); - Subscriber<String> observer = TestHelper.mockSubscriber(); - take.subscribe(observer); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, never()).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + take.subscribe(subscriber); + + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, never()).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -55,13 +56,14 @@ public void testTake2() { Flowable<String> w = Flowable.fromIterable(Arrays.asList("one", "two", "three")); Flowable<String> take = w.take(1); - Subscriber<String> observer = TestHelper.mockSubscriber(); - take.subscribe(observer); - verify(observer, times(1)).onNext("one"); - verify(observer, never()).onNext("two"); - verify(observer, never()).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + take.subscribe(subscriber); + + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onNext("two"); + verify(subscriber, never()).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test(expected = IllegalArgumentException.class) @@ -85,10 +87,11 @@ public Integer apply(Integer t1) { } }); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - w.subscribe(observer); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onError(any(IllegalArgumentException.class)); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + w.subscribe(subscriber); + + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onError(any(IllegalArgumentException.class)); inOrder.verifyNoMoreInteractions(); } @@ -101,34 +104,42 @@ public Integer apply(Integer t1) { } }); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - w.subscribe(observer); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onError(any(IllegalArgumentException.class)); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + w.subscribe(subscriber); + + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onError(any(IllegalArgumentException.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testTakeDoesntLeakErrors() { - Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { - @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext("one"); - observer.onError(new Throwable("test failed")); - } - }); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { + @Override + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext("one"); + subscriber.onError(new Throwable("test failed")); + } + }); + + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Subscriber<String> observer = TestHelper.mockSubscriber(); + source.take(1).subscribe(subscriber); - source.take(1).subscribe(observer); + verify(subscriber).onSubscribe((Subscription)notNull()); + verify(subscriber, times(1)).onNext("one"); + // even though onError is called we take(1) so shouldn't see it + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verifyNoMoreInteractions(subscriber); - verify(observer).onSubscribe((Subscription)notNull()); - verify(observer, times(1)).onNext("one"); - // even though onError is called we take(1) so shouldn't see it - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verifyNoMoreInteractions(observer); + TestHelper.assertUndeliverable(errors, 0, Throwable.class, "test failed"); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -138,24 +149,25 @@ public void testTakeZeroDoesntLeakError() { final BooleanSubscription bs = new BooleanSubscription(); Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { + public void subscribe(Subscriber<? super String> subscriber) { subscribed.set(true); - observer.onSubscribe(bs); - observer.onError(new Throwable("test failed")); + subscriber.onSubscribe(bs); + subscriber.onError(new Throwable("test failed")); } }); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + + source.take(0).subscribe(subscriber); - source.take(0).subscribe(observer); assertTrue("source subscribed", subscribed.get()); assertTrue("source unsubscribed", bs.isCancelled()); - verify(observer, never()).onNext(anyString()); + verify(subscriber, never()).onNext(anyString()); // even though onError is called we take(0) so shouldn't see it - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verifyNoMoreInteractions(observer); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verifyNoMoreInteractions(subscriber); } @Test @@ -163,10 +175,10 @@ public void testUnsubscribeAfterTake() { TestFlowableFunc f = new TestFlowableFunc("one", "two", "three"); Flowable<String> w = Flowable.unsafeCreate(f); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> take = w.take(1); - take.subscribe(observer); + take.subscribe(subscriber); // wait for the Flowable to complete try { @@ -177,14 +189,14 @@ public void testUnsubscribeAfterTake() { } System.out.println("TestFlowable thread finished"); - verify(observer).onSubscribe((Subscription)notNull()); - verify(observer, times(1)).onNext("one"); - verify(observer, never()).onNext("two"); - verify(observer, never()).onNext("three"); - verify(observer, times(1)).onComplete(); + verify(subscriber).onSubscribe((Subscription)notNull()); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onNext("two"); + verify(subscriber, never()).onNext("three"); + verify(subscriber, times(1)).onComplete(); // FIXME no longer assertable // verify(s, times(1)).unsubscribe(); - verifyNoMoreInteractions(observer); + verifyNoMoreInteractions(subscriber); } @Test(timeout = 2000) @@ -240,8 +252,8 @@ static class TestFlowableFunc implements Publisher<String> { } @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); System.out.println("TestFlowable subscribed to ..."); t = new Thread(new Runnable() { @@ -251,9 +263,9 @@ public void run() { System.out.println("running TestFlowable thread"); for (String s : values) { System.out.println("TestFlowable onNext: " + s); - observer.onNext(s); + subscriber.onNext(s); } - observer.onComplete(); + subscriber.onComplete(); } catch (Throwable e) { throw new RuntimeException(e); } @@ -283,18 +295,18 @@ public void subscribe(Subscriber<? super Long> op) { @Test(timeout = 2000) public void testTakeObserveOn() { - Subscriber<Object> o = TestHelper.mockSubscriber(); - TestSubscriber<Object> ts = new TestSubscriber<Object>(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<Object> ts = new TestSubscriber<Object>(subscriber); INFINITE_OBSERVABLE.onBackpressureDrop() .observeOn(Schedulers.newThread()).take(1).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); - verify(o).onNext(1L); - verify(o, never()).onNext(2L); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(1L); + verify(subscriber, never()).onNext(2L); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -467,8 +479,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.take(2); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.take(2); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTimedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTimedTest.java index cc04d04b6b..db1132e86c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTimedTest.java @@ -36,9 +36,9 @@ public void testTakeTimed() { Flowable<Integer> result = source.take(1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -48,15 +48,15 @@ public void testTakeTimed() { source.onNext(4); - InOrder inOrder = inOrder(o); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onNext(3); - inOrder.verify(o).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(3); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(4); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(4); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -67,9 +67,9 @@ public void testTakeTimedErrorBeforeTime() { Flowable<Integer> result = source.take(1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -80,15 +80,15 @@ public void testTakeTimedErrorBeforeTime() { source.onNext(4); - InOrder inOrder = inOrder(o); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onNext(3); - inOrder.verify(o).onError(any(TestException.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(3); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onComplete(); - verify(o, never()).onNext(4); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(4); } @Test @@ -99,9 +99,9 @@ public void testTakeTimedErrorAfterTime() { Flowable<Integer> result = source.take(1, TimeUnit.SECONDS, scheduler); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -112,15 +112,15 @@ public void testTakeTimedErrorAfterTime() { source.onNext(4); source.onError(new TestException()); - InOrder inOrder = inOrder(o); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onNext(3); - inOrder.verify(o).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(3); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onNext(4); - verify(o, never()).onError(any(TestException.class)); + verify(subscriber, never()).onNext(4); + verify(subscriber, never()).onError(any(TestException.class)); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java index 4060487c64..22e96421f0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java @@ -34,54 +34,54 @@ public class FlowableTakeUntilPredicateTest { @Test public void takeEmpty() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); Flowable.empty().takeUntil(new Predicate<Object>() { @Override public boolean test(Object v) { return true; } - }).subscribe(o); + }).subscribe(subscriber); - verify(o, never()).onNext(any()); - verify(o, never()).onError(any(Throwable.class)); - verify(o).onComplete(); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber).onComplete(); } @Test public void takeAll() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); Flowable.just(1, 2).takeUntil(new Predicate<Integer>() { @Override public boolean test(Integer v) { return false; } - }).subscribe(o); + }).subscribe(subscriber); - verify(o).onNext(1); - verify(o).onNext(2); - verify(o, never()).onError(any(Throwable.class)); - verify(o).onComplete(); + verify(subscriber).onNext(1); + verify(subscriber).onNext(2); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber).onComplete(); } @Test public void takeFirst() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); Flowable.just(1, 2).takeUntil(new Predicate<Integer>() { @Override public boolean test(Integer v) { return true; } - }).subscribe(o); + }).subscribe(subscriber); - verify(o).onNext(1); - verify(o, never()).onNext(2); - verify(o, never()).onError(any(Throwable.class)); - verify(o).onComplete(); + verify(subscriber).onNext(1); + verify(subscriber, never()).onNext(2); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber).onComplete(); } @Test public void takeSome() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); Flowable.just(1, 2, 3).takeUntil(new Predicate<Integer>() { @Override @@ -89,17 +89,17 @@ public boolean test(Integer t1) { return t1 == 2; } }) - .subscribe(o); + .subscribe(subscriber); - verify(o).onNext(1); - verify(o).onNext(2); - verify(o, never()).onNext(3); - verify(o, never()).onError(any(Throwable.class)); - verify(o).onComplete(); + verify(subscriber).onNext(1); + verify(subscriber).onNext(2); + verify(subscriber, never()).onNext(3); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber).onComplete(); } @Test public void functionThrows() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); Predicate<Integer> predicate = new Predicate<Integer>() { @Override @@ -107,17 +107,17 @@ public boolean test(Integer t1) { throw new TestException("Forced failure"); } }; - Flowable.just(1, 2, 3).takeUntil(predicate).subscribe(o); + Flowable.just(1, 2, 3).takeUntil(predicate).subscribe(subscriber); - verify(o).onNext(1); - verify(o, never()).onNext(2); - verify(o, never()).onNext(3); - verify(o).onError(any(TestException.class)); - verify(o, never()).onComplete(); + verify(subscriber).onNext(1); + verify(subscriber, never()).onNext(2); + verify(subscriber, never()).onNext(3); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); } @Test public void sourceThrows() { - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); Flowable.just(1) .concatWith(Flowable.<Integer>error(new TestException())) @@ -127,12 +127,12 @@ public void sourceThrows() { public boolean test(Integer v) { return false; } - }).subscribe(o); + }).subscribe(subscriber); - verify(o).onNext(1); - verify(o, never()).onNext(2); - verify(o).onError(any(TestException.class)); - verify(o, never()).onComplete(); + verify(subscriber).onNext(1); + verify(subscriber, never()).onNext(2); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); } @Test public void backpressure() { @@ -178,8 +178,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.takeUntil(Functions.alwaysFalse()); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.takeUntil(Functions.alwaysFalse()); } }); } @@ -190,12 +190,12 @@ public void badSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onComplete(); - observer.onNext(1); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); + subscriber.onNext(1); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .takeUntil(Functions.alwaysFalse()) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java index be7bc1621b..428eefa467 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java @@ -155,7 +155,7 @@ public void testTakeUntilOtherCompleted() { private static class TestObservable implements Publisher<String> { - Subscriber<? super String> observer; + Subscriber<? super String> subscriber; Subscription s; TestObservable(Subscription s) { @@ -164,23 +164,23 @@ private static class TestObservable implements Publisher<String> { /* used to simulate subscription */ public void sendOnCompleted() { - observer.onComplete(); + subscriber.onComplete(); } /* used to simulate subscription */ public void sendOnNext(String value) { - observer.onNext(value); + subscriber.onNext(value); } /* used to simulate subscription */ public void sendOnError(Throwable e) { - observer.onError(e); + subscriber.onError(e); } @Override - public void subscribe(Subscriber<? super String> observer) { - this.observer = observer; - observer.onSubscribe(s); + public void subscribe(Subscriber<? super String> subscriber) { + this.subscriber = subscriber; + subscriber.onSubscribe(s); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java index 4ad532f94f..f05b8e9fae 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java @@ -17,6 +17,8 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +import java.util.List; + import org.junit.*; import org.reactivestreams.*; @@ -25,6 +27,7 @@ import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.*; import io.reactivex.subscribers.TestSubscriber; @@ -40,13 +43,14 @@ public boolean test(Integer input) { } }); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - take.subscribe(observer); - verify(observer, times(1)).onNext(1); - verify(observer, times(1)).onNext(2); - verify(observer, never()).onNext(3); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + take.subscribe(subscriber); + + verify(subscriber, times(1)).onNext(1); + verify(subscriber, times(1)).onNext(2); + verify(subscriber, never()).onNext(3); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -59,8 +63,8 @@ public boolean test(Integer input) { } }); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); - take.subscribe(observer); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + take.subscribe(subscriber); s.onNext(1); s.onNext(2); @@ -69,13 +73,13 @@ public boolean test(Integer input) { s.onNext(5); s.onComplete(); - verify(observer, times(1)).onNext(1); - verify(observer, times(1)).onNext(2); - verify(observer, never()).onNext(3); - verify(observer, never()).onNext(4); - verify(observer, never()).onNext(5); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(1); + verify(subscriber, times(1)).onNext(2); + verify(subscriber, never()).onNext(3); + verify(subscriber, never()).onNext(4); + verify(subscriber, never()).onNext(5); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -90,32 +94,40 @@ public boolean test(String input) { } }); - Subscriber<String> observer = TestHelper.mockSubscriber(); - take.subscribe(observer); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, never()).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + take.subscribe(subscriber); + + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, never()).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testTakeWhileDoesntLeakErrors() { - Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { - @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext("one"); - observer.onError(new Throwable("test failed")); - } - }); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { + @Override + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext("one"); + subscriber.onError(new TestException("test failed")); + } + }); - source.takeWhile(new Predicate<String>() { - @Override - public boolean test(String s) { - return false; - } - }).blockingLast(""); + source.takeWhile(new Predicate<String>() { + @Override + public boolean test(String s) { + return false; + } + }).blockingLast(""); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "test failed"); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -123,7 +135,7 @@ public void testTakeWhileProtectsPredicateCall() { TestFlowable source = new TestFlowable(mock(Subscription.class), "one"); final RuntimeException testException = new RuntimeException("test exception"); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> take = Flowable.unsafeCreate(source) .takeWhile(new Predicate<String>() { @Override @@ -131,7 +143,7 @@ public boolean test(String s) { throw testException; } }); - take.subscribe(observer); + take.subscribe(subscriber); // wait for the Flowable to complete try { @@ -141,8 +153,8 @@ public boolean test(String s) { fail(e.getMessage()); } - verify(observer, never()).onNext(any(String.class)); - verify(observer, times(1)).onError(testException); + verify(subscriber, never()).onNext(any(String.class)); + verify(subscriber, times(1)).onError(testException); } @Test @@ -150,7 +162,7 @@ public void testUnsubscribeAfterTake() { Subscription s = mock(Subscription.class); TestFlowable w = new TestFlowable(s, "one", "two", "three"); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> take = Flowable.unsafeCreate(w) .takeWhile(new Predicate<String>() { int index; @@ -160,7 +172,7 @@ public boolean test(String s) { return index++ < 1; } }); - take.subscribe(observer); + take.subscribe(subscriber); // wait for the Flowable to complete try { @@ -171,9 +183,9 @@ public boolean test(String s) { } System.out.println("TestFlowable thread finished"); - verify(observer, times(1)).onNext("one"); - verify(observer, never()).onNext("two"); - verify(observer, never()).onNext("three"); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, never()).onNext("two"); + verify(subscriber, never()).onNext("three"); verify(s, times(1)).cancel(); } @@ -189,9 +201,9 @@ private static class TestFlowable implements Publisher<String> { } @Override - public void subscribe(final Subscriber<? super String> observer) { + public void subscribe(final Subscriber<? super String> subscriber) { System.out.println("TestFlowable subscribed to ..."); - observer.onSubscribe(s); + subscriber.onSubscribe(s); t = new Thread(new Runnable() { @Override @@ -200,9 +212,9 @@ public void run() { System.out.println("running TestFlowable thread"); for (String s : values) { System.out.println("TestFlowable onNext: " + s); - observer.onNext(s); + subscriber.onNext(s); } - observer.onComplete(); + subscriber.onComplete(); } catch (Throwable e) { throw new RuntimeException(e); } @@ -280,8 +292,8 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.takeWhile(Functions.alwaysTrue()); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.takeWhile(Functions.alwaysTrue()); } }); } @@ -290,10 +302,10 @@ public Flowable<Object> apply(Flowable<Object> o) throws Exception { public void badSource() { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onComplete(); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); + subscriber.onComplete(); } } .takeWhile(Functions.alwaysTrue()) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java index 278b98a53a..f9dc9c01f1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java @@ -34,40 +34,40 @@ public class FlowableThrottleFirstTest { private TestScheduler scheduler; private Scheduler.Worker innerScheduler; - private Subscriber<String> observer; + private Subscriber<String> subscriber; @Before public void before() { scheduler = new TestScheduler(); innerScheduler = scheduler.createWorker(); - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); } @Test public void testThrottlingWithCompleted() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - publishNext(observer, 100, "one"); // publish as it's first - publishNext(observer, 300, "two"); // skip as it's last within the first 400 - publishNext(observer, 900, "three"); // publish - publishNext(observer, 905, "four"); // skip - publishCompleted(observer, 1000); // Should be published as soon as the timeout expires. + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + publishNext(subscriber, 100, "one"); // publish as it's first + publishNext(subscriber, 300, "two"); // skip as it's last within the first 400 + publishNext(subscriber, 900, "three"); // publish + publishNext(subscriber, 905, "four"); // skip + publishCompleted(subscriber, 1000); // Should be published as soon as the timeout expires. } }); Flowable<String> sampled = source.throttleFirst(400, TimeUnit.MILLISECONDS, scheduler); - sampled.subscribe(observer); + sampled.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); - inOrder.verify(observer, times(1)).onNext("one"); - inOrder.verify(observer, times(0)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - inOrder.verify(observer, times(0)).onNext("four"); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("one"); + inOrder.verify(subscriber, times(0)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + inOrder.verify(subscriber, times(0)).onNext("four"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -75,59 +75,59 @@ public void subscribe(Subscriber<? super String> observer) { public void testThrottlingWithError() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); Exception error = new TestException(); - publishNext(observer, 100, "one"); // Should be published since it is first - publishNext(observer, 200, "two"); // Should be skipped since onError will arrive before the timeout expires - publishError(observer, 300, error); // Should be published as soon as the timeout expires. + publishNext(subscriber, 100, "one"); // Should be published since it is first + publishNext(subscriber, 200, "two"); // Should be skipped since onError will arrive before the timeout expires + publishError(subscriber, 300, error); // Should be published as soon as the timeout expires. } }); Flowable<String> sampled = source.throttleFirst(400, TimeUnit.MILLISECONDS, scheduler); - sampled.subscribe(observer); + sampled.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(400, TimeUnit.MILLISECONDS); - inOrder.verify(observer).onNext("one"); - inOrder.verify(observer).onError(any(TestException.class)); + inOrder.verify(subscriber).onNext("one"); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); } - private <T> void publishCompleted(final Subscriber<T> observer, long delay) { + private <T> void publishCompleted(final Subscriber<T> subscriber, long delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onComplete(); + subscriber.onComplete(); } }, delay, TimeUnit.MILLISECONDS); } - private <T> void publishError(final Subscriber<T> observer, long delay, final Exception error) { + private <T> void publishError(final Subscriber<T> subscriber, long delay, final Exception error) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onError(error); + subscriber.onError(error); } }, delay, TimeUnit.MILLISECONDS); } - private <T> void publishNext(final Subscriber<T> observer, long delay, final T value) { + private <T> void publishNext(final Subscriber<T> subscriber, long delay, final T value) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onNext(value); + subscriber.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } @Test public void testThrottle() { - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); TestScheduler s = new TestScheduler(); PublishProcessor<Integer> o = PublishProcessor.create(); - o.throttleFirst(500, TimeUnit.MILLISECONDS, s).subscribe(observer); + o.throttleFirst(500, TimeUnit.MILLISECONDS, s).subscribe(subscriber); // send events with simulated time increments s.advanceTimeTo(0, TimeUnit.MILLISECONDS); @@ -145,11 +145,11 @@ public void testThrottle() { s.advanceTimeTo(1501, TimeUnit.MILLISECONDS); o.onComplete(); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onNext(1); - inOrder.verify(observer).onNext(3); - inOrder.verify(observer).onNext(7); - inOrder.verify(observer).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(3); + inOrder.verify(subscriber).onNext(7); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -173,14 +173,14 @@ public void badSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onNext(2); - observer.onComplete(); - observer.onNext(3); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(1); + subscriber.onNext(2); + subscriber.onComplete(); + subscriber.onNext(3); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .throttleFirst(1, TimeUnit.DAYS) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeIntervalTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeIntervalTest.java index bf96ef9e45..1dc6369aba 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeIntervalTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeIntervalTest.java @@ -32,40 +32,40 @@ public class FlowableTimeIntervalTest { private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS; - private Subscriber<Timed<Integer>> observer; + private Subscriber<Timed<Integer>> subscriber; private TestScheduler testScheduler; - private PublishProcessor<Integer> subject; - private Flowable<Timed<Integer>> observable; + private PublishProcessor<Integer> processor; + private Flowable<Timed<Integer>> flowable; @Before public void setUp() { - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); testScheduler = new TestScheduler(); - subject = PublishProcessor.create(); - observable = subject.timeInterval(testScheduler); + processor = PublishProcessor.create(); + flowable = processor.timeInterval(testScheduler); } @Test public void testTimeInterval() { - InOrder inOrder = inOrder(observer); - observable.subscribe(observer); + InOrder inOrder = inOrder(subscriber); + flowable.subscribe(subscriber); testScheduler.advanceTimeBy(1000, TIME_UNIT); - subject.onNext(1); + processor.onNext(1); testScheduler.advanceTimeBy(2000, TIME_UNIT); - subject.onNext(2); + processor.onNext(2); testScheduler.advanceTimeBy(3000, TIME_UNIT); - subject.onNext(3); - subject.onComplete(); + processor.onNext(3); + processor.onComplete(); - inOrder.verify(observer, times(1)).onNext( + inOrder.verify(subscriber, times(1)).onNext( new Timed<Integer>(1, 1000, TIME_UNIT)); - inOrder.verify(observer, times(1)).onNext( + inOrder.verify(subscriber, times(1)).onNext( new Timed<Integer>(2, 2000, TIME_UNIT)); - inOrder.verify(observer, times(1)).onNext( + inOrder.verify(subscriber, times(1)).onNext( new Timed<Integer>(3, 3000, TIME_UNIT)); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java index b119bd00e4..ded3661e95 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java @@ -50,23 +50,23 @@ public void setUp() { @Test public void shouldNotTimeoutIfOnNextWithinTimeout() { - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); withTimeout.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); - verify(observer).onNext("One"); + verify(subscriber).onNext("One"); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); ts.cancel(); } @Test public void shouldNotTimeoutIfSecondOnNextWithinTimeout() { - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); withTimeout.subscribe(ts); @@ -74,59 +74,59 @@ public void shouldNotTimeoutIfSecondOnNextWithinTimeout() { underlyingSubject.onNext("One"); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("Two"); - verify(observer).onNext("Two"); + verify(subscriber).onNext("Two"); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); ts.dispose(); } @Test public void shouldTimeoutIfOnNextNotWithinTimeout() { - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); withTimeout.subscribe(ts); testScheduler.advanceTimeBy(TIMEOUT + 1, TimeUnit.SECONDS); - verify(observer).onError(any(TimeoutException.class)); + verify(subscriber).onError(any(TimeoutException.class)); ts.dispose(); } @Test public void shouldTimeoutIfSecondOnNextNotWithinTimeout() { - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); - withTimeout.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); + withTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); - verify(observer).onNext("One"); + verify(subscriber).onNext("One"); testScheduler.advanceTimeBy(TIMEOUT + 1, TimeUnit.SECONDS); - verify(observer).onError(any(TimeoutException.class)); + verify(subscriber).onError(any(TimeoutException.class)); ts.dispose(); } @Test public void shouldCompleteIfUnderlyingComletes() { - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); - withTimeout.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); + withTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onComplete(); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); - verify(observer).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); ts.dispose(); } @Test public void shouldErrorIfUnderlyingErrors() { - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); - withTimeout.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); + withTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onError(new UnsupportedOperationException()); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); - verify(observer).onError(any(UnsupportedOperationException.class)); + verify(subscriber).onError(any(UnsupportedOperationException.class)); ts.dispose(); } @@ -135,20 +135,20 @@ public void shouldSwitchToOtherIfOnNextNotWithinTimeout() { Flowable<String> other = Flowable.just("a", "b", "c"); Flowable<String> source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); source.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); testScheduler.advanceTimeBy(4, TimeUnit.SECONDS); underlyingSubject.onNext("Two"); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("One"); - inOrder.verify(observer, times(1)).onNext("a"); - inOrder.verify(observer, times(1)).onNext("b"); - inOrder.verify(observer, times(1)).onNext("c"); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("One"); + inOrder.verify(subscriber, times(1)).onNext("a"); + inOrder.verify(subscriber, times(1)).onNext("b"); + inOrder.verify(subscriber, times(1)).onNext("c"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); ts.dispose(); } @@ -158,20 +158,20 @@ public void shouldSwitchToOtherIfOnErrorNotWithinTimeout() { Flowable<String> other = Flowable.just("a", "b", "c"); Flowable<String> source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); source.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); testScheduler.advanceTimeBy(4, TimeUnit.SECONDS); underlyingSubject.onError(new UnsupportedOperationException()); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("One"); - inOrder.verify(observer, times(1)).onNext("a"); - inOrder.verify(observer, times(1)).onNext("b"); - inOrder.verify(observer, times(1)).onNext("c"); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("One"); + inOrder.verify(subscriber, times(1)).onNext("a"); + inOrder.verify(subscriber, times(1)).onNext("b"); + inOrder.verify(subscriber, times(1)).onNext("c"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); ts.dispose(); } @@ -181,20 +181,20 @@ public void shouldSwitchToOtherIfOnCompletedNotWithinTimeout() { Flowable<String> other = Flowable.just("a", "b", "c"); Flowable<String> source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); source.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); testScheduler.advanceTimeBy(4, TimeUnit.SECONDS); underlyingSubject.onComplete(); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("One"); - inOrder.verify(observer, times(1)).onNext("a"); - inOrder.verify(observer, times(1)).onNext("b"); - inOrder.verify(observer, times(1)).onNext("c"); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("One"); + inOrder.verify(subscriber, times(1)).onNext("a"); + inOrder.verify(subscriber, times(1)).onNext("b"); + inOrder.verify(subscriber, times(1)).onNext("c"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); ts.dispose(); } @@ -204,8 +204,8 @@ public void shouldSwitchToOtherAndCanBeUnsubscribedIfOnNextNotWithinTimeout() { PublishProcessor<String> other = PublishProcessor.create(); Flowable<String> source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); source.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); @@ -222,10 +222,10 @@ public void shouldSwitchToOtherAndCanBeUnsubscribedIfOnNextNotWithinTimeout() { other.onNext("d"); other.onComplete(); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("One"); - inOrder.verify(observer, times(1)).onNext("a"); - inOrder.verify(observer, times(1)).onNext("b"); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("One"); + inOrder.verify(subscriber, times(1)).onNext("a"); + inOrder.verify(subscriber, times(1)).onNext("b"); inOrder.verifyNoMoreInteractions(); } @@ -235,8 +235,8 @@ public void shouldTimeoutIfSynchronizedFlowableEmitFirstOnNextNotWithinTimeout() final CountDownLatch exit = new CountDownLatch(1); final CountDownLatch timeoutSetuped = new CountDownLatch(1); - final Subscriber<String> observer = TestHelper.mockSubscriber(); - final TestSubscriber<String> ts = new TestSubscriber<String>(observer); + final Subscriber<String> subscriber = TestHelper.mockSubscriber(); + final TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); new Thread(new Runnable() { @@ -265,8 +265,8 @@ public void subscribe(Subscriber<? super String> subscriber) { timeoutSetuped.await(); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onError(isA(TimeoutException.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onError(isA(TimeoutException.class)); inOrder.verifyNoMoreInteractions(); exit.countDown(); // exit the thread @@ -287,14 +287,14 @@ public void subscribe(Subscriber<? super String> subscriber) { TestScheduler testScheduler = new TestScheduler(); Flowable<String> observableWithTimeout = never.timeout(1000, TimeUnit.MILLISECONDS, testScheduler); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); observableWithTimeout.subscribe(ts); testScheduler.advanceTimeBy(2000, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onError(isA(TimeoutException.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onError(isA(TimeoutException.class)); inOrder.verifyNoMoreInteractions(); verify(s, times(1)).cancel(); @@ -318,14 +318,14 @@ public void subscribe(Subscriber<? super String> subscriber) { Flowable<String> observableWithTimeout = immediatelyComplete.timeout(1000, TimeUnit.MILLISECONDS, testScheduler); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); observableWithTimeout.subscribe(ts); testScheduler.advanceTimeBy(2000, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); verify(s, times(1)).cancel(); @@ -349,14 +349,14 @@ public void subscribe(Subscriber<? super String> subscriber) { Flowable<String> observableWithTimeout = immediatelyError.timeout(1000, TimeUnit.MILLISECONDS, testScheduler); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); observableWithTimeout.subscribe(ts); testScheduler.advanceTimeBy(2000, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onError(isA(IOException.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onError(isA(IOException.class)); inOrder.verifyNoMoreInteractions(); verify(s, times(1)).cancel(); @@ -364,18 +364,18 @@ public void subscribe(Subscriber<? super String> subscriber) { @Test public void shouldUnsubscribeFromUnderlyingSubscriptionOnDispose() { - final PublishProcessor<String> subject = PublishProcessor.create(); + final PublishProcessor<String> processor = PublishProcessor.create(); final TestScheduler scheduler = new TestScheduler(); - final TestSubscriber<String> observer = subject + final TestSubscriber<String> subscriber = processor .timeout(100, TimeUnit.MILLISECONDS, scheduler) .test(); - assertTrue(subject.hasSubscribers()); + assertTrue(processor.hasSubscribers()); - observer.dispose(); + subscriber.dispose(); - assertFalse(subject.hasSubscribers()); + assertFalse(processor.hasSubscribers()); } @Test @@ -431,14 +431,14 @@ public void badSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - - observer.onNext(1); - observer.onComplete(); - observer.onNext(2); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + + subscriber.onNext(1); + subscriber.onComplete(); + subscriber.onNext(2); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .timeout(1, TimeUnit.DAYS) @@ -457,14 +457,14 @@ public void badSourceOther() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - - observer.onNext(1); - observer.onComplete(); - observer.onNext(2); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + + subscriber.onNext(1); + subscriber.onComplete(); + subscriber.onNext(2); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .timeout(1, TimeUnit.DAYS, Flowable.just(3)) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java index b1667e1e56..178e015413 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java @@ -53,22 +53,22 @@ public Flowable<Integer> apply(Integer t1) { Flowable<Integer> other = Flowable.fromIterable(Arrays.asList(100)); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.timeout(timeout, timeoutFunc, other).subscribe(o); + source.timeout(timeout, timeoutFunc, other).subscribe(subscriber); source.onNext(1); source.onNext(2); source.onNext(3); timeout.onNext(1); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o).onNext(3); - inOrder.verify(o).onNext(100); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onNext(3); + inOrder.verify(subscriber).onNext(100); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @@ -86,16 +86,16 @@ public Flowable<Integer> apply(Integer t1) { Flowable<Integer> other = Flowable.fromIterable(Arrays.asList(100)); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.timeout(timeout, timeoutFunc, other).subscribe(o); + source.timeout(timeout, timeoutFunc, other).subscribe(subscriber); timeout.onNext(1); - inOrder.verify(o).onNext(100); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(100); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @@ -120,13 +120,13 @@ public Flowable<Integer> call() { Flowable<Integer> other = Flowable.fromIterable(Arrays.asList(100)); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.timeout(Flowable.defer(firstTimeoutFunc), timeoutFunc, other).subscribe(o); + source.timeout(Flowable.defer(firstTimeoutFunc), timeoutFunc, other).subscribe(subscriber); - verify(o).onError(any(TestException.class)); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @@ -144,16 +144,16 @@ public Flowable<Integer> apply(Integer t1) { Flowable<Integer> other = Flowable.fromIterable(Arrays.asList(100)); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.timeout(timeout, timeoutFunc, other).subscribe(o); + source.timeout(timeout, timeoutFunc, other).subscribe(subscriber); source.onNext(1); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onError(any(TestException.class)); - verify(o, never()).onComplete(); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); } @@ -171,13 +171,13 @@ public Flowable<Integer> apply(Integer t1) { Flowable<Integer> other = Flowable.fromIterable(Arrays.asList(100)); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.timeout(Flowable.<Integer> error(new TestException()), timeoutFunc, other).subscribe(o); + source.timeout(Flowable.<Integer> error(new TestException()), timeoutFunc, other).subscribe(subscriber); - verify(o).onError(any(TestException.class)); - verify(o, never()).onNext(any()); - verify(o, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onNext(any()); + verify(subscriber, never()).onComplete(); } @@ -195,16 +195,16 @@ public Flowable<Integer> apply(Integer t1) { Flowable<Integer> other = Flowable.fromIterable(Arrays.asList(100)); - Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.timeout(timeout, timeoutFunc, other).subscribe(o); + source.timeout(timeout, timeoutFunc, other).subscribe(subscriber); source.onNext(1); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onError(any(TestException.class)); - verify(o, never()).onComplete(); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); } @@ -220,13 +220,13 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - source.timeout(timeout, timeoutFunc).subscribe(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + source.timeout(timeout, timeoutFunc).subscribe(subscriber); timeout.onNext(1); - InOrder inOrder = inOrder(o); - inOrder.verify(o).onError(isA(TimeoutException.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onError(isA(TimeoutException.class)); inOrder.verifyNoMoreInteractions(); } @@ -242,15 +242,15 @@ public Flowable<Integer> apply(Integer t1) { } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); - source.timeout(PublishProcessor.create(), timeoutFunc).subscribe(o); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + source.timeout(PublishProcessor.create(), timeoutFunc).subscribe(subscriber); source.onNext(1); timeout.onNext(1); - InOrder inOrder = inOrder(o); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onError(isA(TimeoutException.class)); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onError(isA(TimeoutException.class)); inOrder.verifyNoMoreInteractions(); } @@ -308,7 +308,7 @@ public void subscribe(Subscriber<? super Integer> subscriber) { } }; - final Subscriber<Integer> o = TestHelper.mockSubscriber(); + final Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); doAnswer(new Answer<Void>() { @Override @@ -317,7 +317,7 @@ public Void answer(InvocationOnMock invocation) throws Throwable { return null; } - }).when(o).onNext(2); + }).when(subscriber).onNext(2); doAnswer(new Answer<Void>() { @Override @@ -326,9 +326,9 @@ public Void answer(InvocationOnMock invocation) throws Throwable { return null; } - }).when(o).onComplete(); + }).when(subscriber).onComplete(); - final TestSubscriber<Integer> ts = new TestSubscriber<Integer>(o); + final TestSubscriber<Integer> ts = new TestSubscriber<Integer>(subscriber); new Thread(new Runnable() { @@ -363,12 +363,12 @@ public void run() { assertFalse("CoundDownLatch timeout", latchTimeout.get()); - InOrder inOrder = inOrder(o); - inOrder.verify(o).onSubscribe((Subscription)notNull()); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onNext(2); - inOrder.verify(o, never()).onNext(3); - inOrder.verify(o).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber).onSubscribe((Subscription)notNull()); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber, never()).onNext(3); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -383,15 +383,15 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.timeout(Functions.justFunction(Flowable.never())); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.timeout(Functions.justFunction(Flowable.never())); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.timeout(Functions.justFunction(Flowable.never()), Flowable.never()); + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.timeout(Functions.justFunction(Flowable.never()), Flowable.never()); } }); } @@ -434,12 +434,12 @@ public void badInnerSource() { TestSubscriber<Integer> ts = pp .timeout(Functions.justFunction(new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onError(new TestException("First")); - observer.onNext(2); - observer.onError(new TestException("Second")); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onError(new TestException("First")); + subscriber.onNext(2); + subscriber.onError(new TestException("Second")); + subscriber.onComplete(); } })) .test(); @@ -463,12 +463,12 @@ public void badInnerSourceOther() { TestSubscriber<Integer> ts = pp .timeout(Functions.justFunction(new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onError(new TestException("First")); - observer.onNext(2); - observer.onError(new TestException("Second")); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onError(new TestException("First")); + subscriber.onNext(2); + subscriber.onError(new TestException("Second")); + subscriber.onComplete(); } }), Flowable.just(2)) .test(); @@ -493,22 +493,30 @@ public void withOtherMainError() { @Test public void badSourceTimeout() { - new Flowable<Integer>() { - @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onNext(2); - observer.onError(new TestException("First")); - observer.onNext(3); - observer.onComplete(); - observer.onError(new TestException("Second")); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new Flowable<Integer>() { + @Override + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(1); + subscriber.onNext(2); + subscriber.onError(new TestException("First")); + subscriber.onNext(3); + subscriber.onComplete(); + subscriber.onError(new TestException("Second")); + } } + .timeout(Functions.justFunction(Flowable.never()), Flowable.<Integer>never()) + .take(1) + .test() + .assertResult(1); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "First"); + TestHelper.assertUndeliverable(errors, 1, TestException.class, "Second"); + } finally { + RxJavaPlugins.reset(); } - .timeout(Functions.justFunction(Flowable.never()), Flowable.<Integer>never()) - .take(1) - .test() - .assertResult(1); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java index ec18215c00..21009d0da7 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java @@ -35,29 +35,29 @@ public class FlowableTimerTest { @Mock - Subscriber<Object> observer; + Subscriber<Object> subscriber; @Mock - Subscriber<Long> observer2; + Subscriber<Long> subscriber2; TestScheduler scheduler; @Before public void before() { - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); - observer2 = TestHelper.mockSubscriber(); + subscriber2 = TestHelper.mockSubscriber(); scheduler = new TestScheduler(); } @Test public void testTimerOnce() { - Flowable.timer(100, TimeUnit.MILLISECONDS, scheduler).subscribe(observer); + Flowable.timer(100, TimeUnit.MILLISECONDS, scheduler).subscribe(subscriber); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); - verify(observer, times(1)).onNext(0L); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onNext(0L); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -239,26 +239,26 @@ public void onNext(Long t) { @Override public void onError(Throwable e) { - observer.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - observer.onComplete(); + subscriber.onComplete(); } }); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - verify(observer).onError(any(TestException.class)); - verify(observer, never()).onNext(anyLong()); - verify(observer, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); + verify(subscriber, never()).onNext(anyLong()); + verify(subscriber, never()).onComplete(); } @Test public void testPeriodicObserverThrows() { Flowable<Long> source = Flowable.interval(100, 100, TimeUnit.MILLISECONDS, scheduler); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); source.safeSubscribe(new DefaultSubscriber<Long>() { @@ -267,26 +267,26 @@ public void onNext(Long t) { if (t > 0) { throw new TestException(); } - observer.onNext(t); + subscriber.onNext(t); } @Override public void onError(Throwable e) { - observer.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - observer.onComplete(); + subscriber.onComplete(); } }); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - inOrder.verify(observer).onNext(0L); - inOrder.verify(observer).onError(any(TestException.class)); + inOrder.verify(subscriber).onNext(0L); + inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); - verify(observer, never()).onComplete(); + verify(subscriber, never()).onComplete(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimestampTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimestampTest.java index 1172245f9c..295f4d3a2b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimestampTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimestampTest.java @@ -28,11 +28,11 @@ import io.reactivex.schedulers.*; public class FlowableTimestampTest { - Subscriber<Object> observer; + Subscriber<Object> subscriber; @Before public void before() { - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); } @Test @@ -41,7 +41,7 @@ public void timestampWithScheduler() { PublishProcessor<Integer> source = PublishProcessor.create(); Flowable<Timed<Integer>> m = source.timestamp(scheduler); - m.subscribe(observer); + m.subscribe(subscriber); source.onNext(1); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); @@ -49,14 +49,14 @@ public void timestampWithScheduler() { scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); source.onNext(3); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); - inOrder.verify(observer, times(1)).onNext(new Timed<Integer>(1, 0, TimeUnit.MILLISECONDS)); - inOrder.verify(observer, times(1)).onNext(new Timed<Integer>(2, 100, TimeUnit.MILLISECONDS)); - inOrder.verify(observer, times(1)).onNext(new Timed<Integer>(3, 200, TimeUnit.MILLISECONDS)); + inOrder.verify(subscriber, times(1)).onNext(new Timed<Integer>(1, 0, TimeUnit.MILLISECONDS)); + inOrder.verify(subscriber, times(1)).onNext(new Timed<Integer>(2, 100, TimeUnit.MILLISECONDS)); + inOrder.verify(subscriber, times(1)).onNext(new Timed<Integer>(3, 200, TimeUnit.MILLISECONDS)); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); } @Test @@ -65,7 +65,7 @@ public void timestampWithScheduler2() { PublishProcessor<Integer> source = PublishProcessor.create(); Flowable<Timed<Integer>> m = source.timestamp(scheduler); - m.subscribe(observer); + m.subscribe(subscriber); source.onNext(1); source.onNext(2); @@ -73,14 +73,14 @@ public void timestampWithScheduler2() { scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); source.onNext(3); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); - inOrder.verify(observer, times(1)).onNext(new Timed<Integer>(1, 0, TimeUnit.MILLISECONDS)); - inOrder.verify(observer, times(1)).onNext(new Timed<Integer>(2, 0, TimeUnit.MILLISECONDS)); - inOrder.verify(observer, times(1)).onNext(new Timed<Integer>(3, 200, TimeUnit.MILLISECONDS)); + inOrder.verify(subscriber, times(1)).onNext(new Timed<Integer>(1, 0, TimeUnit.MILLISECONDS)); + inOrder.verify(subscriber, times(1)).onNext(new Timed<Integer>(2, 0, TimeUnit.MILLISECONDS)); + inOrder.verify(subscriber, times(1)).onNext(new Timed<Integer>(3, 200, TimeUnit.MILLISECONDS)); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToFutureTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToFutureTest.java index afe111c919..2fb5920d57 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToFutureTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToFutureTest.java @@ -34,17 +34,17 @@ public void testSuccess() throws Exception { Object value = new Object(); when(future.get()).thenReturn(value); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - TestSubscriber<Object> ts = new TestSubscriber<Object>(o); + TestSubscriber<Object> ts = new TestSubscriber<Object>(subscriber); Flowable.fromFuture(future).subscribe(ts); ts.dispose(); - verify(o, times(1)).onNext(value); - verify(o, times(1)).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onNext(value); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); verify(future, never()).cancel(anyBoolean()); } @@ -55,18 +55,18 @@ public void testSuccessOperatesOnSuppliedScheduler() throws Exception { Object value = new Object(); when(future.get()).thenReturn(value); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); TestScheduler scheduler = new TestScheduler(); - TestSubscriber<Object> ts = new TestSubscriber<Object>(o); + TestSubscriber<Object> ts = new TestSubscriber<Object>(subscriber); Flowable.fromFuture(future, scheduler).subscribe(ts); - verify(o, never()).onNext(value); + verify(subscriber, never()).onNext(value); scheduler.triggerActions(); - verify(o, times(1)).onNext(value); + verify(subscriber, times(1)).onNext(value); } @Test @@ -76,17 +76,17 @@ public void testFailure() throws Exception { RuntimeException e = new RuntimeException(); when(future.get()).thenThrow(e); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - TestSubscriber<Object> ts = new TestSubscriber<Object>(o); + TestSubscriber<Object> ts = new TestSubscriber<Object>(subscriber); Flowable.fromFuture(future).subscribe(ts); ts.dispose(); - verify(o, never()).onNext(null); - verify(o, never()).onComplete(); - verify(o, times(1)).onError(e); + verify(subscriber, never()).onNext(null); + verify(subscriber, never()).onComplete(); + verify(subscriber, times(1)).onError(e); verify(future, never()).cancel(anyBoolean()); } @@ -97,9 +97,9 @@ public void testCancelledBeforeSubscribe() throws Exception { CancellationException e = new CancellationException("unit test synthetic cancellation"); when(future.get()).thenThrow(e); - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - TestSubscriber<Object> ts = new TestSubscriber<Object>(o); + TestSubscriber<Object> ts = new TestSubscriber<Object>(subscriber); ts.dispose(); Flowable.fromFuture(future).subscribe(ts); @@ -143,9 +143,9 @@ public Object get(long timeout, TimeUnit unit) throws InterruptedException, Exec } }; - Subscriber<Object> o = TestHelper.mockSubscriber(); + Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - TestSubscriber<Object> ts = new TestSubscriber<Object>(o); + TestSubscriber<Object> ts = new TestSubscriber<Object>(subscriber); Flowable<Object> futureObservable = Flowable.fromFuture(future); futureObservable.subscribeOn(Schedulers.computation()).subscribe(ts); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java index 4c18a1ce29..20a0534285 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java @@ -36,66 +36,69 @@ public class FlowableToListTest { @Test public void testListFlowable() { Flowable<String> w = Flowable.fromIterable(Arrays.asList("one", "two", "three")); - Flowable<List<String>> observable = w.toList().toFlowable(); + Flowable<List<String>> flowable = w.toList().toFlowable(); - Subscriber<List<String>> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); - verify(observer, times(1)).onNext(Arrays.asList("one", "two", "three")); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<List<String>> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); + + verify(subscriber, times(1)).onNext(Arrays.asList("one", "two", "three")); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testListViaFlowableFlowable() { Flowable<String> w = Flowable.fromIterable(Arrays.asList("one", "two", "three")); - Flowable<List<String>> observable = w.toList().toFlowable(); + Flowable<List<String>> flowable = w.toList().toFlowable(); - Subscriber<List<String>> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); - verify(observer, times(1)).onNext(Arrays.asList("one", "two", "three")); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<List<String>> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); + + verify(subscriber, times(1)).onNext(Arrays.asList("one", "two", "three")); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testListMultipleSubscribersFlowable() { Flowable<String> w = Flowable.fromIterable(Arrays.asList("one", "two", "three")); - Flowable<List<String>> observable = w.toList().toFlowable(); + Flowable<List<String>> flowable = w.toList().toFlowable(); - Subscriber<List<String>> o1 = TestHelper.mockSubscriber(); - observable.subscribe(o1); + Subscriber<List<String>> subscriber1 = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber1); - Subscriber<List<String>> o2 = TestHelper.mockSubscriber(); - observable.subscribe(o2); + Subscriber<List<String>> subscriber2 = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber2); List<String> expected = Arrays.asList("one", "two", "three"); - verify(o1, times(1)).onNext(expected); - verify(o1, Mockito.never()).onError(any(Throwable.class)); - verify(o1, times(1)).onComplete(); + verify(subscriber1, times(1)).onNext(expected); + verify(subscriber1, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber1, times(1)).onComplete(); - verify(o2, times(1)).onNext(expected); - verify(o2, Mockito.never()).onError(any(Throwable.class)); - verify(o2, times(1)).onComplete(); + verify(subscriber2, times(1)).onNext(expected); + verify(subscriber2, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber2, times(1)).onComplete(); } @Test @Ignore("Null values are not allowed") public void testListWithNullValueFlowable() { Flowable<String> w = Flowable.fromIterable(Arrays.asList("one", null, "three")); - Flowable<List<String>> observable = w.toList().toFlowable(); + Flowable<List<String>> flowable = w.toList().toFlowable(); - Subscriber<List<String>> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); - verify(observer, times(1)).onNext(Arrays.asList("one", null, "three")); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<List<String>> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); + + verify(subscriber, times(1)).onNext(Arrays.asList("one", null, "three")); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testListWithBlockingFirstFlowable() { - Flowable<String> o = Flowable.fromIterable(Arrays.asList("one", "two", "three")); - List<String> actual = o.toList().toFlowable().blockingFirst(); + Flowable<String> f = Flowable.fromIterable(Arrays.asList("one", "two", "three")); + List<String> actual = f.toList().toFlowable().blockingFirst(); Assert.assertEquals(Arrays.asList("one", "two", "three"), actual); } @Test @@ -170,10 +173,10 @@ public void capacityHintFlowable() { @Test public void testList() { Flowable<String> w = Flowable.fromIterable(Arrays.asList("one", "two", "three")); - Single<List<String>> observable = w.toList(); + Single<List<String>> single = w.toList(); SingleObserver<List<String>> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(Arrays.asList("one", "two", "three")); verify(observer, Mockito.never()).onError(any(Throwable.class)); } @@ -181,10 +184,10 @@ public void testList() { @Test public void testListViaFlowable() { Flowable<String> w = Flowable.fromIterable(Arrays.asList("one", "two", "three")); - Single<List<String>> observable = w.toList(); + Single<List<String>> single = w.toList(); SingleObserver<List<String>> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(Arrays.asList("one", "two", "three")); verify(observer, Mockito.never()).onError(any(Throwable.class)); } @@ -192,13 +195,13 @@ public void testListViaFlowable() { @Test public void testListMultipleSubscribers() { Flowable<String> w = Flowable.fromIterable(Arrays.asList("one", "two", "three")); - Single<List<String>> observable = w.toList(); + Single<List<String>> single = w.toList(); SingleObserver<List<String>> o1 = TestHelper.mockSingleObserver(); - observable.subscribe(o1); + single.subscribe(o1); SingleObserver<List<String>> o2 = TestHelper.mockSingleObserver(); - observable.subscribe(o2); + single.subscribe(o2); List<String> expected = Arrays.asList("one", "two", "three"); @@ -213,18 +216,18 @@ public void testListMultipleSubscribers() { @Ignore("Null values are not allowed") public void testListWithNullValue() { Flowable<String> w = Flowable.fromIterable(Arrays.asList("one", null, "three")); - Single<List<String>> observable = w.toList(); + Single<List<String>> single = w.toList(); SingleObserver<List<String>> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(Arrays.asList("one", null, "three")); verify(observer, Mockito.never()).onError(any(Throwable.class)); } @Test public void testListWithBlockingFirst() { - Flowable<String> o = Flowable.fromIterable(Arrays.asList("one", "two", "three")); - List<String> actual = o.toList().blockingGet(); + Flowable<String> f = Flowable.fromIterable(Arrays.asList("one", "two", "three")); + List<String> actual = f.toList().blockingGet(); Assert.assertEquals(Arrays.asList("one", "two", "three"), actual); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMapTest.java index 8723a291bc..f8914e7182 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMapTest.java @@ -25,12 +25,12 @@ import io.reactivex.functions.Function; public class FlowableToMapTest { - Subscriber<Object> objectObserver; + Subscriber<Object> objectSubscriber; SingleObserver<Object> singleObserver; @Before public void before() { - objectObserver = TestHelper.mockSubscriber(); + objectSubscriber = TestHelper.mockSubscriber(); singleObserver = TestHelper.mockSingleObserver(); } @@ -59,11 +59,11 @@ public void testToMapFlowable() { expected.put(3, "ccc"); expected.put(4, "dddd"); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, never()).onError(any(Throwable.class)); - verify(objectObserver, times(1)).onNext(expected); - verify(objectObserver, times(1)).onComplete(); + verify(objectSubscriber, never()).onError(any(Throwable.class)); + verify(objectSubscriber, times(1)).onNext(expected); + verify(objectSubscriber, times(1)).onComplete(); } @Test @@ -78,11 +78,11 @@ public void testToMapWithValueSelectorFlowable() { expected.put(3, "cccccc"); expected.put(4, "dddddddd"); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, never()).onError(any(Throwable.class)); - verify(objectObserver, times(1)).onNext(expected); - verify(objectObserver, times(1)).onComplete(); + verify(objectSubscriber, never()).onError(any(Throwable.class)); + verify(objectSubscriber, times(1)).onNext(expected); + verify(objectSubscriber, times(1)).onComplete(); } @Test @@ -106,11 +106,11 @@ public Integer apply(String t1) { expected.put(3, "ccc"); expected.put(4, "dddd"); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, never()).onNext(expected); - verify(objectObserver, never()).onComplete(); - verify(objectObserver, times(1)).onError(any(Throwable.class)); + verify(objectSubscriber, never()).onNext(expected); + verify(objectSubscriber, never()).onComplete(); + verify(objectSubscriber, times(1)).onError(any(Throwable.class)); } @@ -136,11 +136,11 @@ public String apply(String t1) { expected.put(3, "cccccc"); expected.put(4, "dddddddd"); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, never()).onNext(expected); - verify(objectObserver, never()).onComplete(); - verify(objectObserver, times(1)).onError(any(Throwable.class)); + verify(objectSubscriber, never()).onNext(expected); + verify(objectSubscriber, never()).onComplete(); + verify(objectSubscriber, times(1)).onError(any(Throwable.class)); } @@ -181,11 +181,11 @@ public String apply(String v) { expected.put(3, "ccc"); expected.put(4, "dddd"); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, never()).onError(any(Throwable.class)); - verify(objectObserver, times(1)).onNext(expected); - verify(objectObserver, times(1)).onComplete(); + verify(objectSubscriber, never()).onError(any(Throwable.class)); + verify(objectSubscriber, times(1)).onNext(expected); + verify(objectSubscriber, times(1)).onComplete(); } @Test @@ -217,11 +217,11 @@ public String apply(String v) { expected.put(3, "ccc"); expected.put(4, "dddd"); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, never()).onNext(expected); - verify(objectObserver, never()).onComplete(); - verify(objectObserver, times(1)).onError(any(Throwable.class)); + verify(objectSubscriber, never()).onNext(expected); + verify(objectSubscriber, never()).onComplete(); + verify(objectSubscriber, times(1)).onError(any(Throwable.class)); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMultimapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMultimapTest.java index af642121fb..1546815355 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMultimapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMultimapTest.java @@ -25,13 +25,13 @@ import io.reactivex.functions.Function; public class FlowableToMultimapTest { - Subscriber<Object> objectObserver; + Subscriber<Object> objectSubscriber; SingleObserver<Object> singleObserver; @Before public void before() { - objectObserver = TestHelper.mockSubscriber(); + objectSubscriber = TestHelper.mockSubscriber(); singleObserver = TestHelper.mockSingleObserver(); } @@ -58,11 +58,11 @@ public void testToMultimapFlowable() { expected.put(1, Arrays.asList("a", "b")); expected.put(2, Arrays.asList("cc", "dd")); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, never()).onError(any(Throwable.class)); - verify(objectObserver, times(1)).onNext(expected); - verify(objectObserver, times(1)).onComplete(); + verify(objectSubscriber, never()).onError(any(Throwable.class)); + verify(objectSubscriber, times(1)).onNext(expected); + verify(objectSubscriber, times(1)).onComplete(); } @Test @@ -75,11 +75,11 @@ public void testToMultimapWithValueSelectorFlowable() { expected.put(1, Arrays.asList("aa", "bb")); expected.put(2, Arrays.asList("cccc", "dddd")); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, never()).onError(any(Throwable.class)); - verify(objectObserver, times(1)).onNext(expected); - verify(objectObserver, times(1)).onComplete(); + verify(objectSubscriber, never()).onError(any(Throwable.class)); + verify(objectSubscriber, times(1)).onNext(expected); + verify(objectSubscriber, times(1)).onComplete(); } @Test @@ -121,11 +121,11 @@ public Collection<String> apply(Integer e) { expected.put(2, Arrays.asList("cc", "dd")); expected.put(3, Arrays.asList("eee", "fff")); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, never()).onError(any(Throwable.class)); - verify(objectObserver, times(1)).onNext(expected); - verify(objectObserver, times(1)).onComplete(); + verify(objectSubscriber, never()).onError(any(Throwable.class)); + verify(objectSubscriber, times(1)).onNext(expected); + verify(objectSubscriber, times(1)).onComplete(); } @Test @@ -163,11 +163,11 @@ public Map<Integer, Collection<String>> call() { expected.put(2, Arrays.asList("cc", "dd")); expected.put(3, new HashSet<String>(Arrays.asList("eee"))); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, never()).onError(any(Throwable.class)); - verify(objectObserver, times(1)).onNext(expected); - verify(objectObserver, times(1)).onComplete(); + verify(objectSubscriber, never()).onError(any(Throwable.class)); + verify(objectSubscriber, times(1)).onNext(expected); + verify(objectSubscriber, times(1)).onComplete(); } @Test @@ -190,11 +190,11 @@ public Integer apply(String t1) { expected.put(1, Arrays.asList("a", "b")); expected.put(2, Arrays.asList("cc", "dd")); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, times(1)).onError(any(Throwable.class)); - verify(objectObserver, never()).onNext(expected); - verify(objectObserver, never()).onComplete(); + verify(objectSubscriber, times(1)).onError(any(Throwable.class)); + verify(objectSubscriber, never()).onNext(expected); + verify(objectSubscriber, never()).onComplete(); } @Test @@ -217,11 +217,11 @@ public String apply(String t1) { expected.put(1, Arrays.asList("aa", "bb")); expected.put(2, Arrays.asList("cccc", "dddd")); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, times(1)).onError(any(Throwable.class)); - verify(objectObserver, never()).onNext(expected); - verify(objectObserver, never()).onComplete(); + verify(objectSubscriber, times(1)).onError(any(Throwable.class)); + verify(objectSubscriber, never()).onNext(expected); + verify(objectSubscriber, never()).onComplete(); } @Test @@ -247,11 +247,11 @@ public String apply(String v) { expected.put(2, Arrays.asList("cc", "dd")); expected.put(3, Arrays.asList("eee", "fff")); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, times(1)).onError(any(Throwable.class)); - verify(objectObserver, never()).onNext(expected); - verify(objectObserver, never()).onComplete(); + verify(objectSubscriber, times(1)).onError(any(Throwable.class)); + verify(objectSubscriber, never()).onNext(expected); + verify(objectSubscriber, never()).onComplete(); } @Test @@ -289,11 +289,11 @@ public Map<Integer, Collection<String>> call() { expected.put(2, Arrays.asList("cc", "dd")); expected.put(3, Collections.singleton("eee")); - mapped.subscribe(objectObserver); + mapped.subscribe(objectSubscriber); - verify(objectObserver, times(1)).onError(any(Throwable.class)); - verify(objectObserver, never()).onNext(expected); - verify(objectObserver, never()).onComplete(); + verify(objectSubscriber, times(1)).onError(any(Throwable.class)); + verify(objectSubscriber, never()).onNext(expected); + verify(objectSubscriber, never()).onComplete(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java index db118e2ab1..bea7ef749a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java @@ -34,19 +34,20 @@ public class FlowableToSortedListTest { @Test public void testSortedListFlowable() { Flowable<Integer> w = Flowable.just(1, 3, 2, 5, 4); - Flowable<List<Integer>> observable = w.toSortedList().toFlowable(); + Flowable<List<Integer>> flowable = w.toSortedList().toFlowable(); - Subscriber<List<Integer>> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); - verify(observer, times(1)).onNext(Arrays.asList(1, 2, 3, 4, 5)); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<List<Integer>> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); + + verify(subscriber, times(1)).onNext(Arrays.asList(1, 2, 3, 4, 5)); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testSortedListWithCustomFunctionFlowable() { Flowable<Integer> w = Flowable.just(1, 3, 2, 5, 4); - Flowable<List<Integer>> observable = w.toSortedList(new Comparator<Integer>() { + Flowable<List<Integer>> flowable = w.toSortedList(new Comparator<Integer>() { @Override public int compare(Integer t1, Integer t2) { @@ -55,17 +56,18 @@ public int compare(Integer t1, Integer t2) { }).toFlowable(); - Subscriber<List<Integer>> observer = TestHelper.mockSubscriber(); - observable.subscribe(observer); - verify(observer, times(1)).onNext(Arrays.asList(5, 4, 3, 2, 1)); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + Subscriber<List<Integer>> subscriber = TestHelper.mockSubscriber(); + flowable.subscribe(subscriber); + + verify(subscriber, times(1)).onNext(Arrays.asList(5, 4, 3, 2, 1)); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testWithFollowingFirstFlowable() { - Flowable<Integer> o = Flowable.just(1, 3, 2, 5, 4); - assertEquals(Arrays.asList(1, 2, 3, 4, 5), o.toSortedList().toFlowable().blockingFirst()); + Flowable<Integer> f = Flowable.just(1, 3, 2, 5, 4); + assertEquals(Arrays.asList(1, 2, 3, 4, 5), f.toSortedList().toFlowable().blockingFirst()); } @Test public void testBackpressureHonoredFlowable() { @@ -169,10 +171,10 @@ public int compare(Integer a, Integer b) { @Test public void testSortedList() { Flowable<Integer> w = Flowable.just(1, 3, 2, 5, 4); - Single<List<Integer>> observable = w.toSortedList(); + Single<List<Integer>> single = w.toSortedList(); SingleObserver<List<Integer>> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(Arrays.asList(1, 2, 3, 4, 5)); verify(observer, Mockito.never()).onError(any(Throwable.class)); } @@ -180,7 +182,7 @@ public void testSortedList() { @Test public void testSortedListWithCustomFunction() { Flowable<Integer> w = Flowable.just(1, 3, 2, 5, 4); - Single<List<Integer>> observable = w.toSortedList(new Comparator<Integer>() { + Single<List<Integer>> single = w.toSortedList(new Comparator<Integer>() { @Override public int compare(Integer t1, Integer t2) { @@ -190,15 +192,15 @@ public int compare(Integer t1, Integer t2) { }); SingleObserver<List<Integer>> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(Arrays.asList(5, 4, 3, 2, 1)); verify(observer, Mockito.never()).onError(any(Throwable.class)); } @Test public void testWithFollowingFirst() { - Flowable<Integer> o = Flowable.just(1, 3, 2, 5, 4); - assertEquals(Arrays.asList(1, 2, 3, 4, 5), o.toSortedList().blockingGet()); + Flowable<Integer> f = Flowable.just(1, 3, 2, 5, 4); + assertEquals(Arrays.asList(1, 2, 3, 4, 5), f.toSortedList().blockingGet()); } @Test @Ignore("Single doesn't do backpressure") diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java index d678bf11bf..3ed444424f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java @@ -97,13 +97,13 @@ public void subscribe(Subscriber<? super Integer> t1) { } }); - TestSubscriber<Integer> observer = new TestSubscriber<Integer>(); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); w.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.computation()) .unsubscribeOn(uiEventLoop) .take(2) - .subscribe(observer); + .subscribe(ts); - observer.awaitTerminalEvent(1, TimeUnit.SECONDS); + ts.awaitTerminalEvent(1, TimeUnit.SECONDS); Thread unsubscribeThread = subscription.getThread(); @@ -119,8 +119,8 @@ public void subscribe(Subscriber<? super Integer> t1) { System.out.println("subscribeThread.get(): " + subscribeThread.get()); assertSame(unsubscribeThread, uiEventLoop.getThread()); - observer.assertValues(1, 2); - observer.assertTerminated(); + ts.assertValues(1, 2); + ts.assertTerminated(); } finally { uiEventLoop.shutdown(); } @@ -250,12 +250,12 @@ public void signalAfterDispose() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onNext(2); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(1); + subscriber.onNext(2); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .unsubscribeOn(Schedulers.single()) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java index e836796924..ad3869f4ac 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java @@ -87,16 +87,16 @@ public Flowable<String> apply(Resource res) { } }; - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable<String> observable = Flowable.using(resourceFactory, observableFactory, + Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory, new DisposeAction(), disposeEagerly); - observable.subscribe(observer); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext("Hello"); - inOrder.verify(observer, times(1)).onNext("world!"); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext("Hello"); + inOrder.verify(subscriber, times(1)).onNext("world!"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); // The resouce should be closed @@ -147,22 +147,22 @@ public Flowable<String> apply(Resource res) { } }; - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable<String> observable = Flowable.using(resourceFactory, observableFactory, + Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory, new DisposeAction(), disposeEagerly); - observable.subscribe(observer); - observable.subscribe(observer); + flowable.subscribe(subscriber); + flowable.subscribe(subscriber); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); - inOrder.verify(observer, times(1)).onNext("Hello"); - inOrder.verify(observer, times(1)).onNext("world!"); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("Hello"); + inOrder.verify(subscriber, times(1)).onNext("world!"); + inOrder.verify(subscriber, times(1)).onComplete(); - inOrder.verify(observer, times(1)).onNext("Hello"); - inOrder.verify(observer, times(1)).onNext("world!"); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("Hello"); + inOrder.verify(subscriber, times(1)).onNext("world!"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -291,14 +291,14 @@ public Flowable<String> apply(Resource resource) { } }; - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable<String> observable = Flowable.using(resourceFactory, observableFactory, + Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory, new DisposeAction(), true) .doOnCancel(unsub) .doOnComplete(completion); - observable.safeSubscribe(observer); + flowable.safeSubscribe(subscriber); assertEquals(Arrays.asList("disposed", "completed"), events); @@ -318,14 +318,14 @@ public Flowable<String> apply(Resource resource) { } }; - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable<String> observable = Flowable.using(resourceFactory, observableFactory, + Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory, new DisposeAction(), false) .doOnCancel(unsub) .doOnComplete(completion); - observable.safeSubscribe(observer); + flowable.safeSubscribe(subscriber); assertEquals(Arrays.asList("completed", "disposed"), events); @@ -348,14 +348,14 @@ public Flowable<String> apply(Resource resource) { } }; - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable<String> observable = Flowable.using(resourceFactory, observableFactory, + Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory, new DisposeAction(), true) .doOnCancel(unsub) .doOnError(onError); - observable.safeSubscribe(observer); + flowable.safeSubscribe(subscriber); assertEquals(Arrays.asList("disposed", "error"), events); @@ -376,14 +376,14 @@ public Flowable<String> apply(Resource resource) { } }; - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable<String> observable = Flowable.using(resourceFactory, observableFactory, + Flowable<String> flowable = Flowable.using(resourceFactory, observableFactory, new DisposeAction(), false) .doOnCancel(unsub) .doOnError(onError); - observable.safeSubscribe(observer); + flowable.safeSubscribe(subscriber); assertEquals(Arrays.asList("error", "disposed"), events); } @@ -643,9 +643,9 @@ public void sourceSupplierReturnsNull() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) + public Flowable<Object> apply(Flowable<Object> f) throws Exception { - return Flowable.using(Functions.justCallable(1), Functions.justFunction(o), Functions.emptyConsumer()); + return Flowable.using(Functions.justCallable(1), Functions.justFunction(f), Functions.emptyConsumer()); } }); } @@ -656,10 +656,10 @@ public void eagerDisposedOnComplete() { Flowable.using(Functions.justCallable(1), Functions.justFunction(new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); ts.cancel(); - observer.onComplete(); + subscriber.onComplete(); } }), Functions.emptyConsumer(), true) .subscribe(ts); @@ -671,10 +671,10 @@ public void eagerDisposedOnError() { Flowable.using(Functions.justCallable(1), Functions.justFunction(new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); ts.cancel(); - observer.onError(new TestException()); + subscriber.onError(new TestException()); } }), Functions.emptyConsumer(), true) .subscribe(ts); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java index 1bdb7a95e6..a6469281c4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java @@ -40,7 +40,7 @@ public void testWindowViaFlowableNormal1() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); - final Subscriber<Object> o = TestHelper.mockSubscriber(); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); final List<Subscriber<Object>> values = new ArrayList<Subscriber<Object>>(); @@ -55,12 +55,12 @@ public void onNext(Flowable<Integer> args) { @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }; @@ -76,7 +76,7 @@ public void onComplete() { source.onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); assertEquals(n / 3, values.size()); @@ -90,7 +90,7 @@ public void onComplete() { j += 3; } - verify(o).onComplete(); + verify(subscriber).onComplete(); } @Test @@ -98,7 +98,7 @@ public void testWindowViaFlowableBoundaryCompletes() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); - final Subscriber<Object> o = TestHelper.mockSubscriber(); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); final List<Subscriber<Object>> values = new ArrayList<Subscriber<Object>>(); @@ -113,12 +113,12 @@ public void onNext(Flowable<Integer> args) { @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }; @@ -145,8 +145,8 @@ public void onComplete() { j += 3; } - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -154,7 +154,7 @@ public void testWindowViaFlowableBoundaryThrows() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); - final Subscriber<Object> o = TestHelper.mockSubscriber(); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); final List<Subscriber<Object>> values = new ArrayList<Subscriber<Object>>(); @@ -169,12 +169,12 @@ public void onNext(Flowable<Integer> args) { @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }; @@ -195,8 +195,8 @@ public void onComplete() { verify(mo).onNext(2); verify(mo).onError(any(TestException.class)); - verify(o, never()).onComplete(); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); } @Test @@ -204,7 +204,7 @@ public void testWindowViaFlowableThrows() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); - final Subscriber<Object> o = TestHelper.mockSubscriber(); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); final List<Subscriber<Object>> values = new ArrayList<Subscriber<Object>>(); @@ -219,12 +219,12 @@ public void onNext(Flowable<Integer> args) { @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }; @@ -245,8 +245,8 @@ public void onComplete() { verify(mo).onNext(2); verify(mo).onError(any(TestException.class)); - verify(o, never()).onComplete(); - verify(o).onError(any(TestException.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber).onError(any(TestException.class)); } @Test @@ -497,8 +497,8 @@ public void mainError() { public void innerBadSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(Flowable<Integer> o) throws Exception { - return Flowable.just(1).window(o).flatMap(new Function<Flowable<Integer>, Flowable<Integer>>() { + public Object apply(Flowable<Integer> f) throws Exception { + return Flowable.just(1).window(f).flatMap(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Flowable<Integer> v) throws Exception { return v; @@ -509,7 +509,7 @@ public Flowable<Integer> apply(Flowable<Integer> v) throws Exception { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override - public Object apply(final Flowable<Integer> o) throws Exception { + public Object apply(final Flowable<Integer> f) throws Exception { return Flowable.just(1).window(new Callable<Publisher<Integer>>() { int count; @Override @@ -517,7 +517,7 @@ public Publisher<Integer> call() throws Exception { if (++count > 1) { return Flowable.never(); } - return o; + return f; } }) .flatMap(new Function<Flowable<Integer>, Flowable<Integer>>() { @@ -606,8 +606,8 @@ public Flowable<Integer> apply(Flowable<Integer> v) throws Exception { public void badSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Object>, Object>() { @Override - public Object apply(Flowable<Object> o) throws Exception { - return o.window(Flowable.never()).flatMap(new Function<Flowable<Object>, Flowable<Object>>() { + public Object apply(Flowable<Object> f) throws Exception { + return f.window(Flowable.never()).flatMap(new Function<Flowable<Object>, Flowable<Object>>() { @Override public Flowable<Object> apply(Flowable<Object> v) throws Exception { return v; @@ -621,8 +621,8 @@ public Flowable<Object> apply(Flowable<Object> v) throws Exception { public void badSourceCallable() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Object>, Object>() { @Override - public Object apply(Flowable<Object> o) throws Exception { - return o.window(Functions.justCallable(Flowable.never())).flatMap(new Function<Flowable<Object>, Flowable<Object>>() { + public Object apply(Flowable<Object> f) throws Exception { + return f.window(Functions.justCallable(Flowable.never())).flatMap(new Function<Flowable<Object>, Flowable<Object>>() { @Override public Flowable<Object> apply(Flowable<Object> v) throws Exception { return v; @@ -698,19 +698,33 @@ public void oneWindow() { @SuppressWarnings("unchecked") @Test public void boundaryDirectMissingBackpressure() { - BehaviorProcessor.create() - .window(Flowable.error(new TestException())) - .test(0) - .assertFailure(MissingBackpressureException.class); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + BehaviorProcessor.create() + .window(Flowable.error(new TestException())) + .test(0) + .assertFailure(MissingBackpressureException.class); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @SuppressWarnings("unchecked") @Test public void boundaryDirectMissingBackpressureNoNullPointerException() { - BehaviorProcessor.createDefault(1) - .window(Flowable.error(new TestException())) - .test(0) - .assertFailure(MissingBackpressureException.class); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + BehaviorProcessor.createDefault(1) + .window(Flowable.error(new TestException())) + .test(0) + .assertFailure(MissingBackpressureException.class); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -767,9 +781,9 @@ public void mainAndBoundaryBothError() { TestSubscriber<Flowable<Object>> ts = Flowable.error(new TestException("main")) .window(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - ref.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + ref.set(subscriber); } }) .test(); @@ -800,16 +814,16 @@ public void mainCompleteBoundaryErrorRace() { TestSubscriber<Flowable<Object>> ts = new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - refMain.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + refMain.set(subscriber); } } .window(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - ref.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + ref.set(subscriber); } }) .test(); @@ -850,16 +864,16 @@ public void mainNextBoundaryNextRace() { TestSubscriber<Flowable<Object>> ts = new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - refMain.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + refMain.set(subscriber); } } .window(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - ref.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + ref.set(subscriber); } }) .test(); @@ -893,16 +907,16 @@ public void takeOneAnotherBoundary() { TestSubscriber<Flowable<Object>> ts = new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - refMain.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + refMain.set(subscriber); } } .window(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - ref.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + ref.set(subscriber); } }) .test(); @@ -925,16 +939,16 @@ public void disposeMainBoundaryCompleteRace() { final TestSubscriber<Flowable<Object>> ts = new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - refMain.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + refMain.set(subscriber); } } .window(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { + protected void subscribeActual(Subscriber<? super Object> subscriber) { final AtomicInteger counter = new AtomicInteger(); - observer.onSubscribe(new Subscription() { + subscriber.onSubscribe(new Subscription() { @Override public void cancel() { @@ -948,7 +962,7 @@ public void cancel() { public void request(long n) { } }); - ref.set(observer); + ref.set(subscriber); } }) .test(); @@ -962,9 +976,9 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - Subscriber<Object> o = ref.get(); - o.onNext(1); - o.onComplete(); + Subscriber<Object> subscriber = ref.get(); + subscriber.onNext(1); + subscriber.onComplete(); } }; @@ -982,16 +996,16 @@ public void disposeMainBoundaryErrorRace() { final TestSubscriber<Flowable<Object>> ts = new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - refMain.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + refMain.set(subscriber); } } .window(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { + protected void subscribeActual(Subscriber<? super Object> subscriber) { final AtomicInteger counter = new AtomicInteger(); - observer.onSubscribe(new Subscription() { + subscriber.onSubscribe(new Subscription() { @Override public void cancel() { @@ -1005,7 +1019,7 @@ public void cancel() { public void request(long n) { } }); - ref.set(observer); + ref.set(subscriber); } }) .test(); @@ -1019,9 +1033,9 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - Subscriber<Object> o = ref.get(); - o.onNext(1); - o.onError(ex); + Subscriber<Object> subscriber = ref.get(); + subscriber.onNext(1); + subscriber.onError(ex); } }; @@ -1073,9 +1087,9 @@ public void supplierMainAndBoundaryBothError() { TestSubscriber<Flowable<Object>> ts = Flowable.error(new TestException("main")) .window(Functions.justCallable(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - ref.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + ref.set(subscriber); } })) .test(); @@ -1106,16 +1120,16 @@ public void supplierMainCompleteBoundaryErrorRace() { TestSubscriber<Flowable<Object>> ts = new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - refMain.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + refMain.set(subscriber); } } .window(Functions.justCallable(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - ref.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + ref.set(subscriber); } })) .test(); @@ -1156,16 +1170,16 @@ public void supplierMainNextBoundaryNextRace() { TestSubscriber<Flowable<Object>> ts = new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - refMain.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + refMain.set(subscriber); } } .window(Functions.justCallable(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - ref.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + ref.set(subscriber); } })) .test(); @@ -1199,16 +1213,16 @@ public void supplierTakeOneAnotherBoundary() { TestSubscriber<Flowable<Object>> ts = new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - refMain.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + refMain.set(subscriber); } } .window(Functions.justCallable(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - ref.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + ref.set(subscriber); } })) .test(); @@ -1231,16 +1245,16 @@ public void supplierDisposeMainBoundaryCompleteRace() { final TestSubscriber<Flowable<Object>> ts = new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - refMain.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + refMain.set(subscriber); } } .window(Functions.justCallable(new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { + protected void subscribeActual(Subscriber<? super Object> subscriber) { final AtomicInteger counter = new AtomicInteger(); - observer.onSubscribe(new Subscription() { + subscriber.onSubscribe(new Subscription() { @Override public void cancel() { @@ -1254,7 +1268,7 @@ public void cancel() { public void request(long n) { } }); - ref.set(observer); + ref.set(subscriber); } })) .test(); @@ -1268,9 +1282,9 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - Subscriber<Object> o = ref.get(); - o.onNext(1); - o.onComplete(); + Subscriber<Object> subscriber = ref.get(); + subscriber.onNext(1); + subscriber.onComplete(); } }; @@ -1290,9 +1304,9 @@ public void supplierDisposeMainBoundaryErrorRace() { final TestSubscriber<Flowable<Object>> ts = new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - refMain.set(observer); + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + refMain.set(subscriber); } } .window(new Callable<Flowable<Object>>() { @@ -1304,9 +1318,9 @@ public Flowable<Object> call() throws Exception { } return (new Flowable<Object>() { @Override - protected void subscribeActual(Subscriber<? super Object> observer) { + protected void subscribeActual(Subscriber<? super Object> subscriber) { final AtomicInteger counter = new AtomicInteger(); - observer.onSubscribe(new Subscription() { + subscriber.onSubscribe(new Subscription() { @Override public void cancel() { @@ -1320,7 +1334,7 @@ public void cancel() { public void request(long n) { } }); - ref.set(observer); + ref.set(subscriber); } }); } @@ -1336,9 +1350,9 @@ public void run() { Runnable r2 = new Runnable() { @Override public void run() { - Subscriber<Object> o = ref.get(); - o.onNext(1); - o.onError(ex); + Subscriber<Object> subscriber = ref.get(); + subscriber.onNext(1); + subscriber.onError(ex); } }; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java index 32f6443233..aeb5381da7 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java @@ -204,7 +204,7 @@ public void testBackpressureOuter() { final List<Integer> list = new ArrayList<Integer>(); - final Subscriber<Integer> o = TestHelper.mockSubscriber(); + final Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); source.subscribe(new DefaultSubscriber<Flowable<Integer>>() { @Override @@ -220,28 +220,28 @@ public void onNext(Integer t) { } @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }); } @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }); assertEquals(Arrays.asList(1, 2, 3), list); - verify(o, never()).onError(any(Throwable.class)); - verify(o, times(1)).onComplete(); // 1 inner + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); // 1 inner } public static Flowable<Integer> hotStream() { @@ -343,22 +343,22 @@ public void dispose() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Flowable<Object>>>() { @Override - public Flowable<Flowable<Object>> apply(Flowable<Object> o) throws Exception { - return o.window(1); + public Flowable<Flowable<Object>> apply(Flowable<Object> f) throws Exception { + return f.window(1); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Flowable<Object>>>() { @Override - public Flowable<Flowable<Object>> apply(Flowable<Object> o) throws Exception { - return o.window(2, 1); + public Flowable<Flowable<Object>> apply(Flowable<Object> f) throws Exception { + return f.window(2, 1); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Flowable<Object>>>() { @Override - public Flowable<Flowable<Object>> apply(Flowable<Object> o) throws Exception { - return o.window(1, 2); + public Flowable<Flowable<Object>> apply(Flowable<Object> f) throws Exception { + return f.window(1, 2); } }); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java index 561deaf7bb..c1d825afed 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java @@ -49,24 +49,24 @@ public void testFlowableBasedOpenerAndCloser() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, "one", 10); - push(observer, "two", 60); - push(observer, "three", 110); - push(observer, "four", 160); - push(observer, "five", 210); - complete(observer, 500); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, "one", 10); + push(subscriber, "two", 60); + push(subscriber, "three", 110); + push(subscriber, "four", 160); + push(subscriber, "five", 210); + complete(subscriber, 500); } }); Flowable<Object> openings = Flowable.unsafeCreate(new Publisher<Object>() { @Override - public void subscribe(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, new Object(), 50); - push(observer, new Object(), 200); - complete(observer, 250); + public void subscribe(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, new Object(), 50); + push(subscriber, new Object(), 200); + complete(subscriber, 250); } }); @@ -75,10 +75,10 @@ public void subscribe(Subscriber<? super Object> observer) { public Flowable<Object> apply(Object opening) { return Flowable.unsafeCreate(new Publisher<Object>() { @Override - public void subscribe(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, new Object(), 100); - complete(observer, 101); + public void subscribe(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, new Object(), 100); + complete(subscriber, 101); } }); } @@ -100,14 +100,14 @@ public void testFlowableBasedCloser() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, "one", 10); - push(observer, "two", 60); - push(observer, "three", 110); - push(observer, "four", 160); - push(observer, "five", 210); - complete(observer, 250); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, "one", 10); + push(subscriber, "two", 60); + push(subscriber, "three", 110); + push(subscriber, "four", 160); + push(subscriber, "five", 210); + complete(subscriber, 250); } }); @@ -117,16 +117,16 @@ public void subscribe(Subscriber<? super String> observer) { public Flowable<Object> call() { return Flowable.unsafeCreate(new Publisher<Object>() { @Override - public void subscribe(Subscriber<? super Object> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); int c = calls++; if (c == 0) { - push(observer, new Object(), 100); + push(subscriber, new Object(), 100); } else if (c == 1) { - push(observer, new Object(), 100); + push(subscriber, new Object(), 100); } else { - complete(observer, 101); + complete(subscriber, 101); } } }); @@ -151,20 +151,20 @@ private List<String> list(String... args) { return list; } - private <T> void push(final Subscriber<T> observer, final T value, int delay) { + private <T> void push(final Subscriber<T> subscriber, final T value, int delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onNext(value); + subscriber.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } - private void complete(final Subscriber<?> observer, int delay) { + private void complete(final Subscriber<?> subscriber, int delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onComplete(); + subscriber.onComplete(); } }, delay, TimeUnit.MILLISECONDS); } @@ -300,8 +300,8 @@ public Flowable<Integer> apply(Flowable<Integer> v) throws Exception { public void badSourceCallable() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Object>, Object>() { @Override - public Object apply(Flowable<Object> o) throws Exception { - return o.window(Flowable.just(1), Functions.justFunction(Flowable.never())); + public Object apply(Flowable<Object> f) throws Exception { + return f.window(Flowable.just(1), Functions.justFunction(Flowable.never())); } }, false, 1, 1, (Object[])null); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java index 019c2d101f..296c973963 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java @@ -27,6 +27,7 @@ import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.*; import io.reactivex.schedulers.*; import io.reactivex.subscribers.*; @@ -50,14 +51,14 @@ public void testTimedAndCount() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, "one", 10); - push(observer, "two", 90); - push(observer, "three", 110); - push(observer, "four", 190); - push(observer, "five", 210); - complete(observer, 250); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, "one", 10); + push(subscriber, "two", 90); + push(subscriber, "three", 110); + push(subscriber, "four", 190); + push(subscriber, "five", 210); + complete(subscriber, 250); } }); @@ -84,14 +85,14 @@ public void testTimed() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - push(observer, "one", 98); - push(observer, "two", 99); - push(observer, "three", 99); // FIXME happens after the window is open - push(observer, "four", 101); - push(observer, "five", 102); - complete(observer, 150); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + push(subscriber, "one", 98); + push(subscriber, "two", 99); + push(subscriber, "three", 99); // FIXME happens after the window is open + push(subscriber, "four", 101); + push(subscriber, "five", 102); + complete(subscriber, 150); } }); @@ -115,20 +116,20 @@ private List<String> list(String... args) { return list; } - private <T> void push(final Subscriber<T> observer, final T value, int delay) { + private <T> void push(final Subscriber<T> subscriber, final T value, int delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onNext(value); + subscriber.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } - private void complete(final Subscriber<?> observer, int delay) { + private void complete(final Subscriber<?> subscriber, int delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { - observer.onComplete(); + subscriber.onComplete(); } }, delay, TimeUnit.MILLISECONDS); } @@ -366,47 +367,68 @@ public void timeskipOverlapping() { @Test public void exactOnError() { - TestScheduler scheduler = new TestScheduler(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestScheduler scheduler = new TestScheduler(); - PublishProcessor<Integer> pp = PublishProcessor.create(); + PublishProcessor<Integer> pp = PublishProcessor.create(); - TestSubscriber<Integer> ts = pp.window(1, 1, TimeUnit.SECONDS, scheduler) - .flatMap(Functions.<Flowable<Integer>>identity()) - .test(); + TestSubscriber<Integer> ts = pp.window(1, 1, TimeUnit.SECONDS, scheduler) + .flatMap(Functions.<Flowable<Integer>>identity()) + .test(); + + pp.onError(new TestException()); - pp.onError(new TestException()); + ts.assertFailure(TestException.class); - ts.assertFailure(TestException.class); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void overlappingOnError() { - TestScheduler scheduler = new TestScheduler(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestScheduler scheduler = new TestScheduler(); - PublishProcessor<Integer> pp = PublishProcessor.create(); + PublishProcessor<Integer> pp = PublishProcessor.create(); - TestSubscriber<Integer> ts = pp.window(2, 1, TimeUnit.SECONDS, scheduler) - .flatMap(Functions.<Flowable<Integer>>identity()) - .test(); + TestSubscriber<Integer> ts = pp.window(2, 1, TimeUnit.SECONDS, scheduler) + .flatMap(Functions.<Flowable<Integer>>identity()) + .test(); + + pp.onError(new TestException()); - pp.onError(new TestException()); + ts.assertFailure(TestException.class); - ts.assertFailure(TestException.class); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void skipOnError() { - TestScheduler scheduler = new TestScheduler(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestScheduler scheduler = new TestScheduler(); - PublishProcessor<Integer> pp = PublishProcessor.create(); + PublishProcessor<Integer> pp = PublishProcessor.create(); - TestSubscriber<Integer> ts = pp.window(1, 2, TimeUnit.SECONDS, scheduler) - .flatMap(Functions.<Flowable<Integer>>identity()) - .test(); + TestSubscriber<Integer> ts = pp.window(1, 2, TimeUnit.SECONDS, scheduler) + .flatMap(Functions.<Flowable<Integer>>identity()) + .test(); + + pp.onError(new TestException()); - pp.onError(new TestException()); + ts.assertFailure(TestException.class); - ts.assertFailure(TestException.class); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -484,16 +506,23 @@ public void skipBackpressure2() { @Test public void overlapBackpressure2() { - TestScheduler scheduler = new TestScheduler(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestScheduler scheduler = new TestScheduler(); - PublishProcessor<Integer> pp = PublishProcessor.create(); + PublishProcessor<Integer> pp = PublishProcessor.create(); - TestSubscriber<Flowable<Integer>> ts = pp.window(2, 1, TimeUnit.SECONDS, scheduler) - .test(1L); + TestSubscriber<Flowable<Integer>> ts = pp.window(2, 1, TimeUnit.SECONDS, scheduler) + .test(1L); - scheduler.advanceTimeBy(2, TimeUnit.SECONDS); + scheduler.advanceTimeBy(2, TimeUnit.SECONDS); - ts.assertError(MissingBackpressureException.class); + ts.assertError(MissingBackpressureException.class); + + TestHelper.assertError(errors, 0, MissingBackpressureException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java index 360aa9c3bc..e87ff9fe50 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java @@ -51,35 +51,35 @@ public void testSimple() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> other = PublishProcessor.create(); - Subscriber<Integer> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); Flowable<Integer> result = source.withLatestFrom(other, COMBINER); - result.subscribe(o); + result.subscribe(subscriber); source.onNext(1); - inOrder.verify(o, never()).onNext(anyInt()); + inOrder.verify(subscriber, never()).onNext(anyInt()); other.onNext(1); - inOrder.verify(o, never()).onNext(anyInt()); + inOrder.verify(subscriber, never()).onNext(anyInt()); source.onNext(2); - inOrder.verify(o).onNext((2 << 8) + 1); + inOrder.verify(subscriber).onNext((2 << 8) + 1); other.onNext(2); - inOrder.verify(o, never()).onNext(anyInt()); + inOrder.verify(subscriber, never()).onNext(anyInt()); other.onComplete(); - inOrder.verify(o, never()).onComplete(); + inOrder.verify(subscriber, never()).onComplete(); source.onNext(3); - inOrder.verify(o).onNext((3 << 8) + 2); + inOrder.verify(subscriber).onNext((3 << 8) + 2); source.onComplete(); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -641,12 +641,12 @@ public void manyErrors() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onError(new TestException("First")); - observer.onNext(1); - observer.onError(new TestException("Second")); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onError(new TestException("First")); + subscriber.onNext(1); + subscriber.onError(new TestException("Second")); + subscriber.onComplete(); } }.withLatestFrom(Flowable.just(2), Flowable.just(3), new Function3<Integer, Integer, Integer, Object>() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipCompletionTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipCompletionTest.java index 546fdfe62b..6c46093017 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipCompletionTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipCompletionTest.java @@ -35,7 +35,7 @@ public class FlowableZipCompletionTest { PublishProcessor<String> s2; Flowable<String> zipped; - Subscriber<String> observer; + Subscriber<String> subscriber; InOrder inOrder; @Before @@ -51,10 +51,10 @@ public String apply(String t1, String t2) { s2 = PublishProcessor.create(); zipped = Flowable.zip(s1, s2, concat2Strings); - observer = TestHelper.mockSubscriber(); - inOrder = inOrder(observer); + subscriber = TestHelper.mockSubscriber(); + inOrder = inOrder(subscriber); - zipped.subscribe(observer); + zipped.subscribe(subscriber); } @Test @@ -63,10 +63,10 @@ public void testFirstCompletesThenSecondInfinite() { s1.onNext("b"); s1.onComplete(); s2.onNext("1"); - inOrder.verify(observer, times(1)).onNext("a-1"); + inOrder.verify(subscriber, times(1)).onNext("a-1"); s2.onNext("2"); - inOrder.verify(observer, times(1)).onNext("b-2"); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("b-2"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -75,11 +75,11 @@ public void testSecondInfiniteThenFirstCompletes() { s2.onNext("1"); s2.onNext("2"); s1.onNext("a"); - inOrder.verify(observer, times(1)).onNext("a-1"); + inOrder.verify(subscriber, times(1)).onNext("a-1"); s1.onNext("b"); - inOrder.verify(observer, times(1)).onNext("b-2"); + inOrder.verify(subscriber, times(1)).onNext("b-2"); s1.onComplete(); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -89,10 +89,10 @@ public void testSecondCompletesThenFirstInfinite() { s2.onNext("2"); s2.onComplete(); s1.onNext("a"); - inOrder.verify(observer, times(1)).onNext("a-1"); + inOrder.verify(subscriber, times(1)).onNext("a-1"); s1.onNext("b"); - inOrder.verify(observer, times(1)).onNext("b-2"); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("b-2"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -101,11 +101,11 @@ public void testFirstInfiniteThenSecondCompletes() { s1.onNext("a"); s1.onNext("b"); s2.onNext("1"); - inOrder.verify(observer, times(1)).onNext("a-1"); + inOrder.verify(subscriber, times(1)).onNext("a-1"); s2.onNext("2"); - inOrder.verify(observer, times(1)).onNext("b-2"); + inOrder.verify(subscriber, times(1)).onNext("b-2"); s2.onComplete(); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipIterableTest.java index c273d8be14..a86de18f52 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipIterableTest.java @@ -38,7 +38,7 @@ public class FlowableZipIterableTest { PublishProcessor<String> s2; Flowable<String> zipped; - Subscriber<String> observer; + Subscriber<String> subscriber; InOrder inOrder; @Before @@ -54,10 +54,10 @@ public String apply(String t1, String t2) { s2 = PublishProcessor.create(); zipped = Flowable.zip(s1, s2, concat2Strings); - observer = TestHelper.mockSubscriber(); - inOrder = inOrder(observer); + subscriber = TestHelper.mockSubscriber(); + inOrder = inOrder(subscriber); - zipped.subscribe(observer); + zipped.subscribe(subscriber); } BiFunction<Object, Object, String> zipr2 = new BiFunction<Object, Object, String>() { @@ -81,24 +81,24 @@ public String apply(Object t1, Object t2, Object t3) { public void testZipIterableSameSize() { PublishProcessor<String> r1 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> o = TestHelper.mockSubscriber(); - InOrder io = inOrder(o); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder io = inOrder(subscriber); Iterable<String> r2 = Arrays.asList("1", "2", "3"); - r1.zipWith(r2, zipr2).subscribe(o); + r1.zipWith(r2, zipr2).subscribe(subscriber); r1.onNext("one-"); r1.onNext("two-"); r1.onNext("three-"); r1.onComplete(); - io.verify(o).onNext("one-1"); - io.verify(o).onNext("two-2"); - io.verify(o).onNext("three-3"); - io.verify(o).onComplete(); + io.verify(subscriber).onNext("one-1"); + io.verify(subscriber).onNext("two-2"); + io.verify(subscriber).onNext("three-3"); + io.verify(subscriber).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @@ -106,19 +106,19 @@ public void testZipIterableSameSize() { public void testZipIterableEmptyFirstSize() { PublishProcessor<String> r1 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> o = TestHelper.mockSubscriber(); - InOrder io = inOrder(o); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder io = inOrder(subscriber); Iterable<String> r2 = Arrays.asList("1", "2", "3"); - r1.zipWith(r2, zipr2).subscribe(o); + r1.zipWith(r2, zipr2).subscribe(subscriber); r1.onComplete(); - io.verify(o).onComplete(); + io.verify(subscriber).onComplete(); - verify(o, never()).onNext(any(String.class)); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any(String.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @@ -126,44 +126,44 @@ public void testZipIterableEmptyFirstSize() { public void testZipIterableEmptySecond() { PublishProcessor<String> r1 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> o = TestHelper.mockSubscriber(); - InOrder io = inOrder(o); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder io = inOrder(subscriber); Iterable<String> r2 = Arrays.asList(); - r1.zipWith(r2, zipr2).subscribe(o); + r1.zipWith(r2, zipr2).subscribe(subscriber); r1.onNext("one-"); r1.onNext("two-"); r1.onNext("three-"); r1.onComplete(); - io.verify(o).onComplete(); + io.verify(subscriber).onComplete(); - verify(o, never()).onNext(any(String.class)); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any(String.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testZipIterableFirstShorter() { PublishProcessor<String> r1 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> o = TestHelper.mockSubscriber(); - InOrder io = inOrder(o); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder io = inOrder(subscriber); Iterable<String> r2 = Arrays.asList("1", "2", "3"); - r1.zipWith(r2, zipr2).subscribe(o); + r1.zipWith(r2, zipr2).subscribe(subscriber); r1.onNext("one-"); r1.onNext("two-"); r1.onComplete(); - io.verify(o).onNext("one-1"); - io.verify(o).onNext("two-2"); - io.verify(o).onComplete(); + io.verify(subscriber).onNext("one-1"); + io.verify(subscriber).onNext("two-2"); + io.verify(subscriber).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @@ -171,23 +171,23 @@ public void testZipIterableFirstShorter() { public void testZipIterableSecondShorter() { PublishProcessor<String> r1 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> o = TestHelper.mockSubscriber(); - InOrder io = inOrder(o); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder io = inOrder(subscriber); Iterable<String> r2 = Arrays.asList("1", "2"); - r1.zipWith(r2, zipr2).subscribe(o); + r1.zipWith(r2, zipr2).subscribe(subscriber); r1.onNext("one-"); r1.onNext("two-"); r1.onNext("three-"); r1.onComplete(); - io.verify(o).onNext("one-1"); - io.verify(o).onNext("two-2"); - io.verify(o).onComplete(); + io.verify(subscriber).onNext("one-1"); + io.verify(subscriber).onNext("two-2"); + io.verify(subscriber).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @@ -195,22 +195,22 @@ public void testZipIterableSecondShorter() { public void testZipIterableFirstThrows() { PublishProcessor<String> r1 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> o = TestHelper.mockSubscriber(); - InOrder io = inOrder(o); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder io = inOrder(subscriber); Iterable<String> r2 = Arrays.asList("1", "2", "3"); - r1.zipWith(r2, zipr2).subscribe(o); + r1.zipWith(r2, zipr2).subscribe(subscriber); r1.onNext("one-"); r1.onNext("two-"); r1.onError(new TestException()); - io.verify(o).onNext("one-1"); - io.verify(o).onNext("two-2"); - io.verify(o).onError(any(TestException.class)); + io.verify(subscriber).onNext("one-1"); + io.verify(subscriber).onNext("two-2"); + io.verify(subscriber).onError(any(TestException.class)); - verify(o, never()).onComplete(); + verify(subscriber, never()).onComplete(); } @@ -218,8 +218,8 @@ public void testZipIterableFirstThrows() { public void testZipIterableIteratorThrows() { PublishProcessor<String> r1 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> o = TestHelper.mockSubscriber(); - InOrder io = inOrder(o); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder io = inOrder(subscriber); Iterable<String> r2 = new Iterable<String>() { @Override @@ -228,16 +228,16 @@ public Iterator<String> iterator() { } }; - r1.zipWith(r2, zipr2).subscribe(o); + r1.zipWith(r2, zipr2).subscribe(subscriber); r1.onNext("one-"); r1.onNext("two-"); r1.onError(new TestException()); - io.verify(o).onError(any(TestException.class)); + io.verify(subscriber).onError(any(TestException.class)); - verify(o, never()).onComplete(); - verify(o, never()).onNext(any(String.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any(String.class)); } @@ -245,8 +245,8 @@ public Iterator<String> iterator() { public void testZipIterableHasNextThrows() { PublishProcessor<String> r1 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> o = TestHelper.mockSubscriber(); - InOrder io = inOrder(o); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder io = inOrder(subscriber); Iterable<String> r2 = new Iterable<String>() { @@ -279,15 +279,15 @@ public void remove() { }; - r1.zipWith(r2, zipr2).subscribe(o); + r1.zipWith(r2, zipr2).subscribe(subscriber); r1.onNext("one-"); r1.onError(new TestException()); - io.verify(o).onNext("one-1"); - io.verify(o).onError(any(TestException.class)); + io.verify(subscriber).onNext("one-1"); + io.verify(subscriber).onError(any(TestException.class)); - verify(o, never()).onComplete(); + verify(subscriber, never()).onComplete(); } @@ -295,8 +295,8 @@ public void remove() { public void testZipIterableNextThrows() { PublishProcessor<String> r1 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> o = TestHelper.mockSubscriber(); - InOrder io = inOrder(o); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + InOrder io = inOrder(subscriber); Iterable<String> r2 = new Iterable<String>() { @@ -323,14 +323,14 @@ public void remove() { }; - r1.zipWith(r2, zipr2).subscribe(o); + r1.zipWith(r2, zipr2).subscribe(subscriber); r1.onError(new TestException()); - io.verify(o).onError(any(TestException.class)); + io.verify(subscriber).onError(any(TestException.class)); - verify(o, never()).onNext(any(String.class)); - verify(o, never()).onComplete(); + verify(subscriber, never()).onNext(any(String.class)); + verify(subscriber, never()).onComplete(); } @@ -353,12 +353,12 @@ public String apply(Integer t1) { @Test public void testTake2() { - Flowable<Integer> o = Flowable.just(1, 2, 3, 4, 5); + Flowable<Integer> f = Flowable.just(1, 2, 3, 4, 5); Iterable<String> it = Arrays.asList("a", "b", "c", "d", "e"); SquareStr squareStr = new SquareStr(); - o.map(squareStr).zipWith(it, concat2Strings).take(2).subscribe(printer); + f.map(squareStr).zipWith(it, concat2Strings).take(2).subscribe(printer); assertEquals(2, squareStr.counter.get()); } @@ -377,8 +377,8 @@ public Object apply(Integer a, Integer b) throws Exception { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Integer>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Integer> o) throws Exception { - return o.zipWith(Arrays.asList(1), new BiFunction<Integer, Integer, Object>() { + public Flowable<Object> apply(Flowable<Integer> f) throws Exception { + return f.zipWith(Arrays.asList(1), new BiFunction<Integer, Integer, Object>() { @Override public Object apply(Integer a, Integer b) throws Exception { return a + b; @@ -406,13 +406,13 @@ public void badSource() { try { new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onComplete(); - observer.onNext(2); - observer.onError(new TestException()); - observer.onComplete(); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(1); + subscriber.onComplete(); + subscriber.onNext(2); + subscriber.onError(new TestException()); + subscriber.onComplete(); } } .zipWith(Arrays.asList(1), new BiFunction<Integer, Integer, Object>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java index d7304d26ff..b02fa664fe 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java @@ -43,7 +43,7 @@ public class FlowableZipTest { PublishProcessor<String> s2; Flowable<String> zipped; - Subscriber<String> observer; + Subscriber<String> subscriber; InOrder inOrder; @Before @@ -59,10 +59,10 @@ public String apply(String t1, String t2) { s2 = PublishProcessor.create(); zipped = Flowable.zip(s1, s2, concat2Strings); - observer = TestHelper.mockSubscriber(); - inOrder = inOrder(observer); + subscriber = TestHelper.mockSubscriber(); + inOrder = inOrder(subscriber); - zipped.subscribe(observer); + zipped.subscribe(subscriber); } @SuppressWarnings("unchecked") @@ -72,16 +72,16 @@ public void testCollectionSizeDifferentThanFunction() { //Function3<String, Integer, int[], String> /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); @SuppressWarnings("rawtypes") Collection ws = java.util.Collections.singleton(Flowable.just("one", "two")); Flowable<String> w = Flowable.zip(ws, zipr); - w.subscribe(observer); + w.subscribe(subscriber); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, never()).onNext(any(String.class)); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, never()).onNext(any(String.class)); } @Test @@ -99,18 +99,18 @@ public void testStartpingDifferentLengthFlowableSequences1() { /* simulate sending data */ // once for w1 - w1.observer.onNext("1a"); - w1.observer.onComplete(); + w1.subscriber.onNext("1a"); + w1.subscriber.onComplete(); // twice for w2 - w2.observer.onNext("2a"); - w2.observer.onNext("2b"); - w2.observer.onComplete(); + w2.subscriber.onNext("2a"); + w2.subscriber.onNext("2b"); + w2.subscriber.onComplete(); // 4 times for w3 - w3.observer.onNext("3a"); - w3.observer.onNext("3b"); - w3.observer.onNext("3c"); - w3.observer.onNext("3d"); - w3.observer.onComplete(); + w3.subscriber.onNext("3a"); + w3.subscriber.onNext("3b"); + w3.subscriber.onNext("3c"); + w3.subscriber.onNext("3d"); + w3.subscriber.onComplete(); /* we should have been called 1 time on the Subscriber */ InOrder io = inOrder(w); @@ -132,18 +132,18 @@ public void testStartpingDifferentLengthFlowableSequences2() { /* simulate sending data */ // 4 times for w1 - w1.observer.onNext("1a"); - w1.observer.onNext("1b"); - w1.observer.onNext("1c"); - w1.observer.onNext("1d"); - w1.observer.onComplete(); + w1.subscriber.onNext("1a"); + w1.subscriber.onNext("1b"); + w1.subscriber.onNext("1c"); + w1.subscriber.onNext("1d"); + w1.subscriber.onComplete(); // twice for w2 - w2.observer.onNext("2a"); - w2.observer.onNext("2b"); - w2.observer.onComplete(); + w2.subscriber.onNext("2a"); + w2.subscriber.onNext("2b"); + w2.subscriber.onComplete(); // 1 times for w3 - w3.observer.onNext("3a"); - w3.observer.onComplete(); + w3.subscriber.onNext("3a"); + w3.subscriber.onComplete(); /* we should have been called 1 time on the Subscriber */ InOrder io = inOrder(w); @@ -178,32 +178,32 @@ public void testAggregatorSimple() { PublishProcessor<String> r1 = PublishProcessor.create(); PublishProcessor<String> r2 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable.zip(r1, r2, zipr2).subscribe(observer); + Flowable.zip(r1, r2, zipr2).subscribe(subscriber); /* simulate the Flowables pushing data into the aggregator */ r1.onNext("hello"); r2.onNext("world"); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - inOrder.verify(observer, times(1)).onNext("helloworld"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("helloworld"); r1.onNext("hello "); r2.onNext("again"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - inOrder.verify(observer, times(1)).onNext("hello again"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("hello again"); r1.onComplete(); r2.onComplete(); - inOrder.verify(observer, never()).onNext(anyString()); - verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, never()).onNext(anyString()); + verify(subscriber, times(1)).onComplete(); } @Test @@ -213,26 +213,26 @@ public void testAggregatorDifferentSizedResultsWithOnComplete() { PublishProcessor<String> r1 = PublishProcessor.create(); PublishProcessor<String> r2 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); - Flowable.zip(r1, r2, zipr2).subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + Flowable.zip(r1, r2, zipr2).subscribe(subscriber); /* simulate the Flowables pushing data into the aggregator */ r1.onNext("hello"); r2.onNext("world"); r2.onComplete(); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); - inOrder.verify(observer, never()).onError(any(Throwable.class)); - inOrder.verify(observer, times(1)).onNext("helloworld"); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("helloworld"); + inOrder.verify(subscriber, times(1)).onComplete(); r1.onNext("hi"); r1.onComplete(); - inOrder.verify(observer, never()).onError(any(Throwable.class)); - inOrder.verify(observer, never()).onComplete(); - inOrder.verify(observer, never()).onNext(anyString()); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onComplete(); + inOrder.verify(subscriber, never()).onNext(anyString()); } @Test @@ -240,27 +240,27 @@ public void testAggregateMultipleTypes() { PublishProcessor<String> r1 = PublishProcessor.create(); PublishProcessor<Integer> r2 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable.zip(r1, r2, zipr2).subscribe(observer); + Flowable.zip(r1, r2, zipr2).subscribe(subscriber); /* simulate the Flowables pushing data into the aggregator */ r1.onNext("hello"); r2.onNext(1); r2.onComplete(); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); - inOrder.verify(observer, never()).onError(any(Throwable.class)); - inOrder.verify(observer, times(1)).onNext("hello1"); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onNext("hello1"); + inOrder.verify(subscriber, times(1)).onComplete(); r1.onNext("hi"); r1.onComplete(); - inOrder.verify(observer, never()).onError(any(Throwable.class)); - inOrder.verify(observer, never()).onComplete(); - inOrder.verify(observer, never()).onNext(anyString()); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onComplete(); + inOrder.verify(subscriber, never()).onNext(anyString()); } @Test @@ -269,18 +269,18 @@ public void testAggregate3Types() { PublishProcessor<Integer> r2 = PublishProcessor.create(); PublishProcessor<List<Integer>> r3 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable.zip(r1, r2, r3, zipr3).subscribe(observer); + Flowable.zip(r1, r2, r3, zipr3).subscribe(subscriber); /* simulate the Flowables pushing data into the aggregator */ r1.onNext("hello"); r2.onNext(2); r3.onNext(Arrays.asList(5, 6, 7)); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, times(1)).onNext("hello2[5, 6, 7]"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, times(1)).onNext("hello2[5, 6, 7]"); } @Test @@ -288,9 +288,9 @@ public void testAggregatorsWithDifferentSizesAndTiming() { PublishProcessor<String> r1 = PublishProcessor.create(); PublishProcessor<String> r2 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable.zip(r1, r2, zipr2).subscribe(observer); + Flowable.zip(r1, r2, zipr2).subscribe(subscriber); /* simulate the Flowables pushing data into the aggregator */ r1.onNext("one"); @@ -298,24 +298,24 @@ public void testAggregatorsWithDifferentSizesAndTiming() { r1.onNext("three"); r2.onNext("A"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, times(1)).onNext("oneA"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, times(1)).onNext("oneA"); r1.onNext("four"); r1.onComplete(); r2.onNext("B"); - verify(observer, times(1)).onNext("twoB"); + verify(subscriber, times(1)).onNext("twoB"); r2.onNext("C"); - verify(observer, times(1)).onNext("threeC"); + verify(subscriber, times(1)).onNext("threeC"); r2.onNext("D"); - verify(observer, times(1)).onNext("fourD"); + verify(subscriber, times(1)).onNext("fourD"); r2.onNext("E"); - verify(observer, never()).onNext("E"); + verify(subscriber, never()).onNext("E"); r2.onComplete(); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -323,26 +323,26 @@ public void testAggregatorError() { PublishProcessor<String> r1 = PublishProcessor.create(); PublishProcessor<String> r2 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable.zip(r1, r2, zipr2).subscribe(observer); + Flowable.zip(r1, r2, zipr2).subscribe(subscriber); /* simulate the Flowables pushing data into the aggregator */ r1.onNext("hello"); r2.onNext("world"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, times(1)).onNext("helloworld"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, times(1)).onNext("helloworld"); r1.onError(new RuntimeException("")); r1.onNext("hello"); r2.onNext("again"); - verify(observer, times(1)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); + verify(subscriber, times(1)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); // we don't want to be called again after an error - verify(observer, times(0)).onNext("helloagain"); + verify(subscriber, times(0)).onNext("helloagain"); } @Test @@ -350,8 +350,8 @@ public void testAggregatorUnsubscribe() { PublishProcessor<String> r1 = PublishProcessor.create(); PublishProcessor<String> r2 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); Flowable.zip(r1, r2, zipr2).subscribe(ts); @@ -359,18 +359,18 @@ public void testAggregatorUnsubscribe() { r1.onNext("hello"); r2.onNext("world"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); - verify(observer, times(1)).onNext("helloworld"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); + verify(subscriber, times(1)).onNext("helloworld"); ts.dispose(); r1.onNext("hello"); r2.onNext("again"); - verify(observer, times(0)).onError(any(Throwable.class)); - verify(observer, never()).onComplete(); + verify(subscriber, times(0)).onError(any(Throwable.class)); + verify(subscriber, never()).onComplete(); // we don't want to be called again after an error - verify(observer, times(0)).onNext("helloagain"); + verify(subscriber, times(0)).onNext("helloagain"); } @Test @@ -378,9 +378,9 @@ public void testAggregatorEarlyCompletion() { PublishProcessor<String> r1 = PublishProcessor.create(); PublishProcessor<String> r2 = PublishProcessor.create(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); - Flowable.zip(r1, r2, zipr2).subscribe(observer); + Flowable.zip(r1, r2, zipr2).subscribe(subscriber); /* simulate the Flowables pushing data into the aggregator */ r1.onNext("one"); @@ -388,17 +388,17 @@ public void testAggregatorEarlyCompletion() { r1.onComplete(); r2.onNext("A"); - InOrder inOrder = inOrder(observer); + InOrder inOrder = inOrder(subscriber); - inOrder.verify(observer, never()).onError(any(Throwable.class)); - inOrder.verify(observer, never()).onComplete(); - inOrder.verify(observer, times(1)).onNext("oneA"); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, never()).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("oneA"); r2.onComplete(); - inOrder.verify(observer, never()).onError(any(Throwable.class)); - inOrder.verify(observer, times(1)).onComplete(); - inOrder.verify(observer, never()).onNext(anyString()); + inOrder.verify(subscriber, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onComplete(); + inOrder.verify(subscriber, never()).onNext(anyString()); } @Test @@ -406,16 +406,16 @@ public void testStart2Types() { BiFunction<String, Integer, String> zipr = getConcatStringIntegerZipr(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> w = Flowable.zip(Flowable.just("one", "two"), Flowable.just(2, 3, 4), zipr); - w.subscribe(observer); + w.subscribe(subscriber); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("one2"); - verify(observer, times(1)).onNext("two3"); - verify(observer, never()).onNext("4"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one2"); + verify(subscriber, times(1)).onNext("two3"); + verify(subscriber, never()).onNext("4"); } @Test @@ -423,27 +423,27 @@ public void testStart3Types() { Function3<String, Integer, int[], String> zipr = getConcatStringIntegerIntArrayZipr(); /* define a Subscriber to receive aggregated events */ - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); Flowable<String> w = Flowable.zip(Flowable.just("one", "two"), Flowable.just(2), Flowable.just(new int[] { 4, 5, 6 }), zipr); - w.subscribe(observer); + w.subscribe(subscriber); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); - verify(observer, times(1)).onNext("one2[4, 5, 6]"); - verify(observer, never()).onNext("two"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one2[4, 5, 6]"); + verify(subscriber, never()).onNext("two"); } @Test public void testOnNextExceptionInvokesOnError() { BiFunction<Integer, Integer, Integer> zipr = getDivideZipr(); - Subscriber<Integer> observer = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); Flowable<Integer> w = Flowable.zip(Flowable.just(10, 20, 30), Flowable.just(0, 1, 2), zipr); - w.subscribe(observer); + w.subscribe(subscriber); - verify(observer, times(1)).onError(any(Throwable.class)); + verify(subscriber, times(1)).onError(any(Throwable.class)); } @Test @@ -453,8 +453,8 @@ public void testOnFirstCompletion() { Subscriber<String> obs = TestHelper.mockSubscriber(); - Flowable<String> o = Flowable.zip(oA, oB, getConcat2Strings()); - o.subscribe(obs); + Flowable<String> f = Flowable.zip(oA, oB, getConcat2Strings()); + f.subscribe(obs); InOrder io = inOrder(obs); @@ -503,8 +503,8 @@ public void testOnErrorTermination() { Subscriber<String> obs = TestHelper.mockSubscriber(); - Flowable<String> o = Flowable.zip(oA, oB, getConcat2Strings()); - o.subscribe(obs); + Flowable<String> f = Flowable.zip(oA, oB, getConcat2Strings()); + f.subscribe(obs); InOrder io = inOrder(obs); @@ -619,13 +619,13 @@ private static String getStringValue(Object o) { private static class TestFlowable implements Publisher<String> { - Subscriber<? super String> observer; + Subscriber<? super String> subscriber; @Override - public void subscribe(Subscriber<? super String> observer) { + public void subscribe(Subscriber<? super String> subscriber) { // just store the variable where it can be accessed so we can manually trigger it - this.observer = observer; - observer.onSubscribe(new BooleanSubscription()); + this.subscriber = subscriber; + subscriber.onSubscribe(new BooleanSubscription()); } } @@ -636,10 +636,10 @@ public void testFirstCompletesThenSecondInfinite() { s1.onNext("b"); s1.onComplete(); s2.onNext("1"); - inOrder.verify(observer, times(1)).onNext("a-1"); + inOrder.verify(subscriber, times(1)).onNext("a-1"); s2.onNext("2"); - inOrder.verify(observer, times(1)).onNext("b-2"); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("b-2"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -648,11 +648,11 @@ public void testSecondInfiniteThenFirstCompletes() { s2.onNext("1"); s2.onNext("2"); s1.onNext("a"); - inOrder.verify(observer, times(1)).onNext("a-1"); + inOrder.verify(subscriber, times(1)).onNext("a-1"); s1.onNext("b"); - inOrder.verify(observer, times(1)).onNext("b-2"); + inOrder.verify(subscriber, times(1)).onNext("b-2"); s1.onComplete(); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -662,10 +662,10 @@ public void testSecondCompletesThenFirstInfinite() { s2.onNext("2"); s2.onComplete(); s1.onNext("a"); - inOrder.verify(observer, times(1)).onNext("a-1"); + inOrder.verify(subscriber, times(1)).onNext("a-1"); s1.onNext("b"); - inOrder.verify(observer, times(1)).onNext("b-2"); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("b-2"); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -674,11 +674,11 @@ public void testFirstInfiniteThenSecondCompletes() { s1.onNext("a"); s1.onNext("b"); s2.onNext("1"); - inOrder.verify(observer, times(1)).onNext("a-1"); + inOrder.verify(subscriber, times(1)).onNext("a-1"); s2.onNext("2"); - inOrder.verify(observer, times(1)).onNext("b-2"); + inOrder.verify(subscriber, times(1)).onNext("b-2"); s2.onComplete(); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -687,14 +687,14 @@ public void testFirstFails() { s2.onNext("a"); s1.onError(new RuntimeException("Forced failure")); - inOrder.verify(observer, times(1)).onError(any(RuntimeException.class)); + inOrder.verify(subscriber, times(1)).onError(any(RuntimeException.class)); s2.onNext("b"); s1.onNext("1"); s1.onNext("2"); - inOrder.verify(observer, never()).onComplete(); - inOrder.verify(observer, never()).onNext(any(String.class)); + inOrder.verify(subscriber, never()).onComplete(); + inOrder.verify(subscriber, never()).onNext(any(String.class)); inOrder.verifyNoMoreInteractions(); } @@ -704,13 +704,13 @@ public void testSecondFails() { s1.onNext("b"); s2.onError(new RuntimeException("Forced failure")); - inOrder.verify(observer, times(1)).onError(any(RuntimeException.class)); + inOrder.verify(subscriber, times(1)).onError(any(RuntimeException.class)); s2.onNext("1"); s2.onNext("2"); - inOrder.verify(observer, never()).onComplete(); - inOrder.verify(observer, never()).onNext(any(String.class)); + inOrder.verify(subscriber, never()).onComplete(); + inOrder.verify(subscriber, never()).onNext(any(String.class)); inOrder.verifyNoMoreInteractions(); } @@ -718,14 +718,14 @@ public void testSecondFails() { public void testStartWithOnCompletedTwice() { // issue: https://groups.google.com/forum/#!topic/rxjava/79cWTv3TFp0 // The problem is the original "zip" implementation does not wrap - // an internal observer with a SafeSubscriber. However, in the "zip", + // an internal subscriber with a SafeSubscriber. However, in the "zip", // it may calls "onComplete" twice. That breaks the Rx contract. // This test tries to emulate this case. // As "TestHelper.mockSubscriber()" will create an instance in the package "rx", - // we need to wrap "TestHelper.mockSubscriber()" with an observer instance + // we need to wrap "TestHelper.mockSubscriber()" with an subscriber instance // which is in the package "rx.operators". - final Subscriber<Integer> observer = TestHelper.mockSubscriber(); + final Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); Flowable.zip(Flowable.just(1), Flowable.just(1), new BiFunction<Integer, Integer, Integer>() { @@ -737,24 +737,24 @@ public Integer apply(Integer a, Integer b) { @Override public void onComplete() { - observer.onComplete(); + subscriber.onComplete(); } @Override public void onError(Throwable e) { - observer.onError(e); + subscriber.onError(e); } @Override public void onNext(Integer args) { - observer.onNext(args); + subscriber.onNext(args); } }); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onNext(2); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, times(1)).onNext(2); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -858,7 +858,7 @@ public void onNext(String s) { public void testEmitNull() { Flowable<Integer> oi = Flowable.just(1, null, 3); Flowable<String> os = Flowable.just("a", "b", null); - Flowable<String> o = Flowable.zip(oi, os, new BiFunction<Integer, String, String>() { + Flowable<String> f = Flowable.zip(oi, os, new BiFunction<Integer, String, String>() { @Override public String apply(Integer t1, String t2) { @@ -868,7 +868,7 @@ public String apply(Integer t1, String t2) { }); final ArrayList<String> list = new ArrayList<String>(); - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String s) { @@ -906,7 +906,7 @@ static String value(Notification notification) { public void testEmitMaterializedNotifications() { Flowable<Notification<Integer>> oi = Flowable.just(1, 2, 3).materialize(); Flowable<Notification<String>> os = Flowable.just("a", "b", "c").materialize(); - Flowable<String> o = Flowable.zip(oi, os, new BiFunction<Notification<Integer>, Notification<String>, String>() { + Flowable<String> f = Flowable.zip(oi, os, new BiFunction<Notification<Integer>, Notification<String>, String>() { @Override public String apply(Notification<Integer> t1, Notification<String> t2) { @@ -916,7 +916,7 @@ public String apply(Notification<Integer> t1, Notification<String> t2) { }); final ArrayList<String> list = new ArrayList<String>(); - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String s) { @@ -935,7 +935,7 @@ public void accept(String s) { @Test public void testStartEmptyFlowables() { - Flowable<String> o = Flowable.zip(Flowable.<Integer> empty(), Flowable.<String> empty(), new BiFunction<Integer, String, String>() { + Flowable<String> f = Flowable.zip(Flowable.<Integer> empty(), Flowable.<String> empty(), new BiFunction<Integer, String, String>() { @Override public String apply(Integer t1, String t2) { @@ -945,7 +945,7 @@ public String apply(Integer t1, String t2) { }); final ArrayList<String> list = new ArrayList<String>(); - o.subscribe(new Consumer<String>() { + f.subscribe(new Consumer<String>() { @Override public void accept(String s) { @@ -963,7 +963,7 @@ public void testStartEmptyList() { final Object invoked = new Object(); Collection<Flowable<Object>> observables = Collections.emptyList(); - Flowable<Object> o = Flowable.zip(observables, new Function<Object[], Object>() { + Flowable<Object> f = Flowable.zip(observables, new Function<Object[], Object>() { @Override public Object apply(final Object[] args) { assertEquals("No argument should have been passed", 0, args.length); @@ -972,7 +972,7 @@ public Object apply(final Object[] args) { }); TestSubscriber<Object> ts = new TestSubscriber<Object>(); - o.subscribe(ts); + f.subscribe(ts); ts.awaitTerminalEvent(200, TimeUnit.MILLISECONDS); ts.assertNoValues(); } @@ -987,7 +987,7 @@ public void testStartEmptyListBlocking() { final Object invoked = new Object(); Collection<Flowable<Object>> observables = Collections.emptyList(); - Flowable<Object> o = Flowable.zip(observables, new Function<Object[], Object>() { + Flowable<Object> f = Flowable.zip(observables, new Function<Object[], Object>() { @Override public Object apply(final Object[] args) { assertEquals("No argument should have been passed", 0, args.length); @@ -995,18 +995,18 @@ public Object apply(final Object[] args) { } }); - o.blockingLast(); + f.blockingLast(); } @Test public void testBackpressureSync() { AtomicInteger generatedA = new AtomicInteger(); AtomicInteger generatedB = new AtomicInteger(); - Flowable<Integer> o1 = createInfiniteFlowable(generatedA); - Flowable<Integer> o2 = createInfiniteFlowable(generatedB); + Flowable<Integer> f1 = createInfiniteFlowable(generatedA); + Flowable<Integer> f2 = createInfiniteFlowable(generatedB); TestSubscriber<String> ts = new TestSubscriber<String>(); - Flowable.zip(o1, o2, new BiFunction<Integer, Integer, String>() { + Flowable.zip(f1, f2, new BiFunction<Integer, Integer, String>() { @Override public String apply(Integer t1, Integer t2) { @@ -1026,11 +1026,11 @@ public String apply(Integer t1, Integer t2) { public void testBackpressureAsync() { AtomicInteger generatedA = new AtomicInteger(); AtomicInteger generatedB = new AtomicInteger(); - Flowable<Integer> o1 = createInfiniteFlowable(generatedA).subscribeOn(Schedulers.computation()); - Flowable<Integer> o2 = createInfiniteFlowable(generatedB).subscribeOn(Schedulers.computation()); + Flowable<Integer> f1 = createInfiniteFlowable(generatedA).subscribeOn(Schedulers.computation()); + Flowable<Integer> f2 = createInfiniteFlowable(generatedB).subscribeOn(Schedulers.computation()); TestSubscriber<String> ts = new TestSubscriber<String>(); - Flowable.zip(o1, o2, new BiFunction<Integer, Integer, String>() { + Flowable.zip(f1, f2, new BiFunction<Integer, Integer, String>() { @Override public String apply(Integer t1, Integer t2) { @@ -1050,11 +1050,11 @@ public String apply(Integer t1, Integer t2) { public void testDownstreamBackpressureRequestsWithFiniteSyncFlowables() { AtomicInteger generatedA = new AtomicInteger(); AtomicInteger generatedB = new AtomicInteger(); - Flowable<Integer> o1 = createInfiniteFlowable(generatedA).take(Flowable.bufferSize() * 2); - Flowable<Integer> o2 = createInfiniteFlowable(generatedB).take(Flowable.bufferSize() * 2); + Flowable<Integer> f1 = createInfiniteFlowable(generatedA).take(Flowable.bufferSize() * 2); + Flowable<Integer> f2 = createInfiniteFlowable(generatedB).take(Flowable.bufferSize() * 2); TestSubscriber<String> ts = new TestSubscriber<String>(); - Flowable.zip(o1, o2, new BiFunction<Integer, Integer, String>() { + Flowable.zip(f1, f2, new BiFunction<Integer, Integer, String>() { @Override public String apply(Integer t1, Integer t2) { @@ -1075,11 +1075,11 @@ public String apply(Integer t1, Integer t2) { public void testDownstreamBackpressureRequestsWithInfiniteAsyncFlowables() { AtomicInteger generatedA = new AtomicInteger(); AtomicInteger generatedB = new AtomicInteger(); - Flowable<Integer> o1 = createInfiniteFlowable(generatedA).subscribeOn(Schedulers.computation()); - Flowable<Integer> o2 = createInfiniteFlowable(generatedB).subscribeOn(Schedulers.computation()); + Flowable<Integer> f1 = createInfiniteFlowable(generatedA).subscribeOn(Schedulers.computation()); + Flowable<Integer> f2 = createInfiniteFlowable(generatedB).subscribeOn(Schedulers.computation()); TestSubscriber<String> ts = new TestSubscriber<String>(); - Flowable.zip(o1, o2, new BiFunction<Integer, Integer, String>() { + Flowable.zip(f1, f2, new BiFunction<Integer, Integer, String>() { @Override public String apply(Integer t1, Integer t2) { @@ -1100,11 +1100,11 @@ public String apply(Integer t1, Integer t2) { public void testDownstreamBackpressureRequestsWithInfiniteSyncFlowables() { AtomicInteger generatedA = new AtomicInteger(); AtomicInteger generatedB = new AtomicInteger(); - Flowable<Integer> o1 = createInfiniteFlowable(generatedA); - Flowable<Integer> o2 = createInfiniteFlowable(generatedB); + Flowable<Integer> f1 = createInfiniteFlowable(generatedA); + Flowable<Integer> f2 = createInfiniteFlowable(generatedB); TestSubscriber<String> ts = new TestSubscriber<String>(); - Flowable.zip(o1, o2, new BiFunction<Integer, Integer, String>() { + Flowable.zip(f1, f2, new BiFunction<Integer, Integer, String>() { @Override public String apply(Integer t1, Integer t2) { @@ -1122,7 +1122,7 @@ public String apply(Integer t1, Integer t2) { } private Flowable<Integer> createInfiniteFlowable(final AtomicInteger generated) { - Flowable<Integer> observable = Flowable.fromIterable(new Iterable<Integer>() { + Flowable<Integer> flowable = Flowable.fromIterable(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @@ -1143,7 +1143,7 @@ public boolean hasNext() { }; } }); - return observable; + return flowable; } Flowable<Integer> OBSERVABLE_OF_5_INTEGERS = OBSERVABLE_OF_5_INTEGERS(new AtomicInteger()); @@ -1152,18 +1152,18 @@ Flowable<Integer> OBSERVABLE_OF_5_INTEGERS(final AtomicInteger numEmitted) { return Flowable.unsafeCreate(new Publisher<Integer>() { @Override - public void subscribe(final Subscriber<? super Integer> o) { + public void subscribe(final Subscriber<? super Integer> subscriber) { BooleanSubscription bs = new BooleanSubscription(); - o.onSubscribe(bs); + subscriber.onSubscribe(bs); for (int i = 1; i <= 5; i++) { if (bs.isCancelled()) { break; } numEmitted.incrementAndGet(); - o.onNext(i); + subscriber.onNext(i); Thread.yield(); } - o.onComplete(); + subscriber.onComplete(); } }); @@ -1173,9 +1173,9 @@ Flowable<Integer> ASYNC_OBSERVABLE_OF_INFINITE_INTEGERS(final CountDownLatch lat return Flowable.unsafeCreate(new Publisher<Integer>() { @Override - public void subscribe(final Subscriber<? super Integer> o) { + public void subscribe(final Subscriber<? super Integer> subscriber) { final BooleanSubscription bs = new BooleanSubscription(); - o.onSubscribe(bs); + subscriber.onSubscribe(bs); Thread t = new Thread(new Runnable() { @Override @@ -1184,10 +1184,10 @@ public void run() { System.out.println("Starting thread: " + Thread.currentThread()); int i = 1; while (!bs.isCancelled()) { - o.onNext(i++); + subscriber.onNext(i++); Thread.yield(); } - o.onComplete(); + subscriber.onComplete(); latch.countDown(); System.out.println("Ending thread: " + Thread.currentThread()); } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionTest.java index 0b082b5899..e1f7886cb3 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionTest.java @@ -122,12 +122,12 @@ public void withPublisherCallAfterTerminalEvent() { try { Flowable<Integer> f = new Flowable<Integer>() { @Override - protected void subscribeActual(Subscriber<? super Integer> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext(1); - observer.onError(new TestException()); - observer.onComplete(); - observer.onNext(2); + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(1); + subscriber.onError(new TestException()); + subscriber.onComplete(); + subscriber.onNext(2); } }; diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnEventTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnEventTest.java index 6df94cbd82..81930eb12c 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnEventTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnEventTest.java @@ -61,11 +61,11 @@ public void onSubscribeCrash() { new Maybe<Integer>() { @Override - protected void subscribeActual(MaybeObserver<? super Integer> s) { - s.onSubscribe(bs); - s.onError(new TestException("Second")); - s.onComplete(); - s.onSuccess(1); + protected void subscribeActual(MaybeObserver<? super Integer> observer) { + observer.onSubscribe(bs); + observer.onError(new TestException("Second")); + observer.onComplete(); + observer.onSuccess(1); } } .doOnSubscribe(new Consumer<Disposable>() { diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java index 28fabf6080..c78a7cf5d7 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java @@ -410,14 +410,14 @@ public Object call() throws Exception { public MaybeSource<Integer> apply(Object v) throws Exception { return Maybe.wrap(new MaybeSource<Integer>() { @Override - public void subscribe(MaybeObserver<? super Integer> s) { + public void subscribe(MaybeObserver<? super Integer> observer) { Disposable d1 = Disposables.empty(); - s.onSubscribe(d1); + observer.onSubscribe(d1); Disposable d2 = Disposables.empty(); - s.onSubscribe(d2); + observer.onSubscribe(d2); assertFalse(d1.isDisposed()); diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java index fb732ff878..b02992e9fc 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java @@ -240,10 +240,10 @@ public void mainErrorAfterInnerError() { try { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onError(new TestException("outer")); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onError(new TestException("outer")); } } .concatMapMaybe( diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java index b5743dd5d7..cdd5326368 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java @@ -155,10 +155,10 @@ public void mainErrorAfterInnerError() { try { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onError(new TestException("outer")); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onError(new TestException("outer")); } } .concatMapSingle( diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java index 72d4af0d52..c8b1bd3bc4 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java @@ -312,10 +312,10 @@ public void innerErrorThenMainError() { try { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onError(new TestException("main")); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onError(new TestException("main")); } } .switchMapCompletable(Functions.justFunction(Completable.error(new TestException("inner")))) diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java index 363f8c0614..3faa98caa5 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java @@ -353,10 +353,10 @@ public void mainErrorAfterTermination() { try { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onError(new TestException("outer")); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onError(new TestException("outer")); } } .switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() { @@ -384,10 +384,10 @@ public void innerErrorAfterTermination() { TestObserver<Integer> to = new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onError(new TestException("outer")); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onError(new TestException("outer")); } } .switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() { diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java index 92ec3c5523..03c38e54de 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java @@ -322,10 +322,10 @@ public void mainErrorAfterTermination() { try { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onError(new TestException("outer")); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onError(new TestException("outer")); } } .switchMapSingle(new Function<Integer, SingleSource<Integer>>() { @@ -353,10 +353,10 @@ public void innerErrorAfterTermination() { TestObserver<Integer> to = new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onError(new TestException("outer")); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onError(new TestException("outer")); } } .switchMapSingle(new Function<Integer, SingleSource<Integer>>() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java index 5ada2a774e..150a13580f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java @@ -267,7 +267,7 @@ public boolean test(String v) { @Test public void testAnyWithTwoItems() { Observable<Integer> w = Observable.just(1, 2); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer v) { return true; @@ -276,7 +276,7 @@ public boolean test(Integer v) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(false); verify(observer, times(1)).onSuccess(true); @@ -286,11 +286,11 @@ public boolean test(Integer v) { @Test public void testIsEmptyWithTwoItems() { Observable<Integer> w = Observable.just(1, 2); - Single<Boolean> observable = w.isEmpty(); + Single<Boolean> single = w.isEmpty(); SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(true); verify(observer, times(1)).onSuccess(false); @@ -300,7 +300,7 @@ public void testIsEmptyWithTwoItems() { @Test public void testAnyWithOneItem() { Observable<Integer> w = Observable.just(1); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer v) { return true; @@ -309,7 +309,7 @@ public boolean test(Integer v) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(false); verify(observer, times(1)).onSuccess(true); @@ -319,11 +319,11 @@ public boolean test(Integer v) { @Test public void testIsEmptyWithOneItem() { Observable<Integer> w = Observable.just(1); - Single<Boolean> observable = w.isEmpty(); + Single<Boolean> single = w.isEmpty(); SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(true); verify(observer, times(1)).onSuccess(false); @@ -333,7 +333,7 @@ public void testIsEmptyWithOneItem() { @Test public void testAnyWithEmpty() { Observable<Integer> w = Observable.empty(); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer v) { return true; @@ -342,7 +342,7 @@ public boolean test(Integer v) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(false); verify(observer, never()).onSuccess(true); @@ -352,11 +352,11 @@ public boolean test(Integer v) { @Test public void testIsEmptyWithEmpty() { Observable<Integer> w = Observable.empty(); - Single<Boolean> observable = w.isEmpty(); + Single<Boolean> single = w.isEmpty(); SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(true); verify(observer, never()).onSuccess(false); @@ -366,7 +366,7 @@ public void testIsEmptyWithEmpty() { @Test public void testAnyWithPredicate1() { Observable<Integer> w = Observable.just(1, 2, 3); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t1) { return t1 < 2; @@ -375,7 +375,7 @@ public boolean test(Integer t1) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(false); verify(observer, times(1)).onSuccess(true); @@ -385,7 +385,7 @@ public boolean test(Integer t1) { @Test public void testExists1() { Observable<Integer> w = Observable.just(1, 2, 3); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t1) { return t1 < 2; @@ -394,7 +394,7 @@ public boolean test(Integer t1) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, never()).onSuccess(false); verify(observer, times(1)).onSuccess(true); @@ -404,7 +404,7 @@ public boolean test(Integer t1) { @Test public void testAnyWithPredicate2() { Observable<Integer> w = Observable.just(1, 2, 3); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t1) { return t1 < 1; @@ -413,7 +413,7 @@ public boolean test(Integer t1) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(false); verify(observer, never()).onSuccess(true); @@ -424,7 +424,7 @@ public boolean test(Integer t1) { public void testAnyWithEmptyAndPredicate() { // If the source is empty, always output false. Observable<Integer> w = Observable.empty(); - Single<Boolean> observable = w.any(new Predicate<Integer>() { + Single<Boolean> single = w.any(new Predicate<Integer>() { @Override public boolean test(Integer t) { return true; @@ -433,7 +433,7 @@ public boolean test(Integer t) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(false); verify(observer, never()).onSuccess(true); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 3a02b31423..9ce8103e77 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -771,7 +771,7 @@ public void testBufferWithTimeDoesntUnsubscribeDownstream() throws InterruptedEx final Observer<Object> o = TestHelper.mockObserver(); final CountDownLatch cdl = new CountDownLatch(1); - DisposableObserver<Object> s = new DisposableObserver<Object>() { + DisposableObserver<Object> observer = new DisposableObserver<Object>() { @Override public void onNext(Object t) { o.onNext(t); @@ -788,7 +788,7 @@ public void onComplete() { } }; - Observable.range(1, 1).delay(1, TimeUnit.SECONDS).buffer(2, TimeUnit.SECONDS).subscribe(s); + Observable.range(1, 1).delay(1, TimeUnit.SECONDS).buffer(2, TimeUnit.SECONDS).subscribe(observer); cdl.await(); @@ -796,7 +796,7 @@ public void onComplete() { verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); - assertFalse(s.isDisposed()); + assertFalse(observer.isDisposed()); } @SuppressWarnings("unchecked") @@ -1599,24 +1599,24 @@ public void openClosebadSource() { try { new Observable<Object>() { @Override - protected void subscribeActual(Observer<? super Object> s) { + protected void subscribeActual(Observer<? super Object> observer) { Disposable bs1 = Disposables.empty(); Disposable bs2 = Disposables.empty(); - s.onSubscribe(bs1); + observer.onSubscribe(bs1); assertFalse(bs1.isDisposed()); assertFalse(bs2.isDisposed()); - s.onSubscribe(bs2); + observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); - s.onError(new IOException()); - s.onComplete(); - s.onNext(1); - s.onError(new TestException()); + observer.onError(new IOException()); + observer.onComplete(); + observer.onNext(1); + observer.onError(new TestException()); } } .buffer(Observable.never(), Functions.justFunction(Observable.never())) @@ -1720,30 +1720,30 @@ public void openCloseBadOpen() { Observable.never() .buffer(new Observable<Object>() { @Override - protected void subscribeActual(Observer<? super Object> s) { + protected void subscribeActual(Observer<? super Object> observer) { - assertFalse(((Disposable)s).isDisposed()); + assertFalse(((Disposable)observer).isDisposed()); Disposable bs1 = Disposables.empty(); Disposable bs2 = Disposables.empty(); - s.onSubscribe(bs1); + observer.onSubscribe(bs1); assertFalse(bs1.isDisposed()); assertFalse(bs2.isDisposed()); - s.onSubscribe(bs2); + observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); - s.onError(new IOException()); + observer.onError(new IOException()); - assertTrue(((Disposable)s).isDisposed()); + assertTrue(((Disposable)observer).isDisposed()); - s.onComplete(); - s.onNext(1); - s.onError(new TestException()); + observer.onComplete(); + observer.onNext(1); + observer.onError(new TestException()); } }, Functions.justFunction(Observable.never())) .test() @@ -1765,30 +1765,30 @@ public void openCloseBadClose() { .buffer(Observable.just(1).concatWith(Observable.<Integer>never()), Functions.justFunction(new Observable<Object>() { @Override - protected void subscribeActual(Observer<? super Object> s) { + protected void subscribeActual(Observer<? super Object> observer) { - assertFalse(((Disposable)s).isDisposed()); + assertFalse(((Disposable)observer).isDisposed()); Disposable bs1 = Disposables.empty(); Disposable bs2 = Disposables.empty(); - s.onSubscribe(bs1); + observer.onSubscribe(bs1); assertFalse(bs1.isDisposed()); assertFalse(bs2.isDisposed()); - s.onSubscribe(bs2); + observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); - s.onError(new IOException()); + observer.onError(new IOException()); - assertTrue(((Disposable)s).isDisposed()); + assertTrue(((Disposable)observer).isDisposed()); - s.onComplete(); - s.onNext(1); - s.onError(new TestException()); + observer.onComplete(); + observer.onNext(1); + observer.onError(new TestException()); } })) .test() @@ -1872,10 +1872,10 @@ public void bufferBoundaryErrorTwice() { BehaviorSubject.createDefault(1) .buffer(Functions.justCallable(new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onError(new TestException("first")); - s.onError(new TestException("second")); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onError(new TestException("first")); + observer.onError(new TestException("second")); } })) .test() diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java index cee12d300e..55256bccd8 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java @@ -483,7 +483,7 @@ public List<Object> apply(Object[] args) { final CountDownLatch cdl = new CountDownLatch(1); - Observer<List<Object>> s = new DefaultObserver<List<Object>>() { + Observer<List<Object>> observer = new DefaultObserver<List<Object>>() { @Override public void onNext(List<Object> t) { @@ -503,7 +503,7 @@ public void onComplete() { } }; - result.subscribe(s); + result.subscribe(observer); cdl.await(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java index f1f95d2f68..f074441875 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java @@ -663,11 +663,11 @@ public void testConcatWithNonCompliantSourceDoubleOnComplete() { Observable<String> o = Observable.unsafeCreate(new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { - s.onSubscribe(Disposables.empty()); - s.onNext("hello"); - s.onComplete(); - s.onComplete(); + public void subscribe(Observer<? super String> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext("hello"); + observer.onComplete(); + observer.onComplete(); } }); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java index e6a17f1d5a..458d0320c0 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletableTest.java @@ -105,17 +105,17 @@ public void cancelOther() { public void badSource() { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { + protected void subscribeActual(Observer<? super Integer> observer) { Disposable bs1 = Disposables.empty(); - s.onSubscribe(bs1); + observer.onSubscribe(bs1); Disposable bs2 = Disposables.empty(); - s.onSubscribe(bs2); + observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); - s.onComplete(); + observer.onComplete(); } }.concatWith(Completable.complete()) .test() diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java index 3d323a979a..cbbed97785 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java @@ -138,17 +138,17 @@ protected void subscribeActual(Observer<? super Integer> observer) { public void badSource() { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { + protected void subscribeActual(Observer<? super Integer> observer) { Disposable bs1 = Disposables.empty(); - s.onSubscribe(bs1); + observer.onSubscribe(bs1); Disposable bs2 = Disposables.empty(); - s.onSubscribe(bs2); + observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); - s.onComplete(); + observer.onComplete(); } }.concatWith(Maybe.<Integer>empty()) .test() @@ -159,17 +159,17 @@ protected void subscribeActual(Observer<? super Integer> s) { public void badSource2() { Flowable.empty().concatWith(new Maybe<Integer>() { @Override - protected void subscribeActual(MaybeObserver<? super Integer> s) { + protected void subscribeActual(MaybeObserver<? super Integer> observer) { Disposable bs1 = Disposables.empty(); - s.onSubscribe(bs1); + observer.onSubscribe(bs1); Disposable bs2 = Disposables.empty(); - s.onSubscribe(bs2); + observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); - s.onComplete(); + observer.onComplete(); } }) .test() diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java index 3de6edfd0f..824c6ac59e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingleTest.java @@ -110,17 +110,17 @@ protected void subscribeActual(Observer<? super Integer> observer) { public void badSource() { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { + protected void subscribeActual(Observer<? super Integer> observer) { Disposable bs1 = Disposables.empty(); - s.onSubscribe(bs1); + observer.onSubscribe(bs1); Disposable bs2 = Disposables.empty(); - s.onSubscribe(bs2); + observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); - s.onComplete(); + observer.onComplete(); } }.concatWith(Single.<Integer>just(100)) .test() @@ -131,17 +131,17 @@ protected void subscribeActual(Observer<? super Integer> s) { public void badSource2() { Flowable.empty().concatWith(new Single<Integer>() { @Override - protected void subscribeActual(SingleObserver<? super Integer> s) { + protected void subscribeActual(SingleObserver<? super Integer> observer) { Disposable bs1 = Disposables.empty(); - s.onSubscribe(bs1); + observer.onSubscribe(bs1); Disposable bs2 = Disposables.empty(); - s.onSubscribe(bs2); + observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); - s.onSuccess(100); + observer.onSuccess(100); } }) .test() diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java index 26ce6caa9c..9edae7bdc9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java @@ -471,11 +471,11 @@ public void timedDisposedIgnoredBySource() { new Observable<Integer>() { @Override protected void subscribeActual( - Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); + Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); to.cancel(); - s.onNext(1); - s.onComplete(); + observer.onNext(1); + observer.onComplete(); } } .debounce(1, TimeUnit.SECONDS) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDeferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDeferTest.java index 6e83ad1956..47ca034628 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDeferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDeferTest.java @@ -21,7 +21,6 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; -import io.reactivex.observers.DefaultObserver; @SuppressWarnings("unchecked") public class ObservableDeferTest { @@ -69,7 +68,7 @@ public void testDeferFunctionThrows() throws Exception { Observable<String> result = Observable.defer(factory); - DefaultObserver<String> o = mock(DefaultObserver.class); + Observer<String> o = TestHelper.mockObserver(); result.subscribe(o); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java index 74bc2dfbfd..83ba70675b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java @@ -225,13 +225,13 @@ public void ignoreCancel() { try { Observable.wrap(new ObservableSource<Integer>() { @Override - public void subscribe(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onNext(2); - s.onNext(3); - s.onError(new IOException()); - s.onComplete(); + public void subscribe(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onNext(2); + observer.onNext(3); + observer.onError(new IOException()); + observer.onComplete(); } }) .distinctUntilChanged(new BiPredicate<Integer, Integer>() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java index 20538da8ca..161ae3db9e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java @@ -230,12 +230,12 @@ public void ignoreCancel() { try { Observable.wrap(new ObservableSource<Object>() { @Override - public void subscribe(Observer<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onNext(2); - s.onError(new IOException()); - s.onComplete(); + public void subscribe(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onNext(2); + observer.onError(new IOException()); + observer.onComplete(); } }) .doOnNext(new Consumer<Object>() { @@ -260,9 +260,9 @@ public void onErrorAfterCrash() { try { Observable.wrap(new ObservableSource<Object>() { @Override - public void subscribe(Observer<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onError(new TestException()); + public void subscribe(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onError(new TestException()); } }) .doAfterTerminate(new Action() { @@ -287,9 +287,9 @@ public void onCompleteAfterCrash() { try { Observable.wrap(new ObservableSource<Object>() { @Override - public void subscribe(Observer<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onComplete(); + public void subscribe(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); } }) .doAfterTerminate(new Action() { @@ -311,9 +311,9 @@ public void run() throws Exception { public void onCompleteCrash() { Observable.wrap(new ObservableSource<Object>() { @Override - public void subscribe(Observer<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onComplete(); + public void subscribe(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); } }) .doOnComplete(new Action() { @@ -333,12 +333,12 @@ public void ignoreCancelConditional() { try { Observable.wrap(new ObservableSource<Object>() { @Override - public void subscribe(Observer<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onNext(2); - s.onError(new IOException()); - s.onComplete(); + public void subscribe(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onNext(2); + observer.onError(new IOException()); + observer.onComplete(); } }) .doOnNext(new Consumer<Object>() { @@ -364,9 +364,9 @@ public void onErrorAfterCrashConditional() { try { Observable.wrap(new ObservableSource<Object>() { @Override - public void subscribe(Observer<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onError(new TestException()); + public void subscribe(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onError(new TestException()); } }) .doAfterTerminate(new Action() { @@ -408,9 +408,9 @@ public void onCompleteAfterCrashConditional() { try { Observable.wrap(new ObservableSource<Object>() { @Override - public void subscribe(Observer<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onComplete(); + public void subscribe(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); } }) .doAfterTerminate(new Action() { @@ -433,9 +433,9 @@ public void run() throws Exception { public void onCompleteCrashConditional() { Observable.wrap(new ObservableSource<Object>() { @Override - public void subscribe(Observer<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onComplete(); + public void subscribe(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); } }) .doOnComplete(new Action() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnSubscribeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnSubscribeTest.java index dbd4ca88eb..93143efe77 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnSubscribeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnSubscribeTest.java @@ -72,10 +72,10 @@ public void testDoOnUnSubscribeWorksWithRefCount() throws Exception { Observable<Integer> o = Observable.unsafeCreate(new ObservableSource<Integer>() { @Override - public void subscribe(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); + public void subscribe(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); onSubscribed.incrementAndGet(); - sref.set(s); + sref.set(observer); } }).doOnSubscribe(new Consumer<Disposable>() { @@ -114,10 +114,10 @@ public void onSubscribeCrash() { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(bs); - s.onError(new TestException("Second")); - s.onComplete(); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(bs); + observer.onError(new TestException("Second")); + observer.onComplete(); } } .doOnSubscribe(new Consumer<Disposable>() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java index 33ba15307e..84ff5fa5ec 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java @@ -372,14 +372,14 @@ public void innerObserver() { public CompletableSource apply(Integer v) throws Exception { return new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); - assertFalse(((Disposable)s).isDisposed()); + assertFalse(((Disposable)observer).isDisposed()); - ((Disposable)s).dispose(); + ((Disposable)observer).dispose(); - assertTrue(((Disposable)s).isDisposed()); + assertTrue(((Disposable)observer).isDisposed()); } }; } @@ -447,14 +447,14 @@ public void innerObserverObservable() { public CompletableSource apply(Integer v) throws Exception { return new Completable() { @Override - protected void subscribeActual(CompletableObserver s) { - s.onSubscribe(Disposables.empty()); + protected void subscribeActual(CompletableObserver observer) { + observer.onSubscribe(Disposables.empty()); - assertFalse(((Disposable)s).isDisposed()); + assertFalse(((Disposable)observer).isDisposed()); - ((Disposable)s).dispose(); + ((Disposable)observer).dispose(); - assertTrue(((Disposable)s).isDisposed()); + assertTrue(((Disposable)observer).isDisposed()); } }; } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java index ae00fc2403..95c892da87 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java @@ -993,10 +993,8 @@ public void testGroupByOnAsynchronousSourceAcceptsMultipleSubscriptions() throws Observable<GroupedObservable<Boolean, Long>> stream = source.groupBy(IS_EVEN); // create two observers - @SuppressWarnings("unchecked") - DefaultObserver<GroupedObservable<Boolean, Long>> o1 = mock(DefaultObserver.class); - @SuppressWarnings("unchecked") - DefaultObserver<GroupedObservable<Boolean, Long>> o2 = mock(DefaultObserver.class); + Observer<GroupedObservable<Boolean, Long>> o1 = TestHelper.mockObserver(); + Observer<GroupedObservable<Boolean, Long>> o2 = TestHelper.mockObserver(); // subscribe with the observers stream.subscribe(o1); @@ -1222,8 +1220,7 @@ public void accept(GroupedObservable<Integer, Integer> t1) { inner.get().subscribe(); - @SuppressWarnings("unchecked") - DefaultObserver<Integer> o2 = mock(DefaultObserver.class); + Observer<Integer> o2 = TestHelper.mockObserver(); inner.get().subscribe(o2); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java index 1b808a9234..bd6d291d33 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java @@ -343,7 +343,7 @@ public void testThrownErrorHandling() { Observable<String> o1 = Observable.unsafeCreate(new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { + public void subscribe(Observer<? super String> observer) { throw new RuntimeException("fail"); } @@ -559,13 +559,13 @@ public void testConcurrencyWithSleeping() { Observable<Integer> o = Observable.unsafeCreate(new ObservableSource<Integer>() { @Override - public void subscribe(final Observer<? super Integer> s) { + public void subscribe(final Observer<? super Integer> observer) { Worker inner = Schedulers.newThread().createWorker(); final CompositeDisposable as = new CompositeDisposable(); as.add(Disposables.empty()); as.add(inner); - s.onSubscribe(as); + observer.onSubscribe(as); inner.schedule(new Runnable() { @@ -573,7 +573,7 @@ public void subscribe(final Observer<? super Integer> s) { public void run() { try { for (int i = 0; i < 100; i++) { - s.onNext(1); + observer.onNext(1); try { Thread.sleep(1); } catch (InterruptedException e) { @@ -581,10 +581,10 @@ public void run() { } } } catch (Exception e) { - s.onError(e); + observer.onError(e); } as.dispose(); - s.onComplete(); + observer.onComplete(); } }); @@ -609,13 +609,13 @@ public void testConcurrencyWithBrokenOnCompleteContract() { Observable<Integer> o = Observable.unsafeCreate(new ObservableSource<Integer>() { @Override - public void subscribe(final Observer<? super Integer> s) { + public void subscribe(final Observer<? super Integer> observer) { Worker inner = Schedulers.newThread().createWorker(); final CompositeDisposable as = new CompositeDisposable(); as.add(Disposables.empty()); as.add(inner); - s.onSubscribe(as); + observer.onSubscribe(as); inner.schedule(new Runnable() { @@ -623,15 +623,15 @@ public void subscribe(final Observer<? super Integer> s) { public void run() { try { for (int i = 0; i < 10000; i++) { - s.onNext(i); + observer.onNext(i); } } catch (Exception e) { - s.onError(e); + observer.onError(e); } as.dispose(); - s.onComplete(); - s.onComplete(); - s.onComplete(); + observer.onComplete(); + observer.onComplete(); + observer.onComplete(); } }); @@ -840,8 +840,8 @@ public void mergeWithTerminalEventAfterUnsubscribe() { Observable<String> bad = Observable.unsafeCreate(new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { - s.onNext("two"); + public void subscribe(Observer<? super String> observer) { + observer.onNext("two"); // FIXME can't cancel downstream // s.unsubscribe(); // s.onComplete(); @@ -1023,8 +1023,8 @@ public Observable<Integer> apply(final Integer i) { return Observable.unsafeCreate(new ObservableSource<Integer>() { @Override - public void subscribe(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); + public void subscribe(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); if (i < 500) { try { Thread.sleep(1); @@ -1032,8 +1032,8 @@ public void subscribe(Observer<? super Integer> s) { e.printStackTrace(); } } - s.onNext(i); - s.onComplete(); + observer.onNext(i); + observer.onComplete(); } }).subscribeOn(Schedulers.computation()).cache(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java index a7d1edf098..a70e4c2fa8 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java @@ -177,18 +177,18 @@ public void onNext(Integer t) { public void onErrorMainOverflow() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { - final AtomicReference<Observer<?>> subscriber = new AtomicReference<Observer<?>>(); + final AtomicReference<Observer<?>> observerRef = new AtomicReference<Observer<?>>(); TestObserver<Integer> to = new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - subscriber.set(s); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observerRef.set(observer); } } .mergeWith(Maybe.<Integer>error(new IOException())) .test(); - subscriber.get().onError(new TestException()); + observerRef.get().onError(new TestException()); to.assertFailure(IOException.class) ; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java index 5821461787..25ce78d486 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java @@ -169,18 +169,18 @@ public void onNext(Integer t) { public void onErrorMainOverflow() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { - final AtomicReference<Observer<?>> subscriber = new AtomicReference<Observer<?>>(); + final AtomicReference<Observer<?>> observerRef = new AtomicReference<Observer<?>>(); TestObserver<Integer> to = new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - subscriber.set(s); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observerRef.set(observer); } } .mergeWith(Single.<Integer>error(new IOException())) .test(); - subscriber.get().onError(new TestException()); + observerRef.get().onError(new TestException()); to.assertFailure(IOException.class) ; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java index 0062e220ee..3330d8cd85 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java @@ -145,10 +145,8 @@ public void observeOnTheSameSchedulerTwice() { Observable<Integer> o = Observable.just(1, 2, 3); Observable<Integer> o2 = o.observeOn(scheduler); - @SuppressWarnings("unchecked") - DefaultObserver<Object> observer1 = mock(DefaultObserver.class); - @SuppressWarnings("unchecked") - DefaultObserver<Object> observer2 = mock(DefaultObserver.class); + Observer<Object> observer1 = TestHelper.mockObserver(); + Observer<Object> observer2 = TestHelper.mockObserver(); InOrder inOrder1 = inOrder(observer1); InOrder inOrder2 = inOrder(observer2); @@ -368,8 +366,7 @@ public void testDelayedErrorDeliveryWhenSafeSubscriberUnsubscribes() { Observable<Integer> source = Observable.concat(Observable.<Integer> error(new TestException()), Observable.just(1)); - @SuppressWarnings("unchecked") - DefaultObserver<Integer> o = mock(DefaultObserver.class); + Observer<Integer> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); source.observeOn(testScheduler).subscribe(o); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java index ffb1e5c37b..9ba3738ce6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java @@ -126,8 +126,7 @@ public Observable<String> apply(Throwable t1) { }; Observable<String> o = Observable.unsafeCreate(w).onErrorResumeNext(resume); - @SuppressWarnings("unchecked") - DefaultObserver<String> observer = mock(DefaultObserver.class); + Observer<String> observer = TestHelper.mockObserver(); o.subscribe(observer); try { @@ -259,8 +258,7 @@ public Observable<String> apply(Throwable t1) { }); - @SuppressWarnings("unchecked") - DefaultObserver<String> observer = mock(DefaultObserver.class); + Observer<String> observer = TestHelper.mockObserver(); TestObserver<String> to = new TestObserver<String>(observer); o.subscribe(to); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java index c0c8edc358..71f9a809fe 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java @@ -133,8 +133,7 @@ public void subscribe(Observer<? super String> t1) { Observable<String> resume = Observable.just("resume"); Observable<String> observable = testObservable.subscribeOn(Schedulers.io()).onErrorResumeNext(resume); - @SuppressWarnings("unchecked") - DefaultObserver<String> observer = mock(DefaultObserver.class); + Observer<String> observer = TestHelper.mockObserver(); TestObserver<String> to = new TestObserver<String>(observer); observable.subscribe(to); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturnTest.java index 18d43e90d4..142d4a7f9f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturnTest.java @@ -46,8 +46,7 @@ public String apply(Throwable e) { }); - @SuppressWarnings("unchecked") - DefaultObserver<String> observer = mock(DefaultObserver.class); + Observer<String> observer = TestHelper.mockObserver(); observable.subscribe(observer); try { @@ -82,8 +81,7 @@ public String apply(Throwable e) { }); - @SuppressWarnings("unchecked") - DefaultObserver<String> observer = mock(DefaultObserver.class); + Observer<String> observer = TestHelper.mockObserver(); observable.subscribe(observer); try { @@ -128,8 +126,7 @@ public String apply(Throwable t1) { }); - @SuppressWarnings("unchecked") - DefaultObserver<String> observer = mock(DefaultObserver.class); + Observer<String> observer = TestHelper.mockObserver(); TestObserver<String> to = new TestObserver<String>(observer); observable.subscribe(to); to.awaitTerminalEvent(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java index e280f5cf9d..86194a7bf7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java @@ -706,8 +706,8 @@ public void delayedUpstreamOnSubscribe() { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - sub[0] = s; + protected void subscribeActual(Observer<? super Integer> observer) { + sub[0] = observer; } } .publish() diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index d46ae8b204..381b2b964b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -232,22 +232,22 @@ public void run() { } }); - TestObserver<Long> s = new TestObserver<Long>(); - o.publish().refCount().subscribeOn(Schedulers.newThread()).subscribe(s); + TestObserver<Long> observer = new TestObserver<Long>(); + o.publish().refCount().subscribeOn(Schedulers.newThread()).subscribe(observer); System.out.println("send unsubscribe"); // wait until connected subscribeLatch.await(); // now unsubscribe - s.dispose(); + observer.dispose(); System.out.println("DONE sending unsubscribe ... now waiting"); if (!unsubscribeLatch.await(3000, TimeUnit.MILLISECONDS)) { - System.out.println("Errors: " + s.errors()); - if (s.errors().size() > 0) { - s.errors().get(0).printStackTrace(); + System.out.println("Errors: " + observer.errors()); + if (observer.errors().size() > 0) { + observer.errors().get(0).printStackTrace(); } fail("timed out waiting for unsubscribe"); } - s.assertNoErrors(); + observer.assertNoErrors(); } @Test @@ -277,12 +277,12 @@ public void accept(Disposable s) { } }); - TestObserver<Long> s = new TestObserver<Long>(); + TestObserver<Long> observer = new TestObserver<Long>(); - o.publish().refCount().subscribeOn(Schedulers.computation()).subscribe(s); + o.publish().refCount().subscribeOn(Schedulers.computation()).subscribe(observer); System.out.println("send unsubscribe"); // now immediately unsubscribe while subscribeOn is racing to subscribe - s.dispose(); + observer.dispose(); // this generally will mean it won't even subscribe as it is already unsubscribed by the time connect() gets scheduled // give time to the counter to update @@ -297,11 +297,11 @@ public void accept(Disposable s) { assertEquals(0, subUnsubCount.get()); System.out.println("DONE sending unsubscribe ... now waiting"); - System.out.println("Errors: " + s.errors()); - if (s.errors().size() > 0) { - s.errors().get(0).printStackTrace(); + System.out.println("Errors: " + observer.errors()); + if (observer.errors().size() > 0) { + observer.errors().get(0).printStackTrace(); } - s.assertNoErrors(); + observer.assertNoErrors(); } private Observable<Long> synchronousInterval() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java index 8c483fc40d..0c62893a77 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java @@ -1497,8 +1497,8 @@ public void delayedUpstreamOnSubscribe() { new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - sub[0] = s; + protected void subscribeActual(Observer<? super Integer> observer) { + sub[0] = observer; } } .replay() diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java index a776cc97a7..9ebb3fd450 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java @@ -426,9 +426,9 @@ public void testRetryAllowsSubscriptionAfterAllSubscriptionsUnsubscribed() throw final AtomicInteger subsCount = new AtomicInteger(0); ObservableSource<String> onSubscribe = new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { + public void subscribe(Observer<? super String> observer) { subsCount.incrementAndGet(); - s.onSubscribe(Disposables.fromRunnable(new Runnable() { + observer.onSubscribe(Disposables.fromRunnable(new Runnable() { @Override public void run() { subsCount.decrementAndGet(); @@ -455,13 +455,13 @@ public void testSourceObservableCallsUnsubscribe() throws InterruptedException { ObservableSource<String> onSubscribe = new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { + public void subscribe(Observer<? super String> observer) { BooleanSubscription bs = new BooleanSubscription(); // if isUnsubscribed is true that means we have a bug such as // https://github.com/ReactiveX/RxJava/issues/1024 if (!bs.isCancelled()) { subsCount.incrementAndGet(); - s.onError(new RuntimeException("failed")); + observer.onError(new RuntimeException("failed")); // it unsubscribes the child directly // this simulates various error/completion scenarios that could occur // or just a source that proactively triggers cleanup @@ -469,7 +469,7 @@ public void subscribe(Observer<? super String> s) { // s.unsubscribe(); bs.cancel(); } else { - s.onError(new RuntimeException()); + observer.onError(new RuntimeException()); } } }; @@ -486,10 +486,10 @@ public void testSourceObservableRetry1() throws InterruptedException { ObservableSource<String> onSubscribe = new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { - s.onSubscribe(Disposables.empty()); + public void subscribe(Observer<? super String> observer) { + observer.onSubscribe(Disposables.empty()); subsCount.incrementAndGet(); - s.onError(new RuntimeException("failed")); + observer.onError(new RuntimeException("failed")); } }; @@ -505,10 +505,10 @@ public void testSourceObservableRetry0() throws InterruptedException { ObservableSource<String> onSubscribe = new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { - s.onSubscribe(Disposables.empty()); + public void subscribe(Observer<? super String> observer) { + observer.onSubscribe(Disposables.empty()); subsCount.incrementAndGet(); - s.onError(new RuntimeException("failed")); + observer.onError(new RuntimeException("failed")); } }; @@ -634,8 +634,7 @@ public void testUnsubscribeAfterError() { @Test(timeout = 10000) public void testTimeoutWithRetry() { - @SuppressWarnings("unchecked") - DefaultObserver<Long> observer = mock(DefaultObserver.class); + Observer<Long> observer = TestHelper.mockObserver(); // Observable that sends every 100ms (timeout fails instead) SlowObservable so = new SlowObservable(100, 10); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java index db87844952..79ca287629 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java @@ -89,8 +89,7 @@ public void subscribe(Observer<? super Integer> t1) { } }); - @SuppressWarnings("unchecked") - DefaultObserver<Integer> o = mock(DefaultObserver.class); + Observer<Integer> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); source.retry(retryTwice).subscribe(o); @@ -117,8 +116,7 @@ public void subscribe(Observer<? super Integer> t1) { } }); - @SuppressWarnings("unchecked") - DefaultObserver<Integer> o = mock(DefaultObserver.class); + Observer<Integer> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); source.retry(retryTwice).subscribe(o); @@ -153,8 +151,7 @@ public void subscribe(Observer<? super Integer> t1) { } }); - @SuppressWarnings("unchecked") - DefaultObserver<Integer> o = mock(DefaultObserver.class); + Observer<Integer> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); source.retry(retryOnTestException).subscribe(o); @@ -190,8 +187,7 @@ public void subscribe(Observer<? super Integer> t1) { } }); - @SuppressWarnings("unchecked") - DefaultObserver<Integer> o = mock(DefaultObserver.class); + Observer<Integer> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); source.retry(retryOnTestException).subscribe(o); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java index cb4661943c..0ab9e8e914 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableScalarXMapTest.java @@ -35,8 +35,8 @@ public void utilityClass() { static final class CallablePublisher implements ObservableSource<Integer>, Callable<Integer> { @Override - public void subscribe(Observer<? super Integer> s) { - EmptyDisposable.error(new TestException(), s); + public void subscribe(Observer<? super Integer> observer) { + EmptyDisposable.error(new TestException(), observer); } @Override @@ -47,8 +47,8 @@ public Integer call() throws Exception { static final class EmptyCallablePublisher implements ObservableSource<Integer>, Callable<Integer> { @Override - public void subscribe(Observer<? super Integer> s) { - EmptyDisposable.complete(s); + public void subscribe(Observer<? super Integer> observer) { + EmptyDisposable.complete(observer); } @Override @@ -59,9 +59,9 @@ public Integer call() throws Exception { static final class OneCallablePublisher implements ObservableSource<Integer>, Callable<Integer> { @Override - public void subscribe(Observer<? super Integer> s) { - ScalarDisposable<Integer> sd = new ScalarDisposable<Integer>(s, 1); - s.onSubscribe(sd); + public void subscribe(Observer<? super Integer> observer) { + ScalarDisposable<Integer> sd = new ScalarDisposable<Integer>(observer, 1); + observer.onSubscribe(sd); sd.run(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java index 5a5adb36d1..4a7a33ddd6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java @@ -150,9 +150,9 @@ private void verifyError(Observable<Boolean> observable) { inOrder.verifyNoMoreInteractions(); } - private void verifyError(Single<Boolean> observable) { + private void verifyError(Single<Boolean> single) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError(isA(TestException.class)); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSubscribeOnTest.java index 03e5472bde..c80b81e2cd 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSubscribeOnTest.java @@ -78,7 +78,7 @@ public void testThrownErrorHandling() { Observable.unsafeCreate(new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { + public void subscribe(Observer<? super String> observer) { throw new RuntimeException("fail"); } @@ -93,9 +93,9 @@ public void testOnError() { Observable.unsafeCreate(new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { - s.onSubscribe(Disposables.empty()); - s.onError(new RuntimeException("fail")); + public void subscribe(Observer<? super String> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onError(new RuntimeException("fail")); } }).subscribeOn(Schedulers.computation()).subscribe(to); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java index beae5a788c..ab68bd6790 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java @@ -664,9 +664,9 @@ public void switchMapSingleFunctionDoesntReturnSingle() { public SingleSource<Integer> apply(Object v) throws Exception { return new SingleSource<Integer>() { @Override - public void subscribe(SingleObserver<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onSuccess(1); + public void subscribe(SingleObserver<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onSuccess(1); } }; } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java index a738d40462..859e311a2d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java @@ -28,33 +28,33 @@ public class ObservableTakeLastOneTest { @Test public void testLastOfManyReturnsLast() { - TestObserver<Integer> s = new TestObserver<Integer>(); - Observable.range(1, 10).takeLast(1).subscribe(s); - s.assertValue(10); - s.assertNoErrors(); - s.assertTerminated(); + TestObserver<Integer> to = new TestObserver<Integer>(); + Observable.range(1, 10).takeLast(1).subscribe(to); + to.assertValue(10); + to.assertNoErrors(); + to.assertTerminated(); // NO longer assertable // s.assertUnsubscribed(); } @Test public void testLastOfEmptyReturnsEmpty() { - TestObserver<Object> s = new TestObserver<Object>(); - Observable.empty().takeLast(1).subscribe(s); - s.assertNoValues(); - s.assertNoErrors(); - s.assertTerminated(); + TestObserver<Object> to = new TestObserver<Object>(); + Observable.empty().takeLast(1).subscribe(to); + to.assertNoValues(); + to.assertNoErrors(); + to.assertTerminated(); // NO longer assertable // s.assertUnsubscribed(); } @Test public void testLastOfOneReturnsLast() { - TestObserver<Integer> s = new TestObserver<Integer>(); - Observable.just(1).takeLast(1).subscribe(s); - s.assertValue(1); - s.assertNoErrors(); - s.assertTerminated(); + TestObserver<Integer> to = new TestObserver<Integer>(); + Observable.just(1).takeLast(1).subscribe(to); + to.assertValue(1); + to.assertNoErrors(); + to.assertTerminated(); // NO longer assertable // s.assertUnsubscribed(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java index f1f5851fd3..a9b9ae35d9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java @@ -208,13 +208,13 @@ public void testMultiTake() { Observable.unsafeCreate(new ObservableSource<Integer>() { @Override - public void subscribe(Observer<? super Integer> s) { + public void subscribe(Observer<? super Integer> observer) { Disposable bs = Disposables.empty(); - s.onSubscribe(bs); + observer.onSubscribe(bs); for (int i = 0; !bs.isDisposed(); i++) { System.out.println("Emit: " + i); count.incrementAndGet(); - s.onNext(i); + observer.onNext(i); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java index 921cd50383..4d38f049e7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java @@ -562,9 +562,9 @@ public void lateOnTimeoutError() { @Override protected void subscribeActual( - Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - sub[count++] = s; + Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + sub[count++] = observer; } }; @@ -616,10 +616,10 @@ public void lateOnTimeoutFallbackRace() { @Override protected void subscribeActual( - Observer<? super Integer> s) { - assertFalse(((Disposable)s).isDisposed()); - s.onSubscribe(Disposables.empty()); - sub[count++] = s; + Observer<? super Integer> observer) { + assertFalse(((Disposable)observer).isDisposed()); + observer.onSubscribe(Disposables.empty()); + sub[count++] = observer; } }; @@ -671,10 +671,10 @@ public void onErrorOnTimeoutRace() { @Override protected void subscribeActual( - Observer<? super Integer> s) { - assertFalse(((Disposable)s).isDisposed()); - s.onSubscribe(Disposables.empty()); - sub[count++] = s; + Observer<? super Integer> observer) { + assertFalse(((Disposable)observer).isDisposed()); + observer.onSubscribe(Disposables.empty()); + sub[count++] = observer; } }; @@ -726,10 +726,10 @@ public void onCompleteOnTimeoutRace() { @Override protected void subscribeActual( - Observer<? super Integer> s) { - assertFalse(((Disposable)s).isDisposed()); - s.onSubscribe(Disposables.empty()); - sub[count++] = s; + Observer<? super Integer> observer) { + assertFalse(((Disposable)observer).isDisposed()); + observer.onSubscribe(Disposables.empty()); + sub[count++] = observer; } }; @@ -779,10 +779,10 @@ public void onCompleteOnTimeoutRaceFallback() { @Override protected void subscribeActual( - Observer<? super Integer> s) { - assertFalse(((Disposable)s).isDisposed()); - s.onSubscribe(Disposables.empty()); - sub[count++] = s; + Observer<? super Integer> observer) { + assertFalse(((Disposable)observer).isDisposed()); + observer.onSubscribe(Disposables.empty()); + sub[count++] = observer; } }; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java index fa838ad5f1..18447143aa 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java @@ -109,10 +109,10 @@ public void capacityHintObservable() { @Test public void testList() { Observable<String> w = Observable.fromIterable(Arrays.asList("one", "two", "three")); - Single<List<String>> observable = w.toList(); + Single<List<String>> single = w.toList(); SingleObserver<List<String>> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(Arrays.asList("one", "two", "three")); verify(observer, Mockito.never()).onError(any(Throwable.class)); } @@ -120,10 +120,10 @@ public void testList() { @Test public void testListViaObservable() { Observable<String> w = Observable.fromIterable(Arrays.asList("one", "two", "three")); - Single<List<String>> observable = w.toList(); + Single<List<String>> single = w.toList(); SingleObserver<List<String>> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(Arrays.asList("one", "two", "three")); verify(observer, Mockito.never()).onError(any(Throwable.class)); } @@ -131,13 +131,13 @@ public void testListViaObservable() { @Test public void testListMultipleSubscribers() { Observable<String> w = Observable.fromIterable(Arrays.asList("one", "two", "three")); - Single<List<String>> observable = w.toList(); + Single<List<String>> single = w.toList(); SingleObserver<List<String>> o1 = TestHelper.mockSingleObserver(); - observable.subscribe(o1); + single.subscribe(o1); SingleObserver<List<String>> o2 = TestHelper.mockSingleObserver(); - observable.subscribe(o2); + single.subscribe(o2); List<String> expected = Arrays.asList("one", "two", "three"); @@ -152,10 +152,10 @@ public void testListMultipleSubscribers() { @Ignore("Null values are not allowed") public void testListWithNullValue() { Observable<String> w = Observable.fromIterable(Arrays.asList("one", null, "three")); - Single<List<String>> observable = w.toList(); + Single<List<String>> single = w.toList(); SingleObserver<List<String>> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(Arrays.asList("one", null, "three")); verify(observer, Mockito.never()).onError(any(Throwable.class)); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableToSortedListTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableToSortedListTest.java index b00cfbb483..f715b6b08c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableToSortedListTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableToSortedListTest.java @@ -119,10 +119,10 @@ public int compare(Integer a, Integer b) { @Test public void testSortedList() { Observable<Integer> w = Observable.just(1, 3, 2, 5, 4); - Single<List<Integer>> observable = w.toSortedList(); + Single<List<Integer>> single = w.toSortedList(); SingleObserver<List<Integer>> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(Arrays.asList(1, 2, 3, 4, 5)); verify(observer, Mockito.never()).onError(any(Throwable.class)); } @@ -130,7 +130,7 @@ public void testSortedList() { @Test public void testSortedListWithCustomFunction() { Observable<Integer> w = Observable.just(1, 3, 2, 5, 4); - Single<List<Integer>> observable = w.toSortedList(new Comparator<Integer>() { + Single<List<Integer>> single = w.toSortedList(new Comparator<Integer>() { @Override public int compare(Integer t1, Integer t2) { @@ -140,7 +140,7 @@ public int compare(Integer t1, Integer t2) { }); SingleObserver<List<Integer>> observer = TestHelper.mockSingleObserver(); - observable.subscribe(observer); + single.subscribe(observer); verify(observer, times(1)).onSuccess(Arrays.asList(5, 4, 3, 2, 1)); verify(observer, Mockito.never()).onError(any(Throwable.class)); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java index a3f2fedc41..8ef033d5f1 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java @@ -208,13 +208,13 @@ private List<String> list(String... args) { public static Observable<Integer> hotStream() { return Observable.unsafeCreate(new ObservableSource<Integer>() { @Override - public void subscribe(Observer<? super Integer> s) { + public void subscribe(Observer<? super Integer> observer) { Disposable d = Disposables.empty(); - s.onSubscribe(d); + observer.onSubscribe(d); while (!d.isDisposed()) { // burst some number of items for (int i = 0; i < Math.random() * 20; i++) { - s.onNext(i); + observer.onNext(i); } try { // sleep for a random amount of time diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java index 41f3163f98..d1426a5a61 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java @@ -404,11 +404,11 @@ public Observable<Integer> apply(Integer f) throws Exception { return new Observable<Integer>() { @Override protected void subscribeActual( - Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onNext(2); - s.onError(new TestException()); + Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onNext(2); + observer.onError(new TestException()); } }; } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleDelayTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleDelayTest.java index d0c2ea165b..8f0967d8b8 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleDelayTest.java @@ -213,10 +213,10 @@ public void withObservableError2() { Single.just(1) .delaySubscription(new Observable<Integer>() { @Override - protected void subscribeActual(Observer<? super Integer> s) { - s.onSubscribe(Disposables.empty()); - s.onNext(1); - s.onError(new TestException()); + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onError(new TestException()); } }) .test() diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTest.java index 853b21c320..8422a44c12 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTest.java @@ -336,10 +336,10 @@ public void onSubscribeCrash() { new Single<Integer>() { @Override - protected void subscribeActual(SingleObserver<? super Integer> s) { - s.onSubscribe(bs); - s.onError(new TestException("Second")); - s.onSuccess(1); + protected void subscribeActual(SingleObserver<? super Integer> observer) { + observer.onSubscribe(bs); + observer.onError(new TestException("Second")); + observer.onSuccess(1); } } .doOnSubscribe(new Consumer<Disposable>() { diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleLiftTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleLiftTest.java index 1f09902b43..cf2345de35 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleLiftTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleLiftTest.java @@ -25,22 +25,22 @@ public void normal() { Single.just(1).lift(new SingleOperator<Integer, Integer>() { @Override - public SingleObserver<Integer> apply(final SingleObserver<? super Integer> s) throws Exception { + public SingleObserver<Integer> apply(final SingleObserver<? super Integer> observer) throws Exception { return new SingleObserver<Integer>() { @Override public void onSubscribe(Disposable d) { - s.onSubscribe(d); + observer.onSubscribe(d); } @Override public void onSuccess(Integer value) { - s.onSuccess(value + 1); + observer.onSuccess(value + 1); } @Override public void onError(Throwable e) { - s.onError(e); + observer.onError(e); } }; } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java index 160579aab1..c811291851 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java @@ -55,9 +55,9 @@ public void wrap() { Single.wrap(new SingleSource<Object>() { @Override - public void subscribe(SingleObserver<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onSuccess(1); + public void subscribe(SingleObserver<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onSuccess(1); } }) .test() diff --git a/src/test/java/io/reactivex/internal/subscribers/BoundedSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/BoundedSubscriberTest.java index 0fed174be5..17e12986b4 100644 --- a/src/test/java/io/reactivex/internal/subscribers/BoundedSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/BoundedSubscriberTest.java @@ -42,7 +42,7 @@ public class BoundedSubscriberTest { public void onSubscribeThrows() { final List<Object> received = new ArrayList<Object>(); - BoundedSubscriber<Object> o = new BoundedSubscriber<Object>(new Consumer<Object>() { + BoundedSubscriber<Object> subscriber = new BoundedSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { received.add(o); @@ -64,21 +64,21 @@ public void accept(Subscription subscription) throws Exception { } }, 128); - assertFalse(o.isDisposed()); + assertFalse(subscriber.isDisposed()); - Flowable.just(1).subscribe(o); + Flowable.just(1).subscribe(subscriber); assertTrue(received.toString(), received.get(0) instanceof TestException); assertEquals(received.toString(), 1, received.size()); - assertTrue(o.isDisposed()); + assertTrue(subscriber.isDisposed()); } @Test public void onNextThrows() { final List<Object> received = new ArrayList<Object>(); - BoundedSubscriber<Object> o = new BoundedSubscriber<Object>(new Consumer<Object>() { + BoundedSubscriber<Object> subscriber = new BoundedSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { throw new TestException(); @@ -100,14 +100,14 @@ public void accept(Subscription subscription) throws Exception { } }, 128); - assertFalse(o.isDisposed()); + assertFalse(subscriber.isDisposed()); - Flowable.just(1).subscribe(o); + Flowable.just(1).subscribe(subscriber); assertTrue(received.toString(), received.get(0) instanceof TestException); assertEquals(received.toString(), 1, received.size()); - assertTrue(o.isDisposed()); + assertTrue(subscriber.isDisposed()); } @Test @@ -117,7 +117,7 @@ public void onErrorThrows() { try { final List<Object> received = new ArrayList<Object>(); - BoundedSubscriber<Object> o = new BoundedSubscriber<Object>(new Consumer<Object>() { + BoundedSubscriber<Object> subscriber = new BoundedSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { received.add(o); @@ -139,13 +139,13 @@ public void accept(Subscription subscription) throws Exception { } }, 128); - assertFalse(o.isDisposed()); + assertFalse(subscriber.isDisposed()); - Flowable.<Integer>error(new TestException("Outer")).subscribe(o); + Flowable.<Integer>error(new TestException("Outer")).subscribe(subscriber); assertTrue(received.toString(), received.isEmpty()); - assertTrue(o.isDisposed()); + assertTrue(subscriber.isDisposed()); TestHelper.assertError(errors, 0, CompositeException.class); List<Throwable> ce = TestHelper.compositeList(errors.get(0)); @@ -163,7 +163,7 @@ public void onCompleteThrows() { try { final List<Object> received = new ArrayList<Object>(); - BoundedSubscriber<Object> o = new BoundedSubscriber<Object>(new Consumer<Object>() { + BoundedSubscriber<Object> subscriber = new BoundedSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { received.add(o); @@ -185,13 +185,13 @@ public void accept(Subscription subscription) throws Exception { } }, 128); - assertFalse(o.isDisposed()); + assertFalse(subscriber.isDisposed()); - Flowable.<Integer>empty().subscribe(o); + Flowable.<Integer>empty().subscribe(subscriber); assertTrue(received.toString(), received.isEmpty()); - assertTrue(o.isDisposed()); + assertTrue(subscriber.isDisposed()); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { @@ -294,7 +294,7 @@ public void subscribe(Subscriber<? super Integer> s) { final List<Object> received = new ArrayList<Object>(); - BoundedSubscriber<Object> o = new BoundedSubscriber<Object>(new Consumer<Object>() { + BoundedSubscriber<Object> subscriber = new BoundedSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object v) throws Exception { received.add(v); @@ -316,7 +316,7 @@ public void accept(Subscription s) throws Exception { } }, 128); - source.subscribe(o); + source.subscribe(subscriber); assertEquals(Arrays.asList(1, 100), received); } @@ -339,7 +339,7 @@ public void subscribe(Subscriber<? super Integer> s) { final List<Object> received = new ArrayList<Object>(); - BoundedSubscriber<Object> o = new BoundedSubscriber<Object>(new Consumer<Object>() { + BoundedSubscriber<Object> subscriber = new BoundedSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object v) throws Exception { received.add(v); @@ -361,28 +361,28 @@ public void accept(Subscription s) throws Exception { } }, 128); - source.subscribe(o); + source.subscribe(subscriber); assertEquals(Arrays.asList(1, 100), received); } @Test public void onErrorMissingShouldReportNoCustomOnError() { - BoundedSubscriber<Integer> o = new BoundedSubscriber<Integer>(Functions.<Integer>emptyConsumer(), + BoundedSubscriber<Integer> subscriber = new BoundedSubscriber<Integer>(Functions.<Integer>emptyConsumer(), Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION, Functions.<Subscription>boundedConsumer(128), 128); - assertFalse(o.hasCustomOnError()); + assertFalse(subscriber.hasCustomOnError()); } @Test public void customOnErrorShouldReportCustomOnError() { - BoundedSubscriber<Integer> o = new BoundedSubscriber<Integer>(Functions.<Integer>emptyConsumer(), + BoundedSubscriber<Integer> subscriber = new BoundedSubscriber<Integer>(Functions.<Integer>emptyConsumer(), Functions.<Throwable>emptyConsumer(), Functions.EMPTY_ACTION, Functions.<Subscription>boundedConsumer(128), 128); - assertTrue(o.hasCustomOnError()); + assertTrue(subscriber.hasCustomOnError()); } } diff --git a/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java index b6eef24c5e..7f16d6e0ee 100644 --- a/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java @@ -34,7 +34,7 @@ public class LambdaSubscriberTest { public void onSubscribeThrows() { final List<Object> received = new ArrayList<Object>(); - LambdaSubscriber<Object> o = new LambdaSubscriber<Object>(new Consumer<Object>() { + LambdaSubscriber<Object> subscriber = new LambdaSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object v) throws Exception { received.add(v); @@ -57,21 +57,21 @@ public void accept(Subscription s) throws Exception { } }); - assertFalse(o.isDisposed()); + assertFalse(subscriber.isDisposed()); - Flowable.just(1).subscribe(o); + Flowable.just(1).subscribe(subscriber); assertTrue(received.toString(), received.get(0) instanceof TestException); assertEquals(received.toString(), 1, received.size()); - assertTrue(o.isDisposed()); + assertTrue(subscriber.isDisposed()); } @Test public void onNextThrows() { final List<Object> received = new ArrayList<Object>(); - LambdaSubscriber<Object> o = new LambdaSubscriber<Object>(new Consumer<Object>() { + LambdaSubscriber<Object> subscriber = new LambdaSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object v) throws Exception { throw new TestException(); @@ -94,14 +94,14 @@ public void accept(Subscription s) throws Exception { } }); - assertFalse(o.isDisposed()); + assertFalse(subscriber.isDisposed()); - Flowable.just(1).subscribe(o); + Flowable.just(1).subscribe(subscriber); assertTrue(received.toString(), received.get(0) instanceof TestException); assertEquals(received.toString(), 1, received.size()); - assertTrue(o.isDisposed()); + assertTrue(subscriber.isDisposed()); } @Test @@ -111,7 +111,7 @@ public void onErrorThrows() { try { final List<Object> received = new ArrayList<Object>(); - LambdaSubscriber<Object> o = new LambdaSubscriber<Object>(new Consumer<Object>() { + LambdaSubscriber<Object> subscriber = new LambdaSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object v) throws Exception { received.add(v); @@ -134,13 +134,13 @@ public void accept(Subscription s) throws Exception { } }); - assertFalse(o.isDisposed()); + assertFalse(subscriber.isDisposed()); - Flowable.<Integer>error(new TestException("Outer")).subscribe(o); + Flowable.<Integer>error(new TestException("Outer")).subscribe(subscriber); assertTrue(received.toString(), received.isEmpty()); - assertTrue(o.isDisposed()); + assertTrue(subscriber.isDisposed()); TestHelper.assertError(errors, 0, CompositeException.class); List<Throwable> ce = TestHelper.compositeList(errors.get(0)); @@ -158,7 +158,7 @@ public void onCompleteThrows() { try { final List<Object> received = new ArrayList<Object>(); - LambdaSubscriber<Object> o = new LambdaSubscriber<Object>(new Consumer<Object>() { + LambdaSubscriber<Object> subscriber = new LambdaSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object v) throws Exception { received.add(v); @@ -181,13 +181,13 @@ public void accept(Subscription s) throws Exception { } }); - assertFalse(o.isDisposed()); + assertFalse(subscriber.isDisposed()); - Flowable.<Integer>empty().subscribe(o); + Flowable.<Integer>empty().subscribe(subscriber); assertTrue(received.toString(), received.isEmpty()); - assertTrue(o.isDisposed()); + assertTrue(subscriber.isDisposed()); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { @@ -215,7 +215,7 @@ public void subscribe(Subscriber<? super Integer> s) { final List<Object> received = new ArrayList<Object>(); - LambdaSubscriber<Object> o = new LambdaSubscriber<Object>(new Consumer<Object>() { + LambdaSubscriber<Object> subscriber = new LambdaSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object v) throws Exception { received.add(v); @@ -238,7 +238,7 @@ public void accept(Subscription s) throws Exception { } }); - source.subscribe(o); + source.subscribe(subscriber); assertEquals(Arrays.asList(1, 100), received); } @@ -260,7 +260,7 @@ public void subscribe(Subscriber<? super Integer> s) { final List<Object> received = new ArrayList<Object>(); - LambdaSubscriber<Object> o = new LambdaSubscriber<Object>(new Consumer<Object>() { + LambdaSubscriber<Object> subscriber = new LambdaSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object v) throws Exception { received.add(v); @@ -283,7 +283,7 @@ public void accept(Subscription s) throws Exception { } }); - source.subscribe(o); + source.subscribe(subscriber); assertEquals(Arrays.asList(1, 100), received); } @@ -351,21 +351,21 @@ public void accept(Subscription s) throws Exception { @Test public void onErrorMissingShouldReportNoCustomOnError() { - LambdaSubscriber<Integer> o = new LambdaSubscriber<Integer>(Functions.<Integer>emptyConsumer(), + LambdaSubscriber<Integer> subscriber = new LambdaSubscriber<Integer>(Functions.<Integer>emptyConsumer(), Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION, FlowableInternalHelper.RequestMax.INSTANCE); - assertFalse(o.hasCustomOnError()); + assertFalse(subscriber.hasCustomOnError()); } @Test public void customOnErrorShouldReportCustomOnError() { - LambdaSubscriber<Integer> o = new LambdaSubscriber<Integer>(Functions.<Integer>emptyConsumer(), + LambdaSubscriber<Integer> subscriber = new LambdaSubscriber<Integer>(Functions.<Integer>emptyConsumer(), Functions.<Throwable>emptyConsumer(), Functions.EMPTY_ACTION, FlowableInternalHelper.RequestMax.INSTANCE); - assertTrue(o.hasCustomOnError()); + assertTrue(subscriber.hasCustomOnError()); } } diff --git a/src/test/java/io/reactivex/internal/subscribers/SubscriberResourceWrapperTest.java b/src/test/java/io/reactivex/internal/subscribers/SubscriberResourceWrapperTest.java index c519202ff8..6841d5bffd 100644 --- a/src/test/java/io/reactivex/internal/subscribers/SubscriberResourceWrapperTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/SubscriberResourceWrapperTest.java @@ -88,8 +88,8 @@ public void complete() { public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { @Override - public Flowable<Object> apply(Flowable<Object> o) throws Exception { - return o.lift(new FlowableOperator<Object, Object>() { + public Flowable<Object> apply(Flowable<Object> f) throws Exception { + return f.lift(new FlowableOperator<Object, Object>() { @Override public Subscriber<? super Object> apply( Subscriber<? super Object> s) throws Exception { diff --git a/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java b/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java index 38e099db23..b66f5d5671 100644 --- a/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java +++ b/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java @@ -36,7 +36,7 @@ public void reentrantOnNextOnNext() { final TestObserver ts = new TestObserver(); - Observer s = new Observer() { + Observer observer = new Observer() { @Override public void onSubscribe(Disposable s) { ts.onSubscribe(s); @@ -61,11 +61,11 @@ public void onComplete() { } }; - a[0] = s; + a[0] = observer; - s.onSubscribe(Disposables.empty()); + observer.onSubscribe(Disposables.empty()); - HalfSerializer.onNext(s, 1, wip, error); + HalfSerializer.onNext(observer, 1, wip, error); ts.assertValue(1).assertNoErrors().assertNotComplete(); } @@ -80,7 +80,7 @@ public void reentrantOnNextOnError() { final TestObserver ts = new TestObserver(); - Observer s = new Observer() { + Observer observer = new Observer() { @Override public void onSubscribe(Disposable s) { ts.onSubscribe(s); @@ -105,11 +105,11 @@ public void onComplete() { } }; - a[0] = s; + a[0] = observer; - s.onSubscribe(Disposables.empty()); + observer.onSubscribe(Disposables.empty()); - HalfSerializer.onNext(s, 1, wip, error); + HalfSerializer.onNext(observer, 1, wip, error); ts.assertFailure(TestException.class, 1); } @@ -124,7 +124,7 @@ public void reentrantOnNextOnComplete() { final TestObserver ts = new TestObserver(); - Observer s = new Observer() { + Observer observer = new Observer() { @Override public void onSubscribe(Disposable s) { ts.onSubscribe(s); @@ -149,11 +149,11 @@ public void onComplete() { } }; - a[0] = s; + a[0] = observer; - s.onSubscribe(Disposables.empty()); + observer.onSubscribe(Disposables.empty()); - HalfSerializer.onNext(s, 1, wip, error); + HalfSerializer.onNext(observer, 1, wip, error); ts.assertResult(1); } @@ -168,7 +168,7 @@ public void reentrantErrorOnError() { final TestObserver ts = new TestObserver(); - Observer s = new Observer() { + Observer observer = new Observer() { @Override public void onSubscribe(Disposable s) { ts.onSubscribe(s); @@ -191,11 +191,11 @@ public void onComplete() { } }; - a[0] = s; + a[0] = observer; - s.onSubscribe(Disposables.empty()); + observer.onSubscribe(Disposables.empty()); - HalfSerializer.onError(s, new TestException(), wip, error); + HalfSerializer.onError(observer, new TestException(), wip, error); ts.assertFailure(TestException.class); } diff --git a/src/test/java/io/reactivex/maybe/MaybeTest.java b/src/test/java/io/reactivex/maybe/MaybeTest.java index 18fe1fea4c..94c7c9eb8a 100644 --- a/src/test/java/io/reactivex/maybe/MaybeTest.java +++ b/src/test/java/io/reactivex/maybe/MaybeTest.java @@ -1002,7 +1002,7 @@ public void sourceThrowsNPE() { try { Maybe.unsafeCreate(new MaybeSource<Object>() { @Override - public void subscribe(MaybeObserver<? super Object> s) { + public void subscribe(MaybeObserver<? super Object> observer) { throw new NullPointerException("Forced failure"); } }).test(); @@ -1019,7 +1019,7 @@ public void sourceThrowsIAE() { try { Maybe.unsafeCreate(new MaybeSource<Object>() { @Override - public void subscribe(MaybeObserver<? super Object> s) { + public void subscribe(MaybeObserver<? super Object> observer) { throw new IllegalArgumentException("Forced failure"); } }).test(); diff --git a/src/test/java/io/reactivex/observable/ObservableNullTests.java b/src/test/java/io/reactivex/observable/ObservableNullTests.java index 105a429b1f..d04c324dfe 100644 --- a/src/test/java/io/reactivex/observable/ObservableNullTests.java +++ b/src/test/java/io/reactivex/observable/ObservableNullTests.java @@ -1662,7 +1662,7 @@ public void liftNull() { public void liftReturnsNull() { just1.lift(new ObservableOperator<Object, Integer>() { @Override - public Observer<? super Integer> apply(Observer<? super Object> s) { + public Observer<? super Integer> apply(Observer<? super Object> observer) { return null; } }).blockingSubscribe(); diff --git a/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java b/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java index 5e927ad46b..14af3cf2d0 100644 --- a/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java +++ b/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java @@ -215,7 +215,7 @@ public Observer apply(Observable a, Observer b) throws Exception { static final class BadObservable extends Observable<Integer> { @Override - protected void subscribeActual(Observer<? super Integer> s) { + protected void subscribeActual(Observer<? super Integer> observer) { throw new IllegalArgumentException(); } } diff --git a/src/test/java/io/reactivex/observable/ObservableTest.java b/src/test/java/io/reactivex/observable/ObservableTest.java index 9b549670a8..64c5059bf8 100644 --- a/src/test/java/io/reactivex/observable/ObservableTest.java +++ b/src/test/java/io/reactivex/observable/ObservableTest.java @@ -346,7 +346,7 @@ public void testOnSubscribeFails() { final RuntimeException re = new RuntimeException("bad impl"); Observable<String> o = Observable.unsafeCreate(new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { throw re; } + public void subscribe(Observer<? super String> observer) { throw re; } }); o.subscribe(observer); @@ -1151,16 +1151,16 @@ public void testForEachWithNull() { @Test public void testExtend() { - final TestObserver<Object> subscriber = new TestObserver<Object>(); + final TestObserver<Object> to = new TestObserver<Object>(); final Object value = new Object(); Object returned = Observable.just(value).to(new Function<Observable<Object>, Object>() { @Override public Object apply(Observable<Object> onSubscribe) { - onSubscribe.subscribe(subscriber); - subscriber.assertNoErrors(); - subscriber.assertComplete(); - subscriber.assertValue(value); - return subscriber.values().get(0); + onSubscribe.subscribe(to); + to.assertNoErrors(); + to.assertComplete(); + to.assertValue(value); + return to.values().get(0); } }); assertSame(returned, value); @@ -1168,16 +1168,16 @@ public Object apply(Observable<Object> onSubscribe) { @Test public void testAsExtend() { - final TestObserver<Object> subscriber = new TestObserver<Object>(); + final TestObserver<Object> to = new TestObserver<Object>(); final Object value = new Object(); Object returned = Observable.just(value).as(new ObservableConverter<Object, Object>() { @Override public Object apply(Observable<Object> onSubscribe) { - onSubscribe.subscribe(subscriber); - subscriber.assertNoErrors(); - subscriber.assertComplete(); - subscriber.assertValue(value); - return subscriber.values().get(0); + onSubscribe.subscribe(to); + to.assertNoErrors(); + to.assertComplete(); + to.assertValue(value); + return to.values().get(0); } }); assertSame(returned, value); diff --git a/src/test/java/io/reactivex/observers/SafeObserverTest.java b/src/test/java/io/reactivex/observers/SafeObserverTest.java index ee6eb83f43..54d1269138 100644 --- a/src/test/java/io/reactivex/observers/SafeObserverTest.java +++ b/src/test/java/io/reactivex/observers/SafeObserverTest.java @@ -447,7 +447,7 @@ static class SafeObserverTestException extends RuntimeException { @Ignore("Observers can't throw") public void testOnCompletedThrows() { final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); - SafeObserver<Integer> s = new SafeObserver<Integer>(new DefaultObserver<Integer>() { + SafeObserver<Integer> observer = new SafeObserver<Integer>(new DefaultObserver<Integer>() { @Override public void onNext(Integer t) { @@ -463,7 +463,7 @@ public void onComplete() { }); try { - s.onComplete(); + observer.onComplete(); Assert.fail(); } catch (RuntimeException e) { assertNull(error.get()); @@ -483,9 +483,9 @@ public void onError(Throwable e) { public void onComplete() { } }; - SafeObserver<Integer> s = new SafeObserver<Integer>(actual); + SafeObserver<Integer> observer = new SafeObserver<Integer>(actual); - assertSame(actual, s.actual); + assertSame(actual, observer.actual); } @Test diff --git a/src/test/java/io/reactivex/observers/SerializedObserverTest.java b/src/test/java/io/reactivex/observers/SerializedObserverTest.java index 720964c1c0..726ca7aee4 100644 --- a/src/test/java/io/reactivex/observers/SerializedObserverTest.java +++ b/src/test/java/io/reactivex/observers/SerializedObserverTest.java @@ -435,11 +435,11 @@ private static Observable<String> infinite(final AtomicInteger produced) { return Observable.unsafeCreate(new ObservableSource<String>() { @Override - public void subscribe(Observer<? super String> s) { + public void subscribe(Observer<? super String> observer) { Disposable bs = Disposables.empty(); - s.onSubscribe(bs); + observer.onSubscribe(bs); while (!bs.isDisposed()) { - s.onNext("onNext"); + observer.onNext("onNext"); produced.incrementAndGet(); } } diff --git a/src/test/java/io/reactivex/observers/TestObserverTest.java b/src/test/java/io/reactivex/observers/TestObserverTest.java index c183451348..1b638ace38 100644 --- a/src/test/java/io/reactivex/observers/TestObserverTest.java +++ b/src/test/java/io/reactivex/observers/TestObserverTest.java @@ -48,68 +48,68 @@ public class TestObserverTest { @Test public void testAssert() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - oi.subscribe(o); + TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>(); + oi.subscribe(subscriber); - o.assertValues(1, 2); - o.assertValueCount(2); - o.assertTerminated(); + subscriber.assertValues(1, 2); + subscriber.assertValueCount(2); + subscriber.assertTerminated(); } @Test public void testAssertNotMatchCount() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - oi.subscribe(o); + TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>(); + oi.subscribe(subscriber); thrown.expect(AssertionError.class); // FIXME different message format // thrown.expectMessage("Number of items does not match. Provided: 1 Actual: 2"); - o.assertValue(1); - o.assertValueCount(2); - o.assertTerminated(); + subscriber.assertValue(1); + subscriber.assertValueCount(2); + subscriber.assertTerminated(); } @Test public void testAssertNotMatchValue() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - oi.subscribe(o); + TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>(); + oi.subscribe(subscriber); thrown.expect(AssertionError.class); // FIXME different message format // thrown.expectMessage("Value at index: 1 expected to be [3] (Integer) but was: [2] (Integer)"); - o.assertValues(1, 3); - o.assertValueCount(2); - o.assertTerminated(); + subscriber.assertValues(1, 3); + subscriber.assertValueCount(2); + subscriber.assertTerminated(); } @Test public void assertNeverAtNotMatchingValue() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - oi.subscribe(o); + TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>(); + oi.subscribe(subscriber); - o.assertNever(3); - o.assertValueCount(2); - o.assertTerminated(); + subscriber.assertNever(3); + subscriber.assertValueCount(2); + subscriber.assertTerminated(); } @Test public void assertNeverAtMatchingValue() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - oi.subscribe(o); + TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>(); + oi.subscribe(subscriber); - o.assertValues(1, 2); + subscriber.assertValues(1, 2); thrown.expect(AssertionError.class); - o.assertNever(2); - o.assertValueCount(2); - o.assertTerminated(); + subscriber.assertNever(2); + subscriber.assertValueCount(2); + subscriber.assertTerminated(); } @Test @@ -147,8 +147,8 @@ public boolean test(final Integer o) throws Exception { @Test public void testAssertTerminalEventNotReceived() { PublishProcessor<Integer> p = PublishProcessor.create(); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - p.subscribe(o); + TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>(); + p.subscribe(subscriber); p.onNext(1); p.onNext(2); @@ -157,36 +157,36 @@ public void testAssertTerminalEventNotReceived() { // FIXME different message format // thrown.expectMessage("No terminal events received."); - o.assertValues(1, 2); - o.assertValueCount(2); - o.assertTerminated(); + subscriber.assertValues(1, 2); + subscriber.assertValueCount(2); + subscriber.assertTerminated(); } @Test public void testWrappingMock() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - Subscriber<Integer> mockObserver = TestHelper.mockSubscriber(); + Subscriber<Integer> mockSubscriber = TestHelper.mockSubscriber(); - oi.subscribe(new TestSubscriber<Integer>(mockObserver)); + oi.subscribe(new TestSubscriber<Integer>(mockSubscriber)); - InOrder inOrder = inOrder(mockObserver); - inOrder.verify(mockObserver, times(1)).onNext(1); - inOrder.verify(mockObserver, times(1)).onNext(2); - inOrder.verify(mockObserver, times(1)).onComplete(); + InOrder inOrder = inOrder(mockSubscriber); + inOrder.verify(mockSubscriber, times(1)).onNext(1); + inOrder.verify(mockSubscriber, times(1)).onNext(2); + inOrder.verify(mockSubscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testWrappingMockWhenUnsubscribeInvolved() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)).take(2); - Subscriber<Integer> mockObserver = TestHelper.mockSubscriber(); - oi.subscribe(new TestSubscriber<Integer>(mockObserver)); + Subscriber<Integer> mockSubscriber = TestHelper.mockSubscriber(); + oi.subscribe(new TestSubscriber<Integer>(mockSubscriber)); - InOrder inOrder = inOrder(mockObserver); - inOrder.verify(mockObserver, times(1)).onNext(1); - inOrder.verify(mockObserver, times(1)).onNext(2); - inOrder.verify(mockObserver, times(1)).onComplete(); + InOrder inOrder = inOrder(mockSubscriber); + inOrder.verify(mockSubscriber, times(1)).onNext(1); + inOrder.verify(mockSubscriber, times(1)).onNext(2); + inOrder.verify(mockSubscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } diff --git a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java index b3cb2b142d..9fa9cc92d0 100644 --- a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java +++ b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java @@ -708,7 +708,7 @@ public void flowableStart() { try { RxJavaPlugins.setOnFlowableSubscribe(new BiFunction<Flowable, Subscriber, Subscriber>() { @Override - public Subscriber apply(Flowable o, final Subscriber t) { + public Subscriber apply(Flowable f, final Subscriber t) { return new Subscriber() { @Override diff --git a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java index 71251e7c9c..c97f3398e1 100644 --- a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java +++ b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java @@ -44,33 +44,33 @@ protected FlowableProcessor<Object> create() { public void testNeverCompleted() { AsyncProcessor<String> processor = AsyncProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onNext("two"); processor.onNext("three"); - verify(observer, Mockito.never()).onNext(anyString()); - verify(observer, Mockito.never()).onError(testException); - verify(observer, Mockito.never()).onComplete(); + verify(subscriber, Mockito.never()).onNext(anyString()); + verify(subscriber, Mockito.never()).onError(testException); + verify(subscriber, Mockito.never()).onComplete(); } @Test public void testCompleted() { AsyncProcessor<String> processor = AsyncProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onNext("two"); processor.onNext("three"); processor.onComplete(); - verify(observer, times(1)).onNext("three"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -78,40 +78,40 @@ public void testCompleted() { public void testNull() { AsyncProcessor<String> processor = AsyncProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext(null); processor.onComplete(); - verify(observer, times(1)).onNext(null); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext(null); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testSubscribeAfterCompleted() { AsyncProcessor<String> processor = AsyncProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); processor.onNext("one"); processor.onNext("two"); processor.onNext("three"); processor.onComplete(); - processor.subscribe(observer); + processor.subscribe(subscriber); - verify(observer, times(1)).onNext("three"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testSubscribeAfterError() { AsyncProcessor<String> processor = AsyncProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); processor.onNext("one"); processor.onNext("two"); @@ -120,19 +120,19 @@ public void testSubscribeAfterError() { RuntimeException re = new RuntimeException("failed"); processor.onError(re); - processor.subscribe(observer); + processor.subscribe(subscriber); - verify(observer, times(1)).onError(re); - verify(observer, Mockito.never()).onNext(any(String.class)); - verify(observer, Mockito.never()).onComplete(); + verify(subscriber, times(1)).onError(re); + verify(subscriber, Mockito.never()).onNext(any(String.class)); + verify(subscriber, Mockito.never()).onComplete(); } @Test public void testError() { AsyncProcessor<String> processor = AsyncProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onNext("two"); @@ -142,17 +142,17 @@ public void testError() { processor.onError(new Throwable()); processor.onComplete(); - verify(observer, Mockito.never()).onNext(anyString()); - verify(observer, times(1)).onError(testException); - verify(observer, Mockito.never()).onComplete(); + verify(subscriber, Mockito.never()).onNext(anyString()); + verify(subscriber, times(1)).onError(testException); + verify(subscriber, Mockito.never()).onComplete(); } @Test public void testUnsubscribeBeforeCompleted() { AsyncProcessor<String> processor = AsyncProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); processor.subscribe(ts); processor.onNext("one"); @@ -160,31 +160,31 @@ public void testUnsubscribeBeforeCompleted() { ts.dispose(); - verify(observer, Mockito.never()).onNext(anyString()); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, Mockito.never()).onComplete(); + verify(subscriber, Mockito.never()).onNext(anyString()); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, Mockito.never()).onComplete(); processor.onNext("three"); processor.onComplete(); - verify(observer, Mockito.never()).onNext(anyString()); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, Mockito.never()).onComplete(); + verify(subscriber, Mockito.never()).onNext(anyString()); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, Mockito.never()).onComplete(); } @Test public void testEmptySubjectCompleted() { AsyncProcessor<String> processor = AsyncProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onComplete(); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, never()).onNext(null); - inOrder.verify(observer, never()).onNext(any(String.class)); - inOrder.verify(observer, times(1)).onComplete(); + InOrder inOrder = inOrder(subscriber); + inOrder.verify(subscriber, never()).onNext(null); + inOrder.verify(subscriber, never()).onNext(any(String.class)); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } diff --git a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java index fd2677207f..59d8cbff02 100644 --- a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java +++ b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java @@ -47,19 +47,19 @@ protected FlowableProcessor<Object> create() { public void testThatSubscriberReceivesDefaultValueAndSubsequentEvents() { BehaviorProcessor<String> processor = BehaviorProcessor.createDefault("default"); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onNext("two"); processor.onNext("three"); - verify(observer, times(1)).onNext("default"); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, Mockito.never()).onError(testException); - verify(observer, Mockito.never()).onComplete(); + verify(subscriber, times(1)).onNext("default"); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, Mockito.never()).onError(testException); + verify(subscriber, Mockito.never()).onComplete(); } @Test @@ -68,34 +68,34 @@ public void testThatSubscriberReceivesLatestAndThenSubsequentEvents() { processor.onNext("one"); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("two"); processor.onNext("three"); - verify(observer, Mockito.never()).onNext("default"); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, Mockito.never()).onError(testException); - verify(observer, Mockito.never()).onComplete(); + verify(subscriber, Mockito.never()).onNext("default"); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, Mockito.never()).onError(testException); + verify(subscriber, Mockito.never()).onComplete(); } @Test public void testSubscribeThenOnComplete() { BehaviorProcessor<String> processor = BehaviorProcessor.createDefault("default"); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onComplete(); - verify(observer, times(1)).onNext("default"); - verify(observer, times(1)).onNext("one"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("default"); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -104,13 +104,13 @@ public void testSubscribeToCompletedOnlyEmitsOnComplete() { processor.onNext("one"); processor.onComplete(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); - verify(observer, never()).onNext("default"); - verify(observer, never()).onNext("one"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, never()).onNext("default"); + verify(subscriber, never()).onNext("one"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test @@ -120,13 +120,13 @@ public void testSubscribeToErrorOnlyEmitsOnError() { RuntimeException re = new RuntimeException("test error"); processor.onError(re); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); - verify(observer, never()).onNext("default"); - verify(observer, never()).onNext("one"); - verify(observer, times(1)).onError(re); - verify(observer, never()).onComplete(); + verify(subscriber, never()).onNext("default"); + verify(subscriber, never()).onNext("one"); + verify(subscriber, times(1)).onError(re); + verify(subscriber, never()).onComplete(); } @Test @@ -178,69 +178,69 @@ public void testCompletedStopsEmittingData() { public void testCompletedAfterErrorIsNotSent() { BehaviorProcessor<String> processor = BehaviorProcessor.createDefault("default"); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onError(testException); processor.onNext("two"); processor.onComplete(); - verify(observer, times(1)).onNext("default"); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onError(testException); - verify(observer, never()).onNext("two"); - verify(observer, never()).onComplete(); + verify(subscriber, times(1)).onNext("default"); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onError(testException); + verify(subscriber, never()).onNext("two"); + verify(subscriber, never()).onComplete(); } @Test public void testCompletedAfterErrorIsNotSent2() { BehaviorProcessor<String> processor = BehaviorProcessor.createDefault("default"); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onError(testException); processor.onNext("two"); processor.onComplete(); - verify(observer, times(1)).onNext("default"); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onError(testException); - verify(observer, never()).onNext("two"); - verify(observer, never()).onComplete(); + verify(subscriber, times(1)).onNext("default"); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onError(testException); + verify(subscriber, never()).onNext("two"); + verify(subscriber, never()).onComplete(); - Subscriber<Object> o2 = TestHelper.mockSubscriber(); - processor.subscribe(o2); - verify(o2, times(1)).onError(testException); - verify(o2, never()).onNext(any()); - verify(o2, never()).onComplete(); + Subscriber<Object> subscriber2 = TestHelper.mockSubscriber(); + processor.subscribe(subscriber2); + verify(subscriber2, times(1)).onError(testException); + verify(subscriber2, never()).onNext(any()); + verify(subscriber2, never()).onComplete(); } @Test public void testCompletedAfterErrorIsNotSent3() { BehaviorProcessor<String> processor = BehaviorProcessor.createDefault("default"); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onComplete(); processor.onNext("two"); processor.onComplete(); - verify(observer, times(1)).onNext("default"); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onComplete(); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, never()).onNext("two"); + verify(subscriber, times(1)).onNext("default"); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext("two"); - Subscriber<Object> o2 = TestHelper.mockSubscriber(); - processor.subscribe(o2); - verify(o2, times(1)).onComplete(); - verify(o2, never()).onNext(any()); - verify(observer, never()).onError(any(Throwable.class)); + Subscriber<Object> subscriber2 = TestHelper.mockSubscriber(); + processor.subscribe(subscriber2); + verify(subscriber2, times(1)).onComplete(); + verify(subscriber2, never()).onNext(any()); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test(timeout = 1000) @@ -248,8 +248,8 @@ public void testUnsubscriptionCase() { BehaviorProcessor<String> src = BehaviorProcessor.createDefault("null"); // FIXME was plain null which is not allowed for (int i = 0; i < 10; i++) { - final Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); String v = "" + i; src.onNext(v); System.out.printf("Turn: %d%n", i); @@ -264,34 +264,34 @@ public Flowable<String> apply(String t1) { .subscribe(new DefaultSubscriber<String>() { @Override public void onNext(String t) { - o.onNext(t); + subscriber.onNext(t); } @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }); - inOrder.verify(o).onNext(v + ", " + v); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(v + ", " + v); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } } @Test public void testStartEmpty() { BehaviorProcessor<Integer> source = BehaviorProcessor.create(); - final Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); - source.subscribe(o); + source.subscribe(subscriber); - inOrder.verify(o, never()).onNext(any()); - inOrder.verify(o, never()).onComplete(); + inOrder.verify(subscriber, never()).onNext(any()); + inOrder.verify(subscriber, never()).onComplete(); source.onNext(1); @@ -299,10 +299,10 @@ public void testStartEmpty() { source.onNext(2); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); - inOrder.verify(o).onNext(1); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); @@ -310,52 +310,52 @@ public void testStartEmpty() { @Test public void testStartEmptyThenAddOne() { BehaviorProcessor<Integer> source = BehaviorProcessor.create(); - final Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); source.onNext(1); - source.subscribe(o); + source.subscribe(subscriber); - inOrder.verify(o).onNext(1); + inOrder.verify(subscriber).onNext(1); source.onComplete(); source.onNext(2); - inOrder.verify(o).onComplete(); + inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void testStartEmptyCompleteWithOne() { BehaviorProcessor<Integer> source = BehaviorProcessor.create(); - final Subscriber<Object> o = TestHelper.mockSubscriber(); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); source.onNext(1); source.onComplete(); source.onNext(2); - source.subscribe(o); + source.subscribe(subscriber); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); - verify(o, never()).onNext(any()); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(any()); } @Test public void testTakeOneSubscriber() { BehaviorProcessor<Integer> source = BehaviorProcessor.createDefault(1); - final Subscriber<Object> o = TestHelper.mockSubscriber(); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); - source.take(1).subscribe(o); + source.take(1).subscribe(subscriber); - verify(o).onNext(1); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(1); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); assertEquals(0, source.subscriberCount()); assertFalse(source.hasSubscribers()); diff --git a/src/test/java/io/reactivex/processors/PublishProcessorTest.java b/src/test/java/io/reactivex/processors/PublishProcessorTest.java index 9989f6b392..8d9d4b7a88 100644 --- a/src/test/java/io/reactivex/processors/PublishProcessorTest.java +++ b/src/test/java/io/reactivex/processors/PublishProcessorTest.java @@ -42,8 +42,8 @@ protected FlowableProcessor<Object> create() { public void testCompleted() { PublishProcessor<String> processor = PublishProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onNext("two"); @@ -57,7 +57,7 @@ public void testCompleted() { processor.onComplete(); processor.onError(new Throwable()); - assertCompletedSubscriber(observer); + assertCompletedSubscriber(subscriber); // todo bug? assertNeverSubscriber(anotherSubscriber); } @@ -103,20 +103,20 @@ public void testCompletedStopsEmittingData() { inOrderC.verifyNoMoreInteractions(); } - private void assertCompletedSubscriber(Subscriber<String> observer) { - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + private void assertCompletedSubscriber(Subscriber<String> subscriber) { + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testError() { PublishProcessor<String> processor = PublishProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onNext("two"); @@ -130,29 +130,29 @@ public void testError() { processor.onError(new Throwable()); processor.onComplete(); - assertErrorSubscriber(observer); + assertErrorSubscriber(subscriber); // todo bug? assertNeverSubscriber(anotherSubscriber); } - private void assertErrorSubscriber(Subscriber<String> observer) { - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, times(1)).onError(testException); - verify(observer, Mockito.never()).onComplete(); + private void assertErrorSubscriber(Subscriber<String> subscriber) { + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, times(1)).onError(testException); + verify(subscriber, Mockito.never()).onComplete(); } @Test public void testSubscribeMidSequence() { PublishProcessor<String> processor = PublishProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onNext("two"); - assertObservedUntilTwo(observer); + assertObservedUntilTwo(subscriber); Subscriber<String> anotherSubscriber = TestHelper.mockSubscriber(); processor.subscribe(anotherSubscriber); @@ -160,31 +160,31 @@ public void testSubscribeMidSequence() { processor.onNext("three"); processor.onComplete(); - assertCompletedSubscriber(observer); + assertCompletedSubscriber(subscriber); assertCompletedStartingWithThreeSubscriber(anotherSubscriber); } - private void assertCompletedStartingWithThreeSubscriber(Subscriber<String> observer) { - verify(observer, Mockito.never()).onNext("one"); - verify(observer, Mockito.never()).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + private void assertCompletedStartingWithThreeSubscriber(Subscriber<String> subscriber) { + verify(subscriber, Mockito.never()).onNext("one"); + verify(subscriber, Mockito.never()).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); } @Test public void testUnsubscribeFirstSubscriber() { PublishProcessor<String> processor = PublishProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); processor.subscribe(ts); processor.onNext("one"); processor.onNext("two"); ts.dispose(); - assertObservedUntilTwo(observer); + assertObservedUntilTwo(subscriber); Subscriber<String> anotherSubscriber = TestHelper.mockSubscriber(); processor.subscribe(anotherSubscriber); @@ -192,16 +192,16 @@ public void testUnsubscribeFirstSubscriber() { processor.onNext("three"); processor.onComplete(); - assertObservedUntilTwo(observer); + assertObservedUntilTwo(subscriber); assertCompletedStartingWithThreeSubscriber(anotherSubscriber); } - private void assertObservedUntilTwo(Subscriber<String> observer) { - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, Mockito.never()).onNext("three"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, Mockito.never()).onComplete(); + private void assertObservedUntilTwo(Subscriber<String> subscriber) { + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, Mockito.never()).onComplete(); } @Test @@ -262,16 +262,16 @@ public void accept(String v) { public void testReSubscribe() { final PublishProcessor<Integer> pp = PublishProcessor.create(); - Subscriber<Integer> o1 = TestHelper.mockSubscriber(); - TestSubscriber<Integer> ts = new TestSubscriber<Integer>(o1); + Subscriber<Integer> subscriber1 = TestHelper.mockSubscriber(); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(subscriber1); pp.subscribe(ts); // emit pp.onNext(1); // validate we got it - InOrder inOrder1 = inOrder(o1); - inOrder1.verify(o1, times(1)).onNext(1); + InOrder inOrder1 = inOrder(subscriber1); + inOrder1.verify(subscriber1, times(1)).onNext(1); inOrder1.verifyNoMoreInteractions(); // unsubscribe @@ -280,16 +280,16 @@ public void testReSubscribe() { // emit again but nothing will be there to receive it pp.onNext(2); - Subscriber<Integer> o2 = TestHelper.mockSubscriber(); - TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(o2); + Subscriber<Integer> subscriber2 = TestHelper.mockSubscriber(); + TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(subscriber2); pp.subscribe(ts2); // emit pp.onNext(3); // validate we got it - InOrder inOrder2 = inOrder(o2); - inOrder2.verify(o2, times(1)).onNext(3); + InOrder inOrder2 = inOrder(subscriber2); + inOrder2.verify(subscriber2, times(1)).onNext(3); inOrder2.verifyNoMoreInteractions(); ts2.dispose(); @@ -302,8 +302,8 @@ public void testUnsubscriptionCase() { PublishProcessor<String> src = PublishProcessor.create(); for (int i = 0; i < 10; i++) { - final Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); String v = "" + i; System.out.printf("Turn: %d%n", i); src.firstElement().toFlowable() @@ -317,24 +317,24 @@ public Flowable<String> apply(String t1) { .subscribe(new DefaultSubscriber<String>() { @Override public void onNext(String t) { - o.onNext(t); + subscriber.onNext(t); } @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }); src.onNext(v); - inOrder.verify(o).onNext(v + ", " + v); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext(v + ", " + v); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } } diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java index 7edef31ecd..dd0f32821f 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java @@ -39,13 +39,13 @@ public void run() { Flowable.unsafeCreate(new Publisher<Long>() { @Override - public void subscribe(Subscriber<? super Long> o) { + public void subscribe(Subscriber<? super Long> subscriber) { System.out.println("********* Start Source Data ***********"); for (long l = 1; l <= 10000; l++) { - o.onNext(l); + subscriber.onNext(l); } System.out.println("********* Finished Source Data ***********"); - o.onComplete(); + subscriber.onComplete(); } }).subscribe(replay); } @@ -148,13 +148,13 @@ public void run() { Flowable.unsafeCreate(new Publisher<Long>() { @Override - public void subscribe(Subscriber<? super Long> o) { + public void subscribe(Subscriber<? super Long> subscriber) { System.out.println("********* Start Source Data ***********"); for (long l = 1; l <= 10000; l++) { - o.onNext(l); + subscriber.onNext(l); } System.out.println("********* Finished Source Data ***********"); - o.onComplete(); + subscriber.onComplete(); } }).subscribe(replay); } diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java index 62b0817678..e63f8f361f 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java @@ -39,13 +39,13 @@ public void run() { Flowable.unsafeCreate(new Publisher<Long>() { @Override - public void subscribe(Subscriber<? super Long> o) { + public void subscribe(Subscriber<? super Long> subscriber) { System.out.println("********* Start Source Data ***********"); for (long l = 1; l <= 10000; l++) { - o.onNext(l); + subscriber.onNext(l); } System.out.println("********* Finished Source Data ***********"); - o.onComplete(); + subscriber.onComplete(); } }).subscribe(replay); } @@ -148,13 +148,13 @@ public void run() { Flowable.unsafeCreate(new Publisher<Long>() { @Override - public void subscribe(Subscriber<? super Long> o) { + public void subscribe(Subscriber<? super Long> subscriber) { System.out.println("********* Start Source Data ***********"); for (long l = 1; l <= 10000; l++) { - o.onNext(l); + subscriber.onNext(l); } System.out.println("********* Finished Source Data ***********"); - o.onComplete(); + subscriber.onComplete(); } }).subscribe(replay); } diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index 20e6b9a8df..75c013d996 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -47,8 +47,8 @@ protected FlowableProcessor<Object> create() { public void testCompleted() { ReplayProcessor<String> processor = ReplayProcessor.create(); - Subscriber<String> o1 = TestHelper.mockSubscriber(); - processor.subscribe(o1); + Subscriber<String> subscriber1 = TestHelper.mockSubscriber(); + processor.subscribe(subscriber1); processor.onNext("one"); processor.onNext("two"); @@ -59,12 +59,12 @@ public void testCompleted() { processor.onComplete(); processor.onError(new Throwable()); - assertCompletedSubscriber(o1); + assertCompletedSubscriber(subscriber1); // assert that subscribing a 2nd time gets the same data - Subscriber<String> o2 = TestHelper.mockSubscriber(); - processor.subscribe(o2); - assertCompletedSubscriber(o2); + Subscriber<String> subscriber2 = TestHelper.mockSubscriber(); + processor.subscribe(subscriber2); + assertCompletedSubscriber(subscriber2); } @Test @@ -140,7 +140,7 @@ public void testCompletedStopsEmittingData() { public void testCompletedAfterError() { ReplayProcessor<String> processor = ReplayProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); processor.onNext("one"); processor.onError(testException); @@ -148,21 +148,21 @@ public void testCompletedAfterError() { processor.onComplete(); processor.onError(new RuntimeException()); - processor.subscribe(observer); - verify(observer).onSubscribe((Subscription)notNull()); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onError(testException); - verifyNoMoreInteractions(observer); + processor.subscribe(subscriber); + verify(subscriber).onSubscribe((Subscription)notNull()); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onError(testException); + verifyNoMoreInteractions(subscriber); } - private void assertCompletedSubscriber(Subscriber<String> observer) { - InOrder inOrder = inOrder(observer); + private void assertCompletedSubscriber(Subscriber<String> subscriber) { + InOrder inOrder = inOrder(subscriber); - inOrder.verify(observer, times(1)).onNext("one"); - inOrder.verify(observer, times(1)).onNext("two"); - inOrder.verify(observer, times(1)).onNext("three"); - inOrder.verify(observer, Mockito.never()).onError(any(Throwable.class)); - inOrder.verify(observer, times(1)).onComplete(); + inOrder.verify(subscriber, times(1)).onNext("one"); + inOrder.verify(subscriber, times(1)).onNext("two"); + inOrder.verify(subscriber, times(1)).onNext("three"); + inOrder.verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @@ -170,8 +170,8 @@ private void assertCompletedSubscriber(Subscriber<String> observer) { public void testError() { ReplayProcessor<String> processor = ReplayProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onNext("two"); @@ -182,32 +182,32 @@ public void testError() { processor.onError(new Throwable()); processor.onComplete(); - assertErrorSubscriber(observer); + assertErrorSubscriber(subscriber); - observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); - assertErrorSubscriber(observer); + subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); + assertErrorSubscriber(subscriber); } - private void assertErrorSubscriber(Subscriber<String> observer) { - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, times(1)).onError(testException); - verify(observer, Mockito.never()).onComplete(); + private void assertErrorSubscriber(Subscriber<String> subscriber) { + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, times(1)).onError(testException); + verify(subscriber, Mockito.never()).onComplete(); } @Test public void testSubscribeMidSequence() { ReplayProcessor<String> processor = ReplayProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - processor.subscribe(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + processor.subscribe(subscriber); processor.onNext("one"); processor.onNext("two"); - assertObservedUntilTwo(observer); + assertObservedUntilTwo(subscriber); Subscriber<String> anotherSubscriber = TestHelper.mockSubscriber(); processor.subscribe(anotherSubscriber); @@ -216,7 +216,7 @@ public void testSubscribeMidSequence() { processor.onNext("three"); processor.onComplete(); - assertCompletedSubscriber(observer); + assertCompletedSubscriber(subscriber); assertCompletedSubscriber(anotherSubscriber); } @@ -224,15 +224,15 @@ public void testSubscribeMidSequence() { public void testUnsubscribeFirstSubscriber() { ReplayProcessor<String> processor = ReplayProcessor.create(); - Subscriber<String> observer = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(observer); + Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); processor.subscribe(ts); processor.onNext("one"); processor.onNext("two"); ts.dispose(); - assertObservedUntilTwo(observer); + assertObservedUntilTwo(subscriber); Subscriber<String> anotherSubscriber = TestHelper.mockSubscriber(); processor.subscribe(anotherSubscriber); @@ -241,23 +241,23 @@ public void testUnsubscribeFirstSubscriber() { processor.onNext("three"); processor.onComplete(); - assertObservedUntilTwo(observer); + assertObservedUntilTwo(subscriber); assertCompletedSubscriber(anotherSubscriber); } - private void assertObservedUntilTwo(Subscriber<String> observer) { - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, Mockito.never()).onNext("three"); - verify(observer, Mockito.never()).onError(any(Throwable.class)); - verify(observer, Mockito.never()).onComplete(); + private void assertObservedUntilTwo(Subscriber<String> subscriber) { + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, Mockito.never()).onNext("three"); + verify(subscriber, Mockito.never()).onError(any(Throwable.class)); + verify(subscriber, Mockito.never()).onComplete(); } @Test(timeout = 2000) public void testNewSubscriberDoesntBlockExisting() throws InterruptedException { final AtomicReference<String> lastValueForSubscriber1 = new AtomicReference<String>(); - Subscriber<String> observer1 = new DefaultSubscriber<String>() { + Subscriber<String> subscriber1 = new DefaultSubscriber<String>() { @Override public void onComplete() { @@ -281,7 +281,7 @@ public void onNext(String v) { final CountDownLatch oneReceived = new CountDownLatch(1); final CountDownLatch makeSlow = new CountDownLatch(1); final CountDownLatch completed = new CountDownLatch(1); - Subscriber<String> observer2 = new DefaultSubscriber<String>() { + Subscriber<String> subscriber2 = new DefaultSubscriber<String>() { @Override public void onComplete() { @@ -311,14 +311,14 @@ public void onNext(String v) { }; ReplayProcessor<String> processor = ReplayProcessor.create(); - processor.subscribe(observer1); + processor.subscribe(subscriber1); processor.onNext("one"); assertEquals("one", lastValueForSubscriber1.get()); processor.onNext("two"); assertEquals("two", lastValueForSubscriber1.get()); // use subscribeOn to make this async otherwise we deadlock as we are using CountDownLatches - processor.subscribeOn(Schedulers.newThread()).subscribe(observer2); + processor.subscribeOn(Schedulers.newThread()).subscribe(subscriber2); System.out.println("before waiting for one"); @@ -368,8 +368,8 @@ public void testUnsubscriptionCase() { ReplayProcessor<String> src = ReplayProcessor.create(); for (int i = 0; i < 10; i++) { - final Subscriber<Object> o = TestHelper.mockSubscriber(); - InOrder inOrder = inOrder(o); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); String v = "" + i; src.onNext(v); System.out.printf("Turn: %d%n", i); @@ -385,22 +385,22 @@ public Flowable<String> apply(String t1) { @Override public void onNext(String t) { System.out.println(t); - o.onNext(t); + subscriber.onNext(t); } @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }); - inOrder.verify(o).onNext("0, 0"); - inOrder.verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + inOrder.verify(subscriber).onNext("0, 0"); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } } @Test @@ -410,30 +410,30 @@ public void testTerminateOnce() { source.onNext(2); source.onComplete(); - final Subscriber<Integer> o = TestHelper.mockSubscriber(); + final Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); source.subscribe(new DefaultSubscriber<Integer>() { @Override public void onNext(Integer t) { - o.onNext(t); + subscriber.onNext(t); } @Override public void onError(Throwable e) { - o.onError(e); + subscriber.onError(e); } @Override public void onComplete() { - o.onComplete(); + subscriber.onComplete(); } }); - verify(o).onNext(1); - verify(o).onNext(2); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber).onNext(1); + verify(subscriber).onNext(2); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -445,35 +445,35 @@ public void testReplay1AfterTermination() { source.onComplete(); for (int i = 0; i < 1; i++) { - Subscriber<Integer> o = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - source.subscribe(o); + source.subscribe(subscriber); - verify(o, never()).onNext(1); - verify(o).onNext(2); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(1); + verify(subscriber).onNext(2); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } } @Test public void testReplay1Directly() { ReplayProcessor<Integer> source = ReplayProcessor.createWithSize(1); - Subscriber<Integer> o = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); source.onNext(1); source.onNext(2); - source.subscribe(o); + source.subscribe(subscriber); source.onNext(3); source.onComplete(); - verify(o, never()).onNext(1); - verify(o).onNext(2); - verify(o).onNext(3); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(1); + verify(subscriber).onNext(2); + verify(subscriber).onNext(3); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -494,15 +494,15 @@ public void testReplayTimestampedAfterTermination() { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Subscriber<Integer> o = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - source.subscribe(o); + source.subscribe(subscriber); - verify(o, never()).onNext(1); - verify(o, never()).onNext(2); - verify(o, never()).onNext(3); - verify(o).onComplete(); - verify(o, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(1); + verify(subscriber, never()).onNext(2); + verify(subscriber, never()).onNext(3); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); } @Test @@ -514,9 +514,9 @@ public void testReplayTimestampedDirectly() { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Subscriber<Integer> o = TestHelper.mockSubscriber(); + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); - source.subscribe(o); + source.subscribe(subscriber); source.onNext(2); @@ -530,11 +530,11 @@ public void testReplayTimestampedDirectly() { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - verify(o, never()).onError(any(Throwable.class)); - verify(o, never()).onNext(1); - verify(o).onNext(2); - verify(o).onNext(3); - verify(o).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, never()).onNext(1); + verify(subscriber).onNext(2); + verify(subscriber).onNext(3); + verify(subscriber).onComplete(); } // FIXME RS subscribers can't throw diff --git a/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java b/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java index f34ed7b604..120dee09d7 100644 --- a/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java +++ b/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java @@ -290,11 +290,11 @@ public void testRecursionAndOuterUnsubscribe() throws InterruptedException { try { Flowable<Integer> obs = Flowable.unsafeCreate(new Publisher<Integer>() { @Override - public void subscribe(final Subscriber<? super Integer> observer) { + public void subscribe(final Subscriber<? super Integer> subscriber) { inner.schedule(new Runnable() { @Override public void run() { - observer.onNext(42); + subscriber.onNext(42); latch.countDown(); // this will recursively schedule this task for execution again @@ -302,12 +302,12 @@ public void run() { } }); - observer.onSubscribe(new Subscription() { + subscriber.onSubscribe(new Subscription() { @Override public void cancel() { inner.dispose(); - observer.onComplete(); + subscriber.onComplete(); completionLatch.countDown(); } @@ -368,9 +368,9 @@ public final void testSubscribeWithScheduler() throws InterruptedException { final AtomicInteger count = new AtomicInteger(); - Flowable<Integer> o1 = Flowable.<Integer> just(1, 2, 3, 4, 5); + Flowable<Integer> f1 = Flowable.<Integer> just(1, 2, 3, 4, 5); - o1.subscribe(new Consumer<Integer>() { + f1.subscribe(new Consumer<Integer>() { @Override public void accept(Integer t) { @@ -393,7 +393,7 @@ public void accept(Integer t) { final CountDownLatch latch = new CountDownLatch(5); final CountDownLatch first = new CountDownLatch(1); - o1.subscribeOn(scheduler).subscribe(new Consumer<Integer>() { + f1.subscribeOn(scheduler).subscribe(new Consumer<Integer>() { @Override public void accept(Integer t) { diff --git a/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java b/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java index 8d2b56b460..ed67bce571 100644 --- a/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java +++ b/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java @@ -329,11 +329,11 @@ public void run() { public final void testRecursiveSchedulerInObservable() { Flowable<Integer> obs = Flowable.unsafeCreate(new Publisher<Integer>() { @Override - public void subscribe(final Subscriber<? super Integer> observer) { + public void subscribe(final Subscriber<? super Integer> subscriber) { final Scheduler.Worker inner = getScheduler().createWorker(); AsyncSubscription as = new AsyncSubscription(); - observer.onSubscribe(as); + subscriber.onSubscribe(as); as.setResource(inner); inner.schedule(new Runnable() { @@ -343,14 +343,14 @@ public void subscribe(final Subscriber<? super Integer> observer) { public void run() { if (i > 42) { try { - observer.onComplete(); + subscriber.onComplete(); } finally { inner.dispose(); } return; } - observer.onNext(i++); + subscriber.onNext(i++); inner.schedule(this); } @@ -375,18 +375,18 @@ public void accept(Integer v) { public final void testConcurrentOnNextFailsValidation() throws InterruptedException { final int count = 10; final CountDownLatch latch = new CountDownLatch(count); - Flowable<String> o = Flowable.unsafeCreate(new Publisher<String>() { + Flowable<String> f = Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); for (int i = 0; i < count; i++) { final int v = i; new Thread(new Runnable() { @Override public void run() { - observer.onNext("v: " + v); + subscriber.onNext("v: " + v); latch.countDown(); } @@ -397,7 +397,7 @@ public void run() { ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<String>(); // this should call onNext concurrently - o.subscribe(observer); + f.subscribe(observer); if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { fail("timed out"); @@ -412,11 +412,11 @@ public void run() { public final void testObserveOn() throws InterruptedException { final Scheduler scheduler = getScheduler(); - Flowable<String> o = Flowable.fromArray("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"); + Flowable<String> f = Flowable.fromArray("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"); ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<String>(); - o.observeOn(scheduler).subscribe(observer); + f.observeOn(scheduler).subscribe(observer); if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { fail("timed out"); @@ -432,7 +432,7 @@ public final void testObserveOn() throws InterruptedException { public final void testSubscribeOnNestedConcurrency() throws InterruptedException { final Scheduler scheduler = getScheduler(); - Flowable<String> o = Flowable.fromArray("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten") + Flowable<String> f = Flowable.fromArray("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten") .flatMap(new Function<String, Flowable<String>>() { @Override @@ -440,10 +440,10 @@ public Flowable<String> apply(final String v) { return Flowable.unsafeCreate(new Publisher<String>() { @Override - public void subscribe(Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); - observer.onNext("value_after_map-" + v); - observer.onComplete(); + public void subscribe(Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext("value_after_map-" + v); + subscriber.onComplete(); } }).subscribeOn(scheduler); } @@ -451,7 +451,7 @@ public void subscribe(Subscriber<? super String> observer) { ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<String>(); - o.subscribe(observer); + f.subscribe(observer); if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { fail("timed out"); diff --git a/src/test/java/io/reactivex/schedulers/CachedThreadSchedulerTest.java b/src/test/java/io/reactivex/schedulers/CachedThreadSchedulerTest.java index 61b14fac21..df6ba44670 100644 --- a/src/test/java/io/reactivex/schedulers/CachedThreadSchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/CachedThreadSchedulerTest.java @@ -38,9 +38,9 @@ protected Scheduler getScheduler() { @Test public final void testIOScheduler() { - Flowable<Integer> o1 = Flowable.just(1, 2, 3, 4, 5); - Flowable<Integer> o2 = Flowable.just(6, 7, 8, 9, 10); - Flowable<String> o = Flowable.merge(o1, o2).map(new Function<Integer, String>() { + Flowable<Integer> f1 = Flowable.just(1, 2, 3, 4, 5); + Flowable<Integer> f2 = Flowable.just(6, 7, 8, 9, 10); + Flowable<String> f = Flowable.merge(f1, f2).map(new Function<Integer, String>() { @Override public String apply(Integer t) { @@ -49,7 +49,7 @@ public String apply(Integer t) { } }); - o.subscribeOn(Schedulers.io()).blockingForEach(new Consumer<String>() { + f.subscribeOn(Schedulers.io()).blockingForEach(new Consumer<String>() { @Override public void accept(String t) { diff --git a/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java b/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java index 67912db80d..9caa79e7b3 100644 --- a/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java +++ b/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java @@ -91,9 +91,9 @@ public void run() { @Test public final void testComputationThreadPool1() { - Flowable<Integer> o1 = Flowable.<Integer> just(1, 2, 3, 4, 5); - Flowable<Integer> o2 = Flowable.<Integer> just(6, 7, 8, 9, 10); - Flowable<String> o = Flowable.<Integer> merge(o1, o2).map(new Function<Integer, String>() { + Flowable<Integer> f1 = Flowable.<Integer> just(1, 2, 3, 4, 5); + Flowable<Integer> f2 = Flowable.<Integer> just(6, 7, 8, 9, 10); + Flowable<String> f = Flowable.<Integer> merge(f1, f2).map(new Function<Integer, String>() { @Override public String apply(Integer t) { @@ -102,7 +102,7 @@ public String apply(Integer t) { } }); - o.subscribeOn(Schedulers.computation()).blockingForEach(new Consumer<String>() { + f.subscribeOn(Schedulers.computation()).blockingForEach(new Consumer<String>() { @Override public void accept(String t) { @@ -117,9 +117,9 @@ public final void testMergeWithExecutorScheduler() { final String currentThreadName = Thread.currentThread().getName(); - Flowable<Integer> o1 = Flowable.<Integer> just(1, 2, 3, 4, 5); - Flowable<Integer> o2 = Flowable.<Integer> just(6, 7, 8, 9, 10); - Flowable<String> o = Flowable.<Integer> merge(o1, o2).subscribeOn(Schedulers.computation()).map(new Function<Integer, String>() { + Flowable<Integer> f1 = Flowable.<Integer> just(1, 2, 3, 4, 5); + Flowable<Integer> f2 = Flowable.<Integer> just(6, 7, 8, 9, 10); + Flowable<String> f = Flowable.<Integer> merge(f1, f2).subscribeOn(Schedulers.computation()).map(new Function<Integer, String>() { @Override public String apply(Integer t) { @@ -129,7 +129,7 @@ public String apply(Integer t) { } }); - o.blockingForEach(new Consumer<String>() { + f.blockingForEach(new Consumer<String>() { @Override public void accept(String t) { diff --git a/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java b/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java index df40ea63fd..2768a12b1a 100644 --- a/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java @@ -45,9 +45,9 @@ public final void testMergeWithCurrentThreadScheduler1() { final String currentThreadName = Thread.currentThread().getName(); - Flowable<Integer> o1 = Flowable.<Integer> just(1, 2, 3, 4, 5); - Flowable<Integer> o2 = Flowable.<Integer> just(6, 7, 8, 9, 10); - Flowable<String> o = Flowable.<Integer> merge(o1, o2).subscribeOn(Schedulers.trampoline()).map(new Function<Integer, String>() { + Flowable<Integer> f1 = Flowable.<Integer> just(1, 2, 3, 4, 5); + Flowable<Integer> f2 = Flowable.<Integer> just(6, 7, 8, 9, 10); + Flowable<String> f = Flowable.<Integer> merge(f1, f2).subscribeOn(Schedulers.trampoline()).map(new Function<Integer, String>() { @Override public String apply(Integer t) { @@ -56,7 +56,7 @@ public String apply(Integer t) { } }); - o.blockingForEach(new Consumer<String>() { + f.blockingForEach(new Consumer<String>() { @Override public void accept(String t) { @@ -110,8 +110,8 @@ public void run() { @Test public void testTrampolineWorkerHandlesConcurrentScheduling() { final Worker trampolineWorker = Schedulers.trampoline().createWorker(); - final Subscriber<Object> observer = TestHelper.mockSubscriber(); - final TestSubscriber<Disposable> ts = new TestSubscriber<Disposable>(observer); + final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); + final TestSubscriber<Disposable> ts = new TestSubscriber<Disposable>(subscriber); // Spam the trampoline with actions. Flowable.range(0, 50) diff --git a/src/test/java/io/reactivex/single/SingleNullTests.java b/src/test/java/io/reactivex/single/SingleNullTests.java index 374d7ee313..3efcbbcc6e 100644 --- a/src/test/java/io/reactivex/single/SingleNullTests.java +++ b/src/test/java/io/reactivex/single/SingleNullTests.java @@ -664,7 +664,7 @@ public void liftNull() { public void liftFunctionReturnsNull() { just1.lift(new SingleOperator<Object, Integer>() { @Override - public SingleObserver<? super Integer> apply(SingleObserver<? super Object> s) { + public SingleObserver<? super Integer> apply(SingleObserver<? super Object> observer) { return null; } }).blockingGet(); diff --git a/src/test/java/io/reactivex/single/SingleTest.java b/src/test/java/io/reactivex/single/SingleTest.java index ac9df2fafb..9e3d136c6d 100644 --- a/src/test/java/io/reactivex/single/SingleTest.java +++ b/src/test/java/io/reactivex/single/SingleTest.java @@ -131,9 +131,9 @@ public void testCreateSuccess() { Single.unsafeCreate(new SingleSource<Object>() { @Override - public void subscribe(SingleObserver<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onSuccess("Hello"); + public void subscribe(SingleObserver<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onSuccess("Hello"); } }).toFlowable().subscribe(ts); @@ -145,9 +145,9 @@ public void testCreateError() { TestSubscriber<Object> ts = new TestSubscriber<Object>(); Single.unsafeCreate(new SingleSource<Object>() { @Override - public void subscribe(SingleObserver<? super Object> s) { - s.onSubscribe(Disposables.empty()); - s.onError(new RuntimeException("fail")); + public void subscribe(SingleObserver<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onError(new RuntimeException("fail")); } }).toFlowable().subscribe(ts); @@ -202,14 +202,14 @@ public void testTimeout() { TestSubscriber<String> ts = new TestSubscriber<String>(); Single<String> s1 = Single.<String>unsafeCreate(new SingleSource<String>() { @Override - public void subscribe(SingleObserver<? super String> s) { - s.onSubscribe(Disposables.empty()); + public void subscribe(SingleObserver<? super String> observer) { + observer.onSubscribe(Disposables.empty()); try { Thread.sleep(5000); } catch (InterruptedException e) { // ignore as we expect this for the test } - s.onSuccess("success"); + observer.onSuccess("success"); } }).subscribeOn(Schedulers.io()); @@ -224,14 +224,14 @@ public void testTimeoutWithFallback() { TestSubscriber<String> ts = new TestSubscriber<String>(); Single<String> s1 = Single.<String>unsafeCreate(new SingleSource<String>() { @Override - public void subscribe(SingleObserver<? super String> s) { - s.onSubscribe(Disposables.empty()); + public void subscribe(SingleObserver<? super String> observer) { + observer.onSubscribe(Disposables.empty()); try { Thread.sleep(5000); } catch (InterruptedException e) { // ignore as we expect this for the test } - s.onSuccess("success"); + observer.onSuccess("success"); } }).subscribeOn(Schedulers.io()); @@ -251,16 +251,16 @@ public void testUnsubscribe() throws InterruptedException { Single<String> s1 = Single.<String>unsafeCreate(new SingleSource<String>() { @Override - public void subscribe(final SingleObserver<? super String> s) { + public void subscribe(final SingleObserver<? super String> observer) { SerialDisposable sd = new SerialDisposable(); - s.onSubscribe(sd); + observer.onSubscribe(sd); final Thread t = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); - s.onSuccess("success"); + observer.onSuccess("success"); } catch (InterruptedException e) { interrupted.set(true); latch.countDown(); @@ -325,16 +325,16 @@ public void onError(Throwable error) { Single<String> s1 = Single.unsafeCreate(new SingleSource<String>() { @Override - public void subscribe(final SingleObserver<? super String> s) { + public void subscribe(final SingleObserver<? super String> observer) { SerialDisposable sd = new SerialDisposable(); - s.onSubscribe(sd); + observer.onSubscribe(sd); final Thread t = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); - s.onSuccess("success"); + observer.onSuccess("success"); } catch (InterruptedException e) { interrupted.set(true); latch.countDown(); @@ -381,16 +381,16 @@ public void testUnsubscribeViaReturnedSubscription() throws InterruptedException Single<String> s1 = Single.unsafeCreate(new SingleSource<String>() { @Override - public void subscribe(final SingleObserver<? super String> s) { + public void subscribe(final SingleObserver<? super String> observer) { SerialDisposable sd = new SerialDisposable(); - s.onSubscribe(sd); + observer.onSubscribe(sd); final Thread t = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); - s.onSuccess("success"); + observer.onSuccess("success"); } catch (InterruptedException e) { interrupted.set(true); latch.countDown(); diff --git a/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java b/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java index a57aaf6a4a..2e1893d2f8 100644 --- a/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java @@ -117,27 +117,27 @@ public void testOnErrorAfterOnCompleted() { */ private static class TestObservable implements Publisher<String> { - Subscriber<? super String> observer; + Subscriber<? super String> subscriber; /* used to simulate subscription */ public void sendOnCompleted() { - observer.onComplete(); + subscriber.onComplete(); } /* used to simulate subscription */ public void sendOnNext(String value) { - observer.onNext(value); + subscriber.onNext(value); } /* used to simulate subscription */ public void sendOnError(Throwable e) { - observer.onError(e); + subscriber.onError(e); } @Override - public void subscribe(Subscriber<? super String> observer) { - this.observer = observer; - observer.onSubscribe(new Subscription() { + public void subscribe(Subscriber<? super String> subscriber) { + this.subscriber = subscriber; + subscriber.onSubscribe(new Subscription() { @Override public void cancel() { @@ -199,7 +199,7 @@ public void onCompleteFailure() { @Test public void onErrorFailure() { try { - OBSERVER_ONERROR_FAIL().onError(new SafeSubscriberTestException("error!")); + subscriberOnErrorFail().onError(new SafeSubscriberTestException("error!")); fail("expects exception to be thrown"); } catch (Exception e) { assertTrue(e instanceof SafeSubscriberTestException); @@ -211,7 +211,7 @@ public void onErrorFailure() { @Ignore("Observers can't throw") public void onErrorFailureSafe() { try { - new SafeSubscriber<String>(OBSERVER_ONERROR_FAIL()).onError(new SafeSubscriberTestException("error!")); + new SafeSubscriber<String>(subscriberOnErrorFail()).onError(new SafeSubscriberTestException("error!")); fail("expects exception to be thrown"); } catch (Exception e) { e.printStackTrace(); @@ -237,7 +237,7 @@ public void onErrorFailureSafe() { @Ignore("Observers can't throw") public void onErrorNotImplementedFailureSafe() { try { - new SafeSubscriber<String>(OBSERVER_ONERROR_NOTIMPLEMENTED()).onError(new SafeSubscriberTestException("error!")); + new SafeSubscriber<String>(subscriberOnErrorNotImplemented()).onError(new SafeSubscriberTestException("error!")); fail("expects exception to be thrown"); } catch (Exception e) { // assertTrue(e instanceof OnErrorNotImplementedException); @@ -301,10 +301,10 @@ public void request(long n) { @Test @Ignore("Observers can't throw") public void onCompleteSuccessWithUnsubscribeFailure() { - Subscriber<String> o = OBSERVER_SUCCESS(); + Subscriber<String> subscriber = subscriberSuccess(); try { - o.onSubscribe(THROWING_DISPOSABLE); - new SafeSubscriber<String>(o).onComplete(); + subscriber.onSubscribe(THROWING_DISPOSABLE); + new SafeSubscriber<String>(subscriber).onComplete(); fail("expects exception to be thrown"); } catch (Exception e) { e.printStackTrace(); @@ -322,10 +322,10 @@ public void onCompleteSuccessWithUnsubscribeFailure() { @Ignore("Observers can't throw") public void onErrorSuccessWithUnsubscribeFailure() { AtomicReference<Throwable> onError = new AtomicReference<Throwable>(); - Subscriber<String> o = OBSERVER_SUCCESS(onError); + Subscriber<String> subscriber = subscriberSuccess(onError); try { - o.onSubscribe(THROWING_DISPOSABLE); - new SafeSubscriber<String>(o).onError(new SafeSubscriberTestException("failed")); + subscriber.onSubscribe(THROWING_DISPOSABLE); + new SafeSubscriber<String>(subscriber).onError(new SafeSubscriberTestException("failed")); fail("we expect the unsubscribe failure to cause an exception to be thrown"); } catch (Exception e) { e.printStackTrace(); @@ -348,10 +348,10 @@ public void onErrorSuccessWithUnsubscribeFailure() { @Test @Ignore("Observers can't throw") public void onErrorFailureWithUnsubscribeFailure() { - Subscriber<String> o = OBSERVER_ONERROR_FAIL(); + Subscriber<String> subscriber = subscriberOnErrorFail(); try { - o.onSubscribe(THROWING_DISPOSABLE); - new SafeSubscriber<String>(o).onError(new SafeSubscriberTestException("onError failure")); + subscriber.onSubscribe(THROWING_DISPOSABLE); + new SafeSubscriber<String>(subscriber).onError(new SafeSubscriberTestException("onError failure")); fail("expects exception to be thrown"); } catch (Exception e) { e.printStackTrace(); @@ -385,10 +385,10 @@ public void onErrorFailureWithUnsubscribeFailure() { @Test @Ignore("Observers can't throw") public void onErrorNotImplementedFailureWithUnsubscribeFailure() { - Subscriber<String> o = OBSERVER_ONERROR_NOTIMPLEMENTED(); + Subscriber<String> subscriber = subscriberOnErrorNotImplemented(); try { - o.onSubscribe(THROWING_DISPOSABLE); - new SafeSubscriber<String>(o).onError(new SafeSubscriberTestException("error!")); + subscriber.onSubscribe(THROWING_DISPOSABLE); + new SafeSubscriber<String>(subscriber).onError(new SafeSubscriberTestException("error!")); fail("expects exception to be thrown"); } catch (Exception e) { e.printStackTrace(); @@ -415,7 +415,7 @@ public void onErrorNotImplementedFailureWithUnsubscribeFailure() { } } - private static Subscriber<String> OBSERVER_SUCCESS() { + private static Subscriber<String> subscriberSuccess() { return new DefaultSubscriber<String>() { @Override @@ -436,7 +436,7 @@ public void onNext(String args) { } - private static Subscriber<String> OBSERVER_SUCCESS(final AtomicReference<Throwable> onError) { + private static Subscriber<String> subscriberSuccess(final AtomicReference<Throwable> onError) { return new DefaultSubscriber<String>() { @Override @@ -499,7 +499,7 @@ public void onNext(String args) { }; } - private static Subscriber<String> OBSERVER_ONERROR_FAIL() { + private static Subscriber<String> subscriberOnErrorFail() { return new DefaultSubscriber<String>() { @Override @@ -520,7 +520,7 @@ public void onNext(String args) { }; } - private static Subscriber<String> OBSERVER_ONERROR_NOTIMPLEMENTED() { + private static Subscriber<String> subscriberOnErrorNotImplemented() { return new DefaultSubscriber<String>() { @Override diff --git a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java index 6f2e6fc7e6..44d2920699 100644 --- a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java @@ -32,15 +32,15 @@ public class SerializedSubscriberTest { - Subscriber<String> observer; + Subscriber<String> subscriber; @Before public void before() { - observer = TestHelper.mockSubscriber(); + subscriber = TestHelper.mockSubscriber(); } - private Subscriber<String> serializedSubscriber(Subscriber<String> o) { - return new SerializedSubscriber<String>(o); + private Subscriber<String> serializedSubscriber(Subscriber<String> subscriber) { + return new SerializedSubscriber<String>(subscriber); } @Test @@ -48,16 +48,16 @@ public void testSingleThreadedBasic() { TestSingleThreadedPublisher onSubscribe = new TestSingleThreadedPublisher("one", "two", "three"); Flowable<String> w = Flowable.unsafeCreate(onSubscribe); - Subscriber<String> aw = serializedSubscriber(observer); + Subscriber<String> aw = serializedSubscriber(subscriber); w.subscribe(aw); onSubscribe.waitToFinish(); - verify(observer, times(1)).onNext("one"); - verify(observer, times(1)).onNext("two"); - verify(observer, times(1)).onNext("three"); - verify(observer, never()).onError(any(Throwable.class)); - verify(observer, times(1)).onComplete(); + verify(subscriber, times(1)).onNext("one"); + verify(subscriber, times(1)).onNext("two"); + verify(subscriber, times(1)).onNext("three"); + verify(subscriber, never()).onError(any(Throwable.class)); + verify(subscriber, times(1)).onComplete(); // non-deterministic because unsubscribe happens after 'waitToFinish' releases // so commenting out for now as this is not a critical thing to test here // verify(s, times(1)).unsubscribe(); @@ -290,10 +290,10 @@ public void onNext(String t) { } }); - Subscriber<String> o = serializedSubscriber(ts); + Subscriber<String> subscriber = serializedSubscriber(ts); - Future<?> f1 = tp1.submit(new OnNextThread(o, 1, onNextCount, running)); - Future<?> f2 = tp2.submit(new OnNextThread(o, 1, onNextCount, running)); + Future<?> f1 = tp1.submit(new OnNextThread(subscriber, 1, onNextCount, running)); + Future<?> f2 = tp2.submit(new OnNextThread(subscriber, 1, onNextCount, running)); running.await(); // let one of the OnNextThread actually run before proceeding @@ -315,7 +315,7 @@ public void onNext(String t) { assertSame(t1, t2); System.out.println(ts.values()); - o.onComplete(); + subscriber.onComplete(); System.out.println(ts.values()); } } finally { @@ -370,16 +370,16 @@ public void onNext(String t) { } }); - final Subscriber<String> o = serializedSubscriber(ts); + final Subscriber<String> subscriber = serializedSubscriber(ts); AtomicInteger p1 = new AtomicInteger(); AtomicInteger p2 = new AtomicInteger(); - o.onSubscribe(new BooleanSubscription()); + subscriber.onSubscribe(new BooleanSubscription()); ResourceSubscriber<String> as1 = new ResourceSubscriber<String>() { @Override public void onNext(String t) { - o.onNext(t); + subscriber.onNext(t); } @Override @@ -396,7 +396,7 @@ public void onComplete() { ResourceSubscriber<String> as2 = new ResourceSubscriber<String>() { @Override public void onNext(String t) { - o.onNext(t); + subscriber.onNext(t); } @Override @@ -455,29 +455,29 @@ public void subscribe(Subscriber<? super String> s) { public static class OnNextThread implements Runnable { private final CountDownLatch latch; - private final Subscriber<String> observer; + private final Subscriber<String> subscriber; private final int numStringsToSend; final AtomicInteger produced; private final CountDownLatch running; - OnNextThread(Subscriber<String> observer, int numStringsToSend, CountDownLatch latch, CountDownLatch running) { - this(observer, numStringsToSend, new AtomicInteger(), latch, running); + OnNextThread(Subscriber<String> subscriber, int numStringsToSend, CountDownLatch latch, CountDownLatch running) { + this(subscriber, numStringsToSend, new AtomicInteger(), latch, running); } - OnNextThread(Subscriber<String> observer, int numStringsToSend, AtomicInteger produced) { - this(observer, numStringsToSend, produced, null, null); + OnNextThread(Subscriber<String> subscriber, int numStringsToSend, AtomicInteger produced) { + this(subscriber, numStringsToSend, produced, null, null); } - OnNextThread(Subscriber<String> observer, int numStringsToSend, AtomicInteger produced, CountDownLatch latch, CountDownLatch running) { - this.observer = observer; + OnNextThread(Subscriber<String> subscriber, int numStringsToSend, AtomicInteger produced, CountDownLatch latch, CountDownLatch running) { + this.subscriber = subscriber; this.numStringsToSend = numStringsToSend; this.produced = produced; this.latch = latch; this.running = running; } - OnNextThread(Subscriber<String> observer, int numStringsToSend) { - this(observer, numStringsToSend, new AtomicInteger()); + OnNextThread(Subscriber<String> subscriber, int numStringsToSend) { + this(subscriber, numStringsToSend, new AtomicInteger()); } @Override @@ -486,7 +486,7 @@ public void run() { running.countDown(); } for (int i = 0; i < numStringsToSend; i++) { - observer.onNext(Thread.currentThread().getId() + "-" + i); + subscriber.onNext(Thread.currentThread().getId() + "-" + i); if (latch != null) { latch.countDown(); } @@ -500,12 +500,12 @@ public void run() { */ public static class CompletionThread implements Runnable { - private final Subscriber<String> observer; + private final Subscriber<String> subscriber; private final TestConcurrencySubscriberEvent event; private final Future<?>[] waitOnThese; CompletionThread(Subscriber<String> Subscriber, TestConcurrencySubscriberEvent event, Future<?>... waitOnThese) { - this.observer = Subscriber; + this.subscriber = Subscriber; this.event = event; this.waitOnThese = waitOnThese; } @@ -525,9 +525,9 @@ public void run() { /* send the event */ if (event == TestConcurrencySubscriberEvent.onError) { - observer.onError(new RuntimeException("mocked exception")); + subscriber.onError(new RuntimeException("mocked exception")); } else if (event == TestConcurrencySubscriberEvent.onComplete) { - observer.onComplete(); + subscriber.onComplete(); } else { throw new IllegalArgumentException("Expecting either onError or onComplete"); @@ -642,8 +642,8 @@ static class TestSingleThreadedPublisher implements Publisher<String> { } @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); System.out.println("TestSingleThreadedObservable subscribed to ..."); t = new Thread(new Runnable() { @@ -653,9 +653,9 @@ public void run() { System.out.println("running TestSingleThreadedObservable thread"); for (String s : values) { System.out.println("TestSingleThreadedObservable onNext: " + s); - observer.onNext(s); + subscriber.onNext(s); } - observer.onComplete(); + subscriber.onComplete(); } catch (Throwable e) { throw new RuntimeException(e); } @@ -694,8 +694,8 @@ static class TestMultiThreadedObservable implements Publisher<String> { } @Override - public void subscribe(final Subscriber<? super String> observer) { - observer.onSubscribe(new BooleanSubscription()); + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); final NullPointerException npe = new NullPointerException(); System.out.println("TestMultiThreadedObservable subscribed to ..."); t = new Thread(new Runnable() { @@ -725,7 +725,7 @@ public void run() { Thread.sleep(sleep); } } - observer.onNext(s); + subscriber.onNext(s); // capture 'maxThreads' int concurrentThreads = threadsRunning.get(); int maxThreads = maxConcurrentThreads.get(); @@ -733,7 +733,7 @@ public void run() { maxConcurrentThreads.compareAndSet(maxThreads, concurrentThreads); } } catch (Throwable e) { - observer.onError(e); + subscriber.onError(e); } finally { threadsRunning.decrementAndGet(); } @@ -755,7 +755,7 @@ public void run() { } catch (InterruptedException e) { throw new RuntimeException(e); } - observer.onComplete(); + subscriber.onComplete(); } }); System.out.println("starting TestMultiThreadedObservable thread"); diff --git a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java index 98657d5883..a720be050c 100644 --- a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java @@ -46,69 +46,69 @@ public class TestSubscriberTest { @Test public void testAssert() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - oi.subscribe(o); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + oi.subscribe(ts); - o.assertValues(1, 2); - o.assertValueCount(2); - o.assertTerminated(); + ts.assertValues(1, 2); + ts.assertValueCount(2); + ts.assertTerminated(); } @Test public void testAssertNotMatchCount() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - oi.subscribe(o); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + oi.subscribe(ts); thrown.expect(AssertionError.class); // FIXME different message pattern // thrown.expectMessage("Number of items does not match. Provided: 1 Actual: 2"); - o.assertValues(1); - o.assertValueCount(2); - o.assertTerminated(); + ts.assertValues(1); + ts.assertValueCount(2); + ts.assertTerminated(); } @Test public void testAssertNotMatchValue() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - oi.subscribe(o); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + oi.subscribe(ts); thrown.expect(AssertionError.class); // FIXME different message pattern // thrown.expectMessage("Value at index: 1 expected to be [3] (Integer) but was: [2] (Integer)"); - o.assertValues(1, 3); - o.assertValueCount(2); - o.assertTerminated(); + ts.assertValues(1, 3); + ts.assertValueCount(2); + ts.assertTerminated(); } @Test public void assertNeverAtNotMatchingValue() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - oi.subscribe(o); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + oi.subscribe(ts); - o.assertNever(3); - o.assertValueCount(2); - o.assertTerminated(); + ts.assertNever(3); + ts.assertValueCount(2); + ts.assertTerminated(); } @Test public void assertNeverAtMatchingValue() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - oi.subscribe(o); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + oi.subscribe(ts); - o.assertValues(1, 2); + ts.assertValues(1, 2); thrown.expect(AssertionError.class); - o.assertNever(2); - o.assertValueCount(2); - o.assertTerminated(); + ts.assertNever(2); + ts.assertValueCount(2); + ts.assertTerminated(); } @Test @@ -146,8 +146,8 @@ public boolean test(final Integer o) throws Exception { @Test public void testAssertTerminalEventNotReceived() { PublishProcessor<Integer> p = PublishProcessor.create(); - TestSubscriber<Integer> o = new TestSubscriber<Integer>(); - p.subscribe(o); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + p.subscribe(ts); p.onNext(1); p.onNext(2); @@ -156,35 +156,35 @@ public void testAssertTerminalEventNotReceived() { // FIXME different message pattern // thrown.expectMessage("No terminal events received."); - o.assertValues(1, 2); - o.assertValueCount(2); - o.assertTerminated(); + ts.assertValues(1, 2); + ts.assertValueCount(2); + ts.assertTerminated(); } @Test public void testWrappingMock() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2)); - Subscriber<Integer> mockObserver = TestHelper.mockSubscriber(); + Subscriber<Integer> mockSubscriber = TestHelper.mockSubscriber(); - oi.subscribe(new TestSubscriber<Integer>(mockObserver)); + oi.subscribe(new TestSubscriber<Integer>(mockSubscriber)); - InOrder inOrder = inOrder(mockObserver); - inOrder.verify(mockObserver, times(1)).onNext(1); - inOrder.verify(mockObserver, times(1)).onNext(2); - inOrder.verify(mockObserver, times(1)).onComplete(); + InOrder inOrder = inOrder(mockSubscriber); + inOrder.verify(mockSubscriber, times(1)).onNext(1); + inOrder.verify(mockSubscriber, times(1)).onNext(2); + inOrder.verify(mockSubscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void testWrappingMockWhenUnsubscribeInvolved() { Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)).take(2); - Subscriber<Integer> mockObserver = TestHelper.mockSubscriber(); - oi.subscribe(new TestSubscriber<Integer>(mockObserver)); + Subscriber<Integer> mockSubscriber = TestHelper.mockSubscriber(); + oi.subscribe(new TestSubscriber<Integer>(mockSubscriber)); - InOrder inOrder = inOrder(mockObserver); - inOrder.verify(mockObserver, times(1)).onNext(1); - inOrder.verify(mockObserver, times(1)).onNext(2); - inOrder.verify(mockObserver, times(1)).onComplete(); + InOrder inOrder = inOrder(mockSubscriber); + inOrder.verify(mockSubscriber, times(1)).onNext(1); + inOrder.verify(mockSubscriber, times(1)).onNext(2); + inOrder.verify(mockSubscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } diff --git a/src/test/java/io/reactivex/tck/MulticastProcessorRefCountedTckTest.java b/src/test/java/io/reactivex/tck/MulticastProcessorRefCountedTckTest.java index 24a3b8d09f..0e61371f7e 100644 --- a/src/test/java/io/reactivex/tck/MulticastProcessorRefCountedTckTest.java +++ b/src/test/java/io/reactivex/tck/MulticastProcessorRefCountedTckTest.java @@ -26,7 +26,7 @@ public class MulticastProcessorRefCountedTckTest extends IdentityProcessorVerification<Integer> { public MulticastProcessorRefCountedTckTest() { - super(new TestEnvironment(50)); + super(new TestEnvironment(200)); } @Override From 7ade77a94439639d65a8293d7908177d7bd10a7d Mon Sep 17 00:00:00 2001 From: ChanHoHo <41296887+ChanHoHo@users.noreply.github.com> Date: Thu, 2 Aug 2018 00:08:30 +0800 Subject: [PATCH 245/417] Fixed broken link under RxJS in docs/Additional-Reading.md (#6125) * Fixed broken link in docs/Additional-Reading.md * updated broken-link in docs/Additional-reading.md --- docs/Additional-Reading.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/Additional-Reading.md b/docs/Additional-Reading.md index 8693b414c6..6f65b4f677 100644 --- a/docs/Additional-Reading.md +++ b/docs/Additional-Reading.md @@ -1,4 +1,4 @@ -(A more complete and up-to-date list of resources can be found at the reactivex.io site: [[http://reactivex.io/tutorials.html]]) +(A more complete and up-to-date list of resources can be found at the reactivex.io site: [[http://reactivex.io/tutorials.html]]) # Introducing Reactive Programming * [Introduction to Rx](http://www.introtorx.com/): a free, on-line book by Lee Campbell @@ -38,11 +38,11 @@ * [MSDN Rx forum](http://social.msdn.microsoft.com/Forums/en-US/home?forum=rx) # RxJS -* [the RxJS github site](http://reactive-extensions.github.io/RxJS/) +* [the RxJS github site](https://github.com/reactivex/rxjs) * An interactive tutorial: [Functional Programming in Javascript](http://jhusain.github.io/learnrx/) and [an accompanying lecture (video)](http://www.youtube.com/watch?v=LB4lhFJBBq0) by Jafar Husain * [Netflix JavaScript Talks - Async JavaScript with Reactive Extensions](https://www.youtube.com/watch?v=XRYN2xt11Ek) video of a talk by Jafar Husain about the Rx way of programming * [RxJS](https://xgrommx.github.io/rx-book/), an on-line book by @xgrommx -* [Journey from procedural to reactive Javascript with stops](http://bahmutov.calepin.co/journey-from-procedural-to-reactive-javascript-with-stops.html) by Gleb Bahmutov +* [Journey from procedural to reactive Javascript with stops](https://glebbahmutov.com/blog/journey-from-procedural-to-reactive-javascript-with-stops/) by Gleb Bahmutov # Miscellany * [RxJava Observables and Akka Actors](http://onoffswitch.net/rxjava-observables-akka-actors/) by Anton Kropp From a008e03484177f48ec7fef4c311705bb43fd8ec9 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 1 Aug 2018 22:20:36 +0200 Subject: [PATCH 246/417] 2.x: Improve Completable.onErrorResumeNext internals (#6123) * 2.x: Improve Completable.onErrorResumeNext internals * Use ObjectHelper --- .../completable/CompletableResumeNext.java | 76 +++++++++---------- .../completable/CompletableTest.java | 7 +- .../CompletableResumeNextTest.java | 61 +++++++++++++++ 3 files changed, 104 insertions(+), 40 deletions(-) create mode 100644 src/test/java/io/reactivex/internal/operators/completable/CompletableResumeNextTest.java diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java index 16c46aeb24..940942c943 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java @@ -13,11 +13,14 @@ package io.reactivex.internal.operators.completable; +import java.util.concurrent.atomic.AtomicReference; + import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; -import io.reactivex.internal.disposables.SequentialDisposable; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; public final class CompletableResumeNext extends Completable { @@ -35,20 +38,32 @@ public CompletableResumeNext(CompletableSource source, @Override protected void subscribeActual(final CompletableObserver observer) { - - final SequentialDisposable sd = new SequentialDisposable(); - observer.onSubscribe(sd); - source.subscribe(new ResumeNext(observer, sd)); + ResumeNextObserver parent = new ResumeNextObserver(observer, errorMapper); + observer.onSubscribe(parent); + source.subscribe(parent); } - final class ResumeNext implements CompletableObserver { + static final class ResumeNextObserver + extends AtomicReference<Disposable> + implements CompletableObserver, Disposable { + + private static final long serialVersionUID = 5018523762564524046L; final CompletableObserver downstream; - final SequentialDisposable sd; - ResumeNext(CompletableObserver observer, SequentialDisposable sd) { + final Function<? super Throwable, ? extends CompletableSource> errorMapper; + + boolean once; + + ResumeNextObserver(CompletableObserver observer, Function<? super Throwable, ? extends CompletableSource> errorMapper) { this.downstream = observer; - this.sd = sd; + this.errorMapper = errorMapper; + } + + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(this, d); } @Override @@ -58,48 +73,33 @@ public void onComplete() { @Override public void onError(Throwable e) { + if (once) { + downstream.onError(e); + return; + } + once = true; + CompletableSource c; try { - c = errorMapper.apply(e); + c = ObjectHelper.requireNonNull(errorMapper.apply(e), "The errorMapper returned a null CompletableSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - downstream.onError(new CompositeException(ex, e)); + downstream.onError(new CompositeException(e, ex)); return; } - if (c == null) { - NullPointerException npe = new NullPointerException("The CompletableConsumable returned is null"); - npe.initCause(e); - downstream.onError(npe); - return; - } - - c.subscribe(new OnErrorObserver()); + c.subscribe(this); } @Override - public void onSubscribe(Disposable d) { - sd.update(d); + public boolean isDisposed() { + return DisposableHelper.isDisposed(get()); } - final class OnErrorObserver implements CompletableObserver { - - @Override - public void onComplete() { - downstream.onComplete(); - } - - @Override - public void onError(Throwable e) { - downstream.onError(e); - } - - @Override - public void onSubscribe(Disposable d) { - sd.update(d); - } - + @Override + public void dispose() { + DisposableHelper.dispose(this); } } } diff --git a/src/test/java/io/reactivex/completable/CompletableTest.java b/src/test/java/io/reactivex/completable/CompletableTest.java index 5dcfa1b531..dd4bdfc9e3 100644 --- a/src/test/java/io/reactivex/completable/CompletableTest.java +++ b/src/test/java/io/reactivex/completable/CompletableTest.java @@ -2170,8 +2170,11 @@ public Completable apply(Throwable e) { try { c.blockingAwait(); Assert.fail("Did not throw an exception"); - } catch (NullPointerException ex) { - Assert.assertTrue(ex.getCause() instanceof TestException); + } catch (CompositeException ex) { + List<Throwable> errors = ex.getExceptions(); + TestHelper.assertError(errors, 0, TestException.class); + TestHelper.assertError(errors, 1, NullPointerException.class); + assertEquals(2, errors.size()); } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableResumeNextTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableResumeNextTest.java new file mode 100644 index 0000000000..c2a3af2769 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableResumeNextTest.java @@ -0,0 +1,61 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.internal.functions.Functions; + +public class CompletableResumeNextTest { + + @Test + public void resumeWithError() { + Completable.error(new TestException()) + .onErrorResumeNext(Functions.justFunction(Completable.error(new TestException("second")))) + .test() + .assertFailureAndMessage(TestException.class, "second"); + } + + @Test + public void disposeInMain() { + TestHelper.checkDisposedCompletable(new Function<Completable, CompletableSource>() { + @Override + public CompletableSource apply(Completable c) throws Exception { + return c.onErrorResumeNext(Functions.justFunction(Completable.complete())); + } + }); + } + + + @Test + public void disposeInResume() { + TestHelper.checkDisposedCompletable(new Function<Completable, CompletableSource>() { + @Override + public CompletableSource apply(Completable c) throws Exception { + return Completable.error(new TestException()).onErrorResumeNext(Functions.justFunction(c)); + } + }); + } + + @Test + public void disposed() { + TestHelper.checkDisposed( + Completable.error(new TestException()) + .onErrorResumeNext(Functions.justFunction(Completable.never())) + ); + } +} From c0f17ce9d83d6fff506e17020e3881074ec41efd Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Thu, 2 Aug 2018 09:34:23 +0200 Subject: [PATCH 247/417] Add marbles for Single.timer, Single.defer and Single.toXXX operators (#6095) * Add marbles for Single.timer, Single.defer and Single.toXXX operators * Correct image height for marbles --- src/main/java/io/reactivex/Single.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 17d243f7a1..84f40621c4 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -493,6 +493,8 @@ public static <T> Single<T> create(SingleOnSubscribe<T> source) { /** * Calls a {@link Callable} for each individual {@link SingleObserver} to return the actual {@link SingleSource} to * be subscribed to. + * <p> + * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.defer.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code defer} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1243,6 +1245,8 @@ public static <T> Single<T> never() { /** * Signals success with 0L value after the given delay for each SingleObserver. + * <p> + * <img width="640" height="292" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timer.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timer} operates by default on the {@code computation} {@link Scheduler}.</dd> @@ -1260,6 +1264,8 @@ public static Single<Long> timer(long delay, TimeUnit unit) { /** * Signals success with 0L value after the given delay for each SingleObserver. + * <p> + * <img width="640" height="292" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timer.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify the {@link Scheduler} to signal on.</dd> @@ -3705,7 +3711,7 @@ public final Completable ignoreElement() { /** * Converts this Single into a {@link Flowable}. * <p> - * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.toObservable.png" alt=""> + * <img width="640" height="462" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.toFlowable.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -3729,7 +3735,7 @@ public final Flowable<T> toFlowable() { /** * Returns a {@link Future} representing the single value emitted by this {@code Single}. * <p> - * <img width="640" height="395" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/B.toFuture.png" alt=""> + * <img width="640" height="467" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/Single.toFuture.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toFuture} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3747,7 +3753,7 @@ public final Future<T> toFuture() { /** * Converts this Single into a {@link Maybe}. * <p> - * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.toObservable.png" alt=""> + * <img width="640" height="463" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.toMaybe.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toMaybe} does not operate by default on a particular {@link Scheduler}.</dd> From 30afb3b9f82e53fa82a127cf745198b324631bf2 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 2 Aug 2018 10:02:06 +0200 Subject: [PATCH 248/417] 2.x: Flowable.onErrorResumeNext improvements (#6121) --- .../flowable/FlowableOnErrorNext.java | 31 +++++++++++-------- .../reactivex/flowable/FlowableNullTests.java | 22 ++++++++----- 2 files changed, 33 insertions(+), 20 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java index dd1198d0a9..8a36aad3ce 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java @@ -18,6 +18,7 @@ import io.reactivex.*; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; +import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.subscriptions.SubscriptionArbiter; import io.reactivex.plugins.RxJavaPlugins; @@ -35,30 +36,36 @@ public FlowableOnErrorNext(Flowable<T> source, @Override protected void subscribeActual(Subscriber<? super T> s) { OnErrorNextSubscriber<T> parent = new OnErrorNextSubscriber<T>(s, nextSupplier, allowFatal); - s.onSubscribe(parent.arbiter); + s.onSubscribe(parent); source.subscribe(parent); } - static final class OnErrorNextSubscriber<T> implements FlowableSubscriber<T> { + static final class OnErrorNextSubscriber<T> + extends SubscriptionArbiter + implements FlowableSubscriber<T> { + private static final long serialVersionUID = 4063763155303814625L; + final Subscriber<? super T> actual; + final Function<? super Throwable, ? extends Publisher<? extends T>> nextSupplier; + final boolean allowFatal; - final SubscriptionArbiter arbiter; boolean once; boolean done; + long produced; + OnErrorNextSubscriber(Subscriber<? super T> actual, Function<? super Throwable, ? extends Publisher<? extends T>> nextSupplier, boolean allowFatal) { this.actual = actual; this.nextSupplier = nextSupplier; this.allowFatal = allowFatal; - this.arbiter = new SubscriptionArbiter(); } @Override public void onSubscribe(Subscription s) { - arbiter.setSubscription(s); + setSubscription(s); } @Override @@ -66,10 +73,10 @@ public void onNext(T t) { if (done) { return; } - actual.onNext(t); if (!once) { - arbiter.produced(1L); + produced++; } + actual.onNext(t); } @Override @@ -92,18 +99,16 @@ public void onError(Throwable t) { Publisher<? extends T> p; try { - p = nextSupplier.apply(t); + p = ObjectHelper.requireNonNull(nextSupplier.apply(t), "The nextSupplier returned a null Publisher"); } catch (Throwable e) { Exceptions.throwIfFatal(e); actual.onError(new CompositeException(t, e)); return; } - if (p == null) { - NullPointerException npe = new NullPointerException("Publisher is null"); - npe.initCause(t); - actual.onError(npe); - return; + long mainProduced = produced; + if (mainProduced != 0L) { + produced(mainProduced); } p.subscribe(this); diff --git a/src/test/java/io/reactivex/flowable/FlowableNullTests.java b/src/test/java/io/reactivex/flowable/FlowableNullTests.java index 12c7a9b5c1..80f70a75ad 100644 --- a/src/test/java/io/reactivex/flowable/FlowableNullTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableNullTests.java @@ -1648,14 +1648,22 @@ public void onErrorResumeNextFunctionNull() { just1.onErrorResumeNext((Function<Throwable, Publisher<Integer>>)null); } - @Test(expected = NullPointerException.class) + @Test public void onErrorResumeNextFunctionReturnsNull() { - Flowable.error(new TestException()).onErrorResumeNext(new Function<Throwable, Publisher<Object>>() { - @Override - public Publisher<Object> apply(Throwable e) { - return null; - } - }).blockingSubscribe(); + try { + Flowable.error(new TestException()).onErrorResumeNext(new Function<Throwable, Publisher<Object>>() { + @Override + public Publisher<Object> apply(Throwable e) { + return null; + } + }).blockingSubscribe(); + fail("Should have thrown"); + } catch (CompositeException ex) { + List<Throwable> errors = ex.getExceptions(); + TestHelper.assertError(errors, 0, TestException.class); + TestHelper.assertError(errors, 1, NullPointerException.class); + assertEquals(2, errors.size()); + } } @Test(expected = NullPointerException.class) From 2274c42ed4be3f66e999d83bb31a9d23db3a2663 Mon Sep 17 00:00:00 2001 From: JianxinLi <justcoxier@gmail.com> Date: Thu, 2 Aug 2018 20:42:00 +0800 Subject: [PATCH 249/417] 2.x: Remove fromEmitter() in wiki (#6128) --- docs/Creating-Observables.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/Creating-Observables.md b/docs/Creating-Observables.md index 25b215f982..b8a6b90ca7 100644 --- a/docs/Creating-Observables.md +++ b/docs/Creating-Observables.md @@ -2,8 +2,7 @@ This page shows methods that create Observables. * [**`just( )`**](http://reactivex.io/documentation/operators/just.html) — convert an object or several objects into an Observable that emits that object or those objects * [**`from( )`**](http://reactivex.io/documentation/operators/from.html) — convert an Iterable, a Future, or an Array into an Observable -* [**`create( )`**](http://reactivex.io/documentation/operators/create.html) — **advanced use only!** create an Observable from scratch by means of a function, consider `fromEmitter` instead -* [**`fromEmitter()`**](http://reactivex.io/RxJava/javadoc/rx/Observable.html#fromEmitter(rx.functions.Action1,%20rx.AsyncEmitter.BackpressureMode)) — create safe, backpressure-enabled, unsubscription-supporting Observable via a function and push events. +* [**`create( )`**](http://reactivex.io/documentation/operators/create.html) — **advanced use only!** create an Observable from scratch by means of a function * [**`defer( )`**](http://reactivex.io/documentation/operators/defer.html) — do not create the Observable until a Subscriber subscribes; create a fresh Observable on each subscription * [**`range( )`**](http://reactivex.io/documentation/operators/range.html) — create an Observable that emits a range of sequential integers * [**`interval( )`**](http://reactivex.io/documentation/operators/interval.html) — create an Observable that emits a sequence of integers spaced by a given time interval From a58c491b9853e2135d3ae04e08095be79f495ba7 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 3 Aug 2018 22:37:05 +0200 Subject: [PATCH 250/417] 2.x: Update _Sidebar.md with new order of topics (#6133) --- docs/_Sidebar.md | 57 ++++++++++++++++++++++++--------------------- docs/_Sidebar.md.md | 56 +++++++++++++++++++++----------------------- 2 files changed, 57 insertions(+), 56 deletions(-) diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md index d27b620b10..1fe0339407 100644 --- a/docs/_Sidebar.md +++ b/docs/_Sidebar.md @@ -1,26 +1,31 @@ -* [[Getting Started]] -* [[How To Use RxJava]] -* [[Additional Reading]] -* [[Observable]] - * [[Creating Observables]] - * [[Transforming Observables]] - * [[Filtering Observables]] - * [[Combining Observables]] - * [[Error Handling Operators]] - * [[Observable Utility Operators]] - * [[Conditional and Boolean Operators]] - * [[Mathematical and Aggregate Operators]] - * [[Async Operators]] - * [[Connectable Observable Operators]] - * [[Blocking Observable Operators]] - * [[String Observables]] - * [[Alphabetical List of Observable Operators]] - * [[Implementing Your Own Operators]] -* [[Subject]] -* [[Scheduler]] -* [[Plugins]] -* [[Backpressure]] -* [[Error Handling]] -* [[The RxJava Android Module]] -* [[How to Contribute]] -* [Javadoc](http://reactivex.io/RxJava/javadoc/rx/Observable.html) \ No newline at end of file +* [Introduction](https://github.com/ReactiveX/RxJava/wiki/Home) +* [Getting Started](https://github.com/ReactiveX/RxJava/wiki/Getting-Started) +* [How to Use RxJava](https://github.com/ReactiveX/RxJava/wiki/How-To-Use-RxJava) +* [Reactive Streams](https://github.com/ReactiveX/RxJava/wiki/Reactive-Streams) +* [The reactive types of RxJava](https://github.com/ReactiveX/RxJava/wiki/Observable) +* [Schedulers](https://github.com/ReactiveX/RxJava/wiki/Scheduler) +* [Subjects](https://github.com/ReactiveX/RxJava/wiki/Subject) +* [Error Handling](https://github.com/ReactiveX/RxJava/wiki/Error-Handling) +* [Operators (Alphabetical List)](https://github.com/ReactiveX/RxJava/wiki/Alphabetical-List-of-Observable-Operators) + * [Async](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) + * [Blocking](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) + * [Combining](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables) + * [Conditional & Boolean](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators) + * [Connectable](https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators) + * [Creation](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables) + * [Error management](https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators) + * [Filtering](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) + * [Mathematical and Aggregate](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators) + * [Parallel flows](https://github.com/ReactiveX/RxJava/wiki/Parallel-flows) + * [String](https://github.com/ReactiveX/RxJava/wiki/String-Observables) + * [Transformation](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables) + * [Utility](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) + * [Notable 3rd party Operators (Alphabetical List)](https://github.com/ReactiveX/RxJava/wiki/Alphabetical-List-of-3rd-party-Operators) +* [Plugins](https://github.com/ReactiveX/RxJava/wiki/Plugins) +* [How to Contribute](https://github.com/ReactiveX/RxJava/wiki/How-to-Contribute) +* [Writing operators](https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0) +* [Backpressure](https://github.com/ReactiveX/RxJava/wiki/Backpressure-(2.0)) + * [another explanation](https://github.com/ReactiveX/RxJava/wiki/Backpressure) +* [JavaDoc](http://reactivex.io/RxJava/2.x/javadoc) +* [Coming from RxJava 1](https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0) +* [Additional Reading](https://github.com/ReactiveX/RxJava/wiki/Additional-Reading) diff --git a/docs/_Sidebar.md.md b/docs/_Sidebar.md.md index a07aa3d93e..1fe0339407 100644 --- a/docs/_Sidebar.md.md +++ b/docs/_Sidebar.md.md @@ -1,35 +1,31 @@ * [Introduction](https://github.com/ReactiveX/RxJava/wiki/Home) * [Getting Started](https://github.com/ReactiveX/RxJava/wiki/Getting-Started) -* [JavaDoc](http://reactivex.io/RxJava/javadoc) - * [1.x](http://reactivex.io/RxJava/1.x/javadoc/rx/Observable.html) - * [2.x](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html) * [How to Use RxJava](https://github.com/ReactiveX/RxJava/wiki/How-To-Use-RxJava) -* [Additional Reading](https://github.com/ReactiveX/RxJava/wiki/Additional-Reading) -* [The Observable](https://github.com/ReactiveX/RxJava/wiki/Observable) -* Operators [(Alphabetical List)](http://reactivex.io/documentation/operators.html#alphabetical) - * [Async](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) - * [Blocking Observable](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) - * [Combining](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables) - * [Conditional & Boolean](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators) - * [Connectable Observable](https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators) - * [Error Handling Operators](https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators) - * [Filtering](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) - * [Mathematical and Aggregate](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators) - * [Observable Creation](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables) - * [Parallel flows](https://github.com/ReactiveX/RxJava/wiki/Parallel-flows) - * [String](https://github.com/ReactiveX/RxJava/wiki/String-Observables) - * [Transformational](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables) - * [Utility Operators](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) - * [Implementing Custom Operators](https://github.com/ReactiveX/RxJava/wiki/Implementing-custom-operators-(draft)), [previous](https://github.com/ReactiveX/RxJava/wiki/Implementing-Your-Own-Operators) -* [Backpressure](https://github.com/ReactiveX/RxJava/wiki/Backpressure) -* [Error Handling](https://github.com/ReactiveX/RxJava/wiki/Error-Handling) -* [Plugins](https://github.com/ReactiveX/RxJava/wiki/Plugins) +* [Reactive Streams](https://github.com/ReactiveX/RxJava/wiki/Reactive-Streams) +* [The reactive types of RxJava](https://github.com/ReactiveX/RxJava/wiki/Observable) * [Schedulers](https://github.com/ReactiveX/RxJava/wiki/Scheduler) * [Subjects](https://github.com/ReactiveX/RxJava/wiki/Subject) -* [The RxJava Android Module](https://github.com/ReactiveX/RxAndroid/wiki) -* RxJava 2.0 - * [Reactive Streams](https://github.com/ReactiveX/RxJava/wiki/Reactive-Streams) - * [What's different](https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0) - * [Writing operators](https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0) - * [Backpressure](https://github.com/ReactiveX/RxJava/wiki/Backpressure-(2.0)) -* [How to Contribute](https://github.com/ReactiveX/RxJava/wiki/How-to-Contribute) \ No newline at end of file +* [Error Handling](https://github.com/ReactiveX/RxJava/wiki/Error-Handling) +* [Operators (Alphabetical List)](https://github.com/ReactiveX/RxJava/wiki/Alphabetical-List-of-Observable-Operators) + * [Async](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) + * [Blocking](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) + * [Combining](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables) + * [Conditional & Boolean](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators) + * [Connectable](https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators) + * [Creation](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables) + * [Error management](https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators) + * [Filtering](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) + * [Mathematical and Aggregate](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators) + * [Parallel flows](https://github.com/ReactiveX/RxJava/wiki/Parallel-flows) + * [String](https://github.com/ReactiveX/RxJava/wiki/String-Observables) + * [Transformation](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables) + * [Utility](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) + * [Notable 3rd party Operators (Alphabetical List)](https://github.com/ReactiveX/RxJava/wiki/Alphabetical-List-of-3rd-party-Operators) +* [Plugins](https://github.com/ReactiveX/RxJava/wiki/Plugins) +* [How to Contribute](https://github.com/ReactiveX/RxJava/wiki/How-to-Contribute) +* [Writing operators](https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0) +* [Backpressure](https://github.com/ReactiveX/RxJava/wiki/Backpressure-(2.0)) + * [another explanation](https://github.com/ReactiveX/RxJava/wiki/Backpressure) +* [JavaDoc](http://reactivex.io/RxJava/2.x/javadoc) +* [Coming from RxJava 1](https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0) +* [Additional Reading](https://github.com/ReactiveX/RxJava/wiki/Additional-Reading) From 3c27426b764cfcc56df56d1ea2ae2a7f1f019ccc Mon Sep 17 00:00:00 2001 From: Ahmed El-Helw <ahmedre@gmail.com> Date: Sat, 4 Aug 2018 20:33:02 +0400 Subject: [PATCH 251/417] Initial clean up for Combining Observables docs (#6135) * Initial clean up for Combining Observables docs This patch updates the style of the combining observables documentation to be similar to that of #6131 and adds examples for most of the operators therein. Refs #6132. * Address comments --- docs/Combining-Observables.md | 168 ++++++++++++++++++++++++++++++++-- 1 file changed, 161 insertions(+), 7 deletions(-) diff --git a/docs/Combining-Observables.md b/docs/Combining-Observables.md index 2a60e64bd2..0e3796da1f 100644 --- a/docs/Combining-Observables.md +++ b/docs/Combining-Observables.md @@ -1,12 +1,166 @@ This section explains operators you can use to combine multiple Observables. -* [**`startWith( )`**](http://reactivex.io/documentation/operators/startwith.html) — emit a specified sequence of items before beginning to emit the items from the Observable -* [**`merge( )`**](http://reactivex.io/documentation/operators/merge.html) — combine multiple Observables into one -* [**`mergeDelayError( )`**](http://reactivex.io/documentation/operators/merge.html) — combine multiple Observables into one, allowing error-free Observables to continue before propagating errors -* [**`zip( )`**](http://reactivex.io/documentation/operators/zip.html) — combine sets of items emitted by two or more Observables together via a specified function and emit items based on the results of this function -* (`rxjava-joins`) [**`and( )`, `then( )`, and `when( )`**](http://reactivex.io/documentation/operators/and-then-when.html) — combine sets of items emitted by two or more Observables by means of `Pattern` and `Plan` intermediaries -* [**`combineLatest( )`**](http://reactivex.io/documentation/operators/combinelatest.html) — when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function +# Outline + +- [`combineLatest`](#combineLatest) +- [`join` and `groupJoin`](#joins) +- [`merge`](#merge) +- [`mergeDelayError`](#mergeDelayError) +- [`rxjava-joins`](#rxjava-joins) +- [`startWith`](#startWith) +- [`switchOnNext`](#switchOnNext) +- [`zip`](#zip) + +## startWith + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/startwith.html](http://reactivex.io/documentation/operators/startwith.html) + +Emit a specified sequence of items before beginning to emit the items from the Observable. + +#### startWith Example + +```java +Observable<String> names = Observable.just("Spock", "McCoy"); +names.startWith("Kirk").subscribe(item -> System.out.println(item)); + +// prints Kirk, Spock, McCoy +``` + +## merge + +Combines multiple Observables into one. + + +### merge + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/merge.html](http://reactivex.io/documentation/operators/merge.html) + +Combines multiple Observables into one. Any `onError` notifications passed from any of the source observables will immediately be passed through to through to the observers and will terminate the merged `Observable`. + +#### merge Example + +```java +Observable.just(1, 2, 3) + .mergeWith(Observable.just(4, 5, 6)) + .subscribe(item -> System.out.println(item)); + +// prints 1, 2, 3, 4, 5, 6 +``` + +### mergeDelayError + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/merge.html](http://reactivex.io/documentation/operators/merge.html) + +Combines multiple Observables into one. Any `onError` notifications passed from any of the source observables will be withheld until all merged Observables complete, and only then will be passed along to the observers. + +#### mergeDelayError Example + +```java +Observable<String> observable1 = Observable.error(new IllegalArgumentException("")); +Observable<String> observable2 = Observable.just("Four", "Five", "Six"); +Observable.mergeDelayError(observable1, observable2) + .subscribe(item -> System.out.println(item)); + +// emits 4, 5, 6 and then the IllegalArgumentException (in this specific +// example, this throws an `OnErrorNotImplementedException`). +``` + +## zip + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/zip.html](http://reactivex.io/documentation/operators/zip.html) + +Combines sets of items emitted by two or more Observables together via a specified function and emit items based on the results of this function. + +#### zip Example + +```java +Observable<String> firstNames = Observable.just("James", "Jean-Luc", "Benjamin"); +Observable<String> lastNames = Observable.just("Kirk", "Picard", "Sisko"); +firstNames.zipWith(lastNames, (first, last) -> first + " " + last) + .subscribe(item -> System.out.println(item)); + +// prints James Kirk, Jean-Luc Picard, Benjamin Sisko +``` + +## combineLatest + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/combinelatest.html](http://reactivex.io/documentation/operators/combinelatest.html) + +When an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function. + +#### combineLatest Example + +```java +Observable<Long> newsRefreshes = Observable.interval(100, TimeUnit.MILLISECONDS); +Observable<Long> weatherRefreshes = Observable.interval(50, TimeUnit.MILLISECONDS); +Observable.combineLatest(newsRefreshes, weatherRefreshes, + (newsRefreshTimes, weatherRefreshTimes) -> + "Refreshed news " + newsRefreshTimes + " times and weather " + weatherRefreshTimes) + .subscribe(item -> System.out.println(item)); + +// prints: +// Refreshed news 0 times and weather 0 +// Refreshed news 0 times and weather 1 +// Refreshed news 0 times and weather 2 +// Refreshed news 1 times and weather 2 +// Refreshed news 1 times and weather 3 +// Refreshed news 1 times and weather 4 +// Refreshed news 2 times and weather 4 +// Refreshed news 2 times and weather 5 +// ... +``` + +## switchOnNext + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/switch.html](http://reactivex.io/documentation/operators/switch.html) + +Convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently emitted of those Observables. + +#### switchOnNext Example + +```java +Observable<Observable<String>> timeIntervals = + Observable.interval(1, TimeUnit.SECONDS) + .map(ticks -> Observable.interval(100, TimeUnit.MILLISECONDS) + .map(innerInterval -> "outer: " + ticks + " - inner: " + innerInterval)); +Observable.switchOnNext(timeIntervals) + .subscribe(item -> System.out.println(item)); + +// prints: +// outer: 0 - inner: 0 +// outer: 0 - inner: 1 +// outer: 0 - inner: 2 +// outer: 0 - inner: 3 +// outer: 0 - inner: 4 +// outer: 0 - inner: 5 +// outer: 0 - inner: 6 +// outer: 0 - inner: 7 +// outer: 0 - inner: 8 +// outer: 1 - inner: 0 +// outer: 1 - inner: 1 +// outer: 1 - inner: 2 +// outer: 1 - inner: 3 +// ... +``` + +## joins + * [**`join( )` and `groupJoin( )`**](http://reactivex.io/documentation/operators/join.html) — combine the items emitted by two Observables whenever one item from one Observable falls within a window of duration specified by an item emitted by the other Observable -* [**`switchOnNext( )`**](http://reactivex.io/documentation/operators/switch.html) — convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently emitted of those Observables + +## rxjava-joins + +* (`rxjava-joins`) [**`and( )`, `then( )`, and `when( )`**](http://reactivex.io/documentation/operators/and-then-when.html) — combine sets of items emitted by two or more Observables by means of `Pattern` and `Plan` intermediaries > (`rxjava-joins`) — indicates that this operator is currently part of the optional `rxjava-joins` package under `rxjava-contrib` and is not included with the standard RxJava set of operators From c7f3349fec5b230f55f415dc3feeef07b5ed2957 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sat, 4 Aug 2018 19:05:06 +0200 Subject: [PATCH 252/417] 2.x: Expand Creating-Observables.md wiki (#6131) --- docs/Creating-Observables.md | 416 ++++++++++++++++++++++++++++++++++- 1 file changed, 404 insertions(+), 12 deletions(-) diff --git a/docs/Creating-Observables.md b/docs/Creating-Observables.md index b8a6b90ca7..b167c4d866 100644 --- a/docs/Creating-Observables.md +++ b/docs/Creating-Observables.md @@ -1,12 +1,404 @@ -This page shows methods that create Observables. - -* [**`just( )`**](http://reactivex.io/documentation/operators/just.html) — convert an object or several objects into an Observable that emits that object or those objects -* [**`from( )`**](http://reactivex.io/documentation/operators/from.html) — convert an Iterable, a Future, or an Array into an Observable -* [**`create( )`**](http://reactivex.io/documentation/operators/create.html) — **advanced use only!** create an Observable from scratch by means of a function -* [**`defer( )`**](http://reactivex.io/documentation/operators/defer.html) — do not create the Observable until a Subscriber subscribes; create a fresh Observable on each subscription -* [**`range( )`**](http://reactivex.io/documentation/operators/range.html) — create an Observable that emits a range of sequential integers -* [**`interval( )`**](http://reactivex.io/documentation/operators/interval.html) — create an Observable that emits a sequence of integers spaced by a given time interval -* [**`timer( )`**](http://reactivex.io/documentation/operators/timer.html) — create an Observable that emits a single item after a given delay -* [**`empty( )`**](http://reactivex.io/documentation/operators/empty-never-throw.html) — create an Observable that emits nothing and then completes -* [**`error( )`**](http://reactivex.io/documentation/operators/empty-never-throw.html) — create an Observable that emits nothing and then signals an error -* [**`never( )`**](http://reactivex.io/documentation/operators/empty-never-throw.html) — create an Observable that emits nothing at all +This page shows methods that create reactive sources, such as `Observable`s. + +### Outline + +- [`create`](#create) +- [`defer`](#defer) +- [`empty`](#empty) +- [`error`](#error) +- [`from`](#from) +- [`interval`](#interval) +- [`just`](#just) +- [`never`](#never) +- [`range`](#range) +- [`timer`](#timer) + +## just + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/just.html](http://reactivex.io/documentation/operators/just.html) + +Constructs a reactive type by taking a pre-existing object and emitting that specific object to the downstream consumer upon subscription. + +#### just example: + +```java +String greeting = "Hello world!"; + +Observable<String> observable = Observable.just(greeting); + +observable.subscribe(item -> System.out.println(item)); +``` + +There exist overloads with 2 to 9 arguments for convenience, which objects (with the same common type) will be emitted in the order they are specified. + +```java +Observable<Object> observable = Observable.just("1", "A", "3.2", "def"); + +observable.subscribe(item -> System.out.print(item), error -> error.printStackTrace, + () -> System.out.println()); +``` + +## From + +Constructs a sequence from a pre-existing source or generator type. + +*Note: These static methods use the postfix naming convention (i.e., the argument type is repeated in the method name) to avoid overload resolution ambiguities.* + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/from.html](http://reactivex.io/documentation/operators/from.html) + +### fromIterable + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +Signals the items from a `java.lang.Iterable` source (such as `List`s, `Set`s or `Collection`s or custom `Iterable`s) and then completes the sequence. + +#### fromIterable example: + +```java +List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)); + +Observable<Integer> observable = Observable.fromIterable(list); + +observable.subscribe(item -> System.out.println(item), error -> error.printStackTrace(), + () -> System.out.println("Done")); +``` + +### fromArray + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +Signals the elements of the given array and then completes the sequence. + +#### fromArray example: + +```java +Integer[] array = new Integer[10]; +for (int i = 0; i < array.length; i++) { + array[i] = i; +} + +Observable<Integer> observable = Observable.fromIterable(array); + +observable.subscribe(item -> System.out.println(item), error -> error.printStackTrace(), + () -> System.out.println("Done")); +``` + +*Note: RxJava does not support primitive arrays, only (generic) reference arrays.* + +### fromCallable + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +When a consumer subscribes, the given `java.util.concurrent.Callable` is invoked and its returned value (or thrown exception) is relayed to that consumer. + +#### fromCallable example: + +```java +Callable<String> callable = () -> { + System.out.println("Hello World!"); + return "Hello World!"); +} + +Observable<String> observable = Observable.fromCallable(callable); + +observable.subscribe(item -> System.out.println(item), error -> error.printStackTrace(), + () -> System.out.println("Done")); +``` + +*Remark: In `Completable`, the actual returned value is ignored and the `Completable` simply completes.* + +## fromAction + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +When a consumer subscribes, the given `io.reactivex.function.Action` is invoked and the consumer completes or receives the exception the `Action` threw. + +#### fromAction example: + +```java +Action action = () -> System.out.println("Hello World!"); + +Completable completable = Completable.fromAction(action); + +completable.subscribe(() -> System.out.println("Done"), error -> error.printStackTrace()); +``` + +*Note: the difference between `fromAction` and `fromRunnable` is that the `Action` interface allows throwing a checked exception while the `java.lang.Runnable` does not.* + +## fromRunnable + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +When a consumer subscribes, the given `io.reactivex.function.Action` is invoked and the consumer completes or receives the exception the `Action` threw. + +#### fromRunnable example: + +```java +Runnable runnable = () -> System.out.println("Hello World!"); + +Completable completable = Completable.fromRunnable(runnable); + +completable.subscribe(() -> System.out.println("Done"), error -> error.printStackTrace()); +``` + +*Note: the difference between `fromAction` and `fromRunnable` is that the `Action` interface allows throwing a checked exception while the `java.lang.Runnable` does not.* + +### fromFuture + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +Given a pre-existing, already running or already completed `java.util.concurrent.Future`, wait for the `Future` to complete normally or with an exception in a blocking fashion and relay the produced value or exception to the consumers. + +#### fromFuture example: + +```java +ScheduledExecutorService executor = Executors.newSingleThreadedScheduledExecutor(); + +Future<String> future = executor.schedule(() -> "Hello world!", 1, TimeUnit.SECONDS); + +Observable<String> observable = Observable.fromFuture(future); + +observable.subscribe( + item -> System.out.println(item), + error -> error.printStackTrace(), + () -> System.out.println("Done")); + +executor.shutdown(); +``` + +### from{reactive type} + +Wraps or converts another reactive type to the target reactive type. + +The following combinations are available in the various reactive types with the following signature pattern: `targetType.from{sourceType}()` + +**Available in:** + +targetType \ sourceType | Publisher | Observable | Maybe | Single | Completable +----|---------------|-----------|---------|-----------|---------------- +Flowable | ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) | | | | | +Observable | ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) | | | | | +Maybe | | | | ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) | ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) +Single | ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) | ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) | | | +Completable | ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) | ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) | ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) | ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) | + +*Note: not all possible conversion is implemented via the `from{reactive type}` method families. Check out the `to{reactive type}` method families for further conversion possibilities. + +#### from{reactive type} example: + +```java +Flux<Integer> reactorFlux = Flux.fromCompletionStage(CompletableFuture.<Integer>completedFuture(1)); + +Observable<Integer> observable = Observable.fromPublisher(reactorFlux); + +observable.subscribe( + item -> System.out.println(item), + error -> error.printStackTrace(), + () -> System.out.println("Done")); +``` + +## create + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/create.html](http://reactivex.io/documentation/operators/create.html) + +Construct a **safe** reactive type instance which when subscribed to by a consumer, runs an user-provided function and provides a type-specific `Emitter` for this function to generate the signal(s) the designated business logic requires. This method allows bridging the non-reactive, usually listener/callback-style world, with the reactive world. + +#### create example: + +```java +ScheduledExecutorService executor = Executors.newSingleThreadedScheduledExecutor(); + +ObservableOnSubscribe<String> handler = emitter -> { + + Future<Object> future = executor.schedule(() -> { + emitter.onNext("Hello"); + emitter.onNext("World"); + emitter.onComplete(); + return null; + }, 1, TimeUnit.SECONDS); + + emitter.setCancellable(() -> future.cancel(false)); +}; + +Observable<String> observable = Observable.create(handler); + +observable.subscribe(item -> System.out.println(item), error -> error.printStackTrace(), + () -> System.out.println("Done")); + +Thread.sleep(2000); +executor.shutdown(); +``` + +*Note: `Flowable.create()` must also specify the backpressure behavior to be applied when the user-provided function generates more items than the downstream consumer has requested.* + +## defer + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/defer.html](http://reactivex.io/documentation/operators/defer.html) + +Calls an user-provided `java.util.concurrent.Callable` when a consumer subscribes to the reactive type so that the `Callable` can generate the actual reactive instance to relay signals from towards the consumer. `defer` allows: + +- associating a per-consumer state with such generated reactive instances, +- allows executing side-effects before an actual/generated reactive instance gets subscribed to, +- turn hot sources (i.e., `Subject`s and `Processor`s) into cold sources by basically making those hot sources not exist until a consumer subscribes. + +#### defer example: + +```java +Observable<Long> observable = Observable.defer(() -> { + long time = System.currentTimeMillis(); + return Observable.just(time); +}); + +observable.subscribe(time -> System.out.println(time)); + +Thread.sleep(1000); + +observable.subscribe(time -> System.out.println(time)); +``` + +## range + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/range.html](http://reactivex.io/documentation/operators/range.html) + +Generates a sequence of values to each individual consumer. The `range()` method generates `Integer`s, the `rangeLong()` generates `Long`s. + +#### range example: +```java +String greeting = "Hello World!"; + +Observable<Integer> indexes = Observable.range(0, greeting.length()); + +Observable<Char> characters = indexes + .map(index -> greeting.charAt(index)); + +characters.subscribe(character -> System.out.print(character), erro -> error.printStackTrace(), + () -> System.out.println()); +``` + +## interval + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/interval.html](http://reactivex.io/documentation/operators/interval.html) + +Periodically generates an infinite, ever increasing numbers (of type `Long`). The `intervalRange` variant generates a limited amount of such numbers. + +#### interval example: + +```java +Observable<Long> clock = Observable.interval(1, TimeUnit.SECONDS); + +clock.subscribe(time -> { + if (time % 2 == 0) { + System.out.println("Tick"); + } else { + System.out.println("Tock"); + } +}); +``` + +## timer + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/timer.html](http://reactivex.io/documentation/operators/timer.html) + +After the specified time, this reactive source signals a single `0L` (then completes for `Flowable` and `Observable`). + +#### timer example: + +```java +Observable<Long> eggTimer = Observable.timer(5, TimeUnit.MINUTES); + +eggTimer.blockingSubscribe(v -> System.out.println("Egg is ready!")); +``` + +## empty + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/empty-never-throw.html](http://reactivex.io/documentation/operators/empty-never-throw.html) + +This type of source signals completion immediately upon subscription. + +#### empty example: + +```java +Observable<String> empty = Observable.empty(); + +empty.subscribe( + v -> System.out.println("This should never be printed!"), + error -> System.out.println("Or this!"), + () -> System.out.println("Done will be printed.")); +``` + +## never + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/empty-never-throw.html](http://reactivex.io/documentation/operators/empty-never-throw.html) + +This type of source does not signal any `onNext`, `onSuccess`, `onError` or `onComplete`. This type of reactive source is useful in testing or "disabling" certain sources in combinator operators. + +#### never example: + +```java +Observable<String> never = Observable.never(); + +never.subscribe( + v -> System.out.println("This should never be printed!"), + error -> System.out.println("Or this!"), + () -> System.out.println("This neither!")); +``` + +## error + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/empty-never-throw.html](http://reactivex.io/documentation/operators/empty-never-throw.html) + +Signal an error, either pre-existing or generated via a `java.util.concurrent.Callable`, to the consumer. + +#### error example: + +```java +Observable<String> error = Observable.error(new IOException()); + +error.subscribe( + v -> System.out.println("This should never be printed!"), + error -> error.printStackTrace(), + () -> System.out.println("This neither!")); +``` + +A typical use case is to conditionally map or suppress an exception in a chain utilizing `onErrorResumeNext`: + +```java +Observable<String> observable = Observable.fromCallable(() -> { + if (Math.random() < 0.5) { + throw new IOException(); + } + throw new IllegalArgumentException(); +}); + +Observable<String> result = observable.onErrorResumeNext(error -> { + if (error instanceof IllegalArgumentException) { + return Observable.empty(); + } + return Observable.error(error); +}); + +for (int i = 0; i < 10; i++) { + result.subscribe( + v -> System.out.println("This should never be printed!"), + error -> error.printStackTrace(), + () -> System.out.println("Done")); +} +``` From c146374e210caf0b4982825034c0ec51d5505c00 Mon Sep 17 00:00:00 2001 From: Ahmed El-Helw <ahmedre@gmail.com> Date: Sat, 4 Aug 2018 21:21:32 +0400 Subject: [PATCH 253/417] Update RxJava Android Module documentation (#6134) This patch updates the RxJava Android wiki page to point to the RxAndroid project and the RxAndroid wiki page. This refs #6132. --- docs/The-RxJava-Android-Module.md | 111 +----------------------------- 1 file changed, 2 insertions(+), 109 deletions(-) diff --git a/docs/The-RxJava-Android-Module.md b/docs/The-RxJava-Android-Module.md index 108febec04..ad9817c80a 100644 --- a/docs/The-RxJava-Android-Module.md +++ b/docs/The-RxJava-Android-Module.md @@ -1,110 +1,3 @@ -**Note:** This page is out-of-date. See [the RxAndroid wiki](https://github.com/ReactiveX/RxAndroid/wiki) for more up-to-date instructions. +## RxAndroid -*** - -The `rxjava-android` module contains Android-specific bindings for RxJava. It adds a number of classes to RxJava to assist in writing reactive components in Android applications. - -- It provides a `Scheduler` that schedules an `Observable` on a given Android `Handler` thread, particularly the main UI thread. -- It provides operators that make it easier to deal with `Fragment` and `Activity` life-cycle callbacks. -- It provides wrappers for various Android messaging and notification components so that they can be lifted into an Rx call chain -- It provides reusable, self-contained, reactive components for common Android use cases and UI concerns. _(coming soon)_ - -# Binaries - -You can find binaries and dependency information for Maven, Ivy, Gradle and others at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22rxandroid%22). - -Here is an example for [Maven](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22rxandroid%22): - -```xml -<dependency> - <groupId>io.reactivex</groupId> - <artifactId>rxandroid</artifactId> - <version>0.23.0</version> -</dependency> -``` - -…and for Ivy: - -```xml -<dependency org="io.reactivex" name="rxandroid" rev="0.23.0" /> -``` - -The currently supported `minSdkVersion` is `10` (Android 2.3/Gingerbread) - -# Examples - -## Observing on the UI thread - -You commonly deal with asynchronous tasks on Android by observing the task’s result or outcome on the main UI thread. Using vanilla Android, you would typically accomplish this with an `AsyncTask`. With RxJava you would instead declare your `Observable` to be observed on the main thread by using the `observeOn` operator: - -```java -public class ReactiveFragment extends Fragment { - -@Override -public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - Observable.from("one", "two", "three", "four", "five") - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(/* an Observer */); -} -``` - -This executes the Observable on a new thread, which emits results through `onNext` on the main UI thread. - -## Observing on arbitrary threads -The previous example is a specialization of a more general concept: binding asynchronous communication to an Android message loop by using the `Handler` class. In order to observe an `Observable` on an arbitrary thread, create a `Handler` bound to that thread and use the `AndroidSchedulers.handlerThread` scheduler: - -```java -new Thread(new Runnable() { - @Override - public void run() { - final Handler handler = new Handler(); // bound to this thread - Observable.from("one", "two", "three", "four", "five") - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.handlerThread(handler)) - .subscribe(/* an Observer */) - - // perform work, ... - } -}, "custom-thread-1").start(); -``` - -This executes the Observable on a new thread and emits results through `onNext` on `custom-thread-1`. (This example is contrived since you could as well call `observeOn(Schedulers.currentThread())` but it illustrates the idea.) - -## Fragment and Activity life-cycle - -On Android it is tricky for asynchronous actions to access framework objects in their callbacks. That’s because Android may decide to destroy an `Activity`, for instance, while a background thread is still running. The thread will attempt to access views on the now dead `Activity`, which results in a crash. (This will also create a memory leak, since your background thread holds on to the `Activity` even though it’s not visible anymore.) - -This is still a concern when using RxJava on Android, but you can deal with the problem in a more elegant way by using `Subscription`s and a number of Observable operators. In general, when you run an `Observable` inside an `Activity` that subscribes to the result (either directly or through an inner class), you must unsubscribe from the sequence in `onDestroy`, as shown in the following example: - -```java -// MyActivity -private Subscription subscription; - -protected void onCreate(Bundle savedInstanceState) { - this.subscription = observable.subscribe(this); -} - -... - -protected void onDestroy() { - this.subscription.unsubscribe(); - super.onDestroy(); -} -``` - -This ensures that all references to the subscriber (the `Activity`) will be released as soon as possible, and no more notifications will arrive at the subscriber through `onNext`. - -One problem with this is that if the `Activity` is destroyed because of a change in screen orientation, the Observable will fire again in `onCreate`. You can prevent this by using the `cache` or `replay` Observable operators, while making sure the Observable somehow survives the `Activity` life-cycle (for instance, by storing it in a global cache, in a Fragment, etc.) You can use either operator to ensure that when the subscriber subscribes to an Observable that’s already “running,” items emitted by the Observable during the span when it was detached from the `Activity` will be “played back,” and any in-flight notifications from the Observable will be delivered as usual. - -# See also -* [How the New York Times is building its Android app with Groovy/RxJava](http://open.blogs.nytimes.com/2014/08/18/getting-groovy-with-reactive-android/?_php=true&_type=blogs&_php=true&_type=blogs&_r=1&) by Mohit Pandey -* [Functional Reactive Programming on Android With RxJava](http://mttkay.github.io/blog/2013/08/25/functional-reactive-programming-on-android-with-rxjava/) and [Conquering concurrency - bringing the Reactive Extensions to the Android platform](https://speakerdeck.com/mttkay/conquering-concurrency-bringing-the-reactive-extensions-to-the-android-platform) by Matthias Käppler -* [Learning RxJava for Android by example](https://github.com/kaushikgopal/Android-RxJava) by Kaushik Gopal -* [Top 7 Tips for RxJava on Android](http://blog.futurice.com/top-7-tips-for-rxjava-on-android) and [Rx Architectures in Android](http://www.slideshare.net/TimoTuominen1/rxjava-architectures-on-android-8-android-livecode-32531688) by Timo Tuominen -* [FRP on Android](http://slid.es/yaroslavheriatovych/frponandroid) by Yaroslav Heriatovych -* [Rx for .NET and RxJava for Android](http://blog.futurice.com/tech-pick-of-the-week-rx-for-net-and-rxjava-for-android) by Olli Salonen -* [RxJava in Xtend for Android](http://blog.futurice.com/android-development-has-its-own-swift) by Andre Medeiros -* [RxJava and Xtend](http://mnmlst-dvlpr.blogspot.de/2014/07/rxjava-and-xtend.html) by Stefan Oehme -* Grokking RxJava, [Part 1: The Basics](http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/), [Part 2: Operator, Operator](http://blog.danlew.net/2014/09/22/grokking-rxjava-part-2/), [Part 3: Reactive with Benefits](http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3/), [Part 4: Reactive Android](http://blog.danlew.net/2014/10/08/grokking-rxjava-part-4/) - published in Sep/Oct 2014 by Daniel Lew \ No newline at end of file +See the [RxAndroid](https://github.com/ReactiveX/RxAndroid) project page and the [the RxAndroid wiki](https://github.com/ReactiveX/RxAndroid/wiki) for details. From 690258e1c0853664dfebc4ffe8dd99e499eb41c6 Mon Sep 17 00:00:00 2001 From: Ashish Krishnan <ashishkrish09@gmail.com> Date: Sun, 5 Aug 2018 13:31:52 +0530 Subject: [PATCH 254/417] 2.x: Update Getting started docs (#6136) * Remove troubleshooting guide. * Getting Started, all artifacts point to RxJava2. * Fix JFrog links to point to 2.x --- docs/Getting-Started.md | 63 ++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 39 deletions(-) diff --git a/docs/Getting-Started.md b/docs/Getting-Started.md index 1a95121c4e..fb9baa47dd 100644 --- a/docs/Getting-Started.md +++ b/docs/Getting-Started.md @@ -1,20 +1,20 @@ ## Getting Binaries -You can find binaries and dependency information for Maven, Ivy, Gradle, SBT, and others at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22io.reactivex%22%20AND%20a%3A%22rxjava%22). +You can find binaries and dependency information for Maven, Ivy, Gradle, SBT, and others at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Cg%3A"io.reactivex.rxjava2"%20AND%20"rxjava2"). Example for Maven: ```xml <dependency> - <groupId>io.reactivex</groupId> + <groupId>io.reactivex.rxjava2</groupId> <artifactId>rxjava</artifactId> - <version>1.3.4</version> + <version>2.2.0</version> </dependency> ``` and for Ivy: ```xml -<dependency org="io.reactivex" name="rxjava" rev="1.3.4" /> +<dependency org="io.reactivex.rxjava2" name="rxjava" rev="2.2.0" /> ``` and for SBT: @@ -22,35 +22,35 @@ and for SBT: ```scala libraryDependencies += "io.reactivex" %% "rxscala" % "0.26.5" -libraryDependencies += "io.reactivex" % "rxjava" % "1.3.4" +libraryDependencies += "io.reactivex.rxjava2" % "rxjava" % "2.2.0" ``` and for Gradle: ```groovy -compile 'io.reactivex:rxjava:1.3.4' +compile 'io.reactivex.rxjava2:rxjava:2.2.0' ``` If you need to download the jars instead of using a build system, create a Maven `pom` file like this with the desired version: ```xml <?xml version="1.0"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0%20http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>com.netflix.rxjava.download</groupId> - <artifactId>rxjava-download</artifactId> - <version>1.0-SNAPSHOT</version> - <name>Simple POM to download rxjava and dependencies</name> - <url>http://github.com/ReactiveX/RxJava</url> - <dependencies> - <dependency> - <groupId>io.reactivex</groupId> - <artifactId>rxjava</artifactId> - <version>1.3.4</version> - <scope/> - </dependency> - </dependencies> + <modelVersion>4.0.0</modelVersion> + <groupId>io.reactivex.rxjava2</groupId> + <artifactId>rxjava</artifactId> + <version>2.2.0</version> + <name>RxJava</name> + <description>Reactive Extensions for Java</description> + <url>https://github.com/ReactiveX/RxJava</url> + <dependencies> + <dependency> + <groupId>io.reactivex.rxjava2</groupId> + <artifactId>rxjava</artifactId> + <version>2.2.0</version> + </dependency> + </dependencies> </project> ``` @@ -66,7 +66,7 @@ You need Java 6 or later. ### Snapshots -Snapshots are available via [JFrog](https://oss.jfrog.org/webapp/search/artifact/?5&q=rxjava): +Snapshots are available via [JFrog](https://oss.jfrog.org/libs-snapshot/io/reactivex/rxjava2/rxjava/): ```groovy repositories { @@ -74,7 +74,7 @@ repositories { } dependencies { - compile 'io.reactivex:rxjava:1.3.y-SNAPSHOT' + compile 'io.reactivex.rxjava2:rxjava:2.2.0-SNAPSHOT' } ``` @@ -124,18 +124,3 @@ On a clean build you will see the unit tests run. They will look something like ``` > Building > :rxjava:test > 91 tests completed ``` - -#### Troubleshooting - -One developer reported getting the following error: - -> Could not resolve all dependencies for configuration ':language-adaptors:rxjava-scala:provided' - -He was able to resolve the problem by removing old versions of `scala-library` from `.gradle/caches` and `.m2/repository/org/scala-lang/` and then doing a clean build. <a href="https://gist.github.com/jaceklaskowski/9496058">(See this page for details.)</a> - -You may get the following error during building RxJava: - -> Failed to apply plugin [id 'java'] -> Could not generate a proxy class for class nebula.core.NamedContainerProperOrder. - -It's a JVM issue, see [GROOVY-6951](https://jira.codehaus.org/browse/GROOVY-6951) for details. If so, you can run `export GRADLE_OPTS=-noverify` before building RxJava, or update your JDK. From bb939111a026a12880a1e9b75c5579c366177fe0 Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Sun, 5 Aug 2018 14:31:07 +0200 Subject: [PATCH 255/417] 2.x: Add marbles for Single.concat operator (#6137) * Add marbles for Single.concat operator * Update URL for Single.concat marble diagram * Update Single.concat marble's height --- src/main/java/io/reactivex/Single.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 84f40621c4..8ae6ac777c 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -166,6 +166,8 @@ public static <T> Single<T> ambArray(final SingleSource<? extends T>... sources) /** * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided by * an Iterable sequence. + * <p> + * <img width="640" height="319" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.i.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -187,6 +189,8 @@ public static <T> Flowable<T> concat(Iterable<? extends SingleSource<? extends T /** * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided by * an Observable sequence. + * <p> + * <img width="640" height="319" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> @@ -207,6 +211,8 @@ public static <T> Observable<T> concat(ObservableSource<? extends SingleSource<? /** * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided by * a Publisher sequence. + * <p> + * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer @@ -229,6 +235,8 @@ public static <T> Flowable<T> concat(Publisher<? extends SingleSource<? extends /** * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided by * a Publisher sequence and prefetched by the specified amount. + * <p> + * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.pn.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer @@ -255,7 +263,7 @@ public static <T> Flowable<T> concat(Publisher<? extends SingleSource<? extends /** * Returns a Flowable that emits the items emitted by two Singles, one after the other. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.png" alt=""> + * <img width="640" height="366" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -286,7 +294,7 @@ public static <T> Flowable<T> concat( /** * Returns a Flowable that emits the items emitted by three Singles, one after the other. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.png" alt=""> + * <img width="640" height="366" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.o3.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -321,7 +329,7 @@ public static <T> Flowable<T> concat( /** * Returns a Flowable that emits the items emitted by four Singles, one after the other. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.png" alt=""> + * <img width="640" height="362" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.o4.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -359,6 +367,8 @@ public static <T> Flowable<T> concat( /** * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided in * an array. + * <p> + * <img width="640" height="319" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatArray.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> From c8b0a0e82ea7e616325fe21e6d56391c80f99d42 Mon Sep 17 00:00:00 2001 From: lorenzpahl <l.pahl@outlook.com> Date: Sun, 5 Aug 2018 20:28:02 +0200 Subject: [PATCH 256/417] 2.x: Update Mathematical and Aggregate Operators docs (#6140) * Update document structure; remove obsolete operators * Add examples * Change formatting * Include 'Flowable' in the introduction * Add additional notes to the mathematical operators * Rename section; add additional note * Create additional sections --- docs/Mathematical-and-Aggregate-Operators.md | 391 +++++++++++++++++-- 1 file changed, 366 insertions(+), 25 deletions(-) diff --git a/docs/Mathematical-and-Aggregate-Operators.md b/docs/Mathematical-and-Aggregate-Operators.md index f4a976f9d3..574111ad0e 100644 --- a/docs/Mathematical-and-Aggregate-Operators.md +++ b/docs/Mathematical-and-Aggregate-Operators.md @@ -1,25 +1,366 @@ -This page shows operators that perform mathematical or other operations over an entire sequence of items emitted by an Observable. Because these operations must wait for the source Observable to complete emitting items before they can construct their own emissions (and must usually buffer these items), these operators are dangerous to use on Observables that may have very long or infinite sequences. - -#### Operators in the `rxjava-math` module -* [**`averageInteger( )`**](http://reactivex.io/documentation/operators/average.html) — calculates the average of Integers emitted by an Observable and emits this average -* [**`averageLong( )`**](http://reactivex.io/documentation/operators/average.html) — calculates the average of Longs emitted by an Observable and emits this average -* [**`averageFloat( )`**](http://reactivex.io/documentation/operators/average.html) — calculates the average of Floats emitted by an Observable and emits this average -* [**`averageDouble( )`**](http://reactivex.io/documentation/operators/average.html) — calculates the average of Doubles emitted by an Observable and emits this average -* [**`max( )`**](http://reactivex.io/documentation/operators/max.html) — emits the maximum value emitted by a source Observable -* [**`maxBy( )`**](http://reactivex.io/documentation/operators/max.html) — emits the item emitted by the source Observable that has the maximum key value -* [**`min( )`**](http://reactivex.io/documentation/operators/min.html) — emits the minimum value emitted by a source Observable -* [**`minBy( )`**](http://reactivex.io/documentation/operators/min.html) — emits the item emitted by the source Observable that has the minimum key value -* [**`sumInteger( )`**](http://reactivex.io/documentation/operators/sum.html) — adds the Integers emitted by an Observable and emits this sum -* [**`sumLong( )`**](http://reactivex.io/documentation/operators/sum.html) — adds the Longs emitted by an Observable and emits this sum -* [**`sumFloat( )`**](http://reactivex.io/documentation/operators/sum.html) — adds the Floats emitted by an Observable and emits this sum -* [**`sumDouble( )`**](http://reactivex.io/documentation/operators/sum.html) — adds the Doubles emitted by an Observable and emits this sum - -#### Other Aggregate Operators -* [**`concat( )`**](http://reactivex.io/documentation/operators/concat.html) — concatenate two or more Observables sequentially -* [**`count( )` and `countLong( )`**](http://reactivex.io/documentation/operators/count.html) — counts the number of items emitted by an Observable and emits this count -* [**`reduce( )`**](http://reactivex.io/documentation/operators/reduce.html) — apply a function to each emitted item, sequentially, and emit only the final accumulated value -* [**`collect( )`**](http://reactivex.io/documentation/operators/reduce.html) — collect items emitted by the source Observable into a single mutable data structure and return an Observable that emits this structure -* [**`toList( )`**](http://reactivex.io/documentation/operators/to.html) — collect all items from an Observable and emit them as a single List -* [**`toSortedList( )`**](http://reactivex.io/documentation/operators/to.html) — collect all items from an Observable and emit them as a single, sorted List -* [**`toMap( )`**](http://reactivex.io/documentation/operators/to.html) — convert the sequence of items emitted by an Observable into a map keyed by a specified key function -* [**`toMultiMap( )`**](http://reactivex.io/documentation/operators/to.html) — convert the sequence of items emitted by an Observable into an ArrayList that is also a map keyed by a specified key function \ No newline at end of file +This page shows operators that perform mathematical or other operations over an entire sequence of items emitted by an `Observable` or `Flowable`. Because these operations must wait for the source `Observable`/`Flowable` to complete emitting items before they can construct their own emissions (and must usually buffer these items), these operators are dangerous to use on `Observable`s and `Flowable`s that may have very long or infinite sequences. + +# Outline + +- [Mathematical Operators](#mathematical-operators) + - [`averageDouble`](#averagedouble) + - [`averageFloat`](#averagefloat) + - [`max`](#max) + - [`min`](#min) + - [`sumDouble`](#sumdouble) + - [`sumFloat`](#sumfloat) + - [`sumInt`](#sumint) + - [`sumLong`](#sumlong) +- [Standard Aggregate Operators](#standard-aggregate-operators) + - [`count`](#count) + - [`reduce`](#reduce) + - [`reduceWith`](#reducewith) + - [`collect`](#collect) + - [`collectInto`](#collectinto) + - [`toList`](#tolist) + - [`toSortedList`](#tosortedlist) + - [`toMap`](#tomap) + - [`toMultimap`](#tomultimap) + +## Mathematical Operators + +> The operators in this section are part of the [`RxJava2Extensions`](https://github.com/akarnokd/RxJava2Extensions) project. You have to add the `rxjava2-extensions` module as a dependency to your project. It can be found at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.github.akarnokd%22). + +> Note that unlike the standard RxJava aggregator operators, these mathematical operators return `Observable` and `Flowable` instead of the `Single` or `Maybe`. + +*The examples below assume that the `MathObservable` and `MathFlowable` classes are imported from the `rxjava2-extensions` module:* + +```java +import hu.akarnokd.rxjava2.math.MathObservable; +import hu.akarnokd.rxjava2.math.MathFlowable; +``` + +### averageDouble + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/average.html](http://reactivex.io/documentation/operators/average.html) + +Calculates the average of `Number`s emitted by an `Observable` and emits this average as a `Double`. + +#### averageDouble example + +```java +Observable<Integer> numbers = Observable.just(1, 2, 3); +MathObservable.averageDouble(numbers).subscribe((Double avg) -> System.out.println(avg)); + +// prints 2.0 +``` + +### averageFloat + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/average.html](http://reactivex.io/documentation/operators/average.html) + +Calculates the average of `Number`s emitted by an `Observable` and emits this average as a `Float`. + +#### averageFloat example + +```java +Observable<Integer> numbers = Observable.just(1, 2, 3); +MathObservable.averageFloat(numbers).subscribe((Float avg) -> System.out.println(avg)); + +// prints 2.0 +``` + +### max + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/max.html](http://reactivex.io/documentation/operators/max.html) + +Emits the maximum value emitted by a source `Observable`. A `Comparator` can be specified that will be used to compare the elements emitted by the `Observable`. + +#### max example + +```java +Observable<Integer> numbers = Observable.just(4, 9, 5); +MathObservable.max(numbers).subscribe(System.out::println); + +// prints 9 +``` + +The following example specifies a `Comparator` to find the longest `String` in the source `Observable`: + +```java +final Observable<String> names = Observable.just("Kirk", "Spock", "Chekov", "Sulu"); +MathObservable.max(names, Comparator.comparingInt(String::length)) + .subscribe(System.out::println); + +// prints Chekov +``` + +### min + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/min.html](http://reactivex.io/documentation/operators/min.html) + +Emits the minimum value emitted by a source `Observable`. A `Comparator` can be specified that will be used to compare the elements emitted by the `Observable`. + +#### min example + +```java +Observable<Integer> numbers = Observable.just(4, 9, 5); +MathObservable.min(numbers).subscribe(System.out::println); + +// prints 4 +``` + +### sumDouble + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) + +Adds the `Double`s emitted by an `Observable` and emits this sum. + +#### sumDouble example + +```java +Observable<Double> numbers = Observable.just(1.0, 2.0, 3.0); +MathObservable.sumDouble(numbers).subscribe((Double sum) -> System.out.println(sum)); + +// prints 6.0 +``` + +### sumFloat + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) + +Adds the `Float`s emitted by an `Observable` and emits this sum. + +#### sumFloat example + +```java +Observable<Float> numbers = Observable.just(1.0F, 2.0F, 3.0F); +MathObservable.sumFloat(numbers).subscribe((Float sum) -> System.out.println(sum)); + +// prints 6.0 +``` + +### sumInt + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) + +Adds the `Integer`s emitted by an `Observable` and emits this sum. + +#### sumInt example + +```java +Observable<Integer> numbers = Observable.range(1, 100); +MathObservable.sumInt(numbers).subscribe((Integer sum) -> System.out.println(sum)); + +// prints 5050 +``` + +### sumLong + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) + +Adds the `Long`s emitted by an `Observable` and emits this sum. + +#### sumLong example + +```java +Observable<Long> numbers = Observable.rangeLong(1L, 100L); +MathObservable.sumLong(numbers).subscribe((Long sum) -> System.out.println(sum)); + +// prints 5050 +``` + +## Standard Aggregate Operators + +> Note that these standard aggregate operators return a `Single` or `Maybe` because the number of output items is always know to be at most one. + +### count + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/count.html](http://reactivex.io/documentation/operators/count.html) + +Counts the number of items emitted by an `Observable` and emits this count as a `Long`. + +#### count example + +```java +Observable.just(1, 2, 3).count().subscribe(System.out::println); + +// prints 3 +``` + +### reduce + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) + +Apply a function to each emitted item, sequentially, and emit only the final accumulated value. + +#### reduce example + +```java +Observable.range(1, 5) + .reduce((product, x) -> product * x) + .subscribe(System.out::println); + +// prints 120 +``` + +### reduceWith + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) + +Apply a function to each emitted item, sequentially, and emit only the final accumulated value. + + +#### reduceWith example + +```java +Observable.just(1, 2, 2, 3, 4, 4, 4, 5) + .reduceWith(TreeSet::new, (set, x) -> { + set.add(x); + return set; + }) + .subscribe(System.out::println); + +// prints [1, 2, 3, 4, 5] +``` + +### collect + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) + +Collect items emitted by the source `Observable` into a single mutable data structure and return an `Observable` that emits this structure. + +#### collect example + +```java +Observable.just("Kirk", "Spock", "Chekov", "Sulu") + .collect(() -> new StringJoiner(" \uD83D\uDD96 "), StringJoiner::add) + .map(StringJoiner::toString) + .subscribe(System.out::println); + +// prints Kirk 🖖 Spock 🖖 Chekov 🖖 Sulu +``` + +### collectInto + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) + +Collect items emitted by the source `Observable` into a single mutable data structure and return an `Observable` that emits this structure. + +#### collectInto example + +*Note: the mutable value that will collect the items (here the `StringBuilder`) will be shared between multiple subscribers.* + +```java +Observable.just('R', 'x', 'J', 'a', 'v', 'a') + .collectInto(new StringBuilder(), StringBuilder::append) + .map(StringBuilder::toString) + .subscribe(System.out::println); + +// prints RxJava +``` + +### toList + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) + +Collect all items from an `Observable` and emit them as a single `List`. + +#### toList example + +```java +Observable.just(2, 1, 3) + .toList() + .subscribe(System.out::println); + +// prints [2, 1, 3] +``` + +### toSortedList + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) + +Collect all items from an `Observable` and emit them as a single, sorted `List`. + +#### toSortedList example + +```java +Observable.just(2, 1, 3) + .toSortedList(Comparator.reverseOrder()) + .subscribe(System.out::println); + +// prints [3, 2, 1] +``` + +### toMap + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) + +Convert the sequence of items emitted by an `Observable` into a `Map` keyed by a specified key function. + +#### toMap example + +```java +Observable.just(1, 2, 3, 4) + .toMap((x) -> { + // defines the key in the Map + return x; + }, (x) -> { + // defines the value that is mapped to the key + return (x % 2 == 0) ? "even" : "odd"; + }) + .subscribe(System.out::println); + +// prints {1=odd, 2=even, 3=odd, 4=even} +``` + +### toMultimap + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) + +Convert the sequence of items emitted by an `Observable` into a `Collection` that is also a `Map` keyed by a specified key function. + +#### toMultimap example + +```java +Observable.just(1, 2, 3, 4) + .toMultimap((x) -> { + // defines the key in the Map + return (x % 2 == 0) ? "even" : "odd"; + }, (x) -> { + // defines the value that is mapped to the key + return x; + }) + .subscribe(System.out::println); + +// prints {even=[2, 4], odd=[1, 3]} +``` From 579e90dc21937b900877a8baf3918cdca22d3a91 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sun, 5 Aug 2018 21:14:21 +0200 Subject: [PATCH 257/417] 2.x: Cleaunp - rename fields to upstream and downstream (#6129) * 2.x: Cleaunp - rename fields to upstream and downstream * Make links in MaybeEmitter.setDisposable --- src/jmh/java/io/reactivex/MemoryPerf.java | 10 +- src/main/java/io/reactivex/Completable.java | 6 +- .../java/io/reactivex/CompletableEmitter.java | 8 +- .../java/io/reactivex/CompletableSource.java | 6 +- src/main/java/io/reactivex/Flowable.java | 2 +- .../java/io/reactivex/FlowableEmitter.java | 12 +- src/main/java/io/reactivex/Maybe.java | 6 +- src/main/java/io/reactivex/MaybeEmitter.java | 12 +- src/main/java/io/reactivex/Observable.java | 6 +- .../java/io/reactivex/ObservableEmitter.java | 8 +- src/main/java/io/reactivex/Single.java | 6 +- src/main/java/io/reactivex/SingleEmitter.java | 10 +- .../observers/BasicFuseableObserver.java | 46 +++--- .../observers/BlockingBaseObserver.java | 6 +- .../observers/BlockingFirstObserver.java | 2 +- .../observers/BlockingMultiObserver.java | 6 +- .../internal/observers/BlockingObserver.java | 4 +- .../observers/DeferredScalarDisposable.java | 14 +- .../observers/DeferredScalarObserver.java | 18 +-- .../observers/DisposableLambdaObserver.java | 36 ++--- .../observers/ForEachWhileObserver.java | 4 +- .../internal/observers/FutureObserver.java | 24 +-- .../observers/FutureSingleObserver.java | 22 +-- .../observers/InnerQueuedObserver.java | 14 +- .../internal/observers/LambdaObserver.java | 6 +- .../observers/QueueDrainObserver.java | 8 +- .../observers/ResumeSingleObserver.java | 10 +- .../SubscriberCompletableObserver.java | 8 +- .../completable/CompletableCache.java | 10 +- .../completable/CompletableConcat.java | 28 ++-- .../completable/CompletableConcatArray.java | 8 +- .../CompletableConcatIterable.java | 12 +- .../completable/CompletableCreate.java | 10 +- .../completable/CompletableDetach.java | 34 ++-- .../completable/CompletableDisposeOn.java | 16 +- .../completable/CompletableDoFinally.java | 20 +-- .../completable/CompletableFromPublisher.java | 28 ++-- .../completable/CompletableHide.java | 24 +-- .../completable/CompletableMerge.java | 36 ++--- .../completable/CompletableMergeArray.java | 8 +- .../CompletableMergeDelayErrorArray.java | 8 +- .../completable/CompletableMergeIterable.java | 8 +- .../completable/CompletableObserveOn.java | 10 +- .../completable/CompletablePeek.java | 32 ++-- .../completable/CompletableSubscribeOn.java | 8 +- .../completable/CompletableTimer.java | 8 +- .../completable/CompletableUsing.java | 28 ++-- .../operators/flowable/FlowableAll.java | 16 +- .../operators/flowable/FlowableAllSingle.java | 36 ++--- .../operators/flowable/FlowableAmb.java | 26 ++-- .../operators/flowable/FlowableAny.java | 16 +- .../operators/flowable/FlowableAnySingle.java | 36 ++--- .../operators/flowable/FlowableBuffer.java | 76 ++++----- .../flowable/FlowableBufferBoundary.java | 6 +- .../FlowableBufferBoundarySupplier.java | 24 +-- .../flowable/FlowableBufferExactBoundary.java | 20 +-- .../flowable/FlowableBufferTimed.java | 58 +++---- .../operators/flowable/FlowableCollect.java | 14 +- .../flowable/FlowableCollectSingle.java | 28 ++-- .../flowable/FlowableCombineLatest.java | 8 +- .../flowable/FlowableConcatArray.java | 18 +-- .../operators/flowable/FlowableConcatMap.java | 88 +++++------ .../flowable/FlowableConcatMapEager.java | 24 +-- .../FlowableConcatWithCompletable.java | 12 +- .../flowable/FlowableConcatWithMaybe.java | 8 +- .../flowable/FlowableConcatWithSingle.java | 6 +- .../operators/flowable/FlowableCount.java | 16 +- .../flowable/FlowableCountSingle.java | 28 ++-- .../operators/flowable/FlowableCreate.java | 46 +++--- .../operators/flowable/FlowableDebounce.java | 24 +-- .../flowable/FlowableDebounceTimed.java | 22 +-- .../operators/flowable/FlowableDelay.java | 30 ++-- .../FlowableDelaySubscriptionOther.java | 7 +- .../flowable/FlowableDematerialize.java | 28 ++-- .../operators/flowable/FlowableDetach.java | 36 ++--- .../operators/flowable/FlowableDistinct.java | 12 +- .../FlowableDistinctUntilChanged.java | 16 +- .../flowable/FlowableDoAfterNext.java | 6 +- .../operators/flowable/FlowableDoFinally.java | 46 +++--- .../operators/flowable/FlowableDoOnEach.java | 22 +-- .../flowable/FlowableDoOnLifecycle.java | 30 ++-- .../operators/flowable/FlowableElementAt.java | 18 +-- .../flowable/FlowableElementAtMaybe.java | 32 ++-- .../flowable/FlowableElementAtSingle.java | 34 ++-- .../operators/flowable/FlowableFilter.java | 12 +- .../operators/flowable/FlowableFlatMap.java | 14 +- .../flowable/FlowableFlatMapCompletable.java | 28 ++-- ...FlowableFlatMapCompletableCompletable.java | 28 ++-- .../flowable/FlowableFlatMapMaybe.java | 40 ++--- .../flowable/FlowableFlatMapSingle.java | 32 ++-- .../flowable/FlowableFlattenIterable.java | 30 ++-- .../operators/flowable/FlowableFromArray.java | 16 +- .../flowable/FlowableFromIterable.java | 16 +- .../flowable/FlowableFromObservable.java | 22 +-- .../operators/flowable/FlowableGenerate.java | 10 +- .../operators/flowable/FlowableGroupBy.java | 30 ++-- .../operators/flowable/FlowableGroupJoin.java | 6 +- .../operators/flowable/FlowableHide.java | 24 +-- .../flowable/FlowableIgnoreElements.java | 20 +-- .../FlowableIgnoreElementsCompletable.java | 28 ++-- .../operators/flowable/FlowableInterval.java | 10 +- .../flowable/FlowableIntervalRange.java | 10 +- .../operators/flowable/FlowableJoin.java | 6 +- .../operators/flowable/FlowableLastMaybe.java | 30 ++-- .../flowable/FlowableLastSingle.java | 30 ++-- .../operators/flowable/FlowableLimit.java | 16 +- .../operators/flowable/FlowableMap.java | 10 +- .../flowable/FlowableMapNotification.java | 8 +- .../flowable/FlowableMaterialize.java | 6 +- .../FlowableMergeWithCompletable.java | 20 +-- .../flowable/FlowableMergeWithMaybe.java | 12 +- .../flowable/FlowableMergeWithSingle.java | 12 +- .../operators/flowable/FlowableObserveOn.java | 70 ++++----- .../FlowableOnBackpressureBuffer.java | 24 +-- .../FlowableOnBackpressureBufferStrategy.java | 20 +-- .../flowable/FlowableOnBackpressureDrop.java | 20 +-- .../flowable/FlowableOnBackpressureError.java | 22 +-- .../FlowableOnBackpressureLatest.java | 18 +-- .../flowable/FlowableOnErrorNext.java | 14 +- .../flowable/FlowableOnErrorReturn.java | 6 +- .../flowable/FlowablePublishMulticast.java | 48 +++--- .../operators/flowable/FlowableRange.java | 16 +- .../operators/flowable/FlowableRangeLong.java | 16 +- .../operators/flowable/FlowableReduce.java | 28 ++-- .../flowable/FlowableReduceMaybe.java | 22 +-- .../flowable/FlowableReduceSeedSingle.java | 28 ++-- .../operators/flowable/FlowableRefCount.java | 12 +- .../operators/flowable/FlowableRepeat.java | 10 +- .../flowable/FlowableRepeatUntil.java | 12 +- .../flowable/FlowableRepeatWhen.java | 25 ++- .../flowable/FlowableRetryBiPredicate.java | 12 +- .../flowable/FlowableRetryPredicate.java | 14 +- .../operators/flowable/FlowableRetryWhen.java | 2 +- .../flowable/FlowableSamplePublisher.java | 36 ++--- .../flowable/FlowableSampleTimed.java | 26 ++-- .../operators/flowable/FlowableScan.java | 24 +-- .../operators/flowable/FlowableScanSeed.java | 20 +-- .../flowable/FlowableSequenceEqual.java | 10 +- .../flowable/FlowableSequenceEqualSingle.java | 20 +-- .../operators/flowable/FlowableSingle.java | 20 +-- .../flowable/FlowableSingleMaybe.java | 36 ++--- .../flowable/FlowableSingleSingle.java | 34 ++-- .../operators/flowable/FlowableSkip.java | 22 +-- .../operators/flowable/FlowableSkipLast.java | 24 +-- .../flowable/FlowableSkipLastTimed.java | 16 +- .../operators/flowable/FlowableSkipUntil.java | 28 ++-- .../operators/flowable/FlowableSkipWhile.java | 30 ++-- .../flowable/FlowableSubscribeOn.java | 30 ++-- .../flowable/FlowableSwitchIfEmpty.java | 10 +- .../operators/flowable/FlowableSwitchMap.java | 22 +-- .../operators/flowable/FlowableTake.java | 38 +++-- .../operators/flowable/FlowableTakeLast.java | 18 +-- .../flowable/FlowableTakeLastOne.java | 18 +-- .../flowable/FlowableTakeLastTimed.java | 16 +- .../operators/flowable/FlowableTakeUntil.java | 30 ++-- .../flowable/FlowableTakeUntilPredicate.java | 28 ++-- .../operators/flowable/FlowableTakeWhile.java | 28 ++-- .../flowable/FlowableThrottleFirstTimed.java | 22 +-- .../flowable/FlowableTimeInterval.java | 22 +-- .../operators/flowable/FlowableTimeout.java | 32 ++-- .../flowable/FlowableTimeoutTimed.java | 34 ++-- .../operators/flowable/FlowableTimer.java | 12 +- .../operators/flowable/FlowableToList.java | 12 +- .../flowable/FlowableToListSingle.java | 26 ++-- .../flowable/FlowableUnsubscribeOn.java | 22 +-- .../operators/flowable/FlowableUsing.java | 38 ++--- .../operators/flowable/FlowableWindow.java | 66 ++++---- .../flowable/FlowableWindowBoundary.java | 4 +- .../FlowableWindowBoundarySelector.java | 18 +-- .../FlowableWindowBoundarySupplier.java | 8 +- .../flowable/FlowableWindowTimed.java | 76 ++++----- .../flowable/FlowableWithLatestFrom.java | 15 +- .../flowable/FlowableWithLatestFromMany.java | 32 ++-- .../operators/flowable/FlowableZip.java | 6 +- .../flowable/FlowableZipIterable.java | 30 ++-- .../internal/operators/maybe/MaybeAmb.java | 12 +- .../internal/operators/maybe/MaybeCache.java | 10 +- .../operators/maybe/MaybeConcatArray.java | 8 +- .../maybe/MaybeConcatArrayDelayError.java | 6 +- .../operators/maybe/MaybeConcatIterable.java | 8 +- .../operators/maybe/MaybeContains.java | 30 ++-- .../internal/operators/maybe/MaybeCount.java | 32 ++-- .../internal/operators/maybe/MaybeCreate.java | 14 +- .../internal/operators/maybe/MaybeDelay.java | 12 +- .../maybe/MaybeDelayOtherPublisher.java | 34 ++-- .../MaybeDelaySubscriptionOtherPublisher.java | 40 ++--- .../maybe/MaybeDelayWithCompletable.java | 22 +-- .../internal/operators/maybe/MaybeDetach.java | 40 ++--- .../operators/maybe/MaybeDoAfterSuccess.java | 22 +-- .../operators/maybe/MaybeDoFinally.java | 22 +-- .../operators/maybe/MaybeDoOnEvent.java | 34 ++-- .../operators/maybe/MaybeEqualSingle.java | 12 +- .../internal/operators/maybe/MaybeFilter.java | 28 ++-- .../operators/maybe/MaybeFilterSingle.java | 26 ++-- .../maybe/MaybeFlatMapBiSelector.java | 20 +-- .../maybe/MaybeFlatMapCompletable.java | 8 +- .../maybe/MaybeFlatMapIterableFlowable.java | 28 ++-- .../maybe/MaybeFlatMapIterableObservable.java | 24 +-- .../maybe/MaybeFlatMapNotification.java | 26 ++-- .../operators/maybe/MaybeFlatMapSingle.java | 26 ++-- .../maybe/MaybeFlatMapSingleElement.java | 26 ++-- .../operators/maybe/MaybeFlatten.java | 26 ++-- .../operators/maybe/MaybeFromCompletable.java | 28 ++-- .../operators/maybe/MaybeFromSingle.java | 28 ++-- .../internal/operators/maybe/MaybeHide.java | 26 ++-- .../operators/maybe/MaybeIgnoreElement.java | 32 ++-- .../maybe/MaybeIgnoreElementCompletable.java | 32 ++-- .../operators/maybe/MaybeIsEmpty.java | 24 +-- .../operators/maybe/MaybeIsEmptySingle.java | 32 ++-- .../internal/operators/maybe/MaybeMap.java | 26 ++-- .../operators/maybe/MaybeMergeArray.java | 8 +- .../operators/maybe/MaybeObserveOn.java | 12 +- .../operators/maybe/MaybeOnErrorComplete.java | 26 ++-- .../operators/maybe/MaybeOnErrorNext.java | 32 ++-- .../operators/maybe/MaybeOnErrorReturn.java | 24 +-- .../internal/operators/maybe/MaybePeek.java | 40 ++--- .../operators/maybe/MaybeSubscribeOn.java | 12 +- .../operators/maybe/MaybeSwitchIfEmpty.java | 22 +-- .../maybe/MaybeSwitchIfEmptySingle.java | 20 +-- .../operators/maybe/MaybeTakeUntilMaybe.java | 16 +- .../maybe/MaybeTakeUntilPublisher.java | 16 +- .../operators/maybe/MaybeTimeoutMaybe.java | 26 ++-- .../maybe/MaybeTimeoutPublisher.java | 26 ++-- .../internal/operators/maybe/MaybeTimer.java | 8 +- .../operators/maybe/MaybeToFlowable.java | 18 +-- .../operators/maybe/MaybeToObservable.java | 14 +- .../operators/maybe/MaybeToSingle.java | 32 ++-- .../operators/maybe/MaybeUnsubscribeOn.java | 12 +- .../internal/operators/maybe/MaybeUsing.java | 34 ++-- .../operators/maybe/MaybeZipArray.java | 12 +- .../mixed/ObservableConcatMapCompletable.java | 10 +- .../mixed/ObservableConcatMapMaybe.java | 6 +- .../mixed/ObservableConcatMapSingle.java | 6 +- .../mixed/ObservableSwitchMapCompletable.java | 6 +- .../mixed/ObservableSwitchMapMaybe.java | 6 +- .../mixed/ObservableSwitchMapSingle.java | 6 +- .../BlockingObservableIterable.java | 4 +- .../operators/observable/ObservableAll.java | 32 ++-- .../observable/ObservableAllSingle.java | 28 ++-- .../operators/observable/ObservableAmb.java | 30 ++-- .../operators/observable/ObservableAny.java | 32 ++-- .../observable/ObservableAnySingle.java | 28 ++-- .../observable/ObservableBuffer.java | 64 ++++---- .../observable/ObservableBufferBoundary.java | 24 +-- .../ObservableBufferBoundarySupplier.java | 28 ++-- .../ObservableBufferExactBoundary.java | 24 +-- .../observable/ObservableBufferTimed.java | 74 ++++----- .../operators/observable/ObservableCache.java | 4 +- .../observable/ObservableCollect.java | 26 ++-- .../observable/ObservableCollectSingle.java | 24 +-- .../observable/ObservableCombineLatest.java | 12 +- .../observable/ObservableConcatMap.java | 76 ++++----- .../observable/ObservableConcatMapEager.java | 22 +-- .../ObservableConcatWithCompletable.java | 12 +- .../observable/ObservableConcatWithMaybe.java | 16 +- .../ObservableConcatWithSingle.java | 14 +- .../operators/observable/ObservableCount.java | 26 ++-- .../observable/ObservableCountSingle.java | 28 ++-- .../observable/ObservableCreate.java | 4 +- .../observable/ObservableDebounce.java | 26 ++-- .../observable/ObservableDebounceTimed.java | 22 +-- .../operators/observable/ObservableDelay.java | 22 +-- .../observable/ObservableDematerialize.java | 30 ++-- .../observable/ObservableDetach.java | 40 ++--- .../observable/ObservableDistinct.java | 10 +- .../ObservableDistinctUntilChanged.java | 6 +- .../observable/ObservableDoAfterNext.java | 4 +- .../observable/ObservableDoFinally.java | 22 +-- .../observable/ObservableDoOnEach.java | 26 ++-- .../observable/ObservableElementAt.java | 32 ++-- .../observable/ObservableElementAtMaybe.java | 26 ++-- .../observable/ObservableElementAtSingle.java | 28 ++-- .../observable/ObservableFilter.java | 6 +- .../observable/ObservableFlatMap.java | 34 ++-- .../ObservableFlatMapCompletable.java | 26 ++-- ...servableFlatMapCompletableCompletable.java | 26 ++-- .../observable/ObservableFlatMapMaybe.java | 30 ++-- .../observable/ObservableFlatMapSingle.java | 26 ++-- .../observable/ObservableFlattenIterable.java | 40 ++--- .../observable/ObservableFromArray.java | 10 +- .../observable/ObservableFromIterable.java | 12 +- .../observable/ObservableFromPublisher.java | 24 +-- .../observable/ObservableGenerate.java | 10 +- .../observable/ObservableGroupBy.java | 28 ++-- .../observable/ObservableGroupJoin.java | 14 +- .../operators/observable/ObservableHide.java | 24 +-- .../observable/ObservableIgnoreElements.java | 20 +-- .../ObservableIgnoreElementsCompletable.java | 20 +-- .../observable/ObservableInterval.java | 8 +- .../observable/ObservableIntervalRange.java | 8 +- .../operators/observable/ObservableJoin.java | 6 +- .../observable/ObservableLastMaybe.java | 32 ++-- .../observable/ObservableLastSingle.java | 32 ++-- .../operators/observable/ObservableMap.java | 6 +- .../observable/ObservableMapNotification.java | 34 ++-- .../observable/ObservableMaterialize.java | 30 ++-- .../ObservableMergeWithCompletable.java | 16 +- .../observable/ObservableMergeWithMaybe.java | 12 +- .../observable/ObservableMergeWithSingle.java | 12 +- .../observable/ObservableObserveOn.java | 36 ++--- .../observable/ObservableOnErrorNext.java | 20 +-- .../observable/ObservableOnErrorReturn.java | 30 ++-- .../observable/ObservablePublish.java | 8 +- .../observable/ObservablePublishSelector.java | 24 +-- .../operators/observable/ObservableRange.java | 6 +- .../observable/ObservableRangeLong.java | 6 +- .../observable/ObservableReduceMaybe.java | 24 +-- .../ObservableReduceSeedSingle.java | 22 +-- .../observable/ObservableRefCount.java | 14 +- .../observable/ObservableRepeat.java | 14 +- .../observable/ObservableRepeatUntil.java | 20 +-- .../observable/ObservableRepeatWhen.java | 26 ++-- .../ObservableRetryBiPredicate.java | 22 +-- .../observable/ObservableRetryPredicate.java | 24 +-- .../observable/ObservableRetryWhen.java | 26 ++-- .../observable/ObservableSampleTimed.java | 32 ++-- .../ObservableSampleWithObservable.java | 40 ++--- .../operators/observable/ObservableScan.java | 26 ++-- .../observable/ObservableScanSeed.java | 28 ++-- .../observable/ObservableSequenceEqual.java | 30 ++-- .../ObservableSequenceEqualSingle.java | 24 +-- .../observable/ObservableSingleMaybe.java | 30 ++-- .../observable/ObservableSingleSingle.java | 28 ++-- .../operators/observable/ObservableSkip.java | 22 +-- .../observable/ObservableSkipLast.java | 24 +-- .../observable/ObservableSkipLastTimed.java | 18 +-- .../observable/ObservableSkipUntil.java | 40 ++--- .../observable/ObservableSkipWhile.java | 30 ++-- .../observable/ObservableSubscribeOn.java | 22 +-- .../observable/ObservableSwitchIfEmpty.java | 14 +- .../observable/ObservableSwitchMap.java | 32 ++-- .../operators/observable/ObservableTake.java | 32 ++-- .../observable/ObservableTakeLast.java | 20 +-- .../observable/ObservableTakeLastOne.java | 26 ++-- .../observable/ObservableTakeLastTimed.java | 16 +- .../ObservableTakeUntilPredicate.java | 32 ++-- .../observable/ObservableTakeWhile.java | 30 ++-- .../ObservableThrottleFirstTimed.java | 22 +-- .../observable/ObservableThrottleLatest.java | 6 +- .../observable/ObservableTimeInterval.java | 24 +-- .../observable/ObservableTimeout.java | 44 +++--- .../observable/ObservableTimeoutTimed.java | 46 +++--- .../operators/observable/ObservableTimer.java | 10 +- .../observable/ObservableToList.java | 27 ++-- .../observable/ObservableToListSingle.java | 22 +-- .../observable/ObservableUnsubscribeOn.java | 22 +-- .../operators/observable/ObservableUsing.java | 36 ++--- .../observable/ObservableWindow.java | 48 +++--- .../ObservableWindowBoundarySelector.java | 18 +-- .../observable/ObservableWindowTimed.java | 72 ++++----- .../observable/ObservableWithLatestFrom.java | 44 +++--- .../ObservableWithLatestFromMany.java | 30 ++-- .../operators/observable/ObservableZip.java | 16 +- .../observable/ObservableZipIterable.java | 32 ++-- .../observable/ObserverResourceWrapper.java | 24 +-- .../operators/parallel/ParallelCollect.java | 10 +- .../parallel/ParallelDoOnNextTry.java | 49 +++--- .../operators/parallel/ParallelFilter.java | 40 ++--- .../operators/parallel/ParallelFilterTry.java | 40 ++--- .../parallel/ParallelFromPublisher.java | 16 +- .../operators/parallel/ParallelJoin.java | 14 +- .../operators/parallel/ParallelMap.java | 46 +++--- .../operators/parallel/ParallelMapTry.java | 49 +++--- .../operators/parallel/ParallelPeek.java | 26 ++-- .../operators/parallel/ParallelReduce.java | 10 +- .../parallel/ParallelReduceFull.java | 4 +- .../operators/parallel/ParallelRunOn.java | 34 ++-- .../parallel/ParallelSortedJoin.java | 6 +- .../operators/single/SingleCache.java | 8 +- .../operators/single/SingleCreate.java | 17 +- .../single/SingleDelayWithCompletable.java | 10 +- .../single/SingleDelayWithObservable.java | 10 +- .../single/SingleDelayWithPublisher.java | 20 +-- .../single/SingleDelayWithSingle.java | 10 +- .../operators/single/SingleDetach.java | 34 ++-- .../single/SingleDoAfterSuccess.java | 20 +-- .../single/SingleDoAfterTerminate.java | 20 +-- .../operators/single/SingleDoFinally.java | 20 +-- .../operators/single/SingleDoOnDispose.java | 20 +-- .../operators/single/SingleDoOnSubscribe.java | 12 +- .../operators/single/SingleFlatMap.java | 26 ++-- .../single/SingleFlatMapCompletable.java | 8 +- .../single/SingleFlatMapIterableFlowable.java | 26 ++-- .../SingleFlatMapIterableObservable.java | 24 +-- .../operators/single/SingleFlatMapMaybe.java | 26 ++-- .../single/SingleFlatMapPublisher.java | 18 +-- .../operators/single/SingleFromPublisher.java | 26 ++-- .../internal/operators/single/SingleHide.java | 22 +-- .../operators/single/SingleObserveOn.java | 10 +- .../operators/single/SingleResumeNext.java | 12 +- .../operators/single/SingleSubscribeOn.java | 8 +- .../operators/single/SingleTakeUntil.java | 12 +- .../operators/single/SingleTimeout.java | 20 +-- .../operators/single/SingleTimer.java | 8 +- .../operators/single/SingleToFlowable.java | 16 +- .../operators/single/SingleToObservable.java | 14 +- .../operators/single/SingleUnsubscribeOn.java | 10 +- .../operators/single/SingleUsing.java | 28 ++-- .../operators/single/SingleZipArray.java | 10 +- .../internal/schedulers/DisposeOnCancel.java | 7 +- .../BasicFuseableConditionalSubscriber.java | 26 ++-- .../subscribers/BasicFuseableSubscriber.java | 26 ++-- .../subscribers/BlockingBaseSubscriber.java | 12 +- .../subscribers/BlockingFirstSubscriber.java | 2 +- .../subscribers/DeferredScalarSubscriber.java | 20 +-- .../subscribers/FutureSubscriber.java | 22 +-- .../subscribers/QueueDrainSubscriber.java | 10 +- .../SinglePostCompleteSubscriber.java | 26 ++-- .../subscribers/StrictSubscriber.java | 24 +-- .../SubscriberResourceWrapper.java | 24 +-- .../DeferredScalarSubscription.java | 14 +- .../internal/util/NotificationLite.java | 20 +-- .../reactivex/observers/DefaultObserver.java | 16 +- .../DisposableCompletableObserver.java | 11 +- .../observers/DisposableMaybeObserver.java | 10 +- .../observers/DisposableObserver.java | 10 +- .../observers/DisposableSingleObserver.java | 10 +- .../ResourceCompletableObserver.java | 10 +- .../observers/ResourceMaybeObserver.java | 10 +- .../reactivex/observers/ResourceObserver.java | 10 +- .../observers/ResourceSingleObserver.java | 10 +- .../io/reactivex/observers/SafeObserver.java | 52 +++---- .../observers/SerializedObserver.java | 34 ++-- .../io/reactivex/observers/TestObserver.java | 68 ++++---- .../reactivex/processors/AsyncProcessor.java | 4 +- .../processors/BehaviorProcessor.java | 12 +- .../processors/MulticastProcessor.java | 10 +- .../processors/PublishProcessor.java | 12 +- .../reactivex/processors/ReplayProcessor.java | 10 +- .../processors/UnicastProcessor.java | 28 ++-- .../io/reactivex/subjects/AsyncSubject.java | 8 +- .../reactivex/subjects/BehaviorSubject.java | 10 +- .../subjects/CompletableSubject.java | 8 +- .../io/reactivex/subjects/MaybeSubject.java | 10 +- .../io/reactivex/subjects/PublishSubject.java | 26 ++-- .../io/reactivex/subjects/ReplaySubject.java | 14 +- .../reactivex/subjects/SerializedSubject.java | 8 +- .../io/reactivex/subjects/SingleSubject.java | 8 +- .../io/reactivex/subjects/UnicastSubject.java | 32 ++-- .../subscribers/DefaultSubscriber.java | 14 +- .../reactivex/subscribers/SafeSubscriber.java | 50 +++--- .../subscribers/SerializedSubscriber.java | 32 ++-- .../reactivex/subscribers/TestSubscriber.java | 42 ++--- src/test/java/io/reactivex/TestHelper.java | 104 ++++++------- .../completable/CompletableTest.java | 42 ++--- .../disposables/CompositeDisposableTest.java | 114 +++++++------- .../flowable/FlowableBackpressureTests.java | 8 +- .../flowable/FlowableSubscriberTest.java | 6 +- .../io/reactivex/flowable/FlowableTests.java | 4 +- .../observers/DeferredScalarObserverTest.java | 16 +- .../observers/FutureObserverTest.java | 12 +- .../observers/LambdaObserverTest.java | 26 ++-- .../observers/QueueDrainObserverTest.java | 4 +- .../completable/CompletableDoOnTest.java | 2 +- .../flowable/FlowableBlockingTest.java | 8 +- .../flowable/FlowableCombineLatestTest.java | 4 +- .../flowable/FlowableCreateTest.java | 4 +- .../flowable/FlowableDistinctTest.java | 10 +- .../FlowableFlatMapCompletableTest.java | 10 +- .../flowable/FlowableFromIterableTest.java | 12 +- .../flowable/FlowableObserveOnTest.java | 10 +- ...wableOnErrorResumeNextViaFlowableTest.java | 6 +- .../flowable/FlowablePublishTest.java | 46 +++--- .../flowable/FlowableRefCountTest.java | 52 +++---- .../flowable/FlowableTakeUntilTest.java | 6 +- .../flowable/FlowableTakeWhileTest.java | 6 +- .../operators/flowable/FlowableUsingTest.java | 6 +- .../operators/maybe/MaybeDoOnEventTest.java | 2 +- .../MaybeFlatMapIterableFlowableTest.java | 16 +- .../operators/maybe/MaybeMergeArrayTest.java | 16 +- .../observable/ObservableAmbTest.java | 2 +- .../observable/ObservableConcatTest.java | 4 +- .../observable/ObservableDoFinallyTest.java | 40 ++--- .../ObservableDoOnSubscribeTest.java | 12 +- .../observable/ObservableFlatMapTest.java | 2 +- .../observable/ObservableGroupByTest.java | 6 +- .../observable/ObservableGroupJoinTest.java | 2 +- .../observable/ObservableMergeTest.java | 8 +- .../observable/ObservableObserveOnTest.java | 6 +- ...vableOnErrorResumeNextViaFunctionTest.java | 4 +- ...bleOnErrorResumeNextViaObservableTest.java | 12 +- .../observable/ObservablePublishTest.java | 34 ++-- .../observable/ObservableRefCountTest.java | 70 ++++----- .../observable/ObservableSampleTest.java | 6 +- .../ObservableSwitchIfEmptyTest.java | 2 +- .../observable/ObservableTakeUntilTest.java | 8 +- .../observable/ObservableTakeWhileTest.java | 14 +- .../observable/ObservableTimeoutTests.java | 18 +-- .../ObservableTimeoutWithSelectorTest.java | 4 +- .../observable/ObservableUsingTest.java | 6 +- .../operators/single/SingleDoOnTest.java | 10 +- .../SingleFlatMapIterableFlowableTest.java | 16 +- .../DeferredScalarSubscriberTest.java | 4 +- .../subscribers/StrictSubscriberTest.java | 16 +- .../internal/util/EndConsumerHelperTest.java | 6 +- .../util/HalfSerializerObserverTest.java | 56 +++---- .../observable/ObservableNullTests.java | 2 +- .../reactivex/observable/ObservableTest.java | 4 +- .../reactivex/observers/SafeObserverTest.java | 2 +- .../parallel/ParallelFromPublisherTest.java | 6 +- .../reactivex/plugins/RxJavaPluginsTest.java | 4 +- .../processors/ReplayProcessorTest.java | 4 +- .../schedulers/ExecutorSchedulerTest.java | 20 +-- .../schedulers/SchedulerLifecycleTest.java | 12 +- .../subjects/PublishSubjectTest.java | 6 +- .../reactivex/subjects/ReplaySubjectTest.java | 4 +- .../subscribers/DisposableSubscriberTest.java | 12 +- .../subscribers/ResourceSubscriberTest.java | 12 +- .../subscribers/SafeSubscriberTest.java | 20 +-- .../subscribers/SerializedSubscriberTest.java | 32 ++-- .../subscribers/TestSubscriberTest.java | 16 +- .../io/reactivex/tck/RefCountProcessor.java | 12 +- .../{ => validators}/BaseTypeAnnotations.java | 3 +- .../{ => validators}/BaseTypeParser.java | 2 +- .../CheckLocalVariablesInTests.java | 147 +++++++++++++++++- .../{ => validators}/FixLicenseHeaders.java | 2 +- .../{ => validators}/InternalWrongNaming.java | 2 +- .../JavadocFindUnescapedAngleBrackets.java | 2 +- .../JavadocForAnnotations.java | 4 +- .../{ => validators}/JavadocWording.java | 4 +- .../{ => validators}/MaybeNo2Dot0Since.java | 4 +- .../NoAnonymousInnerClassesTest.java | 2 +- .../{ => validators}/OperatorsAreFinal.java | 2 +- .../ParamValidationCheckerTest.java | 5 +- .../{ => validators}/PublicFinalMethods.java | 4 +- .../{ => validators}/TextualAorAn.java | 2 +- 526 files changed, 5499 insertions(+), 5325 deletions(-) rename src/test/java/io/reactivex/{ => validators}/BaseTypeAnnotations.java (99%) rename src/test/java/io/reactivex/{ => validators}/BaseTypeParser.java (99%) rename src/test/java/io/reactivex/{ => validators}/CheckLocalVariablesInTests.java (65%) rename src/test/java/io/reactivex/{ => validators}/FixLicenseHeaders.java (99%) rename src/test/java/io/reactivex/{ => validators}/InternalWrongNaming.java (99%) rename src/test/java/io/reactivex/{ => validators}/JavadocFindUnescapedAngleBrackets.java (99%) rename src/test/java/io/reactivex/{ => validators}/JavadocForAnnotations.java (99%) rename src/test/java/io/reactivex/{ => validators}/JavadocWording.java (99%) rename src/test/java/io/reactivex/{ => validators}/MaybeNo2Dot0Since.java (98%) rename src/test/java/io/reactivex/{ => validators}/NoAnonymousInnerClassesTest.java (98%) rename src/test/java/io/reactivex/{ => validators}/OperatorsAreFinal.java (98%) rename src/test/java/io/reactivex/{ => validators}/ParamValidationCheckerTest.java (99%) rename src/test/java/io/reactivex/{ => validators}/PublicFinalMethods.java (96%) rename src/test/java/io/reactivex/{ => validators}/TextualAorAn.java (99%) diff --git a/src/jmh/java/io/reactivex/MemoryPerf.java b/src/jmh/java/io/reactivex/MemoryPerf.java index ba92a89b78..2a625c2149 100644 --- a/src/jmh/java/io/reactivex/MemoryPerf.java +++ b/src/jmh/java/io/reactivex/MemoryPerf.java @@ -35,11 +35,11 @@ static long memoryUse() { static final class MyRx2Subscriber implements FlowableSubscriber<Object> { - org.reactivestreams.Subscription s; + org.reactivestreams.Subscription upstream; @Override public void onSubscribe(Subscription s) { - this.s = s; + this.upstream = s; } @Override @@ -61,11 +61,11 @@ public void onNext(Object t) { static final class MyRx2Observer implements io.reactivex.Observer<Object>, io.reactivex.SingleObserver<Object>, io.reactivex.MaybeObserver<Object>, io.reactivex.CompletableObserver { - Disposable s; + Disposable upstream; @Override - public void onSubscribe(Disposable s) { - this.s = s; + public void onSubscribe(Disposable d) { + this.upstream = d; } @Override diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 9a681d8bc5..b4f18a56c2 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1622,11 +1622,11 @@ public final Completable doFinally(Action onFinally) { * // and subsequently this class has to send a Disposable to the downstream. * // Note that relaying the upstream's Disposable directly is not allowed in RxJava * @Override - * public void onSubscribe(Disposable s) { + * public void onSubscribe(Disposable d) { * if (upstream != null) { - * s.cancel(); + * d.dispose(); * } else { - * upstream = s; + * upstream = d; * downstream.onSubscribe(this); * } * } diff --git a/src/main/java/io/reactivex/CompletableEmitter.java b/src/main/java/io/reactivex/CompletableEmitter.java index b32e329c3b..ffbd9ba37b 100644 --- a/src/main/java/io/reactivex/CompletableEmitter.java +++ b/src/main/java/io/reactivex/CompletableEmitter.java @@ -59,15 +59,15 @@ public interface CompletableEmitter { void onError(@NonNull Throwable t); /** - * Sets a Disposable on this emitter; any previous Disposable - * or Cancellation will be disposed/cancelled. + * Sets a Disposable on this emitter; any previous {@link Disposable} + * or {@link Cancellable} will be disposed/cancelled. * @param d the disposable, null is allowed */ void setDisposable(@Nullable Disposable d); /** - * Sets a Cancellable on this emitter; any previous Disposable - * or Cancellation will be disposed/cancelled. + * Sets a Cancellable on this emitter; any previous {@link Disposable} + * or {@link Cancellable} will be disposed/cancelled. * @param c the cancellable resource, null is allowed */ void setCancellable(@Nullable Cancellable c); diff --git a/src/main/java/io/reactivex/CompletableSource.java b/src/main/java/io/reactivex/CompletableSource.java index 57019f3164..145b0404f7 100644 --- a/src/main/java/io/reactivex/CompletableSource.java +++ b/src/main/java/io/reactivex/CompletableSource.java @@ -24,8 +24,8 @@ public interface CompletableSource { /** * Subscribes the given CompletableObserver to this CompletableSource instance. - * @param cs the CompletableObserver, not null - * @throws NullPointerException if {@code cs} is null + * @param co the CompletableObserver, not null + * @throws NullPointerException if {@code co} is null */ - void subscribe(@NonNull CompletableObserver cs); + void subscribe(@NonNull CompletableObserver co); } diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 84d4e6bba5..1afe7b594f 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -10787,7 +10787,7 @@ public final Single<T> lastOrError() { * * // In the subscription phase, the upstream sends a Subscription to this class * // and subsequently this class has to send a Subscription to the downstream. - * // Note that relaying the upstream's Subscription directly is not allowed in RxJava + * // Note that relaying the upstream's Subscription instance directly is not allowed in RxJava * @Override * public void onSubscribe(Subscription s) { * if (upstream != null) { diff --git a/src/main/java/io/reactivex/FlowableEmitter.java b/src/main/java/io/reactivex/FlowableEmitter.java index 06636449c4..1cd91e14b4 100644 --- a/src/main/java/io/reactivex/FlowableEmitter.java +++ b/src/main/java/io/reactivex/FlowableEmitter.java @@ -51,15 +51,15 @@ public interface FlowableEmitter<T> extends Emitter<T> { /** - * Sets a Disposable on this emitter; any previous Disposable - * or Cancellation will be disposed/cancelled. - * @param s the disposable, null is allowed + * Sets a Disposable on this emitter; any previous {@link Disposable} + * or {@link Cancellable} will be disposed/cancelled. + * @param d the disposable, null is allowed */ - void setDisposable(@Nullable Disposable s); + void setDisposable(@Nullable Disposable d); /** - * Sets a Cancellable on this emitter; any previous Disposable - * or Cancellation will be disposed/cancelled. + * Sets a Cancellable on this emitter; any previous {@link Disposable} + * or {@link Cancellable} will be disposed/cancelled. * @param c the cancellable resource, null is allowed */ void setCancellable(@Nullable Cancellable c); diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 9c50ef8518..519a64f6b9 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3237,11 +3237,11 @@ public final Single<Boolean> isEmpty() { * // and subsequently this class has to send a Disposable to the downstream. * // Note that relaying the upstream's Disposable directly is not allowed in RxJava * @Override - * public void onSubscribe(Disposable s) { + * public void onSubscribe(Disposable d) { * if (upstream != null) { - * s.cancel(); + * d.dispose(); * } else { - * upstream = s; + * upstream = d; * downstream.onSubscribe(this); * } * } diff --git a/src/main/java/io/reactivex/MaybeEmitter.java b/src/main/java/io/reactivex/MaybeEmitter.java index f0e6ed6266..4819ce3c3e 100644 --- a/src/main/java/io/reactivex/MaybeEmitter.java +++ b/src/main/java/io/reactivex/MaybeEmitter.java @@ -67,15 +67,15 @@ public interface MaybeEmitter<T> { void onComplete(); /** - * Sets a Disposable on this emitter; any previous Disposable - * or Cancellation will be unsubscribed/cancelled. - * @param s the disposable, null is allowed + * Sets a Disposable on this emitter; any previous {@link Disposable} + * or {@link Cancellable} will be disposed/cancelled. + * @param d the disposable, null is allowed */ - void setDisposable(@Nullable Disposable s); + void setDisposable(@Nullable Disposable d); /** - * Sets a Cancellable on this emitter; any previous Disposable - * or Cancellation will be unsubscribed/cancelled. + * Sets a Cancellable on this emitter; any previous {@link Disposable} + * or {@link Cancellable} will be disposed/cancelled. * @param c the cancellable resource, null is allowed */ void setCancellable(@Nullable Cancellable c); diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 4d672cea00..ab38ab2374 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -9409,11 +9409,11 @@ public final Single<T> lastOrError() { * // and subsequently this class has to send a Disposable to the downstream. * // Note that relaying the upstream's Disposable directly is not allowed in RxJava * @Override - * public void onSubscribe(Disposable s) { + * public void onSubscribe(Disposable d) { * if (upstream != null) { - * s.dispose(); + * d.dispose(); * } else { - * upstream = s; + * upstream = d; * downstream.onSubscribe(this); * } * } diff --git a/src/main/java/io/reactivex/ObservableEmitter.java b/src/main/java/io/reactivex/ObservableEmitter.java index 0adbdb3a8d..9faccf528d 100644 --- a/src/main/java/io/reactivex/ObservableEmitter.java +++ b/src/main/java/io/reactivex/ObservableEmitter.java @@ -50,15 +50,15 @@ public interface ObservableEmitter<T> extends Emitter<T> { /** - * Sets a Disposable on this emitter; any previous Disposable - * or Cancellation will be unsubscribed/cancelled. + * Sets a Disposable on this emitter; any previous {@link Disposable} + * or {@link Cancellable} will be disposed/cancelled. * @param d the disposable, null is allowed */ void setDisposable(@Nullable Disposable d); /** - * Sets a Cancellable on this emitter; any previous Disposable - * or Cancellation will be unsubscribed/cancelled. + * Sets a Cancellable on this emitter; any previous {@link Disposable} + * or {@link Cancellable} will be disposed/cancelled. * @param c the cancellable resource, null is allowed */ void setCancellable(@Nullable Cancellable c); diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 8ae6ac777c..0a461709df 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2708,11 +2708,11 @@ public final T blockingGet() { * // and subsequently this class has to send a Disposable to the downstream. * // Note that relaying the upstream's Disposable directly is not allowed in RxJava * @Override - * public void onSubscribe(Disposable s) { + * public void onSubscribe(Disposable d) { * if (upstream != null) { - * s.cancel(); + * d.dispose(); * } else { - * upstream = s; + * upstream = d; * downstream.onSubscribe(this); * } * } diff --git a/src/main/java/io/reactivex/SingleEmitter.java b/src/main/java/io/reactivex/SingleEmitter.java index 9e98f130e0..9c1ded1575 100644 --- a/src/main/java/io/reactivex/SingleEmitter.java +++ b/src/main/java/io/reactivex/SingleEmitter.java @@ -63,14 +63,14 @@ public interface SingleEmitter<T> { /** * Sets a Disposable on this emitter; any previous Disposable - * or Cancellation will be unsubscribed/cancelled. - * @param s the disposable, null is allowed + * or Cancellable will be disposed/cancelled. + * @param d the disposable, null is allowed */ - void setDisposable(@Nullable Disposable s); + void setDisposable(@Nullable Disposable d); /** - * Sets a Cancellable on this emitter; any previous Disposable - * or Cancellation will be unsubscribed/cancelled. + * Sets a Cancellable on this emitter; any previous {@link Disposable} + * or {@link Cancellable} will be disposed/cancelled. * @param c the cancellable resource, null is allowed */ void setCancellable(@Nullable Cancellable c); diff --git a/src/main/java/io/reactivex/internal/observers/BasicFuseableObserver.java b/src/main/java/io/reactivex/internal/observers/BasicFuseableObserver.java index 64034616f0..56ec76bb61 100644 --- a/src/main/java/io/reactivex/internal/observers/BasicFuseableObserver.java +++ b/src/main/java/io/reactivex/internal/observers/BasicFuseableObserver.java @@ -28,13 +28,13 @@ public abstract class BasicFuseableObserver<T, R> implements Observer<T>, QueueDisposable<R> { /** The downstream subscriber. */ - protected final Observer<? super R> actual; + protected final Observer<? super R> downstream; /** The upstream subscription. */ - protected Disposable s; + protected Disposable upstream; /** The upstream's QueueDisposable if not null. */ - protected QueueDisposable<T> qs; + protected QueueDisposable<T> qd; /** Flag indicating no further onXXX event should be accepted. */ protected boolean done; @@ -44,26 +44,26 @@ public abstract class BasicFuseableObserver<T, R> implements Observer<T>, QueueD /** * Construct a BasicFuseableObserver by wrapping the given subscriber. - * @param actual the subscriber, not null (not verified) + * @param downstream the subscriber, not null (not verified) */ - public BasicFuseableObserver(Observer<? super R> actual) { - this.actual = actual; + public BasicFuseableObserver(Observer<? super R> downstream) { + this.downstream = downstream; } // final: fixed protocol steps to support fuseable and non-fuseable upstream @SuppressWarnings("unchecked") @Override - public final void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { + public final void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { - this.s = s; - if (s instanceof QueueDisposable) { - this.qs = (QueueDisposable<T>)s; + this.upstream = d; + if (d instanceof QueueDisposable) { + this.qd = (QueueDisposable<T>)d; } if (beforeDownstream()) { - actual.onSubscribe(this); + downstream.onSubscribe(this); afterDownstream(); } @@ -97,7 +97,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } /** @@ -106,7 +106,7 @@ public void onError(Throwable t) { */ protected final void fail(Throwable t) { Exceptions.throwIfFatal(t); - s.dispose(); + upstream.dispose(); onError(t); } @@ -116,7 +116,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } /** @@ -124,16 +124,16 @@ public void onComplete() { * saves the established mode in {@link #sourceMode} if that mode doesn't * have the {@link QueueDisposable#BOUNDARY} flag set. * <p> - * If the upstream doesn't support fusion ({@link #qs} is null), the method + * If the upstream doesn't support fusion ({@link #qd} is null), the method * returns {@link QueueDisposable#NONE}. * @param mode the fusion mode requested * @return the established fusion mode */ protected final int transitiveBoundaryFusion(int mode) { - QueueDisposable<T> qs = this.qs; - if (qs != null) { + QueueDisposable<T> qd = this.qd; + if (qd != null) { if ((mode & BOUNDARY) == 0) { - int m = qs.requestFusion(mode); + int m = qd.requestFusion(mode); if (m != NONE) { sourceMode = m; } @@ -149,22 +149,22 @@ protected final int transitiveBoundaryFusion(int mode) { @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override public boolean isEmpty() { - return qs.isEmpty(); + return qd.isEmpty(); } @Override public void clear() { - qs.clear(); + qd.clear(); } // ----------------------------------------------------------- diff --git a/src/main/java/io/reactivex/internal/observers/BlockingBaseObserver.java b/src/main/java/io/reactivex/internal/observers/BlockingBaseObserver.java index 4efb537e08..63078f8e68 100644 --- a/src/main/java/io/reactivex/internal/observers/BlockingBaseObserver.java +++ b/src/main/java/io/reactivex/internal/observers/BlockingBaseObserver.java @@ -24,7 +24,7 @@ public abstract class BlockingBaseObserver<T> extends CountDownLatch T value; Throwable error; - Disposable d; + Disposable upstream; volatile boolean cancelled; @@ -34,7 +34,7 @@ public BlockingBaseObserver() { @Override public final void onSubscribe(Disposable d) { - this.d = d; + this.upstream = d; if (cancelled) { d.dispose(); } @@ -48,7 +48,7 @@ public final void onComplete() { @Override public final void dispose() { cancelled = true; - Disposable d = this.d; + Disposable d = this.upstream; if (d != null) { d.dispose(); } diff --git a/src/main/java/io/reactivex/internal/observers/BlockingFirstObserver.java b/src/main/java/io/reactivex/internal/observers/BlockingFirstObserver.java index 2927679aff..212edb6bdb 100644 --- a/src/main/java/io/reactivex/internal/observers/BlockingFirstObserver.java +++ b/src/main/java/io/reactivex/internal/observers/BlockingFirstObserver.java @@ -24,7 +24,7 @@ public final class BlockingFirstObserver<T> extends BlockingBaseObserver<T> { public void onNext(T t) { if (value == null) { value = t; - d.dispose(); + upstream.dispose(); countDown(); } } diff --git a/src/main/java/io/reactivex/internal/observers/BlockingMultiObserver.java b/src/main/java/io/reactivex/internal/observers/BlockingMultiObserver.java index 934123e381..d96f3efa21 100644 --- a/src/main/java/io/reactivex/internal/observers/BlockingMultiObserver.java +++ b/src/main/java/io/reactivex/internal/observers/BlockingMultiObserver.java @@ -30,7 +30,7 @@ public final class BlockingMultiObserver<T> T value; Throwable error; - Disposable d; + Disposable upstream; volatile boolean cancelled; @@ -40,7 +40,7 @@ public BlockingMultiObserver() { void dispose() { cancelled = true; - Disposable d = this.d; + Disposable d = this.upstream; if (d != null) { d.dispose(); } @@ -48,7 +48,7 @@ void dispose() { @Override public void onSubscribe(Disposable d) { - this.d = d; + this.upstream = d; if (cancelled) { d.dispose(); } diff --git a/src/main/java/io/reactivex/internal/observers/BlockingObserver.java b/src/main/java/io/reactivex/internal/observers/BlockingObserver.java index 3604ad0351..4731dc380d 100644 --- a/src/main/java/io/reactivex/internal/observers/BlockingObserver.java +++ b/src/main/java/io/reactivex/internal/observers/BlockingObserver.java @@ -34,8 +34,8 @@ public BlockingObserver(Queue<Object> queue) { } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); } @Override diff --git a/src/main/java/io/reactivex/internal/observers/DeferredScalarDisposable.java b/src/main/java/io/reactivex/internal/observers/DeferredScalarDisposable.java index a517ed04b2..a975f0aecc 100644 --- a/src/main/java/io/reactivex/internal/observers/DeferredScalarDisposable.java +++ b/src/main/java/io/reactivex/internal/observers/DeferredScalarDisposable.java @@ -27,7 +27,7 @@ public class DeferredScalarDisposable<T> extends BasicIntQueueDisposable<T> { private static final long serialVersionUID = -5502432239815349361L; /** The target of the events. */ - protected final Observer<? super T> actual; + protected final Observer<? super T> downstream; /** The value stored temporarily when in fusion mode. */ protected T value; @@ -47,10 +47,10 @@ public class DeferredScalarDisposable<T> extends BasicIntQueueDisposable<T> { /** * Constructs a DeferredScalarDisposable by wrapping the Observer. - * @param actual the Observer to wrap, not null (not verified) + * @param downstream the Observer to wrap, not null (not verified) */ - public DeferredScalarDisposable(Observer<? super T> actual) { - this.actual = actual; + public DeferredScalarDisposable(Observer<? super T> downstream) { + this.downstream = downstream; } @Override @@ -72,7 +72,7 @@ public final void complete(T value) { if ((state & (FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED)) != 0) { return; } - Observer<? super T> a = actual; + Observer<? super T> a = downstream; if (state == FUSED_EMPTY) { this.value = value; lazySet(FUSED_READY); @@ -97,7 +97,7 @@ public final void error(Throwable t) { return; } lazySet(TERMINATED); - actual.onError(t); + downstream.onError(t); } /** @@ -109,7 +109,7 @@ public final void complete() { return; } lazySet(TERMINATED); - actual.onComplete(); + downstream.onComplete(); } @Nullable diff --git a/src/main/java/io/reactivex/internal/observers/DeferredScalarObserver.java b/src/main/java/io/reactivex/internal/observers/DeferredScalarObserver.java index 4e5319abf4..91236b37c2 100644 --- a/src/main/java/io/reactivex/internal/observers/DeferredScalarObserver.java +++ b/src/main/java/io/reactivex/internal/observers/DeferredScalarObserver.java @@ -29,22 +29,22 @@ public abstract class DeferredScalarObserver<T, R> private static final long serialVersionUID = -266195175408988651L; /** The upstream disposable. */ - protected Disposable s; + protected Disposable upstream; /** * Creates a DeferredScalarObserver instance and wraps a downstream Observer. - * @param actual the downstream subscriber, not null (not verified) + * @param downstream the downstream subscriber, not null (not verified) */ - public DeferredScalarObserver(Observer<? super R> actual) { - super(actual); + public DeferredScalarObserver(Observer<? super R> downstream) { + super(downstream); } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -68,6 +68,6 @@ public void onComplete() { @Override public void dispose() { super.dispose(); - s.dispose(); + upstream.dispose(); } } diff --git a/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java b/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java index 3ba9ebfa68..47d9990d4f 100644 --- a/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java +++ b/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java @@ -21,47 +21,47 @@ import io.reactivex.plugins.RxJavaPlugins; public final class DisposableLambdaObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final Consumer<? super Disposable> onSubscribe; final Action onDispose; - Disposable s; + Disposable upstream; public DisposableLambdaObserver(Observer<? super T> actual, Consumer<? super Disposable> onSubscribe, Action onDispose) { - this.actual = actual; + this.downstream = actual; this.onSubscribe = onSubscribe; this.onDispose = onDispose; } @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { // this way, multiple calls to onSubscribe can show up in tests that use doOnSubscribe to validate behavior try { - onSubscribe.accept(s); + onSubscribe.accept(d); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); - this.s = DisposableHelper.DISPOSED; - EmptyDisposable.error(e, actual); + d.dispose(); + this.upstream = DisposableHelper.DISPOSED; + EmptyDisposable.error(e, downstream); return; } - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - if (s != DisposableHelper.DISPOSED) { - actual.onError(t); + if (upstream != DisposableHelper.DISPOSED) { + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -69,8 +69,8 @@ public void onError(Throwable t) { @Override public void onComplete() { - if (s != DisposableHelper.DISPOSED) { - actual.onComplete(); + if (upstream != DisposableHelper.DISPOSED) { + downstream.onComplete(); } } @@ -83,11 +83,11 @@ public void dispose() { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(e); } - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } } diff --git a/src/main/java/io/reactivex/internal/observers/ForEachWhileObserver.java b/src/main/java/io/reactivex/internal/observers/ForEachWhileObserver.java index aaac865500..54b8fdbd5c 100644 --- a/src/main/java/io/reactivex/internal/observers/ForEachWhileObserver.java +++ b/src/main/java/io/reactivex/internal/observers/ForEachWhileObserver.java @@ -45,8 +45,8 @@ public ForEachWhileObserver(Predicate<? super T> onNext, } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); } @Override diff --git a/src/main/java/io/reactivex/internal/observers/FutureObserver.java b/src/main/java/io/reactivex/internal/observers/FutureObserver.java index 48f6ef0971..b3de7f40b8 100644 --- a/src/main/java/io/reactivex/internal/observers/FutureObserver.java +++ b/src/main/java/io/reactivex/internal/observers/FutureObserver.java @@ -35,22 +35,22 @@ public final class FutureObserver<T> extends CountDownLatch T value; Throwable error; - final AtomicReference<Disposable> s; + final AtomicReference<Disposable> upstream; public FutureObserver() { super(1); - this.s = new AtomicReference<Disposable>(); + this.upstream = new AtomicReference<Disposable>(); } @Override public boolean cancel(boolean mayInterruptIfRunning) { for (;;) { - Disposable a = s.get(); + Disposable a = upstream.get(); if (a == this || a == DisposableHelper.DISPOSED) { return false; } - if (s.compareAndSet(a, DisposableHelper.DISPOSED)) { + if (upstream.compareAndSet(a, DisposableHelper.DISPOSED)) { if (a != null) { a.dispose(); } @@ -62,7 +62,7 @@ public boolean cancel(boolean mayInterruptIfRunning) { @Override public boolean isCancelled() { - return DisposableHelper.isDisposed(s.get()); + return DisposableHelper.isDisposed(upstream.get()); } @Override @@ -108,14 +108,14 @@ public T get(long timeout, TimeUnit unit) throws InterruptedException, Execution } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this.s, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this.upstream, d); } @Override public void onNext(T t) { if (value != null) { - s.get().dispose(); + upstream.get().dispose(); onError(new IndexOutOfBoundsException("More than one element received")); return; } @@ -128,12 +128,12 @@ public void onError(Throwable t) { error = t; for (;;) { - Disposable a = s.get(); + Disposable a = upstream.get(); if (a == this || a == DisposableHelper.DISPOSED) { RxJavaPlugins.onError(t); return; } - if (s.compareAndSet(a, this)) { + if (upstream.compareAndSet(a, this)) { countDown(); return; } @@ -150,11 +150,11 @@ public void onComplete() { return; } for (;;) { - Disposable a = s.get(); + Disposable a = upstream.get(); if (a == this || a == DisposableHelper.DISPOSED) { return; } - if (s.compareAndSet(a, this)) { + if (upstream.compareAndSet(a, this)) { countDown(); return; } diff --git a/src/main/java/io/reactivex/internal/observers/FutureSingleObserver.java b/src/main/java/io/reactivex/internal/observers/FutureSingleObserver.java index 33b5b8099a..fb3b096855 100644 --- a/src/main/java/io/reactivex/internal/observers/FutureSingleObserver.java +++ b/src/main/java/io/reactivex/internal/observers/FutureSingleObserver.java @@ -34,22 +34,22 @@ public final class FutureSingleObserver<T> extends CountDownLatch T value; Throwable error; - final AtomicReference<Disposable> s; + final AtomicReference<Disposable> upstream; public FutureSingleObserver() { super(1); - this.s = new AtomicReference<Disposable>(); + this.upstream = new AtomicReference<Disposable>(); } @Override public boolean cancel(boolean mayInterruptIfRunning) { for (;;) { - Disposable a = s.get(); + Disposable a = upstream.get(); if (a == this || a == DisposableHelper.DISPOSED) { return false; } - if (s.compareAndSet(a, DisposableHelper.DISPOSED)) { + if (upstream.compareAndSet(a, DisposableHelper.DISPOSED)) { if (a != null) { a.dispose(); } @@ -61,7 +61,7 @@ public boolean cancel(boolean mayInterruptIfRunning) { @Override public boolean isCancelled() { - return DisposableHelper.isDisposed(s.get()); + return DisposableHelper.isDisposed(upstream.get()); } @Override @@ -107,31 +107,31 @@ public T get(long timeout, TimeUnit unit) throws InterruptedException, Execution } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this.s, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this.upstream, d); } @Override public void onSuccess(T t) { - Disposable a = s.get(); + Disposable a = upstream.get(); if (a == DisposableHelper.DISPOSED) { return; } value = t; - s.compareAndSet(a, this); + upstream.compareAndSet(a, this); countDown(); } @Override public void onError(Throwable t) { for (;;) { - Disposable a = s.get(); + Disposable a = upstream.get(); if (a == DisposableHelper.DISPOSED) { RxJavaPlugins.onError(t); return; } error = t; - if (s.compareAndSet(a, this)) { + if (upstream.compareAndSet(a, this)) { countDown(); return; } diff --git a/src/main/java/io/reactivex/internal/observers/InnerQueuedObserver.java b/src/main/java/io/reactivex/internal/observers/InnerQueuedObserver.java index 3588db20ef..27d800e183 100644 --- a/src/main/java/io/reactivex/internal/observers/InnerQueuedObserver.java +++ b/src/main/java/io/reactivex/internal/observers/InnerQueuedObserver.java @@ -50,23 +50,23 @@ public InnerQueuedObserver(InnerQueuedObserverSupport<T> parent, int prefetch) { } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.setOnce(this, s)) { - if (s instanceof QueueDisposable) { + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(this, d)) { + if (d instanceof QueueDisposable) { @SuppressWarnings("unchecked") - QueueDisposable<T> qs = (QueueDisposable<T>) s; + QueueDisposable<T> qd = (QueueDisposable<T>) d; - int m = qs.requestFusion(QueueDisposable.ANY); + int m = qd.requestFusion(QueueDisposable.ANY); if (m == QueueSubscription.SYNC) { fusionMode = m; - queue = qs; + queue = qd; done = true; parent.innerComplete(this); return; } if (m == QueueDisposable.ASYNC) { fusionMode = m; - queue = qs; + queue = qd; return; } } diff --git a/src/main/java/io/reactivex/internal/observers/LambdaObserver.java b/src/main/java/io/reactivex/internal/observers/LambdaObserver.java index da3a2b85db..7549910637 100644 --- a/src/main/java/io/reactivex/internal/observers/LambdaObserver.java +++ b/src/main/java/io/reactivex/internal/observers/LambdaObserver.java @@ -44,13 +44,13 @@ public LambdaObserver(Consumer<? super T> onNext, Consumer<? super Throwable> on } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.setOnce(this, s)) { + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(this, d)) { try { onSubscribe.accept(this); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.dispose(); + d.dispose(); onError(ex); } } diff --git a/src/main/java/io/reactivex/internal/observers/QueueDrainObserver.java b/src/main/java/io/reactivex/internal/observers/QueueDrainObserver.java index 366639340a..ab24a709f0 100644 --- a/src/main/java/io/reactivex/internal/observers/QueueDrainObserver.java +++ b/src/main/java/io/reactivex/internal/observers/QueueDrainObserver.java @@ -29,7 +29,7 @@ * @param <V> the value type the child subscriber accepts */ public abstract class QueueDrainObserver<T, U, V> extends QueueDrainSubscriberPad2 implements Observer<T>, ObservableQueueDrain<U, V> { - protected final Observer<? super V> actual; + protected final Observer<? super V> downstream; protected final SimplePlainQueue<U> queue; protected volatile boolean cancelled; @@ -38,7 +38,7 @@ public abstract class QueueDrainObserver<T, U, V> extends QueueDrainSubscriberPa protected Throwable error; public QueueDrainObserver(Observer<? super V> actual, SimplePlainQueue<U> queue) { - this.actual = actual; + this.downstream = actual; this.queue = queue; } @@ -62,7 +62,7 @@ public final boolean fastEnter() { } protected final void fastPathEmit(U value, boolean delayError, Disposable dispose) { - final Observer<? super V> observer = actual; + final Observer<? super V> observer = downstream; final SimplePlainQueue<U> q = queue; if (wip.get() == 0 && wip.compareAndSet(0, 1)) { @@ -86,7 +86,7 @@ protected final void fastPathEmit(U value, boolean delayError, Disposable dispos * @param disposable the resource to dispose if the drain terminates */ protected final void fastPathOrderedEmit(U value, boolean delayError, Disposable disposable) { - final Observer<? super V> observer = actual; + final Observer<? super V> observer = downstream; final SimplePlainQueue<U> q = queue; if (wip.get() == 0 && wip.compareAndSet(0, 1)) { diff --git a/src/main/java/io/reactivex/internal/observers/ResumeSingleObserver.java b/src/main/java/io/reactivex/internal/observers/ResumeSingleObserver.java index 980b4335d9..1dc1c5fa29 100644 --- a/src/main/java/io/reactivex/internal/observers/ResumeSingleObserver.java +++ b/src/main/java/io/reactivex/internal/observers/ResumeSingleObserver.java @@ -29,11 +29,11 @@ public final class ResumeSingleObserver<T> implements SingleObserver<T> { final AtomicReference<Disposable> parent; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; - public ResumeSingleObserver(AtomicReference<Disposable> parent, SingleObserver<? super T> actual) { + public ResumeSingleObserver(AtomicReference<Disposable> parent, SingleObserver<? super T> downstream) { this.parent = parent; - this.actual = actual; + this.downstream = downstream; } @Override @@ -43,11 +43,11 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/observers/SubscriberCompletableObserver.java b/src/main/java/io/reactivex/internal/observers/SubscriberCompletableObserver.java index 425b7c5463..8a5255d937 100644 --- a/src/main/java/io/reactivex/internal/observers/SubscriberCompletableObserver.java +++ b/src/main/java/io/reactivex/internal/observers/SubscriberCompletableObserver.java @@ -22,7 +22,7 @@ public final class SubscriberCompletableObserver<T> implements CompletableObserver, Subscription { final Subscriber<? super T> subscriber; - Disposable d; + Disposable upstream; public SubscriberCompletableObserver(Subscriber<? super T> subscriber) { this.subscriber = subscriber; @@ -40,8 +40,8 @@ public void onError(Throwable e) { @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; subscriber.onSubscribe(this); } @@ -54,6 +54,6 @@ public void request(long n) { @Override public void cancel() { - d.dispose(); + upstream.dispose(); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java index 9a333d3dde..ef1cc3c65f 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableCache.java @@ -76,7 +76,7 @@ public void onError(Throwable e) { error = e; for (InnerCompletableCache inner : observers.getAndSet(TERMINATED)) { if (!inner.get()) { - inner.actual.onError(e); + inner.downstream.onError(e); } } } @@ -85,7 +85,7 @@ public void onError(Throwable e) { public void onComplete() { for (InnerCompletableCache inner : observers.getAndSet(TERMINATED)) { if (!inner.get()) { - inner.actual.onComplete(); + inner.downstream.onComplete(); } } } @@ -149,10 +149,10 @@ final class InnerCompletableCache private static final long serialVersionUID = 8943152917179642732L; - final CompletableObserver actual; + final CompletableObserver downstream; - InnerCompletableCache(CompletableObserver actual) { - this.actual = actual; + InnerCompletableCache(CompletableObserver downstream) { + this.downstream = downstream; } @Override diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcat.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcat.java index 055ae5086e..cf52bf9755 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcat.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcat.java @@ -45,7 +45,7 @@ static final class CompletableConcatSubscriber implements FlowableSubscriber<CompletableSource>, Disposable { private static final long serialVersionUID = 9032184911934499404L; - final CompletableObserver actual; + final CompletableObserver downstream; final int prefetch; @@ -61,14 +61,14 @@ static final class CompletableConcatSubscriber SimpleQueue<CompletableSource> queue; - Subscription s; + Subscription upstream; volatile boolean done; volatile boolean active; CompletableConcatSubscriber(CompletableObserver actual, int prefetch) { - this.actual = actual; + this.downstream = actual; this.prefetch = prefetch; this.inner = new ConcatInnerObserver(this); this.once = new AtomicBoolean(); @@ -77,8 +77,8 @@ static final class CompletableConcatSubscriber @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; long r = prefetch == Integer.MAX_VALUE ? Long.MAX_VALUE : prefetch; @@ -92,14 +92,14 @@ public void onSubscribe(Subscription s) { sourceFused = m; queue = qs; done = true; - actual.onSubscribe(this); + downstream.onSubscribe(this); drain(); return; } if (m == QueueSubscription.ASYNC) { sourceFused = m; queue = qs; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(r); return; } @@ -111,7 +111,7 @@ public void onSubscribe(Subscription s) { queue = new SpscArrayQueue<CompletableSource>(prefetch); } - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(r); } @@ -132,7 +132,7 @@ public void onNext(CompletableSource t) { public void onError(Throwable t) { if (once.compareAndSet(false, true)) { DisposableHelper.dispose(inner); - actual.onError(t); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -146,7 +146,7 @@ public void onComplete() { @Override public void dispose() { - s.cancel(); + upstream.cancel(); DisposableHelper.dispose(inner); } @@ -183,7 +183,7 @@ void drain() { if (d && empty) { if (once.compareAndSet(false, true)) { - actual.onComplete(); + downstream.onComplete(); } return; } @@ -206,7 +206,7 @@ void request() { int p = consumed + 1; if (p == limit) { consumed = 0; - s.request(p); + upstream.request(p); } else { consumed = p; } @@ -215,8 +215,8 @@ void request() { void innerError(Throwable e) { if (once.compareAndSet(false, true)) { - s.cancel(); - actual.onError(e); + upstream.cancel(); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java index f87f2a72ea..6bcf9d5516 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatArray.java @@ -37,7 +37,7 @@ static final class ConcatInnerObserver extends AtomicInteger implements Completa private static final long serialVersionUID = -7965400327305809232L; - final CompletableObserver actual; + final CompletableObserver downstream; final CompletableSource[] sources; int index; @@ -45,7 +45,7 @@ static final class ConcatInnerObserver extends AtomicInteger implements Completa final SequentialDisposable sd; ConcatInnerObserver(CompletableObserver actual, CompletableSource[] sources) { - this.actual = actual; + this.downstream = actual; this.sources = sources; this.sd = new SequentialDisposable(); } @@ -57,7 +57,7 @@ public void onSubscribe(Disposable d) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override @@ -82,7 +82,7 @@ void next() { int idx = index++; if (idx == a.length) { - actual.onComplete(); + downstream.onComplete(); return; } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java index 9ca4d919d8..acc2d12fd0 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableConcatIterable.java @@ -51,13 +51,13 @@ static final class ConcatInnerObserver extends AtomicInteger implements Completa private static final long serialVersionUID = -7965400327305809232L; - final CompletableObserver actual; + final CompletableObserver downstream; final Iterator<? extends CompletableSource> sources; final SequentialDisposable sd; ConcatInnerObserver(CompletableObserver actual, Iterator<? extends CompletableSource> sources) { - this.actual = actual; + this.downstream = actual; this.sources = sources; this.sd = new SequentialDisposable(); } @@ -69,7 +69,7 @@ public void onSubscribe(Disposable d) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override @@ -97,12 +97,12 @@ void next() { b = a.hasNext(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } if (!b) { - actual.onComplete(); + downstream.onComplete(); return; } @@ -112,7 +112,7 @@ void next() { c = ObjectHelper.requireNonNull(a.next(), "The CompletableSource returned is null"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java index c831d899ae..1e2bc74f79 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableCreate.java @@ -49,10 +49,10 @@ static final class Emitter private static final long serialVersionUID = -2467358622224974244L; - final CompletableObserver actual; + final CompletableObserver downstream; - Emitter(CompletableObserver actual) { - this.actual = actual; + Emitter(CompletableObserver downstream) { + this.downstream = downstream; } @Override @@ -61,7 +61,7 @@ public void onComplete() { Disposable d = getAndSet(DisposableHelper.DISPOSED); if (d != DisposableHelper.DISPOSED) { try { - actual.onComplete(); + downstream.onComplete(); } finally { if (d != null) { d.dispose(); @@ -87,7 +87,7 @@ public boolean tryOnError(Throwable t) { Disposable d = getAndSet(DisposableHelper.DISPOSED); if (d != DisposableHelper.DISPOSED) { try { - actual.onError(t); + downstream.onError(t); } finally { if (d != null) { d.dispose(); diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java index 14e74c0485..f19a0a045d 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java @@ -37,51 +37,51 @@ protected void subscribeActual(CompletableObserver observer) { static final class DetachCompletableObserver implements CompletableObserver, Disposable { - CompletableObserver actual; + CompletableObserver downstream; - Disposable d; + Disposable upstream; - DetachCompletableObserver(CompletableObserver actual) { - this.actual = actual; + DetachCompletableObserver(CompletableObserver downstream) { + this.downstream = downstream; } @Override public void dispose() { - actual = null; - d.dispose(); - d = DisposableHelper.DISPOSED; + downstream = null; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - CompletableObserver a = actual; + upstream = DisposableHelper.DISPOSED; + CompletableObserver a = downstream; if (a != null) { - actual = null; + downstream = null; a.onError(e); } } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; - CompletableObserver a = actual; + upstream = DisposableHelper.DISPOSED; + CompletableObserver a = downstream; if (a != null) { - actual = null; + downstream = null; a.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDisposeOn.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDisposeOn.java index df2cfa5e25..904894df7c 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDisposeOn.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDisposeOn.java @@ -31,19 +31,19 @@ public CompletableDisposeOn(CompletableSource source, Scheduler scheduler) { @Override protected void subscribeActual(final CompletableObserver observer) { - source.subscribe(new CompletableObserverImplementation(observer, scheduler)); + source.subscribe(new DisposeOnObserver(observer, scheduler)); } - static final class CompletableObserverImplementation implements CompletableObserver, Disposable, Runnable { + static final class DisposeOnObserver implements CompletableObserver, Disposable, Runnable { final CompletableObserver downstream; final Scheduler scheduler; - Disposable d; + Disposable upstream; volatile boolean disposed; - CompletableObserverImplementation(CompletableObserver observer, Scheduler scheduler) { + DisposeOnObserver(CompletableObserver observer, Scheduler scheduler) { this.downstream = observer; this.scheduler = scheduler; } @@ -67,8 +67,8 @@ public void onError(Throwable e) { @Override public void onSubscribe(final Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; downstream.onSubscribe(this); } @@ -87,8 +87,8 @@ public boolean isDisposed() { @Override public void run() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java index d74169d91c..67e4ad5da1 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableDoFinally.java @@ -47,47 +47,47 @@ static final class DoFinallyObserver extends AtomicInteger implements Completabl private static final long serialVersionUID = 4109457741734051389L; - final CompletableObserver actual; + final CompletableObserver downstream; final Action onFinally; - Disposable d; + Disposable upstream; DoFinallyObserver(CompletableObserver actual, Action onFinally) { - this.actual = actual; + this.downstream = actual; this.onFinally = onFinally; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); runFinally(); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); runFinally(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); runFinally(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } void runFinally() { diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromPublisher.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromPublisher.java index 4d0be70d35..3791931e92 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromPublisher.java @@ -28,26 +28,26 @@ public CompletableFromPublisher(Publisher<T> flowable) { } @Override - protected void subscribeActual(final CompletableObserver cs) { - flowable.subscribe(new FromPublisherSubscriber<T>(cs)); + protected void subscribeActual(final CompletableObserver downstream) { + flowable.subscribe(new FromPublisherSubscriber<T>(downstream)); } static final class FromPublisherSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final CompletableObserver cs; + final CompletableObserver downstream; - Subscription s; + Subscription upstream; - FromPublisherSubscriber(CompletableObserver actual) { - this.cs = actual; + FromPublisherSubscriber(CompletableObserver downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - cs.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -61,23 +61,23 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - cs.onError(t); + downstream.onError(t); } @Override public void onComplete() { - cs.onComplete(); + downstream.onComplete(); } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableHide.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableHide.java index a05e63cda7..0e1828dccb 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableHide.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableHide.java @@ -37,42 +37,42 @@ protected void subscribeActual(CompletableObserver observer) { static final class HideCompletableObserver implements CompletableObserver, Disposable { - final CompletableObserver actual; + final CompletableObserver downstream; - Disposable d; + Disposable upstream; - HideCompletableObserver(CompletableObserver actual) { - this.actual = actual; + HideCompletableObserver(CompletableObserver downstream) { + this.downstream = downstream; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableMerge.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableMerge.java index 890e036d74..a1dff5b342 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableMerge.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableMerge.java @@ -47,7 +47,7 @@ static final class CompletableMergeSubscriber private static final long serialVersionUID = -2108443387387077490L; - final CompletableObserver actual; + final CompletableObserver downstream; final int maxConcurrency; final boolean delayErrors; @@ -55,10 +55,10 @@ static final class CompletableMergeSubscriber final CompositeDisposable set; - Subscription s; + Subscription upstream; CompletableMergeSubscriber(CompletableObserver actual, int maxConcurrency, boolean delayErrors) { - this.actual = actual; + this.downstream = actual; this.maxConcurrency = maxConcurrency; this.delayErrors = delayErrors; this.set = new CompositeDisposable(); @@ -68,7 +68,7 @@ static final class CompletableMergeSubscriber @Override public void dispose() { - s.cancel(); + upstream.cancel(); set.dispose(); } @@ -79,9 +79,9 @@ public boolean isDisposed() { @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); if (maxConcurrency == Integer.MAX_VALUE) { s.request(Long.MAX_VALUE); } else { @@ -106,7 +106,7 @@ public void onError(Throwable t) { if (error.addThrowable(t)) { if (getAndSet(0) > 0) { - actual.onError(error.terminate()); + downstream.onError(error.terminate()); } } else { RxJavaPlugins.onError(t); @@ -114,7 +114,7 @@ public void onError(Throwable t) { } else { if (error.addThrowable(t)) { if (decrementAndGet() == 0) { - actual.onError(error.terminate()); + downstream.onError(error.terminate()); } } else { RxJavaPlugins.onError(t); @@ -127,9 +127,9 @@ public void onComplete() { if (decrementAndGet() == 0) { Throwable ex = error.get(); if (ex != null) { - actual.onError(error.terminate()); + downstream.onError(error.terminate()); } else { - actual.onComplete(); + downstream.onComplete(); } } } @@ -137,12 +137,12 @@ public void onComplete() { void innerError(MergeInnerObserver inner, Throwable t) { set.delete(inner); if (!delayErrors) { - s.cancel(); + upstream.cancel(); set.dispose(); if (error.addThrowable(t)) { if (getAndSet(0) > 0) { - actual.onError(error.terminate()); + downstream.onError(error.terminate()); } } else { RxJavaPlugins.onError(t); @@ -150,10 +150,10 @@ void innerError(MergeInnerObserver inner, Throwable t) { } else { if (error.addThrowable(t)) { if (decrementAndGet() == 0) { - actual.onError(error.terminate()); + downstream.onError(error.terminate()); } else { if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } } } else { @@ -167,13 +167,13 @@ void innerComplete(MergeInnerObserver inner) { if (decrementAndGet() == 0) { Throwable ex = error.get(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } } else { if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeArray.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeArray.java index 64a5b6e8a4..e6a42b105b 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeArray.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeArray.java @@ -55,14 +55,14 @@ public void subscribeActual(final CompletableObserver observer) { static final class InnerCompletableObserver extends AtomicInteger implements CompletableObserver { private static final long serialVersionUID = -8360547806504310570L; - final CompletableObserver actual; + final CompletableObserver downstream; final AtomicBoolean once; final CompositeDisposable set; InnerCompletableObserver(CompletableObserver actual, AtomicBoolean once, CompositeDisposable set, int n) { - this.actual = actual; + this.downstream = actual; this.once = once; this.set = set; this.lazySet(n); @@ -77,7 +77,7 @@ public void onSubscribe(Disposable d) { public void onError(Throwable e) { set.dispose(); if (once.compareAndSet(false, true)) { - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -87,7 +87,7 @@ public void onError(Throwable e) { public void onComplete() { if (decrementAndGet() == 0) { if (once.compareAndSet(false, true)) { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorArray.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorArray.java index 733fa88b40..c2508a46dd 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorArray.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeDelayErrorArray.java @@ -64,14 +64,14 @@ public void subscribeActual(final CompletableObserver observer) { static final class MergeInnerCompletableObserver implements CompletableObserver { - final CompletableObserver actual; + final CompletableObserver downstream; final CompositeDisposable set; final AtomicThrowable error; final AtomicInteger wip; MergeInnerCompletableObserver(CompletableObserver observer, CompositeDisposable set, AtomicThrowable error, AtomicInteger wip) { - this.actual = observer; + this.downstream = observer; this.set = set; this.error = error; this.wip = wip; @@ -100,9 +100,9 @@ void tryTerminate() { if (wip.decrementAndGet() == 0) { Throwable ex = error.terminate(); if (ex == null) { - actual.onComplete(); + downstream.onComplete(); } else { - actual.onError(ex); + downstream.onError(ex); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeIterable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeIterable.java index 6c22819e19..0130250225 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeIterable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableMergeIterable.java @@ -100,12 +100,12 @@ static final class MergeCompletableObserver extends AtomicBoolean implements Com final CompositeDisposable set; - final CompletableObserver actual; + final CompletableObserver downstream; final AtomicInteger wip; MergeCompletableObserver(CompletableObserver actual, CompositeDisposable set, AtomicInteger wip) { - this.actual = actual; + this.downstream = actual; this.set = set; this.wip = wip; } @@ -119,7 +119,7 @@ public void onSubscribe(Disposable d) { public void onError(Throwable e) { set.dispose(); if (compareAndSet(false, true)) { - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -129,7 +129,7 @@ public void onError(Throwable e) { public void onComplete() { if (wip.decrementAndGet() == 0) { if (compareAndSet(false, true)) { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java index 73c86873da..11dbebe280 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java @@ -41,14 +41,14 @@ static final class ObserveOnCompletableObserver private static final long serialVersionUID = 8571289934935992137L; - final CompletableObserver actual; + final CompletableObserver downstream; final Scheduler scheduler; Throwable error; ObserveOnCompletableObserver(CompletableObserver actual, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.scheduler = scheduler; } @@ -65,7 +65,7 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -85,9 +85,9 @@ public void run() { Throwable ex = error; if (ex != null) { error = null; - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java b/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java index 6584131483..327cee0116 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java @@ -53,12 +53,12 @@ protected void subscribeActual(final CompletableObserver observer) { final class CompletableObserverImplementation implements CompletableObserver, Disposable { - final CompletableObserver actual; + final CompletableObserver downstream; - Disposable d; + Disposable upstream; - CompletableObserverImplementation(CompletableObserver actual) { - this.actual = actual; + CompletableObserverImplementation(CompletableObserver downstream) { + this.downstream = downstream; } @@ -69,19 +69,19 @@ public void onSubscribe(final Disposable d) { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); d.dispose(); - this.d = DisposableHelper.DISPOSED; - EmptyDisposable.error(ex, actual); + this.upstream = DisposableHelper.DISPOSED; + EmptyDisposable.error(ex, downstream); return; } - if (DisposableHelper.validate(this.d, d)) { - this.d = d; - actual.onSubscribe(this); + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void onError(Throwable e) { - if (d == DisposableHelper.DISPOSED) { + if (upstream == DisposableHelper.DISPOSED) { RxJavaPlugins.onError(e); return; } @@ -93,14 +93,14 @@ public void onError(Throwable e) { e = new CompositeException(e, ex); } - actual.onError(e); + downstream.onError(e); doAfter(); } @Override public void onComplete() { - if (d == DisposableHelper.DISPOSED) { + if (upstream == DisposableHelper.DISPOSED) { return; } @@ -109,11 +109,11 @@ public void onComplete() { onTerminate.run(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } - actual.onComplete(); + downstream.onComplete(); doAfter(); } @@ -135,12 +135,12 @@ public void dispose() { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(e); } - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableSubscribeOn.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableSubscribeOn.java index d386009f22..3b2b394694 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableSubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableSubscribeOn.java @@ -47,14 +47,14 @@ static final class SubscribeOnObserver private static final long serialVersionUID = 7000911171163930287L; - final CompletableObserver actual; + final CompletableObserver downstream; final SequentialDisposable task; final CompletableSource source; SubscribeOnObserver(CompletableObserver actual, CompletableSource source) { - this.actual = actual; + this.downstream = actual; this.source = source; this.task = new SequentialDisposable(); } @@ -71,12 +71,12 @@ public void onSubscribe(Disposable d) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableTimer.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableTimer.java index 5b85346629..4f1eae40c4 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableTimer.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableTimer.java @@ -45,15 +45,15 @@ protected void subscribeActual(final CompletableObserver observer) { static final class TimerDisposable extends AtomicReference<Disposable> implements Disposable, Runnable { private static final long serialVersionUID = 3167244060586201109L; - final CompletableObserver actual; + final CompletableObserver downstream; - TimerDisposable(final CompletableObserver actual) { - this.actual = actual; + TimerDisposable(final CompletableObserver downstream) { + this.downstream = downstream; } @Override public void run() { - actual.onComplete(); + downstream.onComplete(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java index 88f8a57516..a114199a91 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java @@ -92,25 +92,25 @@ static final class UsingObserver<R> private static final long serialVersionUID = -674404550052917487L; - final CompletableObserver actual; + final CompletableObserver downstream; final Consumer<? super R> disposer; final boolean eager; - Disposable d; + Disposable upstream; UsingObserver(CompletableObserver actual, R resource, Consumer<? super R> disposer, boolean eager) { super(resource); - this.actual = actual; + this.downstream = actual; this.disposer = disposer; this.eager = eager; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; disposeResourceAfter(); } @@ -129,22 +129,22 @@ void disposeResourceAfter() { @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @SuppressWarnings("unchecked") @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; if (eager) { Object resource = getAndSet(this); if (resource != this) { @@ -159,7 +159,7 @@ public void onError(Throwable e) { } } - actual.onError(e); + downstream.onError(e); if (!eager) { disposeResourceAfter(); @@ -169,7 +169,7 @@ public void onError(Throwable e) { @SuppressWarnings("unchecked") @Override public void onComplete() { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; if (eager) { Object resource = getAndSet(this); if (resource != this) { @@ -177,7 +177,7 @@ public void onComplete() { disposer.accept((R)resource); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } } else { @@ -185,7 +185,7 @@ public void onComplete() { } } - actual.onComplete(); + downstream.onComplete(); if (!eager) { disposeResourceAfter(); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAll.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAll.java index 6d7faa61dd..b3f6076f43 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAll.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAll.java @@ -39,7 +39,7 @@ static final class AllSubscriber<T> extends DeferredScalarSubscription<Boolean> private static final long serialVersionUID = -3521127104134758517L; final Predicate<? super T> predicate; - Subscription s; + Subscription upstream; boolean done; @@ -49,9 +49,9 @@ static final class AllSubscriber<T> extends DeferredScalarSubscription<Boolean> } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -66,13 +66,13 @@ public void onNext(T t) { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); onError(e); return; } if (!b) { done = true; - s.cancel(); + upstream.cancel(); complete(false); } } @@ -84,7 +84,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -100,7 +100,7 @@ public void onComplete() { @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java index c3bbc19481..b26087b840 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java @@ -45,23 +45,23 @@ public Flowable<Boolean> fuseToFlowable() { static final class AllSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final SingleObserver<? super Boolean> actual; + final SingleObserver<? super Boolean> downstream; final Predicate<? super T> predicate; - Subscription s; + Subscription upstream; boolean done; AllSubscriber(SingleObserver<? super Boolean> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -76,16 +76,16 @@ public void onNext(T t) { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; onError(e); return; } if (!b) { done = true; - s.cancel(); - s = SubscriptionHelper.CANCELLED; - actual.onSuccess(false); + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; + downstream.onSuccess(false); } } @@ -96,8 +96,8 @@ public void onError(Throwable t) { return; } done = true; - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override @@ -106,20 +106,20 @@ public void onComplete() { return; } done = true; - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; - actual.onSuccess(true); + downstream.onSuccess(true); } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAmb.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAmb.java index 1e14453afa..203c62f999 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAmb.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAmb.java @@ -74,14 +74,14 @@ public void subscribeActual(Subscriber<? super T> s) { } static final class AmbCoordinator<T> implements Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final AmbInnerSubscriber<T>[] subscribers; final AtomicInteger winner = new AtomicInteger(); @SuppressWarnings("unchecked") AmbCoordinator(Subscriber<? super T> actual, int count) { - this.actual = actual; + this.downstream = actual; this.subscribers = new AmbInnerSubscriber[count]; } @@ -89,10 +89,10 @@ public void subscribe(Publisher<? extends T>[] sources) { AmbInnerSubscriber<T>[] as = subscribers; int len = as.length; for (int i = 0; i < len; i++) { - as[i] = new AmbInnerSubscriber<T>(this, i + 1, actual); + as[i] = new AmbInnerSubscriber<T>(this, i + 1, downstream); } winner.lazySet(0); // release the contents of 'as' - actual.onSubscribe(this); + downstream.onSubscribe(this); for (int i = 0; i < len; i++) { if (winner.get() != 0) { @@ -152,16 +152,16 @@ static final class AmbInnerSubscriber<T> extends AtomicReference<Subscription> i private static final long serialVersionUID = -1185974347409665484L; final AmbCoordinator<T> parent; final int index; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; boolean won; final AtomicLong missedRequested = new AtomicLong(); - AmbInnerSubscriber(AmbCoordinator<T> parent, int index, Subscriber<? super T> actual) { + AmbInnerSubscriber(AmbCoordinator<T> parent, int index, Subscriber<? super T> downstream) { this.parent = parent; this.index = index; - this.actual = actual; + this.downstream = downstream; } @Override @@ -177,11 +177,11 @@ public void request(long n) { @Override public void onNext(T t) { if (won) { - actual.onNext(t); + downstream.onNext(t); } else { if (parent.win(index)) { won = true; - actual.onNext(t); + downstream.onNext(t); } else { get().cancel(); } @@ -191,11 +191,11 @@ public void onNext(T t) { @Override public void onError(Throwable t) { if (won) { - actual.onError(t); + downstream.onError(t); } else { if (parent.win(index)) { won = true; - actual.onError(t); + downstream.onError(t); } else { get().cancel(); RxJavaPlugins.onError(t); @@ -206,11 +206,11 @@ public void onError(Throwable t) { @Override public void onComplete() { if (won) { - actual.onComplete(); + downstream.onComplete(); } else { if (parent.win(index)) { won = true; - actual.onComplete(); + downstream.onComplete(); } else { get().cancel(); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAny.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAny.java index 39ed01534a..5a3d7c966f 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAny.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAny.java @@ -38,7 +38,7 @@ static final class AnySubscriber<T> extends DeferredScalarSubscription<Boolean> final Predicate<? super T> predicate; - Subscription s; + Subscription upstream; boolean done; @@ -48,9 +48,9 @@ static final class AnySubscriber<T> extends DeferredScalarSubscription<Boolean> } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -65,13 +65,13 @@ public void onNext(T t) { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); onError(e); return; } if (b) { done = true; - s.cancel(); + upstream.cancel(); complete(true); } } @@ -84,7 +84,7 @@ public void onError(Throwable t) { } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -98,7 +98,7 @@ public void onComplete() { @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java index 47f2ce4ef2..7c665f2ab9 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java @@ -44,23 +44,23 @@ public Flowable<Boolean> fuseToFlowable() { static final class AnySubscriber<T> implements FlowableSubscriber<T>, Disposable { - final SingleObserver<? super Boolean> actual; + final SingleObserver<? super Boolean> downstream; final Predicate<? super T> predicate; - Subscription s; + Subscription upstream; boolean done; AnySubscriber(SingleObserver<? super Boolean> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -75,16 +75,16 @@ public void onNext(T t) { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; onError(e); return; } if (b) { done = true; - s.cancel(); - s = SubscriptionHelper.CANCELLED; - actual.onSuccess(true); + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; + downstream.onSuccess(true); } } @@ -96,28 +96,28 @@ public void onError(Throwable t) { } done = true; - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override public void onComplete() { if (!done) { done = true; - s = SubscriptionHelper.CANCELLED; - actual.onSuccess(false); + upstream = SubscriptionHelper.CANCELLED; + downstream.onSuccess(false); } } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBuffer.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBuffer.java index 87b0d7331e..bf0cda25b1 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBuffer.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBuffer.java @@ -55,7 +55,7 @@ public void subscribeActual(Subscriber<? super C> s) { static final class PublisherBufferExactSubscriber<T, C extends Collection<? super T>> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super C> actual; + final Subscriber<? super C> downstream; final Callable<C> bufferSupplier; @@ -63,14 +63,14 @@ static final class PublisherBufferExactSubscriber<T, C extends Collection<? supe C buffer; - Subscription s; + Subscription upstream; boolean done; int index; PublisherBufferExactSubscriber(Subscriber<? super C> actual, int size, Callable<C> bufferSupplier) { - this.actual = actual; + this.downstream = actual; this.size = size; this.bufferSupplier = bufferSupplier; } @@ -78,21 +78,21 @@ static final class PublisherBufferExactSubscriber<T, C extends Collection<? supe @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { - s.request(BackpressureHelper.multiplyCap(n, size)); + upstream.request(BackpressureHelper.multiplyCap(n, size)); } } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -123,7 +123,7 @@ public void onNext(T t) { if (i == size) { index = 0; buffer = null; - actual.onNext(b); + downstream.onNext(b); } else { index = i; } @@ -136,7 +136,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -149,9 +149,9 @@ public void onComplete() { C b = buffer; if (b != null && !b.isEmpty()) { - actual.onNext(b); + downstream.onNext(b); } - actual.onComplete(); + downstream.onComplete(); } } @@ -162,7 +162,7 @@ static final class PublisherBufferSkipSubscriber<T, C extends Collection<? super private static final long serialVersionUID = -5616169793639412593L; - final Subscriber<? super C> actual; + final Subscriber<? super C> downstream; final Callable<C> bufferSupplier; @@ -172,7 +172,7 @@ static final class PublisherBufferSkipSubscriber<T, C extends Collection<? super C buffer; - Subscription s; + Subscription upstream; boolean done; @@ -180,7 +180,7 @@ static final class PublisherBufferSkipSubscriber<T, C extends Collection<? super PublisherBufferSkipSubscriber(Subscriber<? super C> actual, int size, int skip, Callable<C> bufferSupplier) { - this.actual = actual; + this.downstream = actual; this.size = size; this.skip = skip; this.bufferSupplier = bufferSupplier; @@ -195,25 +195,25 @@ public void request(long n) { // + (n - 1) gaps long v = BackpressureHelper.multiplyCap(skip - size, n - 1); - s.request(BackpressureHelper.addCap(u, v)); + upstream.request(BackpressureHelper.addCap(u, v)); } else { // n full buffer + gap - s.request(BackpressureHelper.multiplyCap(skip, n)); + upstream.request(BackpressureHelper.multiplyCap(skip, n)); } } } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -245,7 +245,7 @@ public void onNext(T t) { b.add(t); if (b.size() == size) { buffer = null; - actual.onNext(b); + downstream.onNext(b); } } @@ -265,7 +265,7 @@ public void onError(Throwable t) { done = true; buffer = null; - actual.onError(t); + downstream.onError(t); } @Override @@ -279,10 +279,10 @@ public void onComplete() { buffer = null; if (b != null) { - actual.onNext(b); + downstream.onNext(b); } - actual.onComplete(); + downstream.onComplete(); } } @@ -293,7 +293,7 @@ static final class PublisherBufferOverlappingSubscriber<T, C extends Collection< private static final long serialVersionUID = -7370244972039324525L; - final Subscriber<? super C> actual; + final Subscriber<? super C> downstream; final Callable<C> bufferSupplier; @@ -305,7 +305,7 @@ static final class PublisherBufferOverlappingSubscriber<T, C extends Collection< final AtomicBoolean once; - Subscription s; + Subscription upstream; boolean done; @@ -317,7 +317,7 @@ static final class PublisherBufferOverlappingSubscriber<T, C extends Collection< PublisherBufferOverlappingSubscriber(Subscriber<? super C> actual, int size, int skip, Callable<C> bufferSupplier) { - this.actual = actual; + this.downstream = actual; this.size = size; this.skip = skip; this.bufferSupplier = bufferSupplier; @@ -333,7 +333,7 @@ public boolean getAsBoolean() { @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { - if (QueueDrainHelper.postCompleteRequest(n, actual, buffers, this, this)) { + if (QueueDrainHelper.postCompleteRequest(n, downstream, buffers, this, this)) { return; } @@ -343,11 +343,11 @@ public void request(long n) { // + 1 full buffer long r = BackpressureHelper.addCap(size, u); - s.request(r); + upstream.request(r); } else { // n skips long r = BackpressureHelper.multiplyCap(skip, n); - s.request(r); + upstream.request(r); } } } @@ -355,15 +355,15 @@ public void request(long n) { @Override public void cancel() { cancelled = true; - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -401,7 +401,7 @@ public void onNext(T t) { produced++; - actual.onNext(b); + downstream.onNext(b); } for (C b0 : bs) { @@ -424,7 +424,7 @@ public void onError(Throwable t) { done = true; buffers.clear(); - actual.onError(t); + downstream.onError(t); } @Override @@ -439,7 +439,7 @@ public void onComplete() { if (p != 0L) { BackpressureHelper.produced(this, p); } - QueueDrainHelper.postComplete(actual, buffers, this, this); + QueueDrainHelper.postComplete(downstream, buffers, this, this); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java index 317ad249ee..44146a5829 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java @@ -58,7 +58,7 @@ static final class BufferBoundarySubscriber<T, C extends Collection<? super T>, private static final long serialVersionUID = -8466418554264089604L; - final Subscriber<? super C> actual; + final Subscriber<? super C> downstream; final Callable<C> bufferSupplier; @@ -91,7 +91,7 @@ static final class BufferBoundarySubscriber<T, C extends Collection<? super T>, Function<? super Open, ? extends Publisher<? extends Close>> bufferClose, Callable<C> bufferSupplier ) { - this.actual = actual; + this.downstream = actual; this.bufferSupplier = bufferSupplier; this.bufferOpen = bufferOpen; this.bufferClose = bufferClose; @@ -250,7 +250,7 @@ void drain() { int missed = 1; long e = emitted; - Subscriber<? super C> a = actual; + Subscriber<? super C> a = downstream; SpscLinkedArrayQueue<C> q = queue; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundarySupplier.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundarySupplier.java index a4cdcb8ced..8c544d958d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundarySupplier.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundarySupplier.java @@ -53,7 +53,7 @@ static final class BufferBoundarySupplierSubscriber<T, U extends Collection<? su final Callable<U> bufferSupplier; final Callable<? extends Publisher<B>> boundarySupplier; - Subscription s; + Subscription upstream; final AtomicReference<Disposable> other = new AtomicReference<Disposable>(); @@ -68,12 +68,12 @@ static final class BufferBoundarySupplierSubscriber<T, U extends Collection<? su @Override public void onSubscribe(Subscription s) { - if (!SubscriptionHelper.validate(this.s, s)) { + if (!SubscriptionHelper.validate(this.upstream, s)) { return; } - this.s = s; + this.upstream = s; - Subscriber<? super U> actual = this.actual; + Subscriber<? super U> actual = this.downstream; U b; @@ -127,7 +127,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { cancel(); - actual.onError(t); + downstream.onError(t); } @Override @@ -143,7 +143,7 @@ public void onComplete() { queue.offer(b); done = true; if (enter()) { - QueueDrainHelper.drainMaxLoop(queue, actual, false, this, this); + QueueDrainHelper.drainMaxLoop(queue, downstream, false, this, this); } } @@ -156,7 +156,7 @@ public void request(long n) { public void cancel() { if (!cancelled) { cancelled = true; - s.cancel(); + upstream.cancel(); disposeOther(); if (enter()) { @@ -178,7 +178,7 @@ void next() { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancel(); - actual.onError(e); + downstream.onError(e); return; } @@ -189,8 +189,8 @@ void next() { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); cancelled = true; - s.cancel(); - actual.onError(ex); + upstream.cancel(); + downstream.onError(ex); return; } @@ -214,7 +214,7 @@ void next() { @Override public void dispose() { - s.cancel(); + upstream.cancel(); disposeOther(); } @@ -225,7 +225,7 @@ public boolean isDisposed() { @Override public boolean accept(Subscriber<? super U> a, U v) { - actual.onNext(v); + downstream.onNext(v); return true; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferExactBoundary.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferExactBoundary.java index 5ed7f84b08..82215ae967 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferExactBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferExactBoundary.java @@ -50,7 +50,7 @@ static final class BufferExactBoundarySubscriber<T, U extends Collection<? super final Callable<U> bufferSupplier; final Publisher<B> boundary; - Subscription s; + Subscription upstream; Disposable other; @@ -65,10 +65,10 @@ static final class BufferExactBoundarySubscriber<T, U extends Collection<? super @Override public void onSubscribe(Subscription s) { - if (!SubscriptionHelper.validate(this.s, s)) { + if (!SubscriptionHelper.validate(this.upstream, s)) { return; } - this.s = s; + this.upstream = s; U b; @@ -78,7 +78,7 @@ public void onSubscribe(Subscription s) { Exceptions.throwIfFatal(e); cancelled = true; s.cancel(); - EmptySubscription.error(e, actual); + EmptySubscription.error(e, downstream); return; } @@ -87,7 +87,7 @@ public void onSubscribe(Subscription s) { BufferBoundarySubscriber<T, U, B> bs = new BufferBoundarySubscriber<T, U, B>(this); other = bs; - actual.onSubscribe(this); + downstream.onSubscribe(this); if (!cancelled) { s.request(Long.MAX_VALUE); @@ -110,7 +110,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { cancel(); - actual.onError(t); + downstream.onError(t); } @Override @@ -126,7 +126,7 @@ public void onComplete() { queue.offer(b); done = true; if (enter()) { - QueueDrainHelper.drainMaxLoop(queue, actual, false, this, this); + QueueDrainHelper.drainMaxLoop(queue, downstream, false, this, this); } } @@ -140,7 +140,7 @@ public void cancel() { if (!cancelled) { cancelled = true; other.dispose(); - s.cancel(); + upstream.cancel(); if (enter()) { queue.clear(); @@ -157,7 +157,7 @@ void next() { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancel(); - actual.onError(e); + downstream.onError(e); return; } @@ -185,7 +185,7 @@ public boolean isDisposed() { @Override public boolean accept(Subscriber<? super U> a, U v) { - actual.onNext(v); + downstream.onNext(v); return true; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java index 8c220a506a..0fb2b19e6a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java @@ -86,7 +86,7 @@ static final class BufferExactUnboundedSubscriber<T, U extends Collection<? supe final TimeUnit unit; final Scheduler scheduler; - Subscription s; + Subscription upstream; U buffer; @@ -104,8 +104,8 @@ static final class BufferExactUnboundedSubscriber<T, U extends Collection<? supe @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; U b; @@ -114,13 +114,13 @@ public void onSubscribe(Subscription s) { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancel(); - EmptySubscription.error(e, actual); + EmptySubscription.error(e, downstream); return; } buffer = b; - actual.onSubscribe(this); + downstream.onSubscribe(this); if (!cancelled) { s.request(Long.MAX_VALUE); @@ -149,7 +149,7 @@ public void onError(Throwable t) { synchronized (this) { buffer = null; } - actual.onError(t); + downstream.onError(t); } @Override @@ -166,7 +166,7 @@ public void onComplete() { queue.offer(b); done = true; if (enter()) { - QueueDrainHelper.drainMaxLoop(queue, actual, false, null, this); + QueueDrainHelper.drainMaxLoop(queue, downstream, false, null, this); } } @@ -178,7 +178,7 @@ public void request(long n) { @Override public void cancel() { cancelled = true; - s.cancel(); + upstream.cancel(); DisposableHelper.dispose(timer); } @@ -191,7 +191,7 @@ public void run() { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancel(); - actual.onError(e); + downstream.onError(e); return; } @@ -210,7 +210,7 @@ public void run() { @Override public boolean accept(Subscriber<? super U> a, U v) { - actual.onNext(v); + downstream.onNext(v); return true; } @@ -234,7 +234,7 @@ static final class BufferSkipBoundedSubscriber<T, U extends Collection<? super T final Worker w; final List<U> buffers; - Subscription s; + Subscription upstream; BufferSkipBoundedSubscriber(Subscriber<? super U> actual, @@ -251,10 +251,10 @@ static final class BufferSkipBoundedSubscriber<T, U extends Collection<? super T @Override public void onSubscribe(Subscription s) { - if (!SubscriptionHelper.validate(this.s, s)) { + if (!SubscriptionHelper.validate(this.upstream, s)) { return; } - this.s = s; + this.upstream = s; final U b; // NOPMD @@ -264,13 +264,13 @@ public void onSubscribe(Subscription s) { Exceptions.throwIfFatal(e); w.dispose(); s.cancel(); - EmptySubscription.error(e, actual); + EmptySubscription.error(e, downstream); return; } buffers.add(b); - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); @@ -293,7 +293,7 @@ public void onError(Throwable t) { done = true; w.dispose(); clear(); - actual.onError(t); + downstream.onError(t); } @Override @@ -309,7 +309,7 @@ public void onComplete() { } done = true; if (enter()) { - QueueDrainHelper.drainMaxLoop(queue, actual, false, w, this); + QueueDrainHelper.drainMaxLoop(queue, downstream, false, w, this); } } @@ -321,7 +321,7 @@ public void request(long n) { @Override public void cancel() { cancelled = true; - s.cancel(); + upstream.cancel(); w.dispose(); clear(); } @@ -344,7 +344,7 @@ public void run() { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancel(); - actual.onError(e); + downstream.onError(e); return; } @@ -395,7 +395,7 @@ static final class BufferExactBoundedSubscriber<T, U extends Collection<? super Disposable timer; - Subscription s; + Subscription upstream; long producerIndex; @@ -417,10 +417,10 @@ static final class BufferExactBoundedSubscriber<T, U extends Collection<? super @Override public void onSubscribe(Subscription s) { - if (!SubscriptionHelper.validate(this.s, s)) { + if (!SubscriptionHelper.validate(this.upstream, s)) { return; } - this.s = s; + this.upstream = s; U b; @@ -430,13 +430,13 @@ public void onSubscribe(Subscription s) { Exceptions.throwIfFatal(e); w.dispose(); s.cancel(); - EmptySubscription.error(e, actual); + EmptySubscription.error(e, downstream); return; } buffer = b; - actual.onSubscribe(this); + downstream.onSubscribe(this); timer = w.schedulePeriodically(this, timespan, timespan, unit); @@ -473,7 +473,7 @@ public void onNext(T t) { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancel(); - actual.onError(e); + downstream.onError(e); return; } @@ -491,7 +491,7 @@ public void onError(Throwable t) { synchronized (this) { buffer = null; } - actual.onError(t); + downstream.onError(t); w.dispose(); } @@ -506,7 +506,7 @@ public void onComplete() { queue.offer(b); done = true; if (enter()) { - QueueDrainHelper.drainMaxLoop(queue, actual, false, this, this); + QueueDrainHelper.drainMaxLoop(queue, downstream, false, this, this); } w.dispose(); @@ -537,7 +537,7 @@ public void dispose() { synchronized (this) { buffer = null; } - s.cancel(); + upstream.cancel(); w.dispose(); } @@ -555,7 +555,7 @@ public void run() { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancel(); - actual.onError(e); + downstream.onError(e); return; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollect.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollect.java index 750a3a5d30..ff858505a0 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollect.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollect.java @@ -55,7 +55,7 @@ static final class CollectSubscriber<T, U> extends DeferredScalarSubscription<U> final U u; - Subscription s; + Subscription upstream; boolean done; @@ -67,9 +67,9 @@ static final class CollectSubscriber<T, U> extends DeferredScalarSubscription<U> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -83,7 +83,7 @@ public void onNext(T t) { collector.accept(u, t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); onError(e); } } @@ -95,7 +95,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -110,7 +110,7 @@ public void onComplete() { @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollectSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollectSingle.java index cda031ebbc..c5d3dc188d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollectSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCollectSingle.java @@ -59,27 +59,27 @@ public Flowable<U> fuseToFlowable() { static final class CollectSubscriber<T, U> implements FlowableSubscriber<T>, Disposable { - final SingleObserver<? super U> actual; + final SingleObserver<? super U> downstream; final BiConsumer<? super U, ? super T> collector; final U u; - Subscription s; + Subscription upstream; boolean done; CollectSubscriber(SingleObserver<? super U> actual, U u, BiConsumer<? super U, ? super T> collector) { - this.actual = actual; + this.downstream = actual; this.collector = collector; this.u = u; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -93,7 +93,7 @@ public void onNext(T t) { collector.accept(u, t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); onError(e); } } @@ -105,8 +105,8 @@ public void onError(Throwable t) { return; } done = true; - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override @@ -115,19 +115,19 @@ public void onComplete() { return; } done = true; - s = SubscriptionHelper.CANCELLED; - actual.onSuccess(u); + upstream = SubscriptionHelper.CANCELLED; + downstream.onSuccess(u); } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java index 6ed1f116ef..a4bc8f6bc4 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java @@ -151,7 +151,7 @@ static final class CombineLatestCoordinator<T, R> private static final long serialVersionUID = -5082275438355852221L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final Function<? super Object[], ? extends R> combiner; @@ -180,7 +180,7 @@ static final class CombineLatestCoordinator<T, R> CombineLatestCoordinator(Subscriber<? super R> actual, Function<? super Object[], ? extends R> combiner, int n, int bufferSize, boolean delayErrors) { - this.actual = actual; + this.downstream = actual; this.combiner = combiner; @SuppressWarnings("unchecked") CombineLatestInnerSubscriber<T>[] a = new CombineLatestInnerSubscriber[n]; @@ -289,7 +289,7 @@ void innerError(int index, Throwable e) { } void drainOutput() { - final Subscriber<? super R> a = actual; + final Subscriber<? super R> a = downstream; final SpscLinkedArrayQueue<Object> q = queue; int missed = 1; @@ -331,7 +331,7 @@ void drainOutput() { @SuppressWarnings("unchecked") void drainAsync() { - final Subscriber<? super R> a = actual; + final Subscriber<? super R> a = downstream; final SpscLinkedArrayQueue<Object> q = queue; int missed = 1; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatArray.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatArray.java index c2ca5de3b3..c06cffa80a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatArray.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatArray.java @@ -44,7 +44,7 @@ static final class ConcatArraySubscriber<T> extends SubscriptionArbiter implemen private static final long serialVersionUID = -8158322871608889516L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Publisher<? extends T>[] sources; @@ -58,8 +58,8 @@ static final class ConcatArraySubscriber<T> extends SubscriptionArbiter implemen long produced; - ConcatArraySubscriber(Publisher<? extends T>[] sources, boolean delayError, Subscriber<? super T> actual) { - this.actual = actual; + ConcatArraySubscriber(Publisher<? extends T>[] sources, boolean delayError, Subscriber<? super T> downstream) { + this.downstream = downstream; this.sources = sources; this.delayError = delayError; this.wip = new AtomicInteger(); @@ -73,7 +73,7 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { produced++; - actual.onNext(t); + downstream.onNext(t); } @Override @@ -87,7 +87,7 @@ public void onError(Throwable t) { list.add(t); onComplete(); } else { - actual.onError(t); + downstream.onError(t); } } @@ -103,12 +103,12 @@ public void onComplete() { List<Throwable> list = errors; if (list != null) { if (list.size() == 1) { - actual.onError(list.get(0)); + downstream.onError(list.get(0)); } else { - actual.onError(new CompositeException(list)); + downstream.onError(new CompositeException(list)); } } else { - actual.onComplete(); + downstream.onComplete(); } return; } @@ -127,7 +127,7 @@ public void onComplete() { i++; continue; } else { - actual.onError(ex); + downstream.onError(ex); return; } } else { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java index 6aee2f7c80..27016a1dd8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java @@ -80,7 +80,7 @@ abstract static class BaseConcatMapSubscriber<T, R> final int limit; - Subscription s; + Subscription upstream; int consumed; @@ -108,8 +108,8 @@ abstract static class BaseConcatMapSubscriber<T, R> @Override public final void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; if (s instanceof QueueSubscription) { @SuppressWarnings("unchecked") QueueSubscription<T> f = (QueueSubscription<T>)s; @@ -151,7 +151,7 @@ public final void onSubscribe(Subscription s) { public final void onNext(T t) { if (sourceMode != QueueSubscription.ASYNC) { if (!queue.offer(t)) { - s.cancel(); + upstream.cancel(); onError(new IllegalStateException("Queue full?!")); return; } @@ -180,7 +180,7 @@ static final class ConcatMapImmediate<T, R> private static final long serialVersionUID = 7898995095634264146L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final AtomicInteger wip; @@ -188,13 +188,13 @@ static final class ConcatMapImmediate<T, R> Function<? super T, ? extends Publisher<? extends R>> mapper, int prefetch) { super(mapper, prefetch); - this.actual = actual; + this.downstream = actual; this.wip = new AtomicInteger(); } @Override void subscribeActual() { - actual.onSubscribe(this); + downstream.onSubscribe(this); } @Override @@ -203,7 +203,7 @@ public void onError(Throwable t) { inner.cancel(); if (getAndIncrement() == 0) { - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); } } else { RxJavaPlugins.onError(t); @@ -213,21 +213,21 @@ public void onError(Throwable t) { @Override public void innerNext(R value) { if (get() == 0 && compareAndSet(0, 1)) { - actual.onNext(value); + downstream.onNext(value); if (compareAndSet(1, 0)) { return; } - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); } } @Override public void innerError(Throwable e) { if (errors.addThrowable(e)) { - s.cancel(); + upstream.cancel(); if (getAndIncrement() == 0) { - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); } } else { RxJavaPlugins.onError(e); @@ -245,7 +245,7 @@ public void cancel() { cancelled = true; inner.cancel(); - s.cancel(); + upstream.cancel(); } } @@ -266,16 +266,16 @@ void drain() { v = queue.poll(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); errors.addThrowable(e); - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); return; } boolean empty = v == null; if (d && empty) { - actual.onComplete(); + downstream.onComplete(); return; } @@ -287,9 +287,9 @@ void drain() { } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); errors.addThrowable(e); - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); return; } @@ -297,7 +297,7 @@ void drain() { int c = consumed + 1; if (c == limit) { consumed = 0; - s.request(c); + upstream.request(c); } else { consumed = c; } @@ -314,9 +314,9 @@ void drain() { vr = callable.call(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); errors.addThrowable(e); - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); return; } @@ -327,9 +327,9 @@ void drain() { if (inner.isUnbounded()) { if (get() == 0 && compareAndSet(0, 1)) { - actual.onNext(vr); + downstream.onNext(vr); if (!compareAndSet(1, 0)) { - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); return; } } @@ -354,20 +354,20 @@ void drain() { } static final class WeakScalarSubscription<T> implements Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final T value; boolean once; - WeakScalarSubscription(T value, Subscriber<? super T> actual) { + WeakScalarSubscription(T value, Subscriber<? super T> downstream) { this.value = value; - this.actual = actual; + this.downstream = downstream; } @Override public void request(long n) { if (n > 0 && !once) { once = true; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; a.onNext(value); a.onComplete(); } @@ -385,7 +385,7 @@ static final class ConcatMapDelayed<T, R> private static final long serialVersionUID = -2945777694260521066L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final boolean veryEnd; @@ -393,13 +393,13 @@ static final class ConcatMapDelayed<T, R> Function<? super T, ? extends Publisher<? extends R>> mapper, int prefetch, boolean veryEnd) { super(mapper, prefetch); - this.actual = actual; + this.downstream = actual; this.veryEnd = veryEnd; } @Override void subscribeActual() { - actual.onSubscribe(this); + downstream.onSubscribe(this); } @Override @@ -414,7 +414,7 @@ public void onError(Throwable t) { @Override public void innerNext(R value) { - actual.onNext(value); + downstream.onNext(value); } @@ -422,7 +422,7 @@ public void innerNext(R value) { public void innerError(Throwable e) { if (errors.addThrowable(e)) { if (!veryEnd) { - s.cancel(); + upstream.cancel(); done = true; } active = false; @@ -443,7 +443,7 @@ public void cancel() { cancelled = true; inner.cancel(); - s.cancel(); + upstream.cancel(); } } @@ -463,7 +463,7 @@ void drain() { if (d && !veryEnd) { Throwable ex = errors.get(); if (ex != null) { - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); return; } } @@ -474,9 +474,9 @@ void drain() { v = queue.poll(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); errors.addThrowable(e); - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); return; } @@ -485,9 +485,9 @@ void drain() { if (d && empty) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } return; } @@ -500,9 +500,9 @@ void drain() { } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); errors.addThrowable(e); - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); return; } @@ -510,7 +510,7 @@ void drain() { int c = consumed + 1; if (c == limit) { consumed = 0; - s.request(c); + upstream.request(c); } else { consumed = c; } @@ -526,9 +526,9 @@ void drain() { vr = supplier.call(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); errors.addThrowable(e); - actual.onError(errors.terminate()); + downstream.onError(errors.terminate()); return; } @@ -537,7 +537,7 @@ void drain() { } if (inner.isUnbounded()) { - actual.onNext(vr); + downstream.onNext(vr); continue; } else { active = true; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java index 991a96f45c..87ee235704 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java @@ -62,7 +62,7 @@ static final class ConcatMapEagerDelayErrorSubscriber<T, R> private static final long serialVersionUID = -4255299542215038287L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final Function<? super T, ? extends Publisher<? extends R>> mapper; @@ -78,7 +78,7 @@ static final class ConcatMapEagerDelayErrorSubscriber<T, R> final SpscLinkedArrayQueue<InnerQueuedSubscriber<R>> subscribers; - Subscription s; + Subscription upstream; volatile boolean cancelled; @@ -89,7 +89,7 @@ static final class ConcatMapEagerDelayErrorSubscriber<T, R> ConcatMapEagerDelayErrorSubscriber(Subscriber<? super R> actual, Function<? super T, ? extends Publisher<? extends R>> mapper, int maxConcurrency, int prefetch, ErrorMode errorMode) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.maxConcurrency = maxConcurrency; this.prefetch = prefetch; @@ -101,10 +101,10 @@ static final class ConcatMapEagerDelayErrorSubscriber<T, R> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(maxConcurrency == Integer.MAX_VALUE ? Long.MAX_VALUE : maxConcurrency); } @@ -119,7 +119,7 @@ public void onNext(T t) { p = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); return; } @@ -162,7 +162,7 @@ public void cancel() { return; } cancelled = true; - s.cancel(); + upstream.cancel(); drainAndCancel(); } @@ -206,7 +206,7 @@ public void innerError(InnerQueuedSubscriber<R> inner, Throwable e) { if (errors.addThrowable(e)) { inner.setDone(); if (errorMode != ErrorMode.END) { - s.cancel(); + upstream.cancel(); } drain(); } else { @@ -228,7 +228,7 @@ public void drain() { int missed = 1; InnerQueuedSubscriber<R> inner = current; - Subscriber<? super R> a = actual; + Subscriber<? super R> a = downstream; ErrorMode em = errorMode; for (;;) { @@ -309,7 +309,7 @@ public void drain() { if (d && empty) { inner = null; current = null; - s.request(1); + upstream.request(1); continueNextSource = true; break; } @@ -350,7 +350,7 @@ public void drain() { if (d && empty) { inner = null; current = null; - s.request(1); + upstream.request(1); continueNextSource = true; } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java index 5523614a9a..8928d20139 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithCompletable.java @@ -49,7 +49,7 @@ static final class ConcatWithSubscriber<T> private static final long serialVersionUID = -7346385463600070225L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; Subscription upstream; @@ -58,7 +58,7 @@ static final class ConcatWithSubscriber<T> boolean inCompletable; ConcatWithSubscriber(Subscriber<? super T> actual, CompletableSource other) { - this.actual = actual; + this.downstream = actual; this.other = other; } @@ -66,7 +66,7 @@ static final class ConcatWithSubscriber<T> public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(upstream, s)) { this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -77,18 +77,18 @@ public void onSubscribe(Disposable d) { @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { if (inCompletable) { - actual.onComplete(); + downstream.onComplete(); } else { inCompletable = true; upstream = SubscriptionHelper.CANCELLED; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java index 3250e0c82c..0081d91feb 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybe.java @@ -70,12 +70,12 @@ public void onSubscribe(Disposable d) { @Override public void onNext(T t) { produced++; - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override @@ -86,10 +86,10 @@ public void onSuccess(T t) { @Override public void onComplete() { if (inMaybe) { - actual.onComplete(); + downstream.onComplete(); } else { inMaybe = true; - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; MaybeSource<? extends T> ms = other; other = null; ms.subscribe(this); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java index a85090166b..23c60ea4fc 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatWithSingle.java @@ -68,12 +68,12 @@ public void onSubscribe(Disposable d) { @Override public void onNext(T t) { produced++; - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override @@ -83,7 +83,7 @@ public void onSuccess(T t) { @Override public void onComplete() { - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; SingleSource<? extends T> ss = other; other = null; ss.subscribe(this); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCount.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCount.java index 95bbfb0d2e..ebe2b07024 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCount.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCount.java @@ -35,19 +35,19 @@ static final class CountSubscriber extends DeferredScalarSubscription<Long> private static final long serialVersionUID = 4973004223787171406L; - Subscription s; + Subscription upstream; long count; - CountSubscriber(Subscriber<? super Long> actual) { - super(actual); + CountSubscriber(Subscriber<? super Long> downstream) { + super(downstream); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -59,7 +59,7 @@ public void onNext(Object t) { @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override @@ -70,7 +70,7 @@ public void onComplete() { @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCountSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCountSingle.java index 13bf0bd9a8..c43f0314f0 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCountSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCountSingle.java @@ -41,21 +41,21 @@ public Flowable<Long> fuseToFlowable() { static final class CountSubscriber implements FlowableSubscriber<Object>, Disposable { - final SingleObserver<? super Long> actual; + final SingleObserver<? super Long> downstream; - Subscription s; + Subscription upstream; long count; - CountSubscriber(SingleObserver<? super Long> actual) { - this.actual = actual; + CountSubscriber(SingleObserver<? super Long> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -67,25 +67,25 @@ public void onNext(Object t) { @Override public void onError(Throwable t) { - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override public void onComplete() { - s = SubscriptionHelper.CANCELLED; - actual.onSuccess(count); + upstream = SubscriptionHelper.CANCELLED; + downstream.onSuccess(count); } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java index c1f506abc1..e7d43e466b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java @@ -210,8 +210,8 @@ void drainLoop() { } @Override - public void setDisposable(Disposable s) { - emitter.setDisposable(s); + public void setDisposable(Disposable d) { + emitter.setDisposable(d); } @Override @@ -245,12 +245,12 @@ abstract static class BaseEmitter<T> implements FlowableEmitter<T>, Subscription { private static final long serialVersionUID = 7326289992464377023L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final SequentialDisposable serial; - BaseEmitter(Subscriber<? super T> actual) { - this.actual = actual; + BaseEmitter(Subscriber<? super T> downstream) { + this.downstream = downstream; this.serial = new SequentialDisposable(); } @@ -264,7 +264,7 @@ protected void complete() { return; } try { - actual.onComplete(); + downstream.onComplete(); } finally { serial.dispose(); } @@ -290,7 +290,7 @@ protected boolean error(Throwable e) { return false; } try { - actual.onError(e); + downstream.onError(e); } finally { serial.dispose(); } @@ -325,8 +325,8 @@ void onRequested() { } @Override - public final void setDisposable(Disposable s) { - serial.update(s); + public final void setDisposable(Disposable d) { + serial.update(d); } @Override @@ -355,8 +355,8 @@ static final class MissingEmitter<T> extends BaseEmitter<T> { private static final long serialVersionUID = 3776720187248809713L; - MissingEmitter(Subscriber<? super T> actual) { - super(actual); + MissingEmitter(Subscriber<? super T> downstream) { + super(downstream); } @Override @@ -366,7 +366,7 @@ public void onNext(T t) { } if (t != null) { - actual.onNext(t); + downstream.onNext(t); } else { onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); return; @@ -386,8 +386,8 @@ abstract static class NoOverflowBaseAsyncEmitter<T> extends BaseEmitter<T> { private static final long serialVersionUID = 4127754106204442833L; - NoOverflowBaseAsyncEmitter(Subscriber<? super T> actual) { - super(actual); + NoOverflowBaseAsyncEmitter(Subscriber<? super T> downstream) { + super(downstream); } @Override @@ -402,7 +402,7 @@ public final void onNext(T t) { } if (get() != 0) { - actual.onNext(t); + downstream.onNext(t); BackpressureHelper.produced(this, 1); } else { onOverflow(); @@ -417,8 +417,8 @@ static final class DropAsyncEmitter<T> extends NoOverflowBaseAsyncEmitter<T> { private static final long serialVersionUID = 8360058422307496563L; - DropAsyncEmitter(Subscriber<? super T> actual) { - super(actual); + DropAsyncEmitter(Subscriber<? super T> downstream) { + super(downstream); } @Override @@ -433,8 +433,8 @@ static final class ErrorAsyncEmitter<T> extends NoOverflowBaseAsyncEmitter<T> { private static final long serialVersionUID = 338953216916120960L; - ErrorAsyncEmitter(Subscriber<? super T> actual) { - super(actual); + ErrorAsyncEmitter(Subscriber<? super T> downstream) { + super(downstream); } @Override @@ -516,7 +516,7 @@ void drain() { } int missed = 1; - final Subscriber<? super T> a = actual; + final Subscriber<? super T> a = downstream; final SpscLinkedArrayQueue<T> q = queue; for (;;) { @@ -599,8 +599,8 @@ static final class LatestAsyncEmitter<T> extends BaseEmitter<T> { final AtomicInteger wip; - LatestAsyncEmitter(Subscriber<? super T> actual) { - super(actual); + LatestAsyncEmitter(Subscriber<? super T> downstream) { + super(downstream); this.queue = new AtomicReference<T>(); this.wip = new AtomicInteger(); } @@ -657,7 +657,7 @@ void drain() { } int missed = 1; - final Subscriber<? super T> a = actual; + final Subscriber<? super T> a = downstream; final AtomicReference<T> q = queue; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounce.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounce.java index 34bc84c4c3..92b1c48254 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounce.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounce.java @@ -45,10 +45,10 @@ static final class DebounceSubscriber<T, U> extends AtomicLong implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = 6725975399620862591L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Function<? super T, ? extends Publisher<U>> debounceSelector; - Subscription s; + Subscription upstream; final AtomicReference<Disposable> debouncer = new AtomicReference<Disposable>(); @@ -58,15 +58,15 @@ static final class DebounceSubscriber<T, U> extends AtomicLong DebounceSubscriber(Subscriber<? super T> actual, Function<? super T, ? extends Publisher<U>> debounceSelector) { - this.actual = actual; + this.downstream = actual; this.debounceSelector = debounceSelector; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -92,7 +92,7 @@ public void onNext(T t) { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancel(); - actual.onError(e); + downstream.onError(e); return; } @@ -106,7 +106,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { DisposableHelper.dispose(debouncer); - actual.onError(t); + downstream.onError(t); } @Override @@ -121,7 +121,7 @@ public void onComplete() { DebounceInnerSubscriber<T, U> dis = (DebounceInnerSubscriber<T, U>)d; dis.emit(); DisposableHelper.dispose(debouncer); - actual.onComplete(); + downstream.onComplete(); } } @@ -134,7 +134,7 @@ public void request(long n) { @Override public void cancel() { - s.cancel(); + upstream.cancel(); DisposableHelper.dispose(debouncer); } @@ -142,11 +142,11 @@ void emit(long idx, T value) { if (idx == index) { long r = get(); if (r != 0L) { - actual.onNext(value); + downstream.onNext(value); BackpressureHelper.produced(this, 1); } else { cancel(); - actual.onError(new MissingBackpressureException("Could not deliver value due to lack of requests")); + downstream.onError(new MissingBackpressureException("Could not deliver value due to lack of requests")); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java index aea5af63e7..36ece502bd 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java @@ -51,12 +51,12 @@ static final class DebounceTimedSubscriber<T> extends AtomicLong implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = -9102637559663639004L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final long timeout; final TimeUnit unit; final Scheduler.Worker worker; - Subscription s; + Subscription upstream; Disposable timer; @@ -65,7 +65,7 @@ static final class DebounceTimedSubscriber<T> extends AtomicLong boolean done; DebounceTimedSubscriber(Subscriber<? super T> actual, long timeout, TimeUnit unit, Worker worker) { - this.actual = actual; + this.downstream = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; @@ -73,9 +73,9 @@ static final class DebounceTimedSubscriber<T> extends AtomicLong @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -110,7 +110,7 @@ public void onError(Throwable t) { if (d != null) { d.dispose(); } - actual.onError(t); + downstream.onError(t); worker.dispose(); } @@ -131,7 +131,7 @@ public void onComplete() { de.emit(); } - actual.onComplete(); + downstream.onComplete(); worker.dispose(); } @@ -144,7 +144,7 @@ public void request(long n) { @Override public void cancel() { - s.cancel(); + upstream.cancel(); worker.dispose(); } @@ -152,13 +152,13 @@ void emit(long idx, T t, DebounceEmitter<T> emitter) { if (idx == index) { long r = get(); if (r != 0L) { - actual.onNext(t); + downstream.onNext(t); BackpressureHelper.produced(this, 1); emitter.dispose(); } else { cancel(); - actual.onError(new MissingBackpressureException("Could not deliver value due to lack of requests")); + downstream.onError(new MissingBackpressureException("Could not deliver value due to lack of requests")); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelay.java index 3732c48d63..684c11f549 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelay.java @@ -38,30 +38,30 @@ public FlowableDelay(Flowable<T> source, long delay, TimeUnit unit, Scheduler sc @Override protected void subscribeActual(Subscriber<? super T> t) { - Subscriber<? super T> s; + Subscriber<? super T> downstream; if (delayError) { - s = t; + downstream = t; } else { - s = new SerializedSubscriber<T>(t); + downstream = new SerializedSubscriber<T>(t); } Scheduler.Worker w = scheduler.createWorker(); - source.subscribe(new DelaySubscriber<T>(s, delay, unit, w, delayError)); + source.subscribe(new DelaySubscriber<T>(downstream, delay, unit, w, delayError)); } static final class DelaySubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final long delay; final TimeUnit unit; final Scheduler.Worker w; final boolean delayError; - Subscription s; + Subscription upstream; DelaySubscriber(Subscriber<? super T> actual, long delay, TimeUnit unit, Worker w, boolean delayError) { super(); - this.actual = actual; + this.downstream = actual; this.delay = delay; this.unit = unit; this.w = w; @@ -70,9 +70,9 @@ static final class DelaySubscriber<T> implements FlowableSubscriber<T>, Subscrip @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -93,12 +93,12 @@ public void onComplete() { @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); w.dispose(); } @@ -111,7 +111,7 @@ final class OnNext implements Runnable { @Override public void run() { - actual.onNext(t); + downstream.onNext(t); } } @@ -125,7 +125,7 @@ final class OnError implements Runnable { @Override public void run() { try { - actual.onError(t); + downstream.onError(t); } finally { w.dispose(); } @@ -136,7 +136,7 @@ final class OnComplete implements Runnable { @Override public void run() { try { - actual.onComplete(); + downstream.onComplete(); } finally { w.dispose(); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOther.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOther.java index 0d0a37db3e..a98892a01c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOther.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOther.java @@ -85,10 +85,11 @@ public void onComplete() { } final class DelaySubscription implements Subscription { - private final Subscription s; + + final Subscription upstream; DelaySubscription(Subscription s) { - this.s = s; + this.upstream = s; } @Override @@ -98,7 +99,7 @@ public void request(long n) { @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java index 5ce85197c3..6257f48803 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java @@ -31,21 +31,21 @@ protected void subscribeActual(Subscriber<? super T> s) { } static final class DematerializeSubscriber<T> implements FlowableSubscriber<Notification<T>>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; boolean done; - Subscription s; + Subscription upstream; - DematerializeSubscriber(Subscriber<? super T> actual) { - this.actual = actual; + DematerializeSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -58,14 +58,14 @@ public void onNext(Notification<T> t) { return; } if (t.isOnError()) { - s.cancel(); + upstream.cancel(); onError(t.getError()); } else if (t.isOnComplete()) { - s.cancel(); + upstream.cancel(); onComplete(); } else { - actual.onNext(t.getValue()); + downstream.onNext(t.getValue()); } } @@ -77,7 +77,7 @@ public void onError(Throwable t) { } done = true; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { @@ -86,17 +86,17 @@ public void onComplete() { } done = true; - actual.onComplete(); + downstream.onComplete(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDetach.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDetach.java index de618949d4..7679ee152e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDetach.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDetach.java @@ -32,54 +32,54 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class DetachSubscriber<T> implements FlowableSubscriber<T>, Subscription { - Subscriber<? super T> actual; + Subscriber<? super T> downstream; - Subscription s; + Subscription upstream; - DetachSubscriber(Subscriber<? super T> actual) { - this.actual = actual; + DetachSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - Subscription s = this.s; - this.s = EmptyComponent.INSTANCE; - this.actual = EmptyComponent.asSubscriber(); + Subscription s = this.upstream; + this.upstream = EmptyComponent.INSTANCE; + this.downstream = EmptyComponent.asSubscriber(); s.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - Subscriber<? super T> a = actual; - this.s = EmptyComponent.INSTANCE; - this.actual = EmptyComponent.asSubscriber(); + Subscriber<? super T> a = downstream; + this.upstream = EmptyComponent.INSTANCE; + this.downstream = EmptyComponent.asSubscriber(); a.onError(t); } @Override public void onComplete() { - Subscriber<? super T> a = actual; - this.s = EmptyComponent.INSTANCE; - this.actual = EmptyComponent.asSubscriber(); + Subscriber<? super T> a = downstream; + this.upstream = EmptyComponent.INSTANCE; + this.downstream = EmptyComponent.asSubscriber(); a.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinct.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinct.java index f12b637737..4e9bc5e1bf 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinct.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinct.java @@ -85,12 +85,12 @@ public void onNext(T value) { } if (b) { - actual.onNext(value); + downstream.onNext(value); } else { - s.request(1); + upstream.request(1); } } else { - actual.onNext(null); + downstream.onNext(null); } } @@ -101,7 +101,7 @@ public void onError(Throwable e) { } else { done = true; collection.clear(); - actual.onError(e); + downstream.onError(e); } } @@ -110,7 +110,7 @@ public void onComplete() { if (!done) { done = true; collection.clear(); - actual.onComplete(); + downstream.onComplete(); } } @@ -129,7 +129,7 @@ public T poll() throws Exception { return v; } else { if (sourceMode == QueueFuseable.ASYNC) { - s.request(1); + upstream.request(1); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChanged.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChanged.java index 9b1944977b..f54be6360b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChanged.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChanged.java @@ -66,7 +66,7 @@ static final class DistinctUntilChangedSubscriber<T, K> extends BasicFuseableSub @Override public void onNext(T t) { if (!tryOnNext(t)) { - s.request(1); + upstream.request(1); } } @@ -76,7 +76,7 @@ public boolean tryOnNext(T t) { return false; } if (sourceMode != NONE) { - actual.onNext(t); + downstream.onNext(t); return true; } @@ -99,7 +99,7 @@ public boolean tryOnNext(T t) { return true; } - actual.onNext(t); + downstream.onNext(t); return true; } @@ -129,7 +129,7 @@ public T poll() throws Exception { } last = key; if (sourceMode != SYNC) { - s.request(1); + upstream.request(1); } } } @@ -157,7 +157,7 @@ static final class DistinctUntilChangedConditionalSubscriber<T, K> extends Basic @Override public void onNext(T t) { if (!tryOnNext(t)) { - s.request(1); + upstream.request(1); } } @@ -167,7 +167,7 @@ public boolean tryOnNext(T t) { return false; } if (sourceMode != NONE) { - return actual.tryOnNext(t); + return downstream.tryOnNext(t); } K key; @@ -189,7 +189,7 @@ public boolean tryOnNext(T t) { return true; } - actual.onNext(t); + downstream.onNext(t); return true; } @@ -219,7 +219,7 @@ public T poll() throws Exception { } last = key; if (sourceMode != SYNC) { - s.request(1); + upstream.request(1); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNext.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNext.java index f7a079d4b7..968c589e2c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNext.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNext.java @@ -59,7 +59,7 @@ public void onNext(T t) { if (done) { return; } - actual.onNext(t); + downstream.onNext(t); if (sourceMode == NONE) { try { @@ -97,7 +97,7 @@ static final class DoAfterConditionalSubscriber<T> extends BasicFuseableConditio @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); if (sourceMode == NONE) { try { @@ -110,7 +110,7 @@ public void onNext(T t) { @Override public boolean tryOnNext(T t) { - boolean b = actual.tryOnNext(t); + boolean b = downstream.tryOnNext(t); try { onAfterNext.accept(t); } catch (Throwable ex) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoFinally.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoFinally.java index 116f81b712..023c55bf7f 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoFinally.java @@ -51,60 +51,60 @@ static final class DoFinallySubscriber<T> extends BasicIntQueueSubscription<T> i private static final long serialVersionUID = 4109457741734051389L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Action onFinally; - Subscription s; + Subscription upstream; QueueSubscription<T> qs; boolean syncFused; DoFinallySubscriber(Subscriber<? super T> actual, Action onFinally) { - this.actual = actual; + this.downstream = actual; this.onFinally = onFinally; } @SuppressWarnings("unchecked") @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; if (s instanceof QueueSubscription) { this.qs = (QueueSubscription<T>)s; } - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); runFinally(); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); runFinally(); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); runFinally(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override @@ -156,65 +156,65 @@ static final class DoFinallyConditionalSubscriber<T> extends BasicIntQueueSubscr private static final long serialVersionUID = 4109457741734051389L; - final ConditionalSubscriber<? super T> actual; + final ConditionalSubscriber<? super T> downstream; final Action onFinally; - Subscription s; + Subscription upstream; QueueSubscription<T> qs; boolean syncFused; DoFinallyConditionalSubscriber(ConditionalSubscriber<? super T> actual, Action onFinally) { - this.actual = actual; + this.downstream = actual; this.onFinally = onFinally; } @SuppressWarnings("unchecked") @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; if (s instanceof QueueSubscription) { this.qs = (QueueSubscription<T>)s; } - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public boolean tryOnNext(T t) { - return actual.tryOnNext(t); + return downstream.tryOnNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); runFinally(); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); runFinally(); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); runFinally(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnEach.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnEach.java index 2d7d49ca46..e913675f69 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnEach.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnEach.java @@ -78,7 +78,7 @@ public void onNext(T t) { } if (sourceMode != NONE) { - actual.onNext(null); + downstream.onNext(null); return; } @@ -89,7 +89,7 @@ public void onNext(T t) { return; } - actual.onNext(t); + downstream.onNext(t); } @Override @@ -104,11 +104,11 @@ public void onError(Throwable t) { onError.accept(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); relay = false; } if (relay) { - actual.onError(t); + downstream.onError(t); } try { @@ -132,7 +132,7 @@ public void onComplete() { } done = true; - actual.onComplete(); + downstream.onComplete(); try { onAfterTerminate.run(); @@ -217,7 +217,7 @@ public void onNext(T t) { } if (sourceMode != NONE) { - actual.onNext(null); + downstream.onNext(null); return; } @@ -228,7 +228,7 @@ public void onNext(T t) { return; } - actual.onNext(t); + downstream.onNext(t); } @Override @@ -244,7 +244,7 @@ public boolean tryOnNext(T t) { return false; } - return actual.tryOnNext(t); + return downstream.tryOnNext(t); } @Override @@ -259,11 +259,11 @@ public void onError(Throwable t) { onError.accept(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); relay = false; } if (relay) { - actual.onError(t); + downstream.onError(t); } try { @@ -287,7 +287,7 @@ public void onComplete() { } done = true; - actual.onComplete(); + downstream.onComplete(); try { onAfterTerminate.run(); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycle.java index e68f1a01e2..f0d233881d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycle.java @@ -39,18 +39,18 @@ protected void subscribeActual(Subscriber<? super T> s) { } static final class SubscriptionLambdaSubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Consumer<? super Subscription> onSubscribe; final LongConsumer onRequest; final Action onCancel; - Subscription s; + Subscription upstream; SubscriptionLambdaSubscriber(Subscriber<? super T> actual, Consumer<? super Subscription> onSubscribe, LongConsumer onRequest, Action onCancel) { - this.actual = actual; + this.downstream = actual; this.onSubscribe = onSubscribe; this.onCancel = onCancel; this.onRequest = onRequest; @@ -64,25 +64,25 @@ public void onSubscribe(Subscription s) { } catch (Throwable e) { Exceptions.throwIfFatal(e); s.cancel(); - this.s = SubscriptionHelper.CANCELLED; - EmptySubscription.error(e, actual); + this.upstream = SubscriptionHelper.CANCELLED; + EmptySubscription.error(e, downstream); return; } - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - if (s != SubscriptionHelper.CANCELLED) { - actual.onError(t); + if (upstream != SubscriptionHelper.CANCELLED) { + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -90,8 +90,8 @@ public void onError(Throwable t) { @Override public void onComplete() { - if (s != SubscriptionHelper.CANCELLED) { - actual.onComplete(); + if (upstream != SubscriptionHelper.CANCELLED) { + downstream.onComplete(); } } @@ -103,7 +103,7 @@ public void request(long n) { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(e); } - s.request(n); + upstream.request(n); } @Override @@ -114,7 +114,7 @@ public void cancel() { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(e); } - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAt.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAt.java index 261cbd88cf..9d3ead4a46 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAt.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAt.java @@ -46,7 +46,7 @@ static final class ElementAtSubscriber<T> extends DeferredScalarSubscription<T> final T defaultValue; final boolean errorOnFewer; - Subscription s; + Subscription upstream; long count; @@ -61,9 +61,9 @@ static final class ElementAtSubscriber<T> extends DeferredScalarSubscription<T> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -76,7 +76,7 @@ public void onNext(T t) { long c = count; if (c == index) { done = true; - s.cancel(); + upstream.cancel(); complete(t); return; } @@ -90,7 +90,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -100,9 +100,9 @@ public void onComplete() { T v = defaultValue; if (v == null) { if (errorOnFewer) { - actual.onError(new NoSuchElementException()); + downstream.onError(new NoSuchElementException()); } else { - actual.onComplete(); + downstream.onComplete(); } } else { complete(v); @@ -113,7 +113,7 @@ public void onComplete() { @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtMaybe.java index 5293af4722..4d411990ac 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtMaybe.java @@ -43,26 +43,26 @@ public Flowable<T> fuseToFlowable() { static final class ElementAtSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final long index; - Subscription s; + Subscription upstream; long count; boolean done; ElementAtSubscriber(MaybeObserver<? super T> actual, long index) { - this.actual = actual; + this.downstream = actual; this.index = index; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -75,9 +75,9 @@ public void onNext(T t) { long c = count; if (c == index) { done = true; - s.cancel(); - s = SubscriptionHelper.CANCELLED; - actual.onSuccess(t); + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; + downstream.onSuccess(t); return; } count = c + 1; @@ -90,28 +90,28 @@ public void onError(Throwable t) { return; } done = true; - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override public void onComplete() { - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; if (!done) { done = true; - actual.onComplete(); + downstream.onComplete(); } } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtSingle.java index 0a08f47fee..7cd542d497 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableElementAtSingle.java @@ -48,28 +48,28 @@ public Flowable<T> fuseToFlowable() { static final class ElementAtSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final long index; final T defaultValue; - Subscription s; + Subscription upstream; long count; boolean done; ElementAtSubscriber(SingleObserver<? super T> actual, long index, T defaultValue) { - this.actual = actual; + this.downstream = actual; this.index = index; this.defaultValue = defaultValue; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -82,9 +82,9 @@ public void onNext(T t) { long c = count; if (c == index) { done = true; - s.cancel(); - s = SubscriptionHelper.CANCELLED; - actual.onSuccess(t); + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; + downstream.onSuccess(t); return; } count = c + 1; @@ -97,35 +97,35 @@ public void onError(Throwable t) { return; } done = true; - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override public void onComplete() { - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; if (!done) { done = true; T v = defaultValue; if (v != null) { - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onError(new NoSuchElementException()); + downstream.onError(new NoSuchElementException()); } } } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFilter.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFilter.java index 96b529f3f2..30487f90d7 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFilter.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFilter.java @@ -50,7 +50,7 @@ static final class FilterSubscriber<T> extends BasicFuseableSubscriber<T, T> @Override public void onNext(T t) { if (!tryOnNext(t)) { - s.request(1); + upstream.request(1); } } @@ -60,7 +60,7 @@ public boolean tryOnNext(T t) { return false; } if (sourceMode != NONE) { - actual.onNext(null); + downstream.onNext(null); return true; } boolean b; @@ -71,7 +71,7 @@ public boolean tryOnNext(T t) { return true; } if (b) { - actual.onNext(t); + downstream.onNext(t); } return b; } @@ -117,7 +117,7 @@ static final class FilterConditionalSubscriber<T> extends BasicFuseableCondition @Override public void onNext(T t) { if (!tryOnNext(t)) { - s.request(1); + upstream.request(1); } } @@ -128,7 +128,7 @@ public boolean tryOnNext(T t) { } if (sourceMode != NONE) { - return actual.tryOnNext(null); + return downstream.tryOnNext(null); } boolean b; @@ -138,7 +138,7 @@ public boolean tryOnNext(T t) { fail(e); return true; } - return b && actual.tryOnNext(t); + return b && downstream.tryOnNext(t); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java index 58e185d12d..07e2b20db3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java @@ -63,7 +63,7 @@ static final class MergeSubscriber<T, U> extends AtomicInteger implements Flowab private static final long serialVersionUID = -2117620485640801370L; - final Subscriber<? super U> actual; + final Subscriber<? super U> downstream; final Function<? super T, ? extends Publisher<? extends U>> mapper; final boolean delayErrors; final int maxConcurrency; @@ -96,7 +96,7 @@ static final class MergeSubscriber<T, U> extends AtomicInteger implements Flowab MergeSubscriber(Subscriber<? super U> actual, Function<? super T, ? extends Publisher<? extends U>> mapper, boolean delayErrors, int maxConcurrency, int bufferSize) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.delayErrors = delayErrors; this.maxConcurrency = maxConcurrency; @@ -109,7 +109,7 @@ static final class MergeSubscriber<T, U> extends AtomicInteger implements Flowab public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); if (!cancelled) { if (maxConcurrency == Integer.MAX_VALUE) { s.request(Long.MAX_VALUE); @@ -231,7 +231,7 @@ void tryEmitScalar(U value) { long r = requested.get(); SimpleQueue<U> q = queue; if (r != 0L && (q == null || q.isEmpty())) { - actual.onNext(value); + downstream.onNext(value); if (r != Long.MAX_VALUE) { requested.decrementAndGet(); } @@ -279,7 +279,7 @@ void tryEmit(U value, InnerSubscriber<T, U> inner) { long r = requested.get(); SimpleQueue<U> q = inner.queue; if (r != 0L && (q == null || q.isEmpty())) { - actual.onNext(value); + downstream.onNext(value); if (r != Long.MAX_VALUE) { requested.decrementAndGet(); } @@ -368,7 +368,7 @@ void drain() { } void drainLoop() { - final Subscriber<? super U> child = this.actual; + final Subscriber<? super U> child = this.downstream; int missed = 1; for (;;) { if (checkTerminate()) { @@ -563,7 +563,7 @@ boolean checkTerminate() { clearScalarQueue(); Throwable ex = errs.terminate(); if (ex != ExceptionHelper.TERMINATED) { - actual.onError(ex); + downstream.onError(ex); } return true; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletable.java index 43546d1376..86311bc27d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletable.java @@ -58,7 +58,7 @@ static final class FlatMapCompletableMainSubscriber<T> extends BasicIntQueueSubs implements FlowableSubscriber<T> { private static final long serialVersionUID = 8443155186132538303L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final AtomicThrowable errors; @@ -70,14 +70,14 @@ static final class FlatMapCompletableMainSubscriber<T> extends BasicIntQueueSubs final int maxConcurrency; - Subscription s; + Subscription upstream; volatile boolean cancelled; FlatMapCompletableMainSubscriber(Subscriber<? super T> subscriber, Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors, int maxConcurrency) { - this.actual = subscriber; + this.downstream = subscriber; this.mapper = mapper; this.delayErrors = delayErrors; this.errors = new AtomicThrowable(); @@ -88,10 +88,10 @@ static final class FlatMapCompletableMainSubscriber<T> extends BasicIntQueueSubs @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); int m = maxConcurrency; if (m == Integer.MAX_VALUE) { @@ -110,7 +110,7 @@ public void onNext(T value) { cs = ObjectHelper.requireNonNull(mapper.apply(value), "The mapper returned a null CompletableSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); return; } @@ -130,17 +130,17 @@ public void onError(Throwable e) { if (delayErrors) { if (decrementAndGet() == 0) { Throwable ex = errors.terminate(); - actual.onError(ex); + downstream.onError(ex); } else { if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } } } else { cancel(); if (getAndSet(0) > 0) { Throwable ex = errors.terminate(); - actual.onError(ex); + downstream.onError(ex); } } } else { @@ -153,13 +153,13 @@ public void onComplete() { if (decrementAndGet() == 0) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } } else { if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } } } @@ -167,7 +167,7 @@ public void onComplete() { @Override public void cancel() { cancelled = true; - s.cancel(); + upstream.cancel(); set.dispose(); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableCompletable.java index 16f126b363..ad5434273b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableCompletable.java @@ -65,7 +65,7 @@ static final class FlatMapCompletableMainSubscriber<T> extends AtomicInteger implements FlowableSubscriber<T>, Disposable { private static final long serialVersionUID = 8443155186132538303L; - final CompletableObserver actual; + final CompletableObserver downstream; final AtomicThrowable errors; @@ -77,14 +77,14 @@ static final class FlatMapCompletableMainSubscriber<T> extends AtomicInteger final int maxConcurrency; - Subscription s; + Subscription upstream; volatile boolean disposed; FlatMapCompletableMainSubscriber(CompletableObserver observer, Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors, int maxConcurrency) { - this.actual = observer; + this.downstream = observer; this.mapper = mapper; this.delayErrors = delayErrors; this.errors = new AtomicThrowable(); @@ -95,10 +95,10 @@ static final class FlatMapCompletableMainSubscriber<T> extends AtomicInteger @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); int m = maxConcurrency; if (m == Integer.MAX_VALUE) { @@ -117,7 +117,7 @@ public void onNext(T value) { cs = ObjectHelper.requireNonNull(mapper.apply(value), "The mapper returned a null CompletableSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); return; } @@ -137,17 +137,17 @@ public void onError(Throwable e) { if (delayErrors) { if (decrementAndGet() == 0) { Throwable ex = errors.terminate(); - actual.onError(ex); + downstream.onError(ex); } else { if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } } } else { dispose(); if (getAndSet(0) > 0) { Throwable ex = errors.terminate(); - actual.onError(ex); + downstream.onError(ex); } } } else { @@ -160,13 +160,13 @@ public void onComplete() { if (decrementAndGet() == 0) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } } else { if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } } } @@ -174,7 +174,7 @@ public void onComplete() { @Override public void dispose() { disposed = true; - s.cancel(); + upstream.cancel(); set.dispose(); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybe.java index 8b27fe702a..ab2950e2a3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybe.java @@ -60,7 +60,7 @@ static final class FlatMapMaybeSubscriber<T, R> private static final long serialVersionUID = 8600231336733376951L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final boolean delayErrors; @@ -78,13 +78,13 @@ static final class FlatMapMaybeSubscriber<T, R> final AtomicReference<SpscLinkedArrayQueue<R>> queue; - Subscription s; + Subscription upstream; volatile boolean cancelled; FlatMapMaybeSubscriber(Subscriber<? super R> actual, Function<? super T, ? extends MaybeSource<? extends R>> mapper, boolean delayErrors, int maxConcurrency) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.delayErrors = delayErrors; this.maxConcurrency = maxConcurrency; @@ -97,10 +97,10 @@ static final class FlatMapMaybeSubscriber<T, R> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); int m = maxConcurrency; if (m == Integer.MAX_VALUE) { @@ -119,7 +119,7 @@ public void onNext(T t) { ms = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null MaybeSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); return; } @@ -155,7 +155,7 @@ public void onComplete() { @Override public void cancel() { cancelled = true; - s.cancel(); + upstream.cancel(); set.dispose(); } @@ -172,22 +172,22 @@ void innerSuccess(InnerObserver inner, R value) { if (get() == 0 && compareAndSet(0, 1)) { boolean d = active.decrementAndGet() == 0; if (requested.get() != 0) { - actual.onNext(value); + downstream.onNext(value); SpscLinkedArrayQueue<R> q = queue.get(); if (d && (q == null || q.isEmpty())) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } return; } BackpressureHelper.produced(requested, 1); if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } } else { SpscLinkedArrayQueue<R> q = getOrCreateQueue(); @@ -228,11 +228,11 @@ void innerError(InnerObserver inner, Throwable e) { set.delete(inner); if (errors.addThrowable(e)) { if (!delayErrors) { - s.cancel(); + upstream.cancel(); set.dispose(); } else { if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } } active.decrementAndGet(); @@ -252,15 +252,15 @@ void innerComplete(InnerObserver inner) { if (d && (q == null || q.isEmpty())) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } return; } if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } if (decrementAndGet() == 0) { return; @@ -269,7 +269,7 @@ void innerComplete(InnerObserver inner) { } else { active.decrementAndGet(); if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } drain(); } @@ -290,7 +290,7 @@ void clear() { void drainLoop() { int missed = 1; - Subscriber<? super R> a = actual; + Subscriber<? super R> a = downstream; AtomicInteger n = active; AtomicReference<SpscLinkedArrayQueue<R>> qr = queue; @@ -372,7 +372,7 @@ void drainLoop() { if (e != 0L) { BackpressureHelper.produced(requested, e); if (maxConcurrency != Integer.MAX_VALUE) { - s.request(e); + upstream.request(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingle.java index 0b6c4bc9be..0633248d8c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingle.java @@ -60,7 +60,7 @@ static final class FlatMapSingleSubscriber<T, R> private static final long serialVersionUID = 8600231336733376951L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final boolean delayErrors; @@ -78,13 +78,13 @@ static final class FlatMapSingleSubscriber<T, R> final AtomicReference<SpscLinkedArrayQueue<R>> queue; - Subscription s; + Subscription upstream; volatile boolean cancelled; FlatMapSingleSubscriber(Subscriber<? super R> actual, Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean delayErrors, int maxConcurrency) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.delayErrors = delayErrors; this.maxConcurrency = maxConcurrency; @@ -97,10 +97,10 @@ static final class FlatMapSingleSubscriber<T, R> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); int m = maxConcurrency; if (m == Integer.MAX_VALUE) { @@ -119,7 +119,7 @@ public void onNext(T t) { ms = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); return; } @@ -155,7 +155,7 @@ public void onComplete() { @Override public void cancel() { cancelled = true; - s.cancel(); + upstream.cancel(); set.dispose(); } @@ -172,22 +172,22 @@ void innerSuccess(InnerObserver inner, R value) { if (get() == 0 && compareAndSet(0, 1)) { boolean d = active.decrementAndGet() == 0; if (requested.get() != 0) { - actual.onNext(value); + downstream.onNext(value); SpscLinkedArrayQueue<R> q = queue.get(); if (d && (q == null || q.isEmpty())) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } return; } BackpressureHelper.produced(requested, 1); if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } } else { SpscLinkedArrayQueue<R> q = getOrCreateQueue(); @@ -228,11 +228,11 @@ void innerError(InnerObserver inner, Throwable e) { set.delete(inner); if (errors.addThrowable(e)) { if (!delayErrors) { - s.cancel(); + upstream.cancel(); set.dispose(); } else { if (maxConcurrency != Integer.MAX_VALUE) { - s.request(1); + upstream.request(1); } } active.decrementAndGet(); @@ -257,7 +257,7 @@ void clear() { void drainLoop() { int missed = 1; - Subscriber<? super R> a = actual; + Subscriber<? super R> a = downstream; AtomicInteger n = active; AtomicReference<SpscLinkedArrayQueue<R>> qr = queue; @@ -339,7 +339,7 @@ void drainLoop() { if (e != 0L) { BackpressureHelper.produced(requested, e); if (maxConcurrency != Integer.MAX_VALUE) { - s.request(e); + upstream.request(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java index 12b1095fa8..29e425f58e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java @@ -88,7 +88,7 @@ static final class FlattenIterableSubscriber<T, R> private static final long serialVersionUID = -3096000382929934955L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final Function<? super T, ? extends Iterable<? extends R>> mapper; @@ -98,7 +98,7 @@ static final class FlattenIterableSubscriber<T, R> final AtomicLong requested; - Subscription s; + Subscription upstream; SimpleQueue<T> queue; @@ -116,7 +116,7 @@ static final class FlattenIterableSubscriber<T, R> FlattenIterableSubscriber(Subscriber<? super R> actual, Function<? super T, ? extends Iterable<? extends R>> mapper, int prefetch) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.prefetch = prefetch; this.limit = prefetch - (prefetch >> 2); @@ -126,8 +126,8 @@ static final class FlattenIterableSubscriber<T, R> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; if (s instanceof QueueSubscription) { @SuppressWarnings("unchecked") @@ -140,7 +140,7 @@ public void onSubscribe(Subscription s) { this.queue = qs; done = true; - actual.onSubscribe(this); + downstream.onSubscribe(this); return; } @@ -148,7 +148,7 @@ public void onSubscribe(Subscription s) { fusionMode = m; this.queue = qs; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(prefetch); return; @@ -157,7 +157,7 @@ public void onSubscribe(Subscription s) { queue = new SpscArrayQueue<T>(prefetch); - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(prefetch); } @@ -207,7 +207,7 @@ public void cancel() { if (!cancelled) { cancelled = true; - s.cancel(); + upstream.cancel(); if (getAndIncrement() == 0) { queue.clear(); @@ -220,7 +220,7 @@ void drain() { return; } - final Subscriber<? super R> a = actual; + final Subscriber<? super R> a = downstream; final SimpleQueue<T> q = queue; final boolean replenish = fusionMode != SYNC; @@ -240,7 +240,7 @@ void drain() { t = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); ExceptionHelper.addThrowable(error, ex); ex = ExceptionHelper.terminate(error); @@ -270,7 +270,7 @@ void drain() { b = it.hasNext(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); ExceptionHelper.addThrowable(error, ex); ex = ExceptionHelper.terminate(error); a.onError(ex); @@ -303,7 +303,7 @@ void drain() { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); current = null; - s.cancel(); + upstream.cancel(); ExceptionHelper.addThrowable(error, ex); ex = ExceptionHelper.terminate(error); a.onError(ex); @@ -325,7 +325,7 @@ void drain() { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); current = null; - s.cancel(); + upstream.cancel(); ExceptionHelper.addThrowable(error, ex); ex = ExceptionHelper.terminate(error); a.onError(ex); @@ -372,7 +372,7 @@ void consumedOne(boolean enabled) { int c = consumed + 1; if (c == limit) { consumed = 0; - s.request(c); + upstream.request(c); } else { consumed = c; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java index b6819d06d5..462a72481f 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java @@ -109,18 +109,18 @@ static final class ArraySubscription<T> extends BaseArraySubscription<T> { private static final long serialVersionUID = 2587302975077663557L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; ArraySubscription(Subscriber<? super T> actual, T[] array) { super(array); - this.actual = actual; + this.downstream = actual; } @Override void fastPath() { T[] arr = array; int f = arr.length; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; for (int i = index; i != f; i++) { if (cancelled) { @@ -146,7 +146,7 @@ void slowPath(long r) { T[] arr = array; int f = arr.length; int i = index; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; for (;;) { @@ -193,18 +193,18 @@ static final class ArrayConditionalSubscription<T> extends BaseArraySubscription private static final long serialVersionUID = 2587302975077663557L; - final ConditionalSubscriber<? super T> actual; + final ConditionalSubscriber<? super T> downstream; ArrayConditionalSubscription(ConditionalSubscriber<? super T> actual, T[] array) { super(array); - this.actual = actual; + this.downstream = actual; } @Override void fastPath() { T[] arr = array; int f = arr.length; - ConditionalSubscriber<? super T> a = actual; + ConditionalSubscriber<? super T> a = downstream; for (int i = index; i != f; i++) { if (cancelled) { @@ -230,7 +230,7 @@ void slowPath(long r) { T[] arr = array; int f = arr.length; int i = index; - ConditionalSubscriber<? super T> a = actual; + ConditionalSubscriber<? super T> a = downstream; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java index ac1b0238dc..9cf14837b6 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java @@ -144,17 +144,17 @@ static final class IteratorSubscription<T> extends BaseRangeSubscription<T> { private static final long serialVersionUID = -6022804456014692607L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; IteratorSubscription(Subscriber<? super T> actual, Iterator<? extends T> it) { super(it); - this.actual = actual; + this.downstream = actual; } @Override void fastPath() { Iterator<? extends T> it = this.it; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; for (;;) { if (cancelled) { return; @@ -209,7 +209,7 @@ void fastPath() { void slowPath(long r) { long e = 0L; Iterator<? extends T> it = this.it; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; for (;;) { @@ -282,17 +282,17 @@ static final class IteratorConditionalSubscription<T> extends BaseRangeSubscript private static final long serialVersionUID = -6022804456014692607L; - final ConditionalSubscriber<? super T> actual; + final ConditionalSubscriber<? super T> downstream; IteratorConditionalSubscription(ConditionalSubscriber<? super T> actual, Iterator<? extends T> it) { super(it); - this.actual = actual; + this.downstream = actual; } @Override void fastPath() { Iterator<? extends T> it = this.it; - ConditionalSubscriber<? super T> a = actual; + ConditionalSubscriber<? super T> a = downstream; for (;;) { if (cancelled) { return; @@ -346,7 +346,7 @@ void fastPath() { void slowPath(long r) { long e = 0L; Iterator<? extends T> it = this.it; - ConditionalSubscriber<? super T> a = actual; + ConditionalSubscriber<? super T> a = downstream; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromObservable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromObservable.java index 7b24ab0ce1..7ad4edb269 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromObservable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromObservable.java @@ -29,37 +29,39 @@ protected void subscribeActual(Subscriber<? super T> s) { upstream.subscribe(new SubscriberObserver<T>(s)); } - static class SubscriberObserver<T> implements Observer<T>, Subscription { - private final Subscriber<? super T> s; - private Disposable d; + static final class SubscriberObserver<T> implements Observer<T>, Subscription { + + final Subscriber<? super T> downstream; + + Disposable upstream; SubscriberObserver(Subscriber<? super T> s) { - this.s = s; + this.downstream = s; } @Override public void onComplete() { - s.onComplete(); + downstream.onComplete(); } @Override public void onError(Throwable e) { - s.onError(e); + downstream.onError(e); } @Override public void onNext(T value) { - s.onNext(value); + downstream.onNext(value); } @Override public void onSubscribe(Disposable d) { - this.d = d; - s.onSubscribe(this); + this.upstream = d; + downstream.onSubscribe(this); } @Override public void cancel() { - d.dispose(); + upstream.dispose(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGenerate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGenerate.java index 54a44151f3..17bdd790b9 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGenerate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGenerate.java @@ -58,7 +58,7 @@ static final class GeneratorSubscription<T, S> private static final long serialVersionUID = 7565982551505011832L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final BiFunction<S, ? super Emitter<T>, S> generator; final Consumer<? super S> disposeState; @@ -73,7 +73,7 @@ static final class GeneratorSubscription<T, S> GeneratorSubscription(Subscriber<? super T> actual, BiFunction<S, ? super Emitter<T>, S> generator, Consumer<? super S> disposeState, S initialState) { - this.actual = actual; + this.downstream = actual; this.generator = generator; this.disposeState = disposeState; this.state = initialState; @@ -171,7 +171,7 @@ public void onNext(T t) { onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); } else { hasNext = true; - actual.onNext(t); + downstream.onNext(t); } } } @@ -186,7 +186,7 @@ public void onError(Throwable t) { t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); } terminate = true; - actual.onError(t); + downstream.onError(t); } } @@ -194,7 +194,7 @@ public void onError(Throwable t) { public void onComplete() { if (!terminate) { terminate = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java index 568cd5141c..14fbc74b99 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java @@ -84,7 +84,7 @@ public static final class GroupBySubscriber<T, K, V> private static final long serialVersionUID = -3688291656102519502L; - final Subscriber<? super GroupedFlowable<K, V>> actual; + final Subscriber<? super GroupedFlowable<K, V>> downstream; final Function<? super T, ? extends K> keySelector; final Function<? super T, ? extends V> valueSelector; final int bufferSize; @@ -95,7 +95,7 @@ public static final class GroupBySubscriber<T, K, V> static final Object NULL_KEY = new Object(); - Subscription s; + Subscription upstream; final AtomicBoolean cancelled = new AtomicBoolean(); @@ -112,7 +112,7 @@ public static final class GroupBySubscriber<T, K, V> public GroupBySubscriber(Subscriber<? super GroupedFlowable<K, V>> actual, Function<? super T, ? extends K> keySelector, Function<? super T, ? extends V> valueSelector, int bufferSize, boolean delayError, Map<Object, GroupedUnicast<K, V>> groups, Queue<GroupedUnicast<K, V>> evictedGroups) { - this.actual = actual; + this.downstream = actual; this.keySelector = keySelector; this.valueSelector = valueSelector; this.bufferSize = bufferSize; @@ -124,9 +124,9 @@ public GroupBySubscriber(Subscriber<? super GroupedFlowable<K, V>> actual, Funct @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(bufferSize); } } @@ -144,7 +144,7 @@ public void onNext(T t) { key = keySelector.apply(t); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); return; } @@ -172,7 +172,7 @@ public void onNext(T t) { v = ObjectHelper.requireNonNull(valueSelector.apply(t), "The valueSelector returned null"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); return; } @@ -237,7 +237,7 @@ public void cancel() { if (cancelled.compareAndSet(false, true)) { completeEvictions(); if (groupCount.decrementAndGet() == 0) { - s.cancel(); + upstream.cancel(); } } } @@ -260,7 +260,7 @@ public void cancel(K key) { Object mapKey = key != null ? key : NULL_KEY; groups.remove(mapKey); if (groupCount.decrementAndGet() == 0) { - s.cancel(); + upstream.cancel(); if (getAndIncrement() == 0) { queue.clear(); @@ -284,7 +284,7 @@ void drainFused() { int missed = 1; final SpscLinkedArrayQueue<GroupedFlowable<K, V>> q = this.queue; - final Subscriber<? super GroupedFlowable<K, V>> a = this.actual; + final Subscriber<? super GroupedFlowable<K, V>> a = this.downstream; for (;;) { if (cancelled.get()) { @@ -326,7 +326,7 @@ void drainNormal() { int missed = 1; final SpscLinkedArrayQueue<GroupedFlowable<K, V>> q = this.queue; - final Subscriber<? super GroupedFlowable<K, V>> a = this.actual; + final Subscriber<? super GroupedFlowable<K, V>> a = this.downstream; for (;;) { @@ -361,7 +361,7 @@ void drainNormal() { if (r != Long.MAX_VALUE) { requested.addAndGet(-e); } - s.request(e); + upstream.request(e); } missed = addAndGet(-missed); @@ -645,7 +645,7 @@ void drainNormal() { if (r != Long.MAX_VALUE) { requested.addAndGet(-e); } - parent.s.request(e); + parent.upstream.request(e); } } @@ -713,7 +713,7 @@ public T poll() { int p = produced; if (p != 0) { produced = 0; - parent.s.request(p); + parent.upstream.request(p); } return null; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java index c0bfb84e6f..d42e3e05af 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java @@ -92,7 +92,7 @@ static final class GroupJoinSubscription<TLeft, TRight, TLeftEnd, TRightEnd, R> private static final long serialVersionUID = -6071216598687999801L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final AtomicLong requested; @@ -131,7 +131,7 @@ static final class GroupJoinSubscription<TLeft, TRight, TLeftEnd, TRightEnd, R> GroupJoinSubscription(Subscriber<? super R> actual, Function<? super TLeft, ? extends Publisher<TLeftEnd>> leftEnd, Function<? super TRight, ? extends Publisher<TRightEnd>> rightEnd, BiFunction<? super TLeft, ? super Flowable<TRight>, ? extends R> resultSelector) { - this.actual = actual; + this.downstream = actual; this.requested = new AtomicLong(); this.disposables = new CompositeDisposable(); this.queue = new SpscLinkedArrayQueue<Object>(bufferSize()); @@ -195,7 +195,7 @@ void drain() { int missed = 1; SpscLinkedArrayQueue<Object> q = queue; - Subscriber<? super R> a = actual; + Subscriber<? super R> a = downstream; for (;;) { for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableHide.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableHide.java index a0d3a33467..0e5f7cc14f 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableHide.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableHide.java @@ -37,45 +37,45 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class HideSubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; - Subscription s; + Subscription upstream; - HideSubscriber(Subscriber<? super T> actual) { - this.actual = actual; + HideSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElements.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElements.java index 270f99e31f..443baf3989 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElements.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElements.java @@ -32,19 +32,19 @@ protected void subscribeActual(final Subscriber<? super T> t) { } static final class IgnoreElementsSubscriber<T> implements FlowableSubscriber<T>, QueueSubscription<T> { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; - Subscription s; + Subscription upstream; - IgnoreElementsSubscriber(Subscriber<? super T> actual) { - this.actual = actual; + IgnoreElementsSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -56,12 +56,12 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override @@ -97,7 +97,7 @@ public void request(long n) { @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsCompletable.java index 88e7577c5a..fc59ae9d8e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsCompletable.java @@ -40,19 +40,19 @@ public Flowable<T> fuseToFlowable() { } static final class IgnoreElementsSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final CompletableObserver actual; + final CompletableObserver downstream; - Subscription s; + Subscription upstream; - IgnoreElementsSubscriber(CompletableObserver actual) { - this.actual = actual; + IgnoreElementsSubscriber(CompletableObserver downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -64,25 +64,25 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override public void onComplete() { - s = SubscriptionHelper.CANCELLED; - actual.onComplete(); + upstream = SubscriptionHelper.CANCELLED; + downstream.onComplete(); } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableInterval.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableInterval.java index ca97aa34e6..35a09373cc 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableInterval.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableInterval.java @@ -62,14 +62,14 @@ static final class IntervalSubscriber extends AtomicLong private static final long serialVersionUID = -2809475196591179431L; - final Subscriber<? super Long> actual; + final Subscriber<? super Long> downstream; long count; final AtomicReference<Disposable> resource = new AtomicReference<Disposable>(); - IntervalSubscriber(Subscriber<? super Long> actual) { - this.actual = actual; + IntervalSubscriber(Subscriber<? super Long> downstream) { + this.downstream = downstream; } @Override @@ -90,10 +90,10 @@ public void run() { long r = get(); if (r != 0L) { - actual.onNext(count++); + downstream.onNext(count++); BackpressureHelper.produced(this, 1); } else { - actual.onError(new MissingBackpressureException("Can't deliver value " + count + " due to lack of requests")); + downstream.onError(new MissingBackpressureException("Can't deliver value " + count + " due to lack of requests")); DisposableHelper.dispose(resource); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableIntervalRange.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableIntervalRange.java index fa697dba41..739460884b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableIntervalRange.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableIntervalRange.java @@ -66,7 +66,7 @@ static final class IntervalRangeSubscriber extends AtomicLong private static final long serialVersionUID = -2809475196591179431L; - final Subscriber<? super Long> actual; + final Subscriber<? super Long> downstream; final long end; long count; @@ -74,7 +74,7 @@ static final class IntervalRangeSubscriber extends AtomicLong final AtomicReference<Disposable> resource = new AtomicReference<Disposable>(); IntervalRangeSubscriber(Subscriber<? super Long> actual, long start, long end) { - this.actual = actual; + this.downstream = actual; this.count = start; this.end = end; } @@ -98,11 +98,11 @@ public void run() { if (r != 0L) { long c = count; - actual.onNext(c); + downstream.onNext(c); if (c == end) { if (resource.get() != DisposableHelper.DISPOSED) { - actual.onComplete(); + downstream.onComplete(); } DisposableHelper.dispose(resource); return; @@ -114,7 +114,7 @@ public void run() { decrementAndGet(); } } else { - actual.onError(new MissingBackpressureException("Can't deliver value " + count + " due to lack of requests")); + downstream.onError(new MissingBackpressureException("Can't deliver value " + count + " due to lack of requests")); DisposableHelper.dispose(resource); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableJoin.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableJoin.java index 36674f13fd..5ff5c97c3f 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableJoin.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableJoin.java @@ -76,7 +76,7 @@ static final class JoinSubscription<TLeft, TRight, TLeftEnd, TRightEnd, R> private static final long serialVersionUID = -6071216598687999801L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final AtomicLong requested; @@ -115,7 +115,7 @@ static final class JoinSubscription<TLeft, TRight, TLeftEnd, TRightEnd, R> JoinSubscription(Subscriber<? super R> actual, Function<? super TLeft, ? extends Publisher<TLeftEnd>> leftEnd, Function<? super TRight, ? extends Publisher<TRightEnd>> rightEnd, BiFunction<? super TLeft, ? super TRight, ? extends R> resultSelector) { - this.actual = actual; + this.downstream = actual; this.requested = new AtomicLong(); this.disposables = new CompositeDisposable(); this.queue = new SpscLinkedArrayQueue<Object>(bufferSize()); @@ -175,7 +175,7 @@ void drain() { int missed = 1; SpscLinkedArrayQueue<Object> q = queue; - Subscriber<? super R> a = actual; + Subscriber<? super R> a = downstream; for (;;) { for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableLastMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableLastMaybe.java index ef36a4bd80..e27efeb403 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableLastMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableLastMaybe.java @@ -41,33 +41,33 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class LastSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - Subscription s; + Subscription upstream; T item; - LastSubscriber(MaybeObserver<? super T> actual) { - this.actual = actual; + LastSubscriber(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -80,20 +80,20 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; item = null; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; T v = item; if (v != null) { item = null; - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableLastSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableLastSingle.java index 8c8a12ee05..344c6f3668 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableLastSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableLastSingle.java @@ -47,36 +47,36 @@ protected void subscribeActual(SingleObserver<? super T> observer) { static final class LastSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final T defaultItem; - Subscription s; + Subscription upstream; T item; LastSubscriber(SingleObserver<? super T> actual, T defaultItem) { - this.actual = actual; + this.downstream = actual; this.defaultItem = defaultItem; } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -89,25 +89,25 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; item = null; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; T v = item; if (v != null) { item = null; - actual.onSuccess(v); + downstream.onSuccess(v); } else { v = defaultItem; if (v != null) { - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onError(new NoSuchElementException()); + downstream.onError(new NoSuchElementException()); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java index a49758dd53..58004d0c69 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableLimit.java @@ -47,14 +47,14 @@ static final class LimitSubscriber<T> private static final long serialVersionUID = 2288246011222124525L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; long remaining; Subscription upstream; LimitSubscriber(Subscriber<? super T> actual, long remaining) { - this.actual = actual; + this.downstream = actual; this.remaining = remaining; lazySet(remaining); } @@ -64,10 +64,10 @@ public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { if (remaining == 0L) { s.cancel(); - EmptySubscription.complete(actual); + EmptySubscription.complete(downstream); } else { this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } } @@ -77,10 +77,10 @@ public void onNext(T t) { long r = remaining; if (r > 0L) { remaining = --r; - actual.onNext(t); + downstream.onNext(t); if (r == 0L) { upstream.cancel(); - actual.onComplete(); + downstream.onComplete(); } } } @@ -89,7 +89,7 @@ public void onNext(T t) { public void onError(Throwable t) { if (remaining > 0L) { remaining = 0L; - actual.onError(t); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -99,7 +99,7 @@ public void onError(Throwable t) { public void onComplete() { if (remaining > 0L) { remaining = 0L; - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMap.java index e9df5a6726..905f3cb6cb 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMap.java @@ -54,7 +54,7 @@ public void onNext(T t) { } if (sourceMode != NONE) { - actual.onNext(null); + downstream.onNext(null); return; } @@ -66,7 +66,7 @@ public void onNext(T t) { fail(ex); return; } - actual.onNext(v); + downstream.onNext(v); } @Override @@ -97,7 +97,7 @@ public void onNext(T t) { } if (sourceMode != NONE) { - actual.onNext(null); + downstream.onNext(null); return; } @@ -109,7 +109,7 @@ public void onNext(T t) { fail(ex); return; } - actual.onNext(v); + downstream.onNext(v); } @Override @@ -126,7 +126,7 @@ public boolean tryOnNext(T t) { fail(ex); return true; } - return actual.tryOnNext(v); + return downstream.tryOnNext(v); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapNotification.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapNotification.java index 0f0ec91d68..4b90d60ea3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapNotification.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapNotification.java @@ -71,12 +71,12 @@ public void onNext(T t) { p = ObjectHelper.requireNonNull(onNextMapper.apply(t), "The onNext publisher returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } produced++; - actual.onNext(p); + downstream.onNext(p); } @Override @@ -87,7 +87,7 @@ public void onError(Throwable t) { p = ObjectHelper.requireNonNull(onErrorMapper.apply(t), "The onError publisher returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); return; } @@ -102,7 +102,7 @@ public void onComplete() { p = ObjectHelper.requireNonNull(onCompleteSupplier.call(), "The onComplete publisher returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMaterialize.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMaterialize.java index 3bceba2dea..91f58105ee 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMaterialize.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMaterialize.java @@ -34,14 +34,14 @@ static final class MaterializeSubscriber<T> extends SinglePostCompleteSubscriber private static final long serialVersionUID = -3740826063558713822L; - MaterializeSubscriber(Subscriber<? super Notification<T>> actual) { - super(actual); + MaterializeSubscriber(Subscriber<? super Notification<T>> downstream) { + super(downstream); } @Override public void onNext(T t) { produced++; - actual.onNext(Notification.createOnNext(t)); + downstream.onNext(Notification.createOnNext(t)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java index 27f8652ff3..271bd9c50d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java @@ -52,7 +52,7 @@ static final class MergeWithSubscriber<T> extends AtomicInteger private static final long serialVersionUID = -4592979584110982903L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final AtomicReference<Subscription> mainSubscription; @@ -66,8 +66,8 @@ static final class MergeWithSubscriber<T> extends AtomicInteger volatile boolean otherDone; - MergeWithSubscriber(Subscriber<? super T> actual) { - this.actual = actual; + MergeWithSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; this.mainSubscription = new AtomicReference<Subscription>(); this.otherObserver = new OtherObserver(this); this.error = new AtomicThrowable(); @@ -75,26 +75,26 @@ static final class MergeWithSubscriber<T> extends AtomicInteger } @Override - public void onSubscribe(Subscription d) { - SubscriptionHelper.deferredSetOnce(mainSubscription, requested, d); + public void onSubscribe(Subscription s) { + SubscriptionHelper.deferredSetOnce(mainSubscription, requested, s); } @Override public void onNext(T t) { - HalfSerializer.onNext(actual, t, this, error); + HalfSerializer.onNext(downstream, t, this, error); } @Override public void onError(Throwable ex) { SubscriptionHelper.cancel(mainSubscription); - HalfSerializer.onError(actual, ex, this, error); + HalfSerializer.onError(downstream, ex, this, error); } @Override public void onComplete() { mainDone = true; if (otherDone) { - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } } @@ -111,13 +111,13 @@ public void cancel() { void otherError(Throwable ex) { SubscriptionHelper.cancel(mainSubscription); - HalfSerializer.onError(actual, ex, this, error); + HalfSerializer.onError(downstream, ex, this, error); } void otherComplete() { otherDone = true; if (mainDone) { - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java index 08430c4a70..a32a0c92fc 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java @@ -55,7 +55,7 @@ static final class MergeWithObserver<T> extends AtomicInteger private static final long serialVersionUID = -4592979584110982903L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final AtomicReference<Subscription> mainSubscription; @@ -87,8 +87,8 @@ static final class MergeWithObserver<T> extends AtomicInteger static final int OTHER_STATE_CONSUMED_OR_EMPTY = 2; - MergeWithObserver(Subscriber<? super T> actual) { - this.actual = actual; + MergeWithObserver(Subscriber<? super T> downstream) { + this.downstream = downstream; this.mainSubscription = new AtomicReference<Subscription>(); this.otherObserver = new OtherObserver<T>(this); this.error = new AtomicThrowable(); @@ -111,7 +111,7 @@ public void onNext(T t) { if (q == null || q.isEmpty()) { emitted = e + 1; - actual.onNext(t); + downstream.onNext(t); int c = consumed + 1; if (c == limit) { @@ -179,7 +179,7 @@ void otherSuccess(T value) { if (requested.get() != e) { emitted = e + 1; - actual.onNext(value); + downstream.onNext(value); otherState = OTHER_STATE_CONSUMED_OR_EMPTY; } else { singleItem = value; @@ -228,7 +228,7 @@ void drain() { } void drainLoop() { - Subscriber<? super T> actual = this.actual; + Subscriber<? super T> actual = this.downstream; int missed = 1; long e = emitted; int c = consumed; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java index 0fee2fa12c..586bc07c07 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java @@ -55,7 +55,7 @@ static final class MergeWithObserver<T> extends AtomicInteger private static final long serialVersionUID = -4592979584110982903L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final AtomicReference<Subscription> mainSubscription; @@ -87,8 +87,8 @@ static final class MergeWithObserver<T> extends AtomicInteger static final int OTHER_STATE_CONSUMED_OR_EMPTY = 2; - MergeWithObserver(Subscriber<? super T> actual) { - this.actual = actual; + MergeWithObserver(Subscriber<? super T> downstream) { + this.downstream = downstream; this.mainSubscription = new AtomicReference<Subscription>(); this.otherObserver = new OtherObserver<T>(this); this.error = new AtomicThrowable(); @@ -111,7 +111,7 @@ public void onNext(T t) { if (q == null || q.isEmpty()) { emitted = e + 1; - actual.onNext(t); + downstream.onNext(t); int c = consumed + 1; if (c == limit) { @@ -179,7 +179,7 @@ void otherSuccess(T value) { if (requested.get() != e) { emitted = e + 1; - actual.onNext(value); + downstream.onNext(value); otherState = OTHER_STATE_CONSUMED_OR_EMPTY; } else { singleItem = value; @@ -223,7 +223,7 @@ void drain() { } void drainLoop() { - Subscriber<? super T> actual = this.actual; + Subscriber<? super T> actual = this.downstream; int missed = 1; long e = emitted; int c = consumed; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java index aaf515bf77..d1c97b6801 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java @@ -72,7 +72,7 @@ abstract static class BaseObserveOnSubscriber<T> final AtomicLong requested; - Subscription s; + Subscription upstream; SimpleQueue<T> queue; @@ -109,7 +109,7 @@ public final void onNext(T t) { return; } if (!queue.offer(t)) { - s.cancel(); + upstream.cancel(); error = new MissingBackpressureException("Queue is full?!"); done = true; @@ -151,7 +151,7 @@ public final void cancel() { } cancelled = true; - s.cancel(); + upstream.cancel(); worker.dispose(); if (getAndIncrement() == 0) { @@ -244,7 +244,7 @@ static final class ObserveOnSubscriber<T> extends BaseObserveOnSubscriber<T> private static final long serialVersionUID = -4547113800637756442L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; ObserveOnSubscriber( Subscriber<? super T> actual, @@ -252,13 +252,13 @@ static final class ObserveOnSubscriber<T> extends BaseObserveOnSubscriber<T> boolean delayError, int prefetch) { super(worker, delayError, prefetch); - this.actual = actual; + this.downstream = actual; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; if (s instanceof QueueSubscription) { @SuppressWarnings("unchecked") @@ -271,14 +271,14 @@ public void onSubscribe(Subscription s) { queue = f; done = true; - actual.onSubscribe(this); + downstream.onSubscribe(this); return; } else if (m == ASYNC) { sourceMode = ASYNC; queue = f; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(prefetch); @@ -288,7 +288,7 @@ public void onSubscribe(Subscription s) { queue = new SpscArrayQueue<T>(prefetch); - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(prefetch); } @@ -298,7 +298,7 @@ public void onSubscribe(Subscription s) { void runSync() { int missed = 1; - final Subscriber<? super T> a = actual; + final Subscriber<? super T> a = downstream; final SimpleQueue<T> q = queue; long e = produced; @@ -314,7 +314,7 @@ void runSync() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); a.onError(ex); worker.dispose(); return; @@ -361,7 +361,7 @@ void runSync() { void runAsync() { int missed = 1; - final Subscriber<? super T> a = actual; + final Subscriber<? super T> a = downstream; final SimpleQueue<T> q = queue; long e = produced; @@ -379,7 +379,7 @@ void runAsync() { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); q.clear(); a.onError(ex); @@ -404,7 +404,7 @@ void runAsync() { if (r != Long.MAX_VALUE) { r = requested.addAndGet(-e); } - s.request(e); + upstream.request(e); e = 0L; } } @@ -438,14 +438,14 @@ void runBackfused() { boolean d = done; - actual.onNext(null); + downstream.onNext(null); if (d) { Throwable e = error; if (e != null) { - actual.onError(e); + downstream.onError(e); } else { - actual.onComplete(); + downstream.onComplete(); } worker.dispose(); return; @@ -466,7 +466,7 @@ public T poll() throws Exception { long p = produced + 1; if (p == limit) { produced = 0; - s.request(p); + upstream.request(p); } else { produced = p; } @@ -481,7 +481,7 @@ static final class ObserveOnConditionalSubscriber<T> private static final long serialVersionUID = 644624475404284533L; - final ConditionalSubscriber<? super T> actual; + final ConditionalSubscriber<? super T> downstream; long consumed; @@ -491,13 +491,13 @@ static final class ObserveOnConditionalSubscriber<T> boolean delayError, int prefetch) { super(worker, delayError, prefetch); - this.actual = actual; + this.downstream = actual; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; if (s instanceof QueueSubscription) { @SuppressWarnings("unchecked") @@ -510,14 +510,14 @@ public void onSubscribe(Subscription s) { queue = f; done = true; - actual.onSubscribe(this); + downstream.onSubscribe(this); return; } else if (m == ASYNC) { sourceMode = ASYNC; queue = f; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(prefetch); @@ -527,7 +527,7 @@ public void onSubscribe(Subscription s) { queue = new SpscArrayQueue<T>(prefetch); - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(prefetch); } @@ -537,7 +537,7 @@ public void onSubscribe(Subscription s) { void runSync() { int missed = 1; - final ConditionalSubscriber<? super T> a = actual; + final ConditionalSubscriber<? super T> a = downstream; final SimpleQueue<T> q = queue; long e = produced; @@ -552,7 +552,7 @@ void runSync() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); a.onError(ex); worker.dispose(); return; @@ -599,7 +599,7 @@ void runSync() { void runAsync() { int missed = 1; - final ConditionalSubscriber<? super T> a = actual; + final ConditionalSubscriber<? super T> a = downstream; final SimpleQueue<T> q = queue; long emitted = produced; @@ -617,7 +617,7 @@ void runAsync() { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); q.clear(); a.onError(ex); @@ -641,7 +641,7 @@ void runAsync() { polled++; if (polled == limit) { - s.request(polled); + upstream.request(polled); polled = 0L; } } @@ -677,14 +677,14 @@ void runBackfused() { boolean d = done; - actual.onNext(null); + downstream.onNext(null); if (d) { Throwable e = error; if (e != null) { - actual.onError(e); + downstream.onError(e); } else { - actual.onComplete(); + downstream.onComplete(); } worker.dispose(); return; @@ -705,7 +705,7 @@ public T poll() throws Exception { long p = consumed + 1; if (p == limit) { consumed = 0; - s.request(p); + upstream.request(p); } else { consumed = p; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBuffer.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBuffer.java index 341cda93c8..20caa2c7e3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBuffer.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBuffer.java @@ -50,12 +50,12 @@ static final class BackpressureBufferSubscriber<T> extends BasicIntQueueSubscrip private static final long serialVersionUID = -2514538129242366402L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final SimplePlainQueue<T> queue; final boolean delayError; final Action onOverflow; - Subscription s; + Subscription upstream; volatile boolean cancelled; @@ -68,7 +68,7 @@ static final class BackpressureBufferSubscriber<T> extends BasicIntQueueSubscrip BackpressureBufferSubscriber(Subscriber<? super T> actual, int bufferSize, boolean unbounded, boolean delayError, Action onOverflow) { - this.actual = actual; + this.downstream = actual; this.onOverflow = onOverflow; this.delayError = delayError; @@ -85,9 +85,9 @@ static final class BackpressureBufferSubscriber<T> extends BasicIntQueueSubscrip @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -95,7 +95,7 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { if (!queue.offer(t)) { - s.cancel(); + upstream.cancel(); MissingBackpressureException ex = new MissingBackpressureException("Buffer is full"); try { onOverflow.run(); @@ -107,7 +107,7 @@ public void onNext(T t) { return; } if (outputFused) { - actual.onNext(null); + downstream.onNext(null); } else { drain(); } @@ -118,7 +118,7 @@ public void onError(Throwable t) { error = t; done = true; if (outputFused) { - actual.onError(t); + downstream.onError(t); } else { drain(); } @@ -128,7 +128,7 @@ public void onError(Throwable t) { public void onComplete() { done = true; if (outputFused) { - actual.onComplete(); + downstream.onComplete(); } else { drain(); } @@ -148,7 +148,7 @@ public void request(long n) { public void cancel() { if (!cancelled) { cancelled = true; - s.cancel(); + upstream.cancel(); if (getAndIncrement() == 0) { queue.clear(); @@ -160,7 +160,7 @@ void drain() { if (getAndIncrement() == 0) { int missed = 1; final SimplePlainQueue<T> q = queue; - final Subscriber<? super T> a = actual; + final Subscriber<? super T> a = downstream; for (;;) { if (checkTerminated(done, q.isEmpty(), a)) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferStrategy.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferStrategy.java index 7f3cdf8017..f11a520e7b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferStrategy.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferStrategy.java @@ -57,7 +57,7 @@ static final class OnBackpressureBufferStrategySubscriber<T> private static final long serialVersionUID = 3240706908776709697L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Action onOverflow; @@ -69,7 +69,7 @@ static final class OnBackpressureBufferStrategySubscriber<T> final Deque<T> deque; - Subscription s; + Subscription upstream; volatile boolean cancelled; @@ -78,7 +78,7 @@ static final class OnBackpressureBufferStrategySubscriber<T> OnBackpressureBufferStrategySubscriber(Subscriber<? super T> actual, Action onOverflow, BackpressureOverflowStrategy strategy, long bufferSize) { - this.actual = actual; + this.downstream = actual; this.onOverflow = onOverflow; this.strategy = strategy; this.bufferSize = bufferSize; @@ -88,10 +88,10 @@ static final class OnBackpressureBufferStrategySubscriber<T> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -134,12 +134,12 @@ public void onNext(T t) { onOverflow.run(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); } } } else if (callError) { - s.cancel(); + upstream.cancel(); onError(new MissingBackpressureException()); } else { drain(); @@ -174,7 +174,7 @@ public void request(long n) { @Override public void cancel() { cancelled = true; - s.cancel(); + upstream.cancel(); if (getAndIncrement() == 0) { clear(deque); @@ -194,7 +194,7 @@ void drain() { int missed = 1; Deque<T> dq = deque; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; for (;;) { long r = requested.get(); long e = 0L; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureDrop.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureDrop.java index eb633af079..df5f4a7e86 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureDrop.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureDrop.java @@ -53,23 +53,23 @@ static final class BackpressureDropSubscriber<T> private static final long serialVersionUID = -6246093802440953054L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Consumer<? super T> onDrop; - Subscription s; + Subscription upstream; boolean done; BackpressureDropSubscriber(Subscriber<? super T> actual, Consumer<? super T> onDrop) { - this.actual = actual; + this.downstream = actual; this.onDrop = onDrop; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -81,7 +81,7 @@ public void onNext(T t) { } long r = get(); if (r != 0L) { - actual.onNext(t); + downstream.onNext(t); BackpressureHelper.produced(this, 1); } else { try { @@ -101,7 +101,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -110,7 +110,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } @Override @@ -122,7 +122,7 @@ public void request(long n) { @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java index a40f92aefd..139e61d410 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java @@ -40,19 +40,19 @@ static final class BackpressureErrorSubscriber<T> extends AtomicLong implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = -3176480756392482682L; - final Subscriber<? super T> actual; - Subscription s; + final Subscriber<? super T> downstream; + Subscription upstream; boolean done; - BackpressureErrorSubscriber(Subscriber<? super T> actual) { - this.actual = actual; + BackpressureErrorSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -64,7 +64,7 @@ public void onNext(T t) { } long r = get(); if (r != 0L) { - actual.onNext(t); + downstream.onNext(t); BackpressureHelper.produced(this, 1); } else { onError(new MissingBackpressureException("could not emit value due to lack of requests")); @@ -78,7 +78,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -87,7 +87,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } @Override @@ -99,7 +99,7 @@ public void request(long n) { @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureLatest.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureLatest.java index 2cd36a6ef0..f981b738e6 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureLatest.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureLatest.java @@ -36,9 +36,9 @@ static final class BackpressureLatestSubscriber<T> extends AtomicInteger impleme private static final long serialVersionUID = 163080509307634843L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; - Subscription s; + Subscription upstream; volatile boolean done; Throwable error; @@ -49,15 +49,15 @@ static final class BackpressureLatestSubscriber<T> extends AtomicInteger impleme final AtomicReference<T> current = new AtomicReference<T>(); - BackpressureLatestSubscriber(Subscriber<? super T> actual) { - this.actual = actual; + BackpressureLatestSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -93,7 +93,7 @@ public void request(long n) { public void cancel() { if (!cancelled) { cancelled = true; - s.cancel(); + upstream.cancel(); if (getAndIncrement() == 0) { current.lazySet(null); @@ -105,7 +105,7 @@ void drain() { if (getAndIncrement() != 0) { return; } - final Subscriber<? super T> a = actual; + final Subscriber<? super T> a = downstream; int missed = 1; final AtomicLong r = requested; final AtomicReference<T> q = current; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java index 8a36aad3ce..4d5b86c880 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java @@ -45,7 +45,7 @@ static final class OnErrorNextSubscriber<T> implements FlowableSubscriber<T> { private static final long serialVersionUID = 4063763155303814625L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Function<? super Throwable, ? extends Publisher<? extends T>> nextSupplier; @@ -58,7 +58,7 @@ static final class OnErrorNextSubscriber<T> long produced; OnErrorNextSubscriber(Subscriber<? super T> actual, Function<? super Throwable, ? extends Publisher<? extends T>> nextSupplier, boolean allowFatal) { - this.actual = actual; + this.downstream = actual; this.nextSupplier = nextSupplier; this.allowFatal = allowFatal; } @@ -76,7 +76,7 @@ public void onNext(T t) { if (!once) { produced++; } - actual.onNext(t); + downstream.onNext(t); } @Override @@ -86,13 +86,13 @@ public void onError(Throwable t) { RxJavaPlugins.onError(t); return; } - actual.onError(t); + downstream.onError(t); return; } once = true; if (allowFatal && !(t instanceof Exception)) { - actual.onError(t); + downstream.onError(t); return; } @@ -102,7 +102,7 @@ public void onError(Throwable t) { p = ObjectHelper.requireNonNull(nextSupplier.apply(t), "The nextSupplier returned a null Publisher"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); return; } @@ -121,7 +121,7 @@ public void onComplete() { } done = true; once = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturn.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturn.java index 333aa1cb27..baf47d608a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturn.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturn.java @@ -47,7 +47,7 @@ static final class OnErrorReturnSubscriber<T> @Override public void onNext(T t) { produced++; - actual.onNext(t); + downstream.onNext(t); } @Override @@ -57,7 +57,7 @@ public void onError(Throwable t) { v = ObjectHelper.requireNonNull(valueSupplier.apply(t), "The valueSupplier returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(new CompositeException(t, ex)); + downstream.onError(new CompositeException(t, ex)); return; } complete(v); @@ -65,7 +65,7 @@ public void onError(Throwable t) { @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java index 079ef019c6..b68e4cf711 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java @@ -75,51 +75,51 @@ protected void subscribeActual(Subscriber<? super R> s) { } static final class OutputCanceller<R> implements FlowableSubscriber<R>, Subscription { - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final MulticastProcessor<?> processor; - Subscription s; + Subscription upstream; OutputCanceller(Subscriber<? super R> actual, MulticastProcessor<?> processor) { - this.actual = actual; + this.downstream = actual; this.processor = processor; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(R t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); processor.dispose(); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); processor.dispose(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); processor.dispose(); } } @@ -142,7 +142,7 @@ static final class MulticastProcessor<T> extends Flowable<T> implements Flowable final boolean delayError; - final AtomicReference<Subscription> s; + final AtomicReference<Subscription> upstream; volatile SimpleQueue<T> queue; @@ -159,13 +159,13 @@ static final class MulticastProcessor<T> extends Flowable<T> implements Flowable this.limit = prefetch - (prefetch >> 2); // request after 75% consumption this.delayError = delayError; this.wip = new AtomicInteger(); - this.s = new AtomicReference<Subscription>(); + this.upstream = new AtomicReference<Subscription>(); this.subscribers = new AtomicReference<MulticastSubscription<T>[]>(EMPTY); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this.s, s)) { + if (SubscriptionHelper.setOnce(this.upstream, s)) { if (s instanceof QueueSubscription) { @SuppressWarnings("unchecked") QueueSubscription<T> qs = (QueueSubscription<T>) s; @@ -194,7 +194,7 @@ public void onSubscribe(Subscription s) { @Override public void dispose() { - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); if (wip.getAndIncrement() == 0) { SimpleQueue<T> q = queue; if (q != null) { @@ -205,7 +205,7 @@ public void dispose() { @Override public boolean isDisposed() { - return SubscriptionHelper.isCancelled(s.get()); + return SubscriptionHelper.isCancelled(upstream.get()); } @Override @@ -214,7 +214,7 @@ public void onNext(T t) { return; } if (sourceMode == QueueSubscription.NONE && !queue.offer(t)) { - s.get().cancel(); + upstream.get().cancel(); onError(new MissingBackpressureException()); return; } @@ -372,7 +372,7 @@ void drain() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); errorAll(ex); return; } @@ -401,7 +401,7 @@ void drain() { if (msr != Long.MAX_VALUE) { ms.emitted++; } - ms.actual.onNext(v); + ms.downstream.onNext(v); } else { subscribersChange = true; } @@ -411,7 +411,7 @@ void drain() { if (canRequest && ++upstreamConsumed == localLimit) { upstreamConsumed = 0; - s.get().request(localLimit); + upstream.get().request(localLimit); } MulticastSubscription<T>[] freshArray = subs.get(); @@ -465,7 +465,7 @@ void drain() { void errorAll(Throwable ex) { for (MulticastSubscription<T> ms : subscribers.getAndSet(TERMINATED)) { if (ms.get() != Long.MIN_VALUE) { - ms.actual.onError(ex); + ms.downstream.onError(ex); } } } @@ -474,7 +474,7 @@ void errorAll(Throwable ex) { void completeAll() { for (MulticastSubscription<T> ms : subscribers.getAndSet(TERMINATED)) { if (ms.get() != Long.MIN_VALUE) { - ms.actual.onComplete(); + ms.downstream.onComplete(); } } } @@ -486,14 +486,14 @@ static final class MulticastSubscription<T> private static final long serialVersionUID = 8664815189257569791L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final MulticastProcessor<T> parent; long emitted; MulticastSubscription(Subscriber<? super T> actual, MulticastProcessor<T> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java index 71e50073b8..198721943b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java @@ -111,17 +111,17 @@ static final class RangeSubscription extends BaseRangeSubscription { private static final long serialVersionUID = 2587302975077663557L; - final Subscriber<? super Integer> actual; + final Subscriber<? super Integer> downstream; RangeSubscription(Subscriber<? super Integer> actual, int index, int end) { super(index, end); - this.actual = actual; + this.downstream = actual; } @Override void fastPath() { int f = end; - Subscriber<? super Integer> a = actual; + Subscriber<? super Integer> a = downstream; for (int i = index; i != f; i++) { if (cancelled) { @@ -140,7 +140,7 @@ void slowPath(long r) { long e = 0; int f = end; int i = index; - Subscriber<? super Integer> a = actual; + Subscriber<? super Integer> a = downstream; for (;;) { @@ -180,17 +180,17 @@ static final class RangeConditionalSubscription extends BaseRangeSubscription { private static final long serialVersionUID = 2587302975077663557L; - final ConditionalSubscriber<? super Integer> actual; + final ConditionalSubscriber<? super Integer> downstream; RangeConditionalSubscription(ConditionalSubscriber<? super Integer> actual, int index, int end) { super(index, end); - this.actual = actual; + this.downstream = actual; } @Override void fastPath() { int f = end; - ConditionalSubscriber<? super Integer> a = actual; + ConditionalSubscriber<? super Integer> a = downstream; for (int i = index; i != f; i++) { if (cancelled) { @@ -209,7 +209,7 @@ void slowPath(long r) { long e = 0; int f = end; int i = index; - ConditionalSubscriber<? super Integer> a = actual; + ConditionalSubscriber<? super Integer> a = downstream; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRangeLong.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRangeLong.java index e049feb815..96bc5cddb0 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRangeLong.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRangeLong.java @@ -112,17 +112,17 @@ static final class RangeSubscription extends BaseRangeSubscription { private static final long serialVersionUID = 2587302975077663557L; - final Subscriber<? super Long> actual; + final Subscriber<? super Long> downstream; RangeSubscription(Subscriber<? super Long> actual, long index, long end) { super(index, end); - this.actual = actual; + this.downstream = actual; } @Override void fastPath() { long f = end; - Subscriber<? super Long> a = actual; + Subscriber<? super Long> a = downstream; for (long i = index; i != f; i++) { if (cancelled) { @@ -141,7 +141,7 @@ void slowPath(long r) { long e = 0; long f = end; long i = index; - Subscriber<? super Long> a = actual; + Subscriber<? super Long> a = downstream; for (;;) { @@ -181,17 +181,17 @@ static final class RangeConditionalSubscription extends BaseRangeSubscription { private static final long serialVersionUID = 2587302975077663557L; - final ConditionalSubscriber<? super Long> actual; + final ConditionalSubscriber<? super Long> downstream; RangeConditionalSubscription(ConditionalSubscriber<? super Long> actual, long index, long end) { super(index, end); - this.actual = actual; + this.downstream = actual; } @Override void fastPath() { long f = end; - ConditionalSubscriber<? super Long> a = actual; + ConditionalSubscriber<? super Long> a = downstream; for (long i = index; i != f; i++) { if (cancelled) { @@ -210,7 +210,7 @@ void slowPath(long r) { long e = 0; long f = end; long i = index; - ConditionalSubscriber<? super Long> a = actual; + ConditionalSubscriber<? super Long> a = downstream; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduce.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduce.java index b83fffd4f6..67be1d18fd 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduce.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduce.java @@ -48,7 +48,7 @@ static final class ReduceSubscriber<T> extends DeferredScalarSubscription<T> imp final BiFunction<T, T, T> reducer; - Subscription s; + Subscription upstream; ReduceSubscriber(Subscriber<? super T> actual, BiFunction<T, T, T> reducer) { super(actual); @@ -57,10 +57,10 @@ static final class ReduceSubscriber<T> extends DeferredScalarSubscription<T> imp @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -68,7 +68,7 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { - if (s == SubscriptionHelper.CANCELLED) { + if (upstream == SubscriptionHelper.CANCELLED) { return; } @@ -80,7 +80,7 @@ public void onNext(T t) { value = ObjectHelper.requireNonNull(reducer.apply(v, t), "The reducer returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); } } @@ -88,34 +88,34 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - if (s == SubscriptionHelper.CANCELLED) { + if (upstream == SubscriptionHelper.CANCELLED) { RxJavaPlugins.onError(t); return; } - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override public void onComplete() { - if (s == SubscriptionHelper.CANCELLED) { + if (upstream == SubscriptionHelper.CANCELLED) { return; } - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; T v = value; if (v != null) { complete(v); } else { - actual.onComplete(); + downstream.onComplete(); } } @Override public void cancel() { super.cancel(); - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceMaybe.java index d6d4781033..7745c047a7 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceMaybe.java @@ -58,24 +58,24 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { } static final class ReduceSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final BiFunction<T, T, T> reducer; T value; - Subscription s; + Subscription upstream; boolean done; ReduceSubscriber(MaybeObserver<? super T> actual, BiFunction<T, T, T> reducer) { - this.actual = actual; + this.downstream = actual; this.reducer = reducer; } @Override public void dispose() { - s.cancel(); + upstream.cancel(); done = true; } @@ -86,10 +86,10 @@ public boolean isDisposed() { @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -108,7 +108,7 @@ public void onNext(T t) { value = ObjectHelper.requireNonNull(reducer.apply(v, t), "The reducer returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); } } @@ -121,7 +121,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -133,9 +133,9 @@ public void onComplete() { T v = value; if (v != null) { // value = null; - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceSeedSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceSeedSingle.java index 5201f1b396..bcd1042d48 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceSeedSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceSeedSingle.java @@ -51,26 +51,26 @@ protected void subscribeActual(SingleObserver<? super R> observer) { static final class ReduceSeedObserver<T, R> implements FlowableSubscriber<T>, Disposable { - final SingleObserver<? super R> actual; + final SingleObserver<? super R> downstream; final BiFunction<R, ? super T, R> reducer; R value; - Subscription s; + Subscription upstream; ReduceSeedObserver(SingleObserver<? super R> actual, BiFunction<R, ? super T, R> reducer, R value) { - this.actual = actual; + this.downstream = actual; this.value = value; this.reducer = reducer; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -84,7 +84,7 @@ public void onNext(T value) { this.value = ObjectHelper.requireNonNull(reducer.apply(v, value), "The reducer returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); } } @@ -94,8 +94,8 @@ public void onNext(T value) { public void onError(Throwable e) { if (value != null) { value = null; - s = SubscriptionHelper.CANCELLED; - actual.onError(e); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -106,20 +106,20 @@ public void onComplete() { R v = value; if (v != null) { value = null; - s = SubscriptionHelper.CANCELLED; - actual.onSuccess(v); + upstream = SubscriptionHelper.CANCELLED; + downstream.onSuccess(v); } } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java index c9f03fdf2c..deec615b20 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java @@ -174,7 +174,7 @@ static final class RefCountSubscriber<T> private static final long serialVersionUID = -7419642935409022375L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final FlowableRefCount<T> parent; @@ -183,21 +183,21 @@ static final class RefCountSubscriber<T> Subscription upstream; RefCountSubscriber(Subscriber<? super T> actual, FlowableRefCount<T> parent, RefConnection connection) { - this.actual = actual; + this.downstream = actual; this.parent = parent; this.connection = connection; } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { if (compareAndSet(false, true)) { parent.terminated(connection); - actual.onError(t); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -207,7 +207,7 @@ public void onError(Throwable t) { public void onComplete() { if (compareAndSet(false, true)) { parent.terminated(connection); - actual.onComplete(); + downstream.onComplete(); } } @@ -229,7 +229,7 @@ public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(upstream, s)) { this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java index a3f7e15d09..fe48ac17ea 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java @@ -40,7 +40,7 @@ static final class RepeatSubscriber<T> extends AtomicInteger implements Flowable private static final long serialVersionUID = -7098360935104053232L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final SubscriptionArbiter sa; final Publisher<? extends T> source; long remaining; @@ -48,7 +48,7 @@ static final class RepeatSubscriber<T> extends AtomicInteger implements Flowable long produced; RepeatSubscriber(Subscriber<? super T> actual, long count, SubscriptionArbiter sa, Publisher<? extends T> source) { - this.actual = actual; + this.downstream = actual; this.sa = sa; this.source = source; this.remaining = count; @@ -62,11 +62,11 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { produced++; - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override @@ -78,7 +78,7 @@ public void onComplete() { if (r != 0L) { subscribeNext(); } else { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java index 250502c8b4..e2dbd532e8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java @@ -42,7 +42,7 @@ static final class RepeatSubscriber<T> extends AtomicInteger implements Flowable private static final long serialVersionUID = -7098360935104053232L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final SubscriptionArbiter sa; final Publisher<? extends T> source; final BooleanSupplier stop; @@ -50,7 +50,7 @@ static final class RepeatSubscriber<T> extends AtomicInteger implements Flowable long produced; RepeatSubscriber(Subscriber<? super T> actual, BooleanSupplier until, SubscriptionArbiter sa, Publisher<? extends T> source) { - this.actual = actual; + this.downstream = actual; this.sa = sa; this.source = source; this.stop = until; @@ -64,11 +64,11 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { produced++; - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override @@ -78,11 +78,11 @@ public void onComplete() { b = stop.getAsBoolean(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } if (b) { - actual.onComplete(); + downstream.onComplete(); } else { subscribeNext(); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java index a95433a74d..ce137d4f52 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java @@ -68,12 +68,11 @@ static final class WhenReceiver<T, U> extends AtomicInteger implements FlowableSubscriber<Object>, Subscription { - private static final long serialVersionUID = 2827772011130406689L; final Publisher<T> source; - final AtomicReference<Subscription> subscription; + final AtomicReference<Subscription> upstream; final AtomicLong requested; @@ -81,20 +80,20 @@ static final class WhenReceiver<T, U> WhenReceiver(Publisher<T> source) { this.source = source; - this.subscription = new AtomicReference<Subscription>(); + this.upstream = new AtomicReference<Subscription>(); this.requested = new AtomicLong(); } @Override public void onSubscribe(Subscription s) { - SubscriptionHelper.deferredSetOnce(subscription, requested, s); + SubscriptionHelper.deferredSetOnce(upstream, requested, s); } @Override public void onNext(Object t) { if (getAndIncrement() == 0) { for (;;) { - if (SubscriptionHelper.isCancelled(subscription.get())) { + if (SubscriptionHelper.isCancelled(upstream.get())) { return; } @@ -110,23 +109,23 @@ public void onNext(Object t) { @Override public void onError(Throwable t) { subscriber.cancel(); - subscriber.actual.onError(t); + subscriber.downstream.onError(t); } @Override public void onComplete() { subscriber.cancel(); - subscriber.actual.onComplete(); + subscriber.downstream.onComplete(); } @Override public void request(long n) { - SubscriptionHelper.deferredRequest(subscription, requested, n); + SubscriptionHelper.deferredRequest(upstream, requested, n); } @Override public void cancel() { - SubscriptionHelper.cancel(subscription); + SubscriptionHelper.cancel(upstream); } } @@ -134,7 +133,7 @@ abstract static class WhenSourceSubscriber<T, U> extends SubscriptionArbiter imp private static final long serialVersionUID = -5604623027276966720L; - protected final Subscriber<? super T> actual; + protected final Subscriber<? super T> downstream; protected final FlowableProcessor<U> processor; @@ -144,7 +143,7 @@ abstract static class WhenSourceSubscriber<T, U> extends SubscriptionArbiter imp WhenSourceSubscriber(Subscriber<? super T> actual, FlowableProcessor<U> processor, Subscription receiver) { - this.actual = actual; + this.downstream = actual; this.processor = processor; this.receiver = receiver; } @@ -157,7 +156,7 @@ public final void onSubscribe(Subscription s) { @Override public final void onNext(T t) { produced++; - actual.onNext(t); + downstream.onNext(t); } protected final void again(U signal) { @@ -190,7 +189,7 @@ static final class RepeatWhenSubscriber<T> extends WhenSourceSubscriber<T, Objec @Override public void onError(Throwable t) { receiver.cancel(); - actual.onError(t); + downstream.onError(t); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java index cf94105249..a049d76d51 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java @@ -44,7 +44,7 @@ static final class RetryBiSubscriber<T> extends AtomicInteger implements Flowabl private static final long serialVersionUID = -7098360935104053232L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final SubscriptionArbiter sa; final Publisher<? extends T> source; final BiPredicate<? super Integer, ? super Throwable> predicate; @@ -54,7 +54,7 @@ static final class RetryBiSubscriber<T> extends AtomicInteger implements Flowabl RetryBiSubscriber(Subscriber<? super T> actual, BiPredicate<? super Integer, ? super Throwable> predicate, SubscriptionArbiter sa, Publisher<? extends T> source) { - this.actual = actual; + this.downstream = actual; this.sa = sa; this.source = source; this.predicate = predicate; @@ -68,7 +68,7 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { produced++; - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { @@ -77,11 +77,11 @@ public void onError(Throwable t) { b = predicate.test(++retries, t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); return; } if (!b) { - actual.onError(t); + downstream.onError(t); return; } subscribeNext(); @@ -89,7 +89,7 @@ public void onError(Throwable t) { @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } /** diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java index 11c4732274..b29b97b70a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java @@ -46,7 +46,7 @@ static final class RetrySubscriber<T> extends AtomicInteger implements FlowableS private static final long serialVersionUID = -7098360935104053232L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final SubscriptionArbiter sa; final Publisher<? extends T> source; final Predicate<? super Throwable> predicate; @@ -56,7 +56,7 @@ static final class RetrySubscriber<T> extends AtomicInteger implements FlowableS RetrySubscriber(Subscriber<? super T> actual, long count, Predicate<? super Throwable> predicate, SubscriptionArbiter sa, Publisher<? extends T> source) { - this.actual = actual; + this.downstream = actual; this.sa = sa; this.source = source; this.predicate = predicate; @@ -71,7 +71,7 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { produced++; - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { @@ -80,18 +80,18 @@ public void onError(Throwable t) { remaining = r - 1; } if (r == 0) { - actual.onError(t); + downstream.onError(t); } else { boolean b; try { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); return; } if (!b) { - actual.onError(t); + downstream.onError(t); return; } subscribeNext(); @@ -100,7 +100,7 @@ public void onError(Throwable t) { @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } /** diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryWhen.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryWhen.java index 27785e5075..4cf535cd90 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryWhen.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryWhen.java @@ -80,7 +80,7 @@ public void onError(Throwable t) { @Override public void onComplete() { receiver.cancel(); - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java index a75f4c1e05..55439eee69 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java @@ -49,25 +49,25 @@ abstract static class SamplePublisherSubscriber<T> extends AtomicReference<T> im private static final long serialVersionUID = -3517602651313910099L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Publisher<?> sampler; final AtomicLong requested = new AtomicLong(); final AtomicReference<Subscription> other = new AtomicReference<Subscription>(); - Subscription s; + Subscription upstream; SamplePublisherSubscriber(Subscriber<? super T> actual, Publisher<?> other) { - this.actual = actual; + this.downstream = actual; this.sampler = other; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); if (other.get() == null) { sampler.subscribe(new SamplerSubscriber<T>(this)); s.request(Long.MAX_VALUE); @@ -84,7 +84,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { SubscriptionHelper.cancel(other); - actual.onError(t); + downstream.onError(t); } @Override @@ -107,16 +107,16 @@ public void request(long n) { @Override public void cancel() { SubscriptionHelper.cancel(other); - s.cancel(); + upstream.cancel(); } public void error(Throwable e) { - s.cancel(); - actual.onError(e); + upstream.cancel(); + downstream.onError(e); } public void complete() { - s.cancel(); + upstream.cancel(); completeOther(); } @@ -125,11 +125,11 @@ void emit() { if (value != null) { long r = requested.get(); if (r != 0L) { - actual.onNext(value); + downstream.onNext(value); BackpressureHelper.produced(requested, 1); } else { cancel(); - actual.onError(new MissingBackpressureException("Couldn't emit value due to lack of requests!")); + downstream.onError(new MissingBackpressureException("Couldn't emit value due to lack of requests!")); } } } @@ -179,12 +179,12 @@ static final class SampleMainNoLast<T> extends SamplePublisherSubscriber<T> { @Override void completeMain() { - actual.onComplete(); + downstream.onComplete(); } @Override void completeOther() { - actual.onComplete(); + downstream.onComplete(); } @Override @@ -211,7 +211,7 @@ void completeMain() { done = true; if (wip.getAndIncrement() == 0) { emit(); - actual.onComplete(); + downstream.onComplete(); } } @@ -220,7 +220,7 @@ void completeOther() { done = true; if (wip.getAndIncrement() == 0) { emit(); - actual.onComplete(); + downstream.onComplete(); } } @@ -231,7 +231,7 @@ void run() { boolean d = done; emit(); if (d) { - actual.onComplete(); + downstream.onComplete(); return; } } while (wip.decrementAndGet() != 0); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSampleTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSampleTimed.java index 4308b99165..47ed31f052 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSampleTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSampleTimed.java @@ -54,7 +54,7 @@ abstract static class SampleTimedSubscriber<T> extends AtomicReference<T> implem private static final long serialVersionUID = -3517602651313910099L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final long period; final TimeUnit unit; final Scheduler scheduler; @@ -63,10 +63,10 @@ abstract static class SampleTimedSubscriber<T> extends AtomicReference<T> implem final SequentialDisposable timer = new SequentialDisposable(); - Subscription s; + Subscription upstream; SampleTimedSubscriber(Subscriber<? super T> actual, long period, TimeUnit unit, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.period = period; this.unit = unit; this.scheduler = scheduler; @@ -74,9 +74,9 @@ abstract static class SampleTimedSubscriber<T> extends AtomicReference<T> implem @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); timer.replace(scheduler.schedulePeriodicallyDirect(this, period, period, unit)); s.request(Long.MAX_VALUE); } @@ -90,7 +90,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { cancelTimer(); - actual.onError(t); + downstream.onError(t); } @Override @@ -113,7 +113,7 @@ public void request(long n) { @Override public void cancel() { cancelTimer(); - s.cancel(); + upstream.cancel(); } void emit() { @@ -121,11 +121,11 @@ void emit() { if (value != null) { long r = requested.get(); if (r != 0L) { - actual.onNext(value); + downstream.onNext(value); BackpressureHelper.produced(requested, 1); } else { cancel(); - actual.onError(new MissingBackpressureException("Couldn't emit value due to lack of requests!")); + downstream.onError(new MissingBackpressureException("Couldn't emit value due to lack of requests!")); } } } @@ -143,7 +143,7 @@ static final class SampleTimedNoLast<T> extends SampleTimedSubscriber<T> { @Override void complete() { - actual.onComplete(); + downstream.onComplete(); } @Override @@ -167,7 +167,7 @@ static final class SampleTimedEmitLast<T> extends SampleTimedSubscriber<T> { void complete() { emit(); if (wip.decrementAndGet() == 0) { - actual.onComplete(); + downstream.onComplete(); } } @@ -176,7 +176,7 @@ public void run() { if (wip.incrementAndGet() == 2) { emit(); if (wip.decrementAndGet() == 0) { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableScan.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableScan.java index 91bb5cc274..0c5aca6bf6 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableScan.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableScan.java @@ -35,25 +35,25 @@ protected void subscribeActual(Subscriber<? super T> s) { } static final class ScanSubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final BiFunction<T, T, T> accumulator; - Subscription s; + Subscription upstream; T value; boolean done; ScanSubscriber(Subscriber<? super T> actual, BiFunction<T, T, T> accumulator) { - this.actual = actual; + this.downstream = actual; this.accumulator = accumulator; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -62,7 +62,7 @@ public void onNext(T t) { if (done) { return; } - final Subscriber<? super T> a = actual; + final Subscriber<? super T> a = downstream; T v = value; if (v == null) { value = t; @@ -74,7 +74,7 @@ public void onNext(T t) { u = ObjectHelper.requireNonNull(accumulator.apply(v, t), "The value returned by the accumulator is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); onError(e); return; } @@ -91,7 +91,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -100,17 +100,17 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableScanSeed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableScanSeed.java index 19b4f3fc68..6586b55253 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableScanSeed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableScanSeed.java @@ -57,7 +57,7 @@ static final class ScanSeedSubscriber<T, R> implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = -1776795561228106469L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final BiFunction<R, ? super T, R> accumulator; @@ -74,14 +74,14 @@ static final class ScanSeedSubscriber<T, R> volatile boolean done; Throwable error; - Subscription s; + Subscription upstream; R value; int consumed; ScanSeedSubscriber(Subscriber<? super R> actual, BiFunction<R, ? super T, R> accumulator, R value, int prefetch) { - this.actual = actual; + this.downstream = actual; this.accumulator = accumulator; this.value = value; this.prefetch = prefetch; @@ -93,10 +93,10 @@ static final class ScanSeedSubscriber<T, R> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(prefetch - 1); } @@ -113,7 +113,7 @@ public void onNext(T t) { v = ObjectHelper.requireNonNull(accumulator.apply(v, t), "The accumulator returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); onError(ex); return; } @@ -146,7 +146,7 @@ public void onComplete() { @Override public void cancel() { cancelled = true; - s.cancel(); + upstream.cancel(); if (getAndIncrement() == 0) { queue.clear(); } @@ -166,7 +166,7 @@ void drain() { } int missed = 1; - Subscriber<? super R> a = actual; + Subscriber<? super R> a = downstream; SimplePlainQueue<R> q = queue; int lim = limit; int c = consumed; @@ -209,7 +209,7 @@ void drain() { e++; if (++c == lim) { c = 0; - s.request(lim); + upstream.request(lim); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqual.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqual.java index be145c3499..fd10367248 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqual.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqual.java @@ -132,7 +132,7 @@ public void drain() { if (ex != null) { cancelAndClear(); - actual.onError(error.terminate()); + downstream.onError(error.terminate()); return; } @@ -146,7 +146,7 @@ public void drain() { Exceptions.throwIfFatal(exc); cancelAndClear(); error.addThrowable(exc); - actual.onError(error.terminate()); + downstream.onError(error.terminate()); return; } v1 = a; @@ -162,7 +162,7 @@ public void drain() { Exceptions.throwIfFatal(exc); cancelAndClear(); error.addThrowable(exc); - actual.onError(error.terminate()); + downstream.onError(error.terminate()); return; } v2 = b; @@ -192,7 +192,7 @@ public void drain() { Exceptions.throwIfFatal(exc); cancelAndClear(); error.addThrowable(exc); - actual.onError(error.terminate()); + downstream.onError(error.terminate()); return; } @@ -220,7 +220,7 @@ public void drain() { if (ex != null) { cancelAndClear(); - actual.onError(error.terminate()); + downstream.onError(error.terminate()); return; } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java index cd0d958c49..c37bd0bac9 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java @@ -59,7 +59,7 @@ static final class EqualCoordinator<T> private static final long serialVersionUID = -6178010334400373240L; - final SingleObserver<? super Boolean> actual; + final SingleObserver<? super Boolean> downstream; final BiPredicate<? super T, ? super T> comparer; @@ -74,7 +74,7 @@ static final class EqualCoordinator<T> T v2; EqualCoordinator(SingleObserver<? super Boolean> actual, int prefetch, BiPredicate<? super T, ? super T> comparer) { - this.actual = actual; + this.downstream = actual; this.comparer = comparer; this.first = new EqualSubscriber<T>(this, prefetch); this.second = new EqualSubscriber<T>(this, prefetch); @@ -132,7 +132,7 @@ public void drain() { if (ex != null) { cancelAndClear(); - actual.onError(error.terminate()); + downstream.onError(error.terminate()); return; } @@ -146,7 +146,7 @@ public void drain() { Exceptions.throwIfFatal(exc); cancelAndClear(); error.addThrowable(exc); - actual.onError(error.terminate()); + downstream.onError(error.terminate()); return; } v1 = a; @@ -162,7 +162,7 @@ public void drain() { Exceptions.throwIfFatal(exc); cancelAndClear(); error.addThrowable(exc); - actual.onError(error.terminate()); + downstream.onError(error.terminate()); return; } v2 = b; @@ -171,12 +171,12 @@ public void drain() { boolean e2 = b == null; if (d1 && d2 && e1 && e2) { - actual.onSuccess(true); + downstream.onSuccess(true); return; } if ((d1 && d2) && (e1 != e2)) { cancelAndClear(); - actual.onSuccess(false); + downstream.onSuccess(false); return; } @@ -192,13 +192,13 @@ public void drain() { Exceptions.throwIfFatal(exc); cancelAndClear(); error.addThrowable(exc); - actual.onError(error.terminate()); + downstream.onError(error.terminate()); return; } if (!c) { cancelAndClear(); - actual.onSuccess(false); + downstream.onSuccess(false); return; } @@ -220,7 +220,7 @@ public void drain() { if (ex != null) { cancelAndClear(); - actual.onError(error.terminate()); + downstream.onError(error.terminate()); return; } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingle.java index 70d29e7ad5..7b4ace56f0 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingle.java @@ -47,7 +47,7 @@ static final class SingleElementSubscriber<T> extends DeferredScalarSubscription final boolean failOnEmpty; - Subscription s; + Subscription upstream; boolean done; @@ -59,9 +59,9 @@ static final class SingleElementSubscriber<T> extends DeferredScalarSubscription @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -73,8 +73,8 @@ public void onNext(T t) { } if (value != null) { done = true; - s.cancel(); - actual.onError(new IllegalArgumentException("Sequence contains more than one element!")); + upstream.cancel(); + downstream.onError(new IllegalArgumentException("Sequence contains more than one element!")); return; } value = t; @@ -87,7 +87,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -103,9 +103,9 @@ public void onComplete() { } if (v == null) { if (failOnEmpty) { - actual.onError(new NoSuchElementException()); + downstream.onError(new NoSuchElementException()); } else { - actual.onComplete(); + downstream.onComplete(); } } else { complete(v); @@ -115,7 +115,7 @@ public void onComplete() { @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java index 4fcc466df0..14be53915a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java @@ -42,23 +42,23 @@ public Flowable<T> fuseToFlowable() { static final class SingleElementSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - Subscription s; + Subscription upstream; boolean done; T value; - SingleElementSubscriber(MaybeObserver<? super T> actual) { - this.actual = actual; + SingleElementSubscriber(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -70,9 +70,9 @@ public void onNext(T t) { } if (value != null) { done = true; - s.cancel(); - s = SubscriptionHelper.CANCELLED; - actual.onError(new IllegalArgumentException("Sequence contains more than one element!")); + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(new IllegalArgumentException("Sequence contains more than one element!")); return; } value = t; @@ -85,8 +85,8 @@ public void onError(Throwable t) { return; } done = true; - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override @@ -95,25 +95,25 @@ public void onComplete() { return; } done = true; - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; T v = value; value = null; if (v == null) { - actual.onComplete(); + downstream.onComplete(); } else { - actual.onSuccess(v); + downstream.onSuccess(v); } } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java index 3ee049ecf2..cb4bce53c5 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleSingle.java @@ -47,26 +47,26 @@ public Flowable<T> fuseToFlowable() { static final class SingleElementSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final T defaultValue; - Subscription s; + Subscription upstream; boolean done; T value; SingleElementSubscriber(SingleObserver<? super T> actual, T defaultValue) { - this.actual = actual; + this.downstream = actual; this.defaultValue = defaultValue; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -78,9 +78,9 @@ public void onNext(T t) { } if (value != null) { done = true; - s.cancel(); - s = SubscriptionHelper.CANCELLED; - actual.onError(new IllegalArgumentException("Sequence contains more than one element!")); + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(new IllegalArgumentException("Sequence contains more than one element!")); return; } value = t; @@ -93,8 +93,8 @@ public void onError(Throwable t) { return; } done = true; - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override @@ -103,7 +103,7 @@ public void onComplete() { return; } done = true; - s = SubscriptionHelper.CANCELLED; + upstream = SubscriptionHelper.CANCELLED; T v = value; value = null; if (v == null) { @@ -111,21 +111,21 @@ public void onComplete() { } if (v != null) { - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onError(new NoSuchElementException()); + downstream.onError(new NoSuchElementException()); } } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkip.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkip.java index 6957ff66c3..58a0446b98 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkip.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkip.java @@ -31,22 +31,22 @@ protected void subscribeActual(Subscriber<? super T> s) { } static final class SkipSubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; long remaining; - Subscription s; + Subscription upstream; SkipSubscriber(Subscriber<? super T> actual, long n) { - this.actual = actual; + this.downstream = actual; this.remaining = n; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { + if (SubscriptionHelper.validate(this.upstream, s)) { long n = remaining; - this.s = s; - actual.onSubscribe(this); + this.upstream = s; + downstream.onSubscribe(this); s.request(n); } } @@ -56,28 +56,28 @@ public void onNext(T t) { if (remaining != 0L) { remaining--; } else { - actual.onNext(t); + downstream.onNext(t); } } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipLast.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipLast.java index a0ed02a567..bbda349db2 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipLast.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipLast.java @@ -36,53 +36,53 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class SkipLastSubscriber<T> extends ArrayDeque<T> implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = -3807491841935125653L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final int skip; - Subscription s; + Subscription upstream; SkipLastSubscriber(Subscriber<? super T> actual, int skip) { super(skip); - this.actual = actual; + this.downstream = actual; this.skip = skip; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { if (skip == size()) { - actual.onNext(poll()); + downstream.onNext(poll()); } else { - s.request(1); + upstream.request(1); } offer(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimed.java index 5cad43dd87..0ffd249f15 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimed.java @@ -47,14 +47,14 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class SkipLastTimedSubscriber<T> extends AtomicInteger implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = -5677354903406201275L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final long time; final TimeUnit unit; final Scheduler scheduler; final SpscLinkedArrayQueue<Object> queue; final boolean delayError; - Subscription s; + Subscription upstream; final AtomicLong requested = new AtomicLong(); @@ -64,7 +64,7 @@ static final class SkipLastTimedSubscriber<T> extends AtomicInteger implements F Throwable error; SkipLastTimedSubscriber(Subscriber<? super T> actual, long time, TimeUnit unit, Scheduler scheduler, int bufferSize, boolean delayError) { - this.actual = actual; + this.downstream = actual; this.time = time; this.unit = unit; this.scheduler = scheduler; @@ -74,9 +74,9 @@ static final class SkipLastTimedSubscriber<T> extends AtomicInteger implements F @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -115,7 +115,7 @@ public void request(long n) { public void cancel() { if (!cancelled) { cancelled = true; - s.cancel(); + upstream.cancel(); if (getAndIncrement() == 0) { queue.clear(); @@ -130,7 +130,7 @@ void drain() { int missed = 1; - final Subscriber<? super T> a = actual; + final Subscriber<? super T> a = downstream; final SpscLinkedArrayQueue<Object> q = queue; final boolean delayError = this.delayError; final TimeUnit unit = this.unit; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipUntil.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipUntil.java index 0f980ac883..0324c720a2 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipUntil.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipUntil.java @@ -43,9 +43,9 @@ static final class SkipUntilMainSubscriber<T> extends AtomicInteger implements ConditionalSubscriber<T>, Subscription { private static final long serialVersionUID = -6270983465606289181L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; - final AtomicReference<Subscription> s; + final AtomicReference<Subscription> upstream; final AtomicLong requested; @@ -55,9 +55,9 @@ static final class SkipUntilMainSubscriber<T> extends AtomicInteger volatile boolean gate; - SkipUntilMainSubscriber(Subscriber<? super T> actual) { - this.actual = actual; - this.s = new AtomicReference<Subscription>(); + SkipUntilMainSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; + this.upstream = new AtomicReference<Subscription>(); this.requested = new AtomicLong(); this.other = new OtherSubscriber(); this.error = new AtomicThrowable(); @@ -65,20 +65,20 @@ static final class SkipUntilMainSubscriber<T> extends AtomicInteger @Override public void onSubscribe(Subscription s) { - SubscriptionHelper.deferredSetOnce(this.s, requested, s); + SubscriptionHelper.deferredSetOnce(this.upstream, requested, s); } @Override public void onNext(T t) { if (!tryOnNext(t)) { - s.get().request(1); + upstream.get().request(1); } } @Override public boolean tryOnNext(T t) { if (gate) { - HalfSerializer.onNext(actual, t, this, error); + HalfSerializer.onNext(downstream, t, this, error); return true; } return false; @@ -87,23 +87,23 @@ public boolean tryOnNext(T t) { @Override public void onError(Throwable t) { SubscriptionHelper.cancel(other); - HalfSerializer.onError(actual, t, SkipUntilMainSubscriber.this, error); + HalfSerializer.onError(downstream, t, SkipUntilMainSubscriber.this, error); } @Override public void onComplete() { SubscriptionHelper.cancel(other); - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } @Override public void request(long n) { - SubscriptionHelper.deferredRequest(s, requested, n); + SubscriptionHelper.deferredRequest(upstream, requested, n); } @Override public void cancel() { - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); SubscriptionHelper.cancel(other); } @@ -125,8 +125,8 @@ public void onNext(Object t) { @Override public void onError(Throwable t) { - SubscriptionHelper.cancel(s); - HalfSerializer.onError(actual, t, SkipUntilMainSubscriber.this, error); + SubscriptionHelper.cancel(upstream); + HalfSerializer.onError(downstream, t, SkipUntilMainSubscriber.this, error); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipWhile.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipWhile.java index 3a2ba35df3..8123be6782 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipWhile.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipWhile.java @@ -33,64 +33,64 @@ protected void subscribeActual(Subscriber<? super T> s) { } static final class SkipWhileSubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Predicate<? super T> predicate; - Subscription s; + Subscription upstream; boolean notSkipping; SkipWhileSubscriber(Subscriber<? super T> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { if (notSkipping) { - actual.onNext(t); + downstream.onNext(t); } else { boolean b; try { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); - actual.onError(e); + upstream.cancel(); + downstream.onError(e); return; } if (b) { - s.request(1); + upstream.request(1); } else { notSkipping = true; - actual.onNext(t); + downstream.onNext(t); } } } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOn.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOn.java index 1bb3f1e829..f603aca819 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOn.java @@ -53,11 +53,11 @@ static final class SubscribeOnSubscriber<T> extends AtomicReference<Thread> private static final long serialVersionUID = 8094547886072529208L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Scheduler.Worker worker; - final AtomicReference<Subscription> s; + final AtomicReference<Subscription> upstream; final AtomicLong requested; @@ -66,10 +66,10 @@ static final class SubscribeOnSubscriber<T> extends AtomicReference<Thread> Publisher<T> source; SubscribeOnSubscriber(Subscriber<? super T> actual, Scheduler.Worker worker, Publisher<T> source, boolean requestOn) { - this.actual = actual; + this.downstream = actual; this.worker = worker; this.source = source; - this.s = new AtomicReference<Subscription>(); + this.upstream = new AtomicReference<Subscription>(); this.requested = new AtomicLong(); this.nonScheduledRequests = !requestOn; } @@ -84,7 +84,7 @@ public void run() { @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this.s, s)) { + if (SubscriptionHelper.setOnce(this.upstream, s)) { long r = requested.getAndSet(0L); if (r != 0L) { requestUpstream(r, s); @@ -94,30 +94,30 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); worker.dispose(); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); worker.dispose(); } @Override public void request(final long n) { if (SubscriptionHelper.validate(n)) { - Subscription s = this.s.get(); + Subscription s = this.upstream.get(); if (s != null) { requestUpstream(n, s); } else { BackpressureHelper.add(requested, n); - s = this.s.get(); + s = this.upstream.get(); if (s != null) { long r = requested.getAndSet(0L); if (r != 0L) { @@ -138,22 +138,22 @@ void requestUpstream(final long n, final Subscription s) { @Override public void cancel() { - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); worker.dispose(); } static final class Request implements Runnable { - private final Subscription s; - private final long n; + final Subscription upstream; + final long n; Request(Subscription s, long n) { - this.s = s; + this.upstream = s; this.n = n; } @Override public void run() { - s.request(n); + upstream.request(n); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmpty.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmpty.java index 33f215bf3d..f9fc7ebc4c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmpty.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmpty.java @@ -33,14 +33,14 @@ protected void subscribeActual(Subscriber<? super T> s) { } static final class SwitchIfEmptySubscriber<T> implements FlowableSubscriber<T> { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Publisher<? extends T> other; final SubscriptionArbiter arbiter; boolean empty; SwitchIfEmptySubscriber(Subscriber<? super T> actual, Publisher<? extends T> other) { - this.actual = actual; + this.downstream = actual; this.other = other; this.empty = true; this.arbiter = new SubscriptionArbiter(); @@ -56,12 +56,12 @@ public void onNext(T t) { if (empty) { empty = false; } - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override @@ -70,7 +70,7 @@ public void onComplete() { empty = false; other.subscribe(this); } else { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java index b7cbe1d3fc..0b00c03c9a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java @@ -52,7 +52,7 @@ protected void subscribeActual(Subscriber<? super R> s) { static final class SwitchMapSubscriber<T, R> extends AtomicInteger implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = -3491074160481096299L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final Function<? super T, ? extends Publisher<? extends R>> mapper; final int bufferSize; final boolean delayErrors; @@ -63,7 +63,7 @@ static final class SwitchMapSubscriber<T, R> extends AtomicInteger implements Fl volatile boolean cancelled; - Subscription s; + Subscription upstream; final AtomicReference<SwitchMapInnerSubscriber<T, R>> active = new AtomicReference<SwitchMapInnerSubscriber<T, R>>(); @@ -80,7 +80,7 @@ static final class SwitchMapSubscriber<T, R> extends AtomicInteger implements Fl SwitchMapSubscriber(Subscriber<? super R> actual, Function<? super T, ? extends Publisher<? extends R>> mapper, int bufferSize, boolean delayErrors) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.bufferSize = bufferSize; this.delayErrors = delayErrors; @@ -89,9 +89,9 @@ static final class SwitchMapSubscriber<T, R> extends AtomicInteger implements Fl @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -114,7 +114,7 @@ public void onNext(T t) { p = ObjectHelper.requireNonNull(mapper.apply(t), "The publisher returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); onError(e); return; } @@ -160,7 +160,7 @@ public void request(long n) { if (SubscriptionHelper.validate(n)) { BackpressureHelper.add(requested, n); if (unique == 0L) { - s.request(Long.MAX_VALUE); + upstream.request(Long.MAX_VALUE); } else { drain(); } @@ -171,7 +171,7 @@ public void request(long n) { public void cancel() { if (!cancelled) { cancelled = true; - s.cancel(); + upstream.cancel(); disposeInner(); } @@ -193,7 +193,7 @@ void drain() { return; } - final Subscriber<? super R> a = actual; + final Subscriber<? super R> a = downstream; int missing = 1; @@ -398,7 +398,7 @@ public void onError(Throwable t) { SwitchMapSubscriber<T, R> p = parent; if (index == p.unique && p.error.addThrowable(t)) { if (!p.delayErrors) { - p.s.cancel(); + p.upstream.cancel(); } done = true; p.drain(); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java index e15abaef84..badf1d8146 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java @@ -36,26 +36,32 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class TakeSubscriber<T> extends AtomicBoolean implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = -5636543848937116287L; - boolean done; - Subscription subscription; - final Subscriber<? super T> actual; + + final Subscriber<? super T> downstream; + final long limit; + + boolean done; + + Subscription upstream; + long remaining; + TakeSubscriber(Subscriber<? super T> actual, long limit) { - this.actual = actual; + this.downstream = actual; this.limit = limit; this.remaining = limit; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.subscription, s)) { - subscription = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + upstream = s; if (limit == 0L) { s.cancel(); done = true; - EmptySubscription.complete(actual); + EmptySubscription.complete(downstream); } else { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } } @@ -63,9 +69,9 @@ public void onSubscribe(Subscription s) { public void onNext(T t) { if (!done && remaining-- > 0) { boolean stop = remaining == 0; - actual.onNext(t); + downstream.onNext(t); if (stop) { - subscription.cancel(); + upstream.cancel(); onComplete(); } } @@ -74,8 +80,8 @@ public void onNext(T t) { public void onError(Throwable t) { if (!done) { done = true; - subscription.cancel(); - actual.onError(t); + upstream.cancel(); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -84,7 +90,7 @@ public void onError(Throwable t) { public void onComplete() { if (!done) { done = true; - actual.onComplete(); + downstream.onComplete(); } } @Override @@ -94,15 +100,15 @@ public void request(long n) { } if (!get() && compareAndSet(false, true)) { if (n >= limit) { - subscription.request(Long.MAX_VALUE); + upstream.request(Long.MAX_VALUE); return; } } - subscription.request(n); + upstream.request(n); } @Override public void cancel() { - subscription.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLast.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLast.java index 4ff36f5c56..60318d0b08 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLast.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLast.java @@ -38,10 +38,10 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class TakeLastSubscriber<T> extends ArrayDeque<T> implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = 7240042530241604978L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final int count; - Subscription s; + Subscription upstream; volatile boolean done; volatile boolean cancelled; @@ -50,15 +50,15 @@ static final class TakeLastSubscriber<T> extends ArrayDeque<T> implements Flowab final AtomicInteger wip = new AtomicInteger(); TakeLastSubscriber(Subscriber<? super T> actual, int count) { - this.actual = actual; + this.downstream = actual; this.count = count; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -73,7 +73,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override @@ -93,12 +93,12 @@ public void request(long n) { @Override public void cancel() { cancelled = true; - s.cancel(); + upstream.cancel(); } void drain() { if (wip.getAndIncrement() == 0) { - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; long r = requested.get(); do { if (cancelled) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOne.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOne.java index 1372bd874e..570bf3c823 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOne.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOne.java @@ -33,17 +33,17 @@ static final class TakeLastOneSubscriber<T> extends DeferredScalarSubscription<T private static final long serialVersionUID = -5467847744262967226L; - Subscription s; + Subscription upstream; - TakeLastOneSubscriber(Subscriber<? super T> actual) { - super(actual); + TakeLastOneSubscriber(Subscriber<? super T> downstream) { + super(downstream); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -56,7 +56,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { value = null; - actual.onError(t); + downstream.onError(t); } @Override @@ -65,14 +65,14 @@ public void onComplete() { if (v != null) { complete(v); } else { - actual.onComplete(); + downstream.onComplete(); } } @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimed.java index b139d31995..b48cdddc0b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimed.java @@ -51,7 +51,7 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class TakeLastTimedSubscriber<T> extends AtomicInteger implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = -5677354903406201275L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final long count; final long time; final TimeUnit unit; @@ -59,7 +59,7 @@ static final class TakeLastTimedSubscriber<T> extends AtomicInteger implements F final SpscLinkedArrayQueue<Object> queue; final boolean delayError; - Subscription s; + Subscription upstream; final AtomicLong requested = new AtomicLong(); @@ -69,7 +69,7 @@ static final class TakeLastTimedSubscriber<T> extends AtomicInteger implements F Throwable error; TakeLastTimedSubscriber(Subscriber<? super T> actual, long count, long time, TimeUnit unit, Scheduler scheduler, int bufferSize, boolean delayError) { - this.actual = actual; + this.downstream = actual; this.count = count; this.time = time; this.unit = unit; @@ -80,9 +80,9 @@ static final class TakeLastTimedSubscriber<T> extends AtomicInteger implements F @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -143,7 +143,7 @@ public void request(long n) { public void cancel() { if (!cancelled) { cancelled = true; - s.cancel(); + upstream.cancel(); if (getAndIncrement() == 0) { queue.clear(); @@ -158,7 +158,7 @@ void drain() { int missed = 1; - final Subscriber<? super T> a = actual; + final Subscriber<? super T> a = downstream; final SpscLinkedArrayQueue<Object> q = queue; final boolean delayError = this.delayError; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntil.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntil.java index 0743eb1d00..180a77ec68 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntil.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntil.java @@ -42,54 +42,54 @@ static final class TakeUntilMainSubscriber<T> extends AtomicInteger implements F private static final long serialVersionUID = -4945480365982832967L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final AtomicLong requested; - final AtomicReference<Subscription> s; + final AtomicReference<Subscription> upstream; final AtomicThrowable error; final OtherSubscriber other; - TakeUntilMainSubscriber(Subscriber<? super T> actual) { - this.actual = actual; + TakeUntilMainSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; this.requested = new AtomicLong(); - this.s = new AtomicReference<Subscription>(); + this.upstream = new AtomicReference<Subscription>(); this.other = new OtherSubscriber(); this.error = new AtomicThrowable(); } @Override public void onSubscribe(Subscription s) { - SubscriptionHelper.deferredSetOnce(this.s, requested, s); + SubscriptionHelper.deferredSetOnce(this.upstream, requested, s); } @Override public void onNext(T t) { - HalfSerializer.onNext(actual, t, this, error); + HalfSerializer.onNext(downstream, t, this, error); } @Override public void onError(Throwable t) { SubscriptionHelper.cancel(other); - HalfSerializer.onError(actual, t, this, error); + HalfSerializer.onError(downstream, t, this, error); } @Override public void onComplete() { SubscriptionHelper.cancel(other); - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } @Override public void request(long n) { - SubscriptionHelper.deferredRequest(s, requested, n); + SubscriptionHelper.deferredRequest(upstream, requested, n); } @Override public void cancel() { - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); SubscriptionHelper.cancel(other); } @@ -110,14 +110,14 @@ public void onNext(Object t) { @Override public void onError(Throwable t) { - SubscriptionHelper.cancel(s); - HalfSerializer.onError(actual, t, TakeUntilMainSubscriber.this, error); + SubscriptionHelper.cancel(upstream); + HalfSerializer.onError(downstream, t, TakeUntilMainSubscriber.this, error); } @Override public void onComplete() { - SubscriptionHelper.cancel(s); - HalfSerializer.onComplete(actual, TakeUntilMainSubscriber.this, error); + SubscriptionHelper.cancel(upstream); + HalfSerializer.onComplete(downstream, TakeUntilMainSubscriber.this, error); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicate.java index 790800dc9d..cad253b254 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicate.java @@ -34,40 +34,40 @@ protected void subscribeActual(Subscriber<? super T> s) { } static final class InnerSubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Predicate<? super T> predicate; - Subscription s; + Subscription upstream; boolean done; InnerSubscriber(Subscriber<? super T> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { if (!done) { - actual.onNext(t); + downstream.onNext(t); boolean b; try { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); onError(e); return; } if (b) { done = true; - s.cancel(); - actual.onComplete(); + upstream.cancel(); + downstream.onComplete(); } } } @@ -76,7 +76,7 @@ public void onNext(T t) { public void onError(Throwable t) { if (!done) { done = true; - actual.onError(t); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -86,18 +86,18 @@ public void onError(Throwable t) { public void onComplete() { if (!done) { done = true; - actual.onComplete(); + downstream.onComplete(); } } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeWhile.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeWhile.java index 2190f0518c..d4436bd0a0 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeWhile.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeWhile.java @@ -34,23 +34,23 @@ protected void subscribeActual(Subscriber<? super T> s) { } static final class TakeWhileSubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Predicate<? super T> predicate; - Subscription s; + Subscription upstream; boolean done; TakeWhileSubscriber(Subscriber<? super T> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -64,19 +64,19 @@ public void onNext(T t) { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.cancel(); + upstream.cancel(); onError(e); return; } if (!b) { done = true; - s.cancel(); - actual.onComplete(); + upstream.cancel(); + downstream.onComplete(); return; } - actual.onNext(t); + downstream.onNext(t); } @Override @@ -86,7 +86,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -95,17 +95,17 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTimed.java index fd6b821609..727bd4d484 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTimed.java @@ -52,12 +52,12 @@ static final class DebounceTimedSubscriber<T> implements FlowableSubscriber<T>, Subscription, Runnable { private static final long serialVersionUID = -9102637559663639004L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final long timeout; final TimeUnit unit; final Scheduler.Worker worker; - Subscription s; + Subscription upstream; final SequentialDisposable timer = new SequentialDisposable(); @@ -66,7 +66,7 @@ static final class DebounceTimedSubscriber<T> boolean done; DebounceTimedSubscriber(Subscriber<? super T> actual, long timeout, TimeUnit unit, Worker worker) { - this.actual = actual; + this.downstream = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; @@ -74,9 +74,9 @@ static final class DebounceTimedSubscriber<T> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -91,12 +91,12 @@ public void onNext(T t) { gate = true; long r = get(); if (r != 0L) { - actual.onNext(t); + downstream.onNext(t); BackpressureHelper.produced(this, 1); } else { done = true; cancel(); - actual.onError(new MissingBackpressureException("Could not deliver value due to lack of requests")); + downstream.onError(new MissingBackpressureException("Could not deliver value due to lack of requests")); return; } @@ -123,7 +123,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); worker.dispose(); } @@ -133,7 +133,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); worker.dispose(); } @@ -146,7 +146,7 @@ public void request(long n) { @Override public void cancel() { - s.cancel(); + upstream.cancel(); worker.dispose(); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeInterval.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeInterval.java index e578736192..4e673da5e6 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeInterval.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeInterval.java @@ -38,26 +38,26 @@ protected void subscribeActual(Subscriber<? super Timed<T>> s) { } static final class TimeIntervalSubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super Timed<T>> actual; + final Subscriber<? super Timed<T>> downstream; final TimeUnit unit; final Scheduler scheduler; - Subscription s; + Subscription upstream; long lastTime; TimeIntervalSubscriber(Subscriber<? super Timed<T>> actual, TimeUnit unit, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.scheduler = scheduler; this.unit = unit; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { + if (SubscriptionHelper.validate(this.upstream, s)) { lastTime = scheduler.now(unit); - this.s = s; - actual.onSubscribe(this); + this.upstream = s; + downstream.onSubscribe(this); } } @@ -67,27 +67,27 @@ public void onNext(T t) { long last = lastTime; lastTime = now; long delta = now - last; - actual.onNext(new Timed<T>(t, delta, unit)); + downstream.onNext(new Timed<T>(t, delta, unit)); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java index 99def36def..6d8300f234 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java @@ -68,7 +68,7 @@ static final class TimeoutSubscriber<T> extends AtomicLong private static final long serialVersionUID = 3764492702657003550L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Function<? super T, ? extends Publisher<?>> itemTimeoutIndicator; @@ -79,7 +79,7 @@ static final class TimeoutSubscriber<T> extends AtomicLong final AtomicLong requested; TimeoutSubscriber(Subscriber<? super T> actual, Function<? super T, ? extends Publisher<?>> itemTimeoutIndicator) { - this.actual = actual; + this.downstream = actual; this.itemTimeoutIndicator = itemTimeoutIndicator; this.task = new SequentialDisposable(); this.upstream = new AtomicReference<Subscription>(); @@ -103,7 +103,7 @@ public void onNext(T t) { d.dispose(); } - actual.onNext(t); + downstream.onNext(t); Publisher<?> itemTimeoutPublisher; @@ -115,7 +115,7 @@ public void onNext(T t) { Exceptions.throwIfFatal(ex); upstream.get().cancel(); getAndSet(Long.MAX_VALUE); - actual.onError(ex); + downstream.onError(ex); return; } @@ -139,7 +139,7 @@ public void onError(Throwable t) { if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onError(t); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -150,7 +150,7 @@ public void onComplete() { if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onComplete(); + downstream.onComplete(); } } @@ -159,7 +159,7 @@ public void onTimeout(long idx) { if (compareAndSet(idx, Long.MAX_VALUE)) { SubscriptionHelper.cancel(upstream); - actual.onError(new TimeoutException()); + downstream.onError(new TimeoutException()); } } @@ -168,7 +168,7 @@ public void onTimeoutError(long idx, Throwable ex) { if (compareAndSet(idx, Long.MAX_VALUE)) { SubscriptionHelper.cancel(upstream); - actual.onError(ex); + downstream.onError(ex); } else { RxJavaPlugins.onError(ex); } @@ -191,7 +191,7 @@ static final class TimeoutFallbackSubscriber<T> extends SubscriptionArbiter private static final long serialVersionUID = 3764492702657003550L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Function<? super T, ? extends Publisher<?>> itemTimeoutIndicator; @@ -208,7 +208,7 @@ static final class TimeoutFallbackSubscriber<T> extends SubscriptionArbiter TimeoutFallbackSubscriber(Subscriber<? super T> actual, Function<? super T, ? extends Publisher<?>> itemTimeoutIndicator, Publisher<? extends T> fallback) { - this.actual = actual; + this.downstream = actual; this.itemTimeoutIndicator = itemTimeoutIndicator; this.task = new SequentialDisposable(); this.upstream = new AtomicReference<Subscription>(); @@ -237,7 +237,7 @@ public void onNext(T t) { consumed++; - actual.onNext(t); + downstream.onNext(t); Publisher<?> itemTimeoutPublisher; @@ -249,7 +249,7 @@ public void onNext(T t) { Exceptions.throwIfFatal(ex); upstream.get().cancel(); index.getAndSet(Long.MAX_VALUE); - actual.onError(ex); + downstream.onError(ex); return; } @@ -273,7 +273,7 @@ public void onError(Throwable t) { if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onError(t); + downstream.onError(t); task.dispose(); } else { @@ -286,7 +286,7 @@ public void onComplete() { if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onComplete(); + downstream.onComplete(); task.dispose(); } @@ -305,7 +305,7 @@ public void onTimeout(long idx) { produced(c); } - f.subscribe(new FlowableTimeoutTimed.FallbackSubscriber<T>(actual, this)); + f.subscribe(new FlowableTimeoutTimed.FallbackSubscriber<T>(downstream, this)); } } @@ -314,7 +314,7 @@ public void onTimeoutError(long idx, Throwable ex) { if (index.compareAndSet(idx, Long.MAX_VALUE)) { SubscriptionHelper.cancel(upstream); - actual.onError(ex); + downstream.onError(ex); } else { RxJavaPlugins.onError(ex); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java index e16f894736..9be6bc847b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java @@ -58,7 +58,7 @@ static final class TimeoutSubscriber<T> extends AtomicLong private static final long serialVersionUID = 3764492702657003550L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final long timeout; @@ -73,7 +73,7 @@ static final class TimeoutSubscriber<T> extends AtomicLong final AtomicLong requested; TimeoutSubscriber(Subscriber<? super T> actual, long timeout, TimeUnit unit, Scheduler.Worker worker) { - this.actual = actual; + this.downstream = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; @@ -96,7 +96,7 @@ public void onNext(T t) { task.get().dispose(); - actual.onNext(t); + downstream.onNext(t); startTimeout(idx + 1); } @@ -110,7 +110,7 @@ public void onError(Throwable t) { if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onError(t); + downstream.onError(t); worker.dispose(); } else { @@ -123,7 +123,7 @@ public void onComplete() { if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onComplete(); + downstream.onComplete(); worker.dispose(); } @@ -134,7 +134,7 @@ public void onTimeout(long idx) { if (compareAndSet(idx, Long.MAX_VALUE)) { SubscriptionHelper.cancel(upstream); - actual.onError(new TimeoutException()); + downstream.onError(new TimeoutException()); worker.dispose(); } @@ -175,7 +175,7 @@ static final class TimeoutFallbackSubscriber<T> extends SubscriptionArbiter private static final long serialVersionUID = 3764492702657003550L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final long timeout; @@ -195,7 +195,7 @@ static final class TimeoutFallbackSubscriber<T> extends SubscriptionArbiter TimeoutFallbackSubscriber(Subscriber<? super T> actual, long timeout, TimeUnit unit, Scheduler.Worker worker, Publisher<? extends T> fallback) { - this.actual = actual; + this.downstream = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; @@ -223,7 +223,7 @@ public void onNext(T t) { consumed++; - actual.onNext(t); + downstream.onNext(t); startTimeout(idx + 1); } @@ -237,7 +237,7 @@ public void onError(Throwable t) { if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onError(t); + downstream.onError(t); worker.dispose(); } else { @@ -250,7 +250,7 @@ public void onComplete() { if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onComplete(); + downstream.onComplete(); worker.dispose(); } @@ -269,7 +269,7 @@ public void onTimeout(long idx) { Publisher<? extends T> f = fallback; fallback = null; - f.subscribe(new FallbackSubscriber<T>(actual, this)); + f.subscribe(new FallbackSubscriber<T>(downstream, this)); worker.dispose(); } @@ -284,12 +284,12 @@ public void cancel() { static final class FallbackSubscriber<T> implements FlowableSubscriber<T> { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final SubscriptionArbiter arbiter; FallbackSubscriber(Subscriber<? super T> actual, SubscriptionArbiter arbiter) { - this.actual = actual; + this.downstream = actual; this.arbiter = arbiter; } @@ -300,17 +300,17 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimer.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimer.java index b7241ea4ac..7c829267cf 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimer.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimer.java @@ -49,12 +49,12 @@ static final class TimerSubscriber extends AtomicReference<Disposable> private static final long serialVersionUID = -2809475196591179431L; - final Subscriber<? super Long> actual; + final Subscriber<? super Long> downstream; volatile boolean requested; - TimerSubscriber(Subscriber<? super Long> actual) { - this.actual = actual; + TimerSubscriber(Subscriber<? super Long> downstream) { + this.downstream = downstream; } @Override @@ -73,12 +73,12 @@ public void cancel() { public void run() { if (get() != DisposableHelper.DISPOSED) { if (requested) { - actual.onNext(0L); + downstream.onNext(0L); lazySet(EmptyDisposable.INSTANCE); - actual.onComplete(); + downstream.onComplete(); } else { lazySet(EmptyDisposable.INSTANCE); - actual.onError(new MissingBackpressureException("Can't deliver value due to lack of requests")); + downstream.onError(new MissingBackpressureException("Can't deliver value due to lack of requests")); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java index 75ef64ce2f..a49c3dcc8c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java @@ -51,7 +51,7 @@ static final class ToListSubscriber<T, U extends Collection<? super T>> private static final long serialVersionUID = -8134157938864266736L; - Subscription s; + Subscription upstream; ToListSubscriber(Subscriber<? super U> actual, U collection) { super(actual); @@ -60,9 +60,9 @@ static final class ToListSubscriber<T, U extends Collection<? super T>> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -78,7 +78,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { value = null; - actual.onError(t); + downstream.onError(t); } @Override @@ -89,7 +89,7 @@ public void onComplete() { @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableToListSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableToListSingle.java index a0738acf11..e4a8abd565 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableToListSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableToListSingle.java @@ -65,22 +65,22 @@ public Flowable<U> fuseToFlowable() { static final class ToListSubscriber<T, U extends Collection<? super T>> implements FlowableSubscriber<T>, Disposable { - final SingleObserver<? super U> actual; + final SingleObserver<? super U> downstream; - Subscription s; + Subscription upstream; U value; ToListSubscriber(SingleObserver<? super U> actual, U collection) { - this.actual = actual; + this.downstream = actual; this.value = collection; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @@ -93,25 +93,25 @@ public void onNext(T t) { @Override public void onError(Throwable t) { value = null; - s = SubscriptionHelper.CANCELLED; - actual.onError(t); + upstream = SubscriptionHelper.CANCELLED; + downstream.onError(t); } @Override public void onComplete() { - s = SubscriptionHelper.CANCELLED; - actual.onSuccess(value); + upstream = SubscriptionHelper.CANCELLED; + downstream.onSuccess(value); } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOn.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOn.java index b5d6a1d001..0790d4b444 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOn.java @@ -37,28 +37,28 @@ static final class UnsubscribeSubscriber<T> extends AtomicBoolean implements Flo private static final long serialVersionUID = 1015244841293359600L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Scheduler scheduler; - Subscription s; + Subscription upstream; UnsubscribeSubscriber(Subscriber<? super T> actual, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.scheduler = scheduler; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { if (!get()) { - actual.onNext(t); + downstream.onNext(t); } } @@ -68,19 +68,19 @@ public void onError(Throwable t) { RxJavaPlugins.onError(t); return; } - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { if (!get()) { - actual.onComplete(); + downstream.onComplete(); } } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override @@ -93,7 +93,7 @@ public void cancel() { final class Cancellation implements Runnable { @Override public void run() { - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableUsing.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableUsing.java index 9cc64d860f..2d3a83fc4a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableUsing.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableUsing.java @@ -78,15 +78,15 @@ static final class UsingSubscriber<T, D> extends AtomicBoolean implements Flowab private static final long serialVersionUID = 5904473792286235046L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final D resource; final Consumer<? super D> disposer; final boolean eager; - Subscription s; + Subscription upstream; UsingSubscriber(Subscriber<? super T> actual, D resource, Consumer<? super D> disposer, boolean eager) { - this.actual = actual; + this.downstream = actual; this.resource = resource; this.disposer = disposer; this.eager = eager; @@ -94,15 +94,15 @@ static final class UsingSubscriber<T, D> extends AtomicBoolean implements Flowab @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override @@ -118,15 +118,15 @@ public void onError(Throwable t) { } } - s.cancel(); + upstream.cancel(); if (innerError != null) { - actual.onError(new CompositeException(t, innerError)); + downstream.onError(new CompositeException(t, innerError)); } else { - actual.onError(t); + downstream.onError(t); } } else { - actual.onError(t); - s.cancel(); + downstream.onError(t); + upstream.cancel(); disposeAfter(); } } @@ -139,29 +139,29 @@ public void onComplete() { disposer.accept(resource); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } } - s.cancel(); - actual.onComplete(); + upstream.cancel(); + downstream.onComplete(); } else { - actual.onComplete(); - s.cancel(); + downstream.onComplete(); + upstream.cancel(); disposeAfter(); } } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { disposeAfter(); - s.cancel(); + upstream.cancel(); } void disposeAfter() { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindow.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindow.java index f678e73ee2..bbe2f2b6e0 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindow.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindow.java @@ -58,7 +58,7 @@ static final class WindowExactSubscriber<T> private static final long serialVersionUID = -2365647875069161133L; - final Subscriber<? super Flowable<T>> actual; + final Subscriber<? super Flowable<T>> downstream; final long size; @@ -68,13 +68,13 @@ static final class WindowExactSubscriber<T> long index; - Subscription s; + Subscription upstream; UnicastProcessor<T> window; WindowExactSubscriber(Subscriber<? super Flowable<T>> actual, long size, int bufferSize) { super(1); - this.actual = actual; + this.downstream = actual; this.size = size; this.once = new AtomicBoolean(); this.bufferSize = bufferSize; @@ -82,9 +82,9 @@ static final class WindowExactSubscriber<T> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -99,7 +99,7 @@ public void onNext(T t) { w = UnicastProcessor.<T>create(bufferSize, this); window = w; - actual.onNext(w); + downstream.onNext(w); } i++; @@ -123,7 +123,7 @@ public void onError(Throwable t) { w.onError(t); } - actual.onError(t); + downstream.onError(t); } @Override @@ -134,14 +134,14 @@ public void onComplete() { w.onComplete(); } - actual.onComplete(); + downstream.onComplete(); } @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { long u = BackpressureHelper.multiplyCap(size, n); - s.request(u); + upstream.request(u); } } @@ -155,7 +155,7 @@ public void cancel() { @Override public void run() { if (decrementAndGet() == 0) { - s.cancel(); + upstream.cancel(); } } } @@ -167,7 +167,7 @@ static final class WindowSkipSubscriber<T> private static final long serialVersionUID = -8792836352386833856L; - final Subscriber<? super Flowable<T>> actual; + final Subscriber<? super Flowable<T>> downstream; final long size; @@ -181,13 +181,13 @@ static final class WindowSkipSubscriber<T> long index; - Subscription s; + Subscription upstream; UnicastProcessor<T> window; WindowSkipSubscriber(Subscriber<? super Flowable<T>> actual, long size, long skip, int bufferSize) { super(1); - this.actual = actual; + this.downstream = actual; this.size = size; this.skip = skip; this.once = new AtomicBoolean(); @@ -197,9 +197,9 @@ static final class WindowSkipSubscriber<T> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -215,7 +215,7 @@ public void onNext(T t) { w = UnicastProcessor.<T>create(bufferSize, this); window = w; - actual.onNext(w); + downstream.onNext(w); } i++; @@ -244,7 +244,7 @@ public void onError(Throwable t) { w.onError(t); } - actual.onError(t); + downstream.onError(t); } @Override @@ -255,7 +255,7 @@ public void onComplete() { w.onComplete(); } - actual.onComplete(); + downstream.onComplete(); } @Override @@ -265,10 +265,10 @@ public void request(long n) { long u = BackpressureHelper.multiplyCap(size, n); long v = BackpressureHelper.multiplyCap(skip - size, n - 1); long w = BackpressureHelper.addCap(u, v); - s.request(w); + upstream.request(w); } else { long u = BackpressureHelper.multiplyCap(skip, n); - s.request(u); + upstream.request(u); } } } @@ -283,7 +283,7 @@ public void cancel() { @Override public void run() { if (decrementAndGet() == 0) { - s.cancel(); + upstream.cancel(); } } } @@ -295,7 +295,7 @@ static final class WindowOverlapSubscriber<T> private static final long serialVersionUID = 2428527070996323976L; - final Subscriber<? super Flowable<T>> actual; + final Subscriber<? super Flowable<T>> downstream; final SpscLinkedArrayQueue<UnicastProcessor<T>> queue; @@ -319,7 +319,7 @@ static final class WindowOverlapSubscriber<T> long produced; - Subscription s; + Subscription upstream; volatile boolean done; Throwable error; @@ -328,7 +328,7 @@ static final class WindowOverlapSubscriber<T> WindowOverlapSubscriber(Subscriber<? super Flowable<T>> actual, long size, long skip, int bufferSize) { super(1); - this.actual = actual; + this.downstream = actual; this.size = size; this.skip = skip; this.queue = new SpscLinkedArrayQueue<UnicastProcessor<T>>(bufferSize); @@ -342,9 +342,9 @@ static final class WindowOverlapSubscriber<T> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -431,7 +431,7 @@ void drain() { return; } - final Subscriber<? super Flowable<T>> a = actual; + final Subscriber<? super Flowable<T>> a = downstream; final SpscLinkedArrayQueue<UnicastProcessor<T>> q = queue; int missed = 1; @@ -508,10 +508,10 @@ public void request(long n) { if (!firstRequest.get() && firstRequest.compareAndSet(false, true)) { long u = BackpressureHelper.multiplyCap(skip, n - 1); long v = BackpressureHelper.addCap(size, u); - s.request(v); + upstream.request(v); } else { long u = BackpressureHelper.multiplyCap(skip, n); - s.request(u); + upstream.request(u); } drain(); @@ -529,7 +529,7 @@ public void cancel() { @Override public void run() { if (decrementAndGet() == 0) { - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java index 46e445bd26..a398eb040f 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java @@ -94,8 +94,8 @@ static final class WindowBoundaryMainSubscriber<T, B> } @Override - public void onSubscribe(Subscription d) { - SubscriptionHelper.setOnce(upstream, d, Long.MAX_VALUE); + public void onSubscribe(Subscription s) { + SubscriptionHelper.setOnce(upstream, s, Long.MAX_VALUE); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java index 55fee47d51..246b1be106 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java @@ -63,7 +63,7 @@ static final class WindowBoundaryMainSubscriber<T, B, V> final int bufferSize; final CompositeDisposable resources; - Subscription s; + Subscription upstream; final AtomicReference<Disposable> boundary = new AtomicReference<Disposable>(); @@ -84,10 +84,10 @@ static final class WindowBoundaryMainSubscriber<T, B, V> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); if (cancelled) { return; @@ -141,7 +141,7 @@ public void onError(Throwable t) { resources.dispose(); } - actual.onError(t); + downstream.onError(t); } @Override @@ -159,15 +159,15 @@ public void onComplete() { resources.dispose(); } - actual.onComplete(); + downstream.onComplete(); } void error(Throwable t) { - s.cancel(); + upstream.cancel(); resources.dispose(); DisposableHelper.dispose(boundary); - actual.onError(t); + downstream.onError(t); } @Override @@ -187,7 +187,7 @@ void dispose() { void drainLoop() { final SimplePlainQueue<Object> q = queue; - final Subscriber<? super Flowable<T>> a = actual; + final Subscriber<? super Flowable<T>> a = downstream; final List<UnicastProcessor<T>> ws = this.ws; int missed = 1; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java index faaf1e7384..f82c56a889 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java @@ -96,13 +96,13 @@ static final class WindowBoundaryMainSubscriber<T, B> } @Override - public void onSubscribe(Subscription d) { - if (SubscriptionHelper.validate(upstream, d)) { - upstream = d; + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.validate(upstream, s)) { + upstream = s; downstream.onSubscribe(this); queue.offer(NEXT_WINDOW); drain(); - d.request(Long.MAX_VALUE); + s.request(Long.MAX_VALUE); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java index 460fd7d814..ae284ef27a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java @@ -82,7 +82,7 @@ static final class WindowExactUnboundedSubscriber<T> final Scheduler scheduler; final int bufferSize; - Subscription s; + Subscription upstream; UnicastProcessor<T> window; @@ -103,12 +103,12 @@ static final class WindowExactUnboundedSubscriber<T> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; window = UnicastProcessor.<T>create(bufferSize); - Subscriber<? super Flowable<T>> a = actual; + Subscriber<? super Flowable<T>> a = downstream; a.onSubscribe(this); long r = requested(); @@ -159,7 +159,7 @@ public void onError(Throwable t) { drainLoop(); } - actual.onError(t); + downstream.onError(t); dispose(); } @@ -170,7 +170,7 @@ public void onComplete() { drainLoop(); } - actual.onComplete(); + downstream.onComplete(); dispose(); } @@ -205,7 +205,7 @@ public void run() { void drainLoop() { final SimplePlainQueue<Object> q = queue; - final Subscriber<? super Flowable<T>> a = actual; + final Subscriber<? super Flowable<T>> a = downstream; UnicastProcessor<T> w = window; int missed = 1; @@ -250,13 +250,13 @@ void drainLoop() { } else { window = null; queue.clear(); - s.cancel(); + upstream.cancel(); dispose(); a.onError(new MissingBackpressureException("Could not deliver first window due to lack of requests.")); return; } } else { - s.cancel(); + upstream.cancel(); } continue; } @@ -287,7 +287,7 @@ static final class WindowExactBoundedSubscriber<T> long producerIndex; - Subscription s; + Subscription upstream; UnicastProcessor<T> window; @@ -315,11 +315,11 @@ static final class WindowExactBoundedSubscriber<T> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { + if (SubscriptionHelper.validate(this.upstream, s)) { - this.s = s; + this.upstream = s; - Subscriber<? super Flowable<T>> a = actual; + Subscriber<? super Flowable<T>> a = downstream; a.onSubscribe(this); @@ -343,15 +343,15 @@ public void onSubscribe(Subscription s) { return; } - Disposable d; + Disposable task; ConsumerIndexHolder consumerIndexHolder = new ConsumerIndexHolder(producerIndex, this); if (restartTimerOnMaxSize) { - d = worker.schedulePeriodically(consumerIndexHolder, timespan, timespan, unit); + task = worker.schedulePeriodically(consumerIndexHolder, timespan, timespan, unit); } else { - d = scheduler.schedulePeriodicallyDirect(consumerIndexHolder, timespan, timespan, unit); + task = scheduler.schedulePeriodicallyDirect(consumerIndexHolder, timespan, timespan, unit); } - if (timer.replace(d)) { + if (timer.replace(task)) { s.request(Long.MAX_VALUE); } } @@ -380,7 +380,7 @@ public void onNext(T t) { if (r != 0L) { w = UnicastProcessor.<T>create(bufferSize); window = w; - actual.onNext(w); + downstream.onNext(w); if (r != Long.MAX_VALUE) { produced(1); } @@ -394,8 +394,8 @@ public void onNext(T t) { } } else { window = null; - s.cancel(); - actual.onError(new MissingBackpressureException("Could not deliver window due to lack of requests")); + upstream.cancel(); + downstream.onError(new MissingBackpressureException("Could not deliver window due to lack of requests")); dispose(); return; } @@ -423,7 +423,7 @@ public void onError(Throwable t) { drainLoop(); } - actual.onError(t); + downstream.onError(t); dispose(); } @@ -434,7 +434,7 @@ public void onComplete() { drainLoop(); } - actual.onComplete(); + downstream.onComplete(); dispose(); } @@ -458,7 +458,7 @@ public void dispose() { void drainLoop() { final SimplePlainQueue<Object> q = queue; - final Subscriber<? super Flowable<T>> a = actual; + final Subscriber<? super Flowable<T>> a = downstream; UnicastProcessor<T> w = window; int missed = 1; @@ -466,7 +466,7 @@ void drainLoop() { for (;;) { if (terminated) { - s.cancel(); + upstream.cancel(); q.clear(); dispose(); return; @@ -513,7 +513,7 @@ void drainLoop() { } else { window = null; queue.clear(); - s.cancel(); + upstream.cancel(); a.onError(new MissingBackpressureException("Could not deliver first window due to lack of requests.")); dispose(); return; @@ -536,7 +536,7 @@ void drainLoop() { if (r != 0L) { w = UnicastProcessor.<T>create(bufferSize); window = w; - actual.onNext(w); + downstream.onNext(w); if (r != Long.MAX_VALUE) { produced(1); } @@ -552,8 +552,8 @@ void drainLoop() { } else { window = null; - s.cancel(); - actual.onError(new MissingBackpressureException("Could not deliver window due to lack of requests")); + upstream.cancel(); + downstream.onError(new MissingBackpressureException("Could not deliver window due to lack of requests")); dispose(); return; } @@ -605,7 +605,7 @@ static final class WindowSkipSubscriber<T> final List<UnicastProcessor<T>> windows; - Subscription s; + Subscription upstream; volatile boolean terminated; @@ -623,11 +623,11 @@ static final class WindowSkipSubscriber<T> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { + if (SubscriptionHelper.validate(this.upstream, s)) { - this.s = s; + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); if (cancelled) { return; @@ -638,7 +638,7 @@ public void onSubscribe(Subscription s) { final UnicastProcessor<T> w = UnicastProcessor.<T>create(bufferSize); windows.add(w); - actual.onNext(w); + downstream.onNext(w); if (r != Long.MAX_VALUE) { produced(1); } @@ -650,7 +650,7 @@ public void onSubscribe(Subscription s) { } else { s.cancel(); - actual.onError(new MissingBackpressureException("Could not emit the first window due to lack of requests")); + downstream.onError(new MissingBackpressureException("Could not emit the first window due to lack of requests")); } } } @@ -681,7 +681,7 @@ public void onError(Throwable t) { drainLoop(); } - actual.onError(t); + downstream.onError(t); dispose(); } @@ -692,7 +692,7 @@ public void onComplete() { drainLoop(); } - actual.onComplete(); + downstream.onComplete(); dispose(); } @@ -720,7 +720,7 @@ void complete(UnicastProcessor<T> w) { @SuppressWarnings("unchecked") void drainLoop() { final SimplePlainQueue<Object> q = queue; - final Subscriber<? super Flowable<T>> a = actual; + final Subscriber<? super Flowable<T>> a = downstream; final List<UnicastProcessor<T>> ws = windows; int missed = 1; @@ -729,7 +729,7 @@ void drainLoop() { for (;;) { if (terminated) { - s.cancel(); + upstream.cancel(); dispose(); q.clear(); ws.clear(); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFrom.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFrom.java index e51c6435e5..5f403fb150 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFrom.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFrom.java @@ -51,7 +51,8 @@ static final class WithLatestFromSubscriber<T, U, R> extends AtomicReference<U> private static final long serialVersionUID = -312246233408980075L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; + final BiFunction<? super T, ? super U, ? extends R> combiner; final AtomicReference<Subscription> s = new AtomicReference<Subscription>(); @@ -61,7 +62,7 @@ static final class WithLatestFromSubscriber<T, U, R> extends AtomicReference<U> final AtomicReference<Subscription> other = new AtomicReference<Subscription>(); WithLatestFromSubscriber(Subscriber<? super R> actual, BiFunction<? super T, ? super U, ? extends R> combiner) { - this.actual = actual; + this.downstream = actual; this.combiner = combiner; } @Override @@ -86,10 +87,10 @@ public boolean tryOnNext(T t) { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancel(); - actual.onError(e); + downstream.onError(e); return false; } - actual.onNext(r); + downstream.onNext(r); return true; } else { return false; @@ -99,13 +100,13 @@ public boolean tryOnNext(T t) { @Override public void onError(Throwable t) { SubscriptionHelper.cancel(other); - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { SubscriptionHelper.cancel(other); - actual.onComplete(); + downstream.onComplete(); } @Override @@ -125,7 +126,7 @@ public boolean setOther(Subscription o) { public void otherError(Throwable e) { SubscriptionHelper.cancel(s); - actual.onError(e); + downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java index 2566fe3e5c..f0a2231f02 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java @@ -99,7 +99,7 @@ static final class WithLatestFromSubscriber<T, R> private static final long serialVersionUID = 1577321883966341961L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final Function<? super Object[], R> combiner; @@ -107,7 +107,7 @@ static final class WithLatestFromSubscriber<T, R> final AtomicReferenceArray<Object> values; - final AtomicReference<Subscription> s; + final AtomicReference<Subscription> upstream; final AtomicLong requested; @@ -116,7 +116,7 @@ static final class WithLatestFromSubscriber<T, R> volatile boolean done; WithLatestFromSubscriber(Subscriber<? super R> actual, Function<? super Object[], R> combiner, int n) { - this.actual = actual; + this.downstream = actual; this.combiner = combiner; WithLatestInnerSubscriber[] s = new WithLatestInnerSubscriber[n]; for (int i = 0; i < n; i++) { @@ -124,14 +124,14 @@ static final class WithLatestFromSubscriber<T, R> } this.subscribers = s; this.values = new AtomicReferenceArray<Object>(n); - this.s = new AtomicReference<Subscription>(); + this.upstream = new AtomicReference<Subscription>(); this.requested = new AtomicLong(); this.error = new AtomicThrowable(); } void subscribe(Publisher<?>[] others, int n) { WithLatestInnerSubscriber[] subscribers = this.subscribers; - AtomicReference<Subscription> s = this.s; + AtomicReference<Subscription> s = this.upstream; for (int i = 0; i < n; i++) { if (SubscriptionHelper.isCancelled(s.get())) { return; @@ -142,13 +142,13 @@ void subscribe(Publisher<?>[] others, int n) { @Override public void onSubscribe(Subscription s) { - SubscriptionHelper.deferredSetOnce(this.s, requested, s); + SubscriptionHelper.deferredSetOnce(this.upstream, requested, s); } @Override public void onNext(T t) { if (!tryOnNext(t) && !done) { - s.get().request(1); + upstream.get().request(1); } } @@ -182,7 +182,7 @@ public boolean tryOnNext(T t) { return false; } - HalfSerializer.onNext(actual, v, this, error); + HalfSerializer.onNext(downstream, v, this, error); return true; } @@ -194,7 +194,7 @@ public void onError(Throwable t) { } done = true; cancelAllBut(-1); - HalfSerializer.onError(actual, t, this, error); + HalfSerializer.onError(downstream, t, this, error); } @Override @@ -202,18 +202,18 @@ public void onComplete() { if (!done) { done = true; cancelAllBut(-1); - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } } @Override public void request(long n) { - SubscriptionHelper.deferredRequest(s, requested, n); + SubscriptionHelper.deferredRequest(upstream, requested, n); } @Override public void cancel() { - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); for (WithLatestInnerSubscriber s : subscribers) { s.dispose(); } @@ -225,17 +225,17 @@ void innerNext(int index, Object o) { void innerError(int index, Throwable t) { done = true; - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); cancelAllBut(index); - HalfSerializer.onError(actual, t, this, error); + HalfSerializer.onError(downstream, t, this, error); } void innerComplete(int index, boolean nonEmpty) { if (!nonEmpty) { done = true; - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); cancelAllBut(index); - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableZip.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableZip.java index c154c2e820..1d585cc02c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableZip.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableZip.java @@ -86,7 +86,7 @@ static final class ZipCoordinator<T, R> private static final long serialVersionUID = -2434867452883857743L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final ZipSubscriber<T, R>[] subscribers; @@ -104,7 +104,7 @@ static final class ZipCoordinator<T, R> ZipCoordinator(Subscriber<? super R> actual, Function<? super Object[], ? extends R> zipper, int n, int prefetch, boolean delayErrors) { - this.actual = actual; + this.downstream = actual; this.zipper = zipper; this.delayErrors = delayErrors; @SuppressWarnings("unchecked") @@ -166,7 +166,7 @@ void drain() { return; } - final Subscriber<? super R> a = actual; + final Subscriber<? super R> a = downstream; final ZipSubscriber<T, R>[] qs = subscribers; final int n = qs.length; Object[] values = current; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableZipIterable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableZipIterable.java index ffec85365d..7a81c2dcba 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableZipIterable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableZipIterable.java @@ -67,26 +67,26 @@ public void subscribeActual(Subscriber<? super V> t) { } static final class ZipIterableSubscriber<T, U, V> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super V> actual; + final Subscriber<? super V> downstream; final Iterator<U> iterator; final BiFunction<? super T, ? super U, ? extends V> zipper; - Subscription s; + Subscription upstream; boolean done; ZipIterableSubscriber(Subscriber<? super V> actual, Iterator<U> iterator, BiFunction<? super T, ? super U, ? extends V> zipper) { - this.actual = actual; + this.downstream = actual; this.iterator = iterator; this.zipper = zipper; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -113,7 +113,7 @@ public void onNext(T t) { return; } - actual.onNext(v); + downstream.onNext(v); boolean b; @@ -126,16 +126,16 @@ public void onNext(T t) { if (!b) { done = true; - s.cancel(); - actual.onComplete(); + upstream.cancel(); + downstream.onComplete(); } } void error(Throwable e) { Exceptions.throwIfFatal(e); done = true; - s.cancel(); - actual.onError(e); + upstream.cancel(); + downstream.onError(e); } @Override @@ -145,7 +145,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -154,17 +154,17 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java index 9087d2ed76..fb6940c479 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java @@ -94,12 +94,12 @@ static final class AmbMaybeObserver<T> private static final long serialVersionUID = -7044685185359438206L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final CompositeDisposable set; - AmbMaybeObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + AmbMaybeObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; this.set = new CompositeDisposable(); } @@ -125,7 +125,7 @@ public void onSuccess(T value) { if (compareAndSet(false, true)) { set.dispose(); - actual.onSuccess(value); + downstream.onSuccess(value); } } @@ -134,7 +134,7 @@ public void onError(Throwable e) { if (compareAndSet(false, true)) { set.dispose(); - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -145,7 +145,7 @@ public void onComplete() { if (compareAndSet(false, true)) { set.dispose(); - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCache.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCache.java index fd7747f18b..c8adbd7ab8 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCache.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCache.java @@ -89,7 +89,7 @@ public void onSuccess(T value) { this.value = value; for (CacheDisposable<T> inner : observers.getAndSet(TERMINATED)) { if (!inner.isDisposed()) { - inner.actual.onSuccess(value); + inner.downstream.onSuccess(value); } } } @@ -100,7 +100,7 @@ public void onError(Throwable e) { this.error = e; for (CacheDisposable<T> inner : observers.getAndSet(TERMINATED)) { if (!inner.isDisposed()) { - inner.actual.onError(e); + inner.downstream.onError(e); } } } @@ -110,7 +110,7 @@ public void onError(Throwable e) { public void onComplete() { for (CacheDisposable<T> inner : observers.getAndSet(TERMINATED)) { if (!inner.isDisposed()) { - inner.actual.onComplete(); + inner.downstream.onComplete(); } } } @@ -175,11 +175,11 @@ static final class CacheDisposable<T> private static final long serialVersionUID = -5791853038359966195L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; CacheDisposable(MaybeObserver<? super T> actual, MaybeCache<T> parent) { super(parent); - this.actual = actual; + this.downstream = actual; } @Override diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatArray.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatArray.java index b67534ade9..0584c47b45 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatArray.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatArray.java @@ -49,7 +49,7 @@ static final class ConcatMaybeObserver<T> private static final long serialVersionUID = 3520831347801429610L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final AtomicLong requested; @@ -64,7 +64,7 @@ static final class ConcatMaybeObserver<T> long produced; ConcatMaybeObserver(Subscriber<? super T> actual, MaybeSource<? extends T>[] sources) { - this.actual = actual; + this.downstream = actual; this.sources = sources; this.requested = new AtomicLong(); this.disposables = new SequentialDisposable(); @@ -97,7 +97,7 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override @@ -113,7 +113,7 @@ void drain() { } AtomicReference<Object> c = current; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; Disposable cancelled = disposables; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayDelayError.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayDelayError.java index ebff9986d9..6c2e1604ab 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayDelayError.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayDelayError.java @@ -51,7 +51,7 @@ static final class ConcatMaybeObserver<T> private static final long serialVersionUID = 3520831347801429610L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final AtomicLong requested; @@ -68,7 +68,7 @@ static final class ConcatMaybeObserver<T> long produced; ConcatMaybeObserver(Subscriber<? super T> actual, MaybeSource<? extends T>[] sources) { - this.actual = actual; + this.downstream = actual; this.sources = sources; this.requested = new AtomicLong(); this.disposables = new SequentialDisposable(); @@ -123,7 +123,7 @@ void drain() { } AtomicReference<Object> c = current; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; Disposable cancelled = disposables; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatIterable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatIterable.java index 1a3c286c71..353afadf83 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatIterable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeConcatIterable.java @@ -63,7 +63,7 @@ static final class ConcatMaybeObserver<T> private static final long serialVersionUID = 3520831347801429610L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final AtomicLong requested; @@ -76,7 +76,7 @@ static final class ConcatMaybeObserver<T> long produced; ConcatMaybeObserver(Subscriber<? super T> actual, Iterator<? extends MaybeSource<? extends T>> sources) { - this.actual = actual; + this.downstream = actual; this.sources = sources; this.requested = new AtomicLong(); this.disposables = new SequentialDisposable(); @@ -109,7 +109,7 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override @@ -125,7 +125,7 @@ void drain() { } AtomicReference<Object> c = current; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; Disposable cancelled = disposables; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeContains.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeContains.java index 3399e84996..aa167b2a08 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeContains.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeContains.java @@ -48,52 +48,52 @@ protected void subscribeActual(SingleObserver<? super Boolean> observer) { static final class ContainsMaybeObserver implements MaybeObserver<Object>, Disposable { - final SingleObserver<? super Boolean> actual; + final SingleObserver<? super Boolean> downstream; final Object value; - Disposable d; + Disposable upstream; ContainsMaybeObserver(SingleObserver<? super Boolean> actual, Object value) { - this.actual = actual; + this.downstream = actual; this.value = value; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; - actual.onSubscribe(this); + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void onSuccess(Object value) { - d = DisposableHelper.DISPOSED; - actual.onSuccess(ObjectHelper.equals(value, this.value)); + upstream = DisposableHelper.DISPOSED; + downstream.onSuccess(ObjectHelper.equals(value, this.value)); } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; - actual.onSuccess(false); + upstream = DisposableHelper.DISPOSED; + downstream.onSuccess(false); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCount.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCount.java index 63d8880d42..df36c7d755 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCount.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCount.java @@ -42,50 +42,50 @@ protected void subscribeActual(SingleObserver<? super Long> observer) { } static final class CountMaybeObserver implements MaybeObserver<Object>, Disposable { - final SingleObserver<? super Long> actual; + final SingleObserver<? super Long> downstream; - Disposable d; + Disposable upstream; - CountMaybeObserver(SingleObserver<? super Long> actual) { - this.actual = actual; + CountMaybeObserver(SingleObserver<? super Long> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(Object value) { - d = DisposableHelper.DISPOSED; - actual.onSuccess(1L); + upstream = DisposableHelper.DISPOSED; + downstream.onSuccess(1L); } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; - actual.onSuccess(0L); + upstream = DisposableHelper.DISPOSED; + downstream.onSuccess(0L); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java index 4c6de982af..5a3852662a 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java @@ -53,10 +53,10 @@ static final class Emitter<T> extends AtomicReference<Disposable> implements MaybeEmitter<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - Emitter(MaybeObserver<? super T> actual) { - this.actual = actual; + Emitter(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @@ -69,9 +69,9 @@ public void onSuccess(T value) { if (d != DisposableHelper.DISPOSED) { try { if (value == null) { - actual.onError(new NullPointerException("onSuccess called with null. Null values are generally not allowed in 2.x operators and sources.")); + downstream.onError(new NullPointerException("onSuccess called with null. Null values are generally not allowed in 2.x operators and sources.")); } else { - actual.onSuccess(value); + downstream.onSuccess(value); } } finally { if (d != null) { @@ -98,7 +98,7 @@ public boolean tryOnError(Throwable t) { Disposable d = getAndSet(DisposableHelper.DISPOSED); if (d != DisposableHelper.DISPOSED) { try { - actual.onError(t); + downstream.onError(t); } finally { if (d != null) { d.dispose(); @@ -116,7 +116,7 @@ public void onComplete() { Disposable d = getAndSet(DisposableHelper.DISPOSED); if (d != DisposableHelper.DISPOSED) { try { - actual.onComplete(); + downstream.onComplete(); } finally { if (d != null) { d.dispose(); diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelay.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelay.java index 1cc31495ed..68a1508195 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelay.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelay.java @@ -51,7 +51,7 @@ static final class DelayMaybeObserver<T> private static final long serialVersionUID = 5566860102500855068L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final long delay; @@ -64,7 +64,7 @@ static final class DelayMaybeObserver<T> Throwable error; DelayMaybeObserver(MaybeObserver<? super T> actual, long delay, TimeUnit unit, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.delay = delay; this.unit = unit; this.scheduler = scheduler; @@ -74,13 +74,13 @@ static final class DelayMaybeObserver<T> public void run() { Throwable ex = error; if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { T v = value; if (v != null) { - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onComplete(); + downstream.onComplete(); } } } @@ -98,7 +98,7 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java index 61ae58f62a..55049d5c95 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java @@ -49,7 +49,7 @@ static final class DelayMaybeObserver<T, U> final Publisher<U> otherSource; - Disposable d; + Disposable upstream; DelayMaybeObserver(MaybeObserver<? super T> actual, Publisher<U> otherSource) { this.other = new OtherSubscriber<T>(actual); @@ -58,8 +58,8 @@ static final class DelayMaybeObserver<T, U> @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; SubscriptionHelper.cancel(other); } @@ -70,30 +70,30 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - other.actual.onSubscribe(this); + other.downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; other.value = value; subscribeNext(); } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; other.error = e; subscribeNext(); } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; subscribeNext(); } @@ -108,14 +108,14 @@ static final class OtherSubscriber<T> extends private static final long serialVersionUID = -1215060610805418006L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; T value; Throwable error; - OtherSubscriber(MaybeObserver<? super T> actual) { - this.actual = actual; + OtherSubscriber(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override @@ -137,9 +137,9 @@ public void onNext(Object t) { public void onError(Throwable t) { Throwable e = error; if (e == null) { - actual.onError(t); + downstream.onError(t); } else { - actual.onError(new CompositeException(e, t)); + downstream.onError(new CompositeException(e, t)); } } @@ -147,13 +147,13 @@ public void onError(Throwable t) { public void onComplete() { Throwable e = error; if (e != null) { - actual.onError(e); + downstream.onError(e); } else { T v = value; if (v != null) { - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionOtherPublisher.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionOtherPublisher.java index 9a52d4af7c..c29fb3fc0a 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionOtherPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelaySubscriptionOtherPublisher.java @@ -48,7 +48,7 @@ static final class OtherSubscriber<T> implements FlowableSubscriber<Object>, Dis MaybeSource<T> source; - Subscription s; + Subscription upstream; OtherSubscriber(MaybeObserver<? super T> actual, MaybeSource<T> source) { this.main = new DelayMaybeObserver<T>(actual); @@ -57,10 +57,10 @@ static final class OtherSubscriber<T> implements FlowableSubscriber<Object>, Dis @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - main.actual.onSubscribe(this); + main.downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -68,9 +68,9 @@ public void onSubscribe(Subscription s) { @Override public void onNext(Object t) { - if (s != SubscriptionHelper.CANCELLED) { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + if (upstream != SubscriptionHelper.CANCELLED) { + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; subscribeNext(); } @@ -78,10 +78,10 @@ public void onNext(Object t) { @Override public void onError(Throwable t) { - if (s != SubscriptionHelper.CANCELLED) { - s = SubscriptionHelper.CANCELLED; + if (upstream != SubscriptionHelper.CANCELLED) { + upstream = SubscriptionHelper.CANCELLED; - main.actual.onError(t); + main.downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -89,8 +89,8 @@ public void onError(Throwable t) { @Override public void onComplete() { - if (s != SubscriptionHelper.CANCELLED) { - s = SubscriptionHelper.CANCELLED; + if (upstream != SubscriptionHelper.CANCELLED) { + upstream = SubscriptionHelper.CANCELLED; subscribeNext(); } @@ -110,8 +110,8 @@ public boolean isDisposed() { @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; DisposableHelper.dispose(main); } } @@ -121,10 +121,10 @@ static final class DelayMaybeObserver<T> extends AtomicReference<Disposable> private static final long serialVersionUID = 706635022205076709L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - DelayMaybeObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + DelayMaybeObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override @@ -134,17 +134,17 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayWithCompletable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayWithCompletable.java index a56f8c9360..da9ff60e81 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayWithCompletable.java @@ -43,12 +43,12 @@ static final class OtherObserver<T> implements CompletableObserver, Disposable { private static final long serialVersionUID = 703409937383992161L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final MaybeSource<T> source; OtherObserver(MaybeObserver<? super T> actual, MaybeSource<T> source) { - this.actual = actual; + this.downstream = actual; this.source = source; } @@ -56,18 +56,18 @@ static final class OtherObserver<T> public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - source.subscribe(new DelayWithMainObserver<T>(this, actual)); + source.subscribe(new DelayWithMainObserver<T>(this, downstream)); } @Override @@ -85,11 +85,11 @@ static final class DelayWithMainObserver<T> implements MaybeObserver<T> { final AtomicReference<Disposable> parent; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - DelayWithMainObserver(AtomicReference<Disposable> parent, MaybeObserver<? super T> actual) { + DelayWithMainObserver(AtomicReference<Disposable> parent, MaybeObserver<? super T> downstream) { this.parent = parent; - this.actual = actual; + this.downstream = downstream; } @Override @@ -99,17 +99,17 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDetach.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDetach.java index 8d0883c45e..c6da27b3bd 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDetach.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDetach.java @@ -35,61 +35,61 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class DetachMaybeObserver<T> implements MaybeObserver<T>, Disposable { - MaybeObserver<? super T> actual; + MaybeObserver<? super T> downstream; - Disposable d; + Disposable upstream; - DetachMaybeObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + DetachMaybeObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void dispose() { - actual = null; - d.dispose(); - d = DisposableHelper.DISPOSED; + downstream = null; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; - MaybeObserver<? super T> a = actual; + upstream = DisposableHelper.DISPOSED; + MaybeObserver<? super T> a = downstream; if (a != null) { - actual = null; + downstream = null; a.onSuccess(value); } } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - MaybeObserver<? super T> a = actual; + upstream = DisposableHelper.DISPOSED; + MaybeObserver<? super T> a = downstream; if (a != null) { - actual = null; + downstream = null; a.onError(e); } } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; - MaybeObserver<? super T> a = actual; + upstream = DisposableHelper.DISPOSED; + MaybeObserver<? super T> a = downstream; if (a != null) { - actual = null; + downstream = null; a.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java index 017412ff41..e87790321f 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoAfterSuccess.java @@ -42,29 +42,29 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class DoAfterObserver<T> implements MaybeObserver<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final Consumer<? super T> onAfterSuccess; - Disposable d; + Disposable upstream; DoAfterObserver(MaybeObserver<? super T> actual, Consumer<? super T> onAfterSuccess) { - this.actual = actual; + this.downstream = actual; this.onAfterSuccess = onAfterSuccess; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T t) { - actual.onSuccess(t); + downstream.onSuccess(t); try { onAfterSuccess.accept(t); @@ -77,22 +77,22 @@ public void onSuccess(T t) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java index c1db295b50..7b5573661f 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoFinally.java @@ -46,53 +46,53 @@ static final class DoFinallyObserver<T> extends AtomicInteger implements MaybeOb private static final long serialVersionUID = 4109457741734051389L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final Action onFinally; - Disposable d; + Disposable upstream; DoFinallyObserver(MaybeObserver<? super T> actual, Action onFinally) { - this.actual = actual; + this.downstream = actual; this.onFinally = onFinally; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T t) { - actual.onSuccess(t); + downstream.onSuccess(t); runFinally(); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); runFinally(); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); runFinally(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); runFinally(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } void runFinally() { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoOnEvent.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoOnEvent.java index a4c624ebb1..4769ee79f4 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoOnEvent.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoOnEvent.java @@ -40,55 +40,55 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { } static final class DoOnEventMaybeObserver<T> implements MaybeObserver<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final BiConsumer<? super T, ? super Throwable> onEvent; - Disposable d; + Disposable upstream; DoOnEventMaybeObserver(MaybeObserver<? super T> actual, BiConsumer<? super T, ? super Throwable> onEvent) { - this.actual = actual; + this.downstream = actual; this.onEvent = onEvent; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; try { onEvent.accept(value, null); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; try { onEvent.accept(null, e); @@ -97,22 +97,22 @@ public void onError(Throwable e) { e = new CompositeException(e, ex); } - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; try { onEvent.accept(null, null); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeEqualSingle.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeEqualSingle.java index f2d69368e3..4f843635aa 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeEqualSingle.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeEqualSingle.java @@ -53,7 +53,7 @@ protected void subscribeActual(SingleObserver<? super Boolean> observer) { static final class EqualCoordinator<T> extends AtomicInteger implements Disposable { - final SingleObserver<? super Boolean> actual; + final SingleObserver<? super Boolean> downstream; final EqualObserver<T> observer1; @@ -63,7 +63,7 @@ static final class EqualCoordinator<T> EqualCoordinator(SingleObserver<? super Boolean> actual, BiPredicate<? super T, ? super T> isEqual) { super(2); - this.actual = actual; + this.downstream = actual; this.isEqual = isEqual; this.observer1 = new EqualObserver<T>(this); this.observer2 = new EqualObserver<T>(this); @@ -98,13 +98,13 @@ void done() { b = isEqual.test((T)o1, (T)o2); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } - actual.onSuccess(b); + downstream.onSuccess(b); } else { - actual.onSuccess(o1 == null && o2 == null); + downstream.onSuccess(o1 == null && o2 == null); } } } @@ -116,7 +116,7 @@ void error(EqualObserver<T> sender, Throwable ex) { } else { observer1.dispose(); } - actual.onError(ex); + downstream.onError(ex); } else { RxJavaPlugins.onError(ex); } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilter.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilter.java index b77b1459f8..fd556c3a66 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilter.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilter.java @@ -41,35 +41,35 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class FilterMaybeObserver<T> implements MaybeObserver<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final Predicate<? super T> predicate; - Disposable d; + Disposable upstream; FilterMaybeObserver(MaybeObserver<? super T> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override public void dispose() { - Disposable d = this.d; - this.d = DisposableHelper.DISPOSED; + Disposable d = this.upstream; + this.upstream = DisposableHelper.DISPOSED; d.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -81,25 +81,25 @@ public void onSuccess(T value) { b = predicate.test(value); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } if (b) { - actual.onSuccess(value); + downstream.onSuccess(value); } else { - actual.onComplete(); + downstream.onComplete(); } } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilterSingle.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilterSingle.java index b1495f5cef..820bc8b7ae 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilterSingle.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilterSingle.java @@ -42,35 +42,35 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class FilterMaybeObserver<T> implements SingleObserver<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final Predicate<? super T> predicate; - Disposable d; + Disposable upstream; FilterMaybeObserver(MaybeObserver<? super T> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override public void dispose() { - Disposable d = this.d; - this.d = DisposableHelper.DISPOSED; + Disposable d = this.upstream; + this.upstream = DisposableHelper.DISPOSED; d.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -82,20 +82,20 @@ public void onSuccess(T value) { b = predicate.test(value); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } if (b) { - actual.onSuccess(value); + downstream.onSuccess(value); } else { - actual.onComplete(); + downstream.onComplete(); } } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapBiSelector.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapBiSelector.java index f7735d0a8e..2b9b8ec339 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapBiSelector.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapBiSelector.java @@ -76,7 +76,7 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(inner, d)) { - inner.actual.onSubscribe(this); + inner.downstream.onSubscribe(this); } } @@ -88,7 +88,7 @@ public void onSuccess(T value) { next = ObjectHelper.requireNonNull(mapper.apply(value), "The mapper returned a null MaybeSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - inner.actual.onError(ex); + inner.downstream.onError(ex); return; } @@ -100,12 +100,12 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - inner.actual.onError(e); + inner.downstream.onError(e); } @Override public void onComplete() { - inner.actual.onComplete(); + inner.downstream.onComplete(); } static final class InnerObserver<T, U, R> @@ -114,7 +114,7 @@ static final class InnerObserver<T, U, R> private static final long serialVersionUID = -2897979525538174559L; - final MaybeObserver<? super R> actual; + final MaybeObserver<? super R> downstream; final BiFunction<? super T, ? super U, ? extends R> resultSelector; @@ -122,7 +122,7 @@ static final class InnerObserver<T, U, R> InnerObserver(MaybeObserver<? super R> actual, BiFunction<? super T, ? super U, ? extends R> resultSelector) { - this.actual = actual; + this.downstream = actual; this.resultSelector = resultSelector; } @@ -142,21 +142,21 @@ public void onSuccess(U value) { r = ObjectHelper.requireNonNull(resultSelector.apply(t, value), "The resultSelector returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } - actual.onSuccess(r); + downstream.onSuccess(r); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapCompletable.java index f0bb42e89d..aa0a7f93bc 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapCompletable.java @@ -50,13 +50,13 @@ static final class FlatMapCompletableObserver<T> private static final long serialVersionUID = -2177128922851101253L; - final CompletableObserver actual; + final CompletableObserver downstream; final Function<? super T, ? extends CompletableSource> mapper; FlatMapCompletableObserver(CompletableObserver actual, Function<? super T, ? extends CompletableSource> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @@ -94,12 +94,12 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowable.java index b93574e23a..5ea9adb386 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowable.java @@ -57,13 +57,13 @@ static final class FlatMapIterableObserver<T, R> private static final long serialVersionUID = -8938804753851907758L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final Function<? super T, ? extends Iterable<? extends R>> mapper; final AtomicLong requested; - Disposable d; + Disposable upstream; volatile Iterator<? extends R> it; @@ -73,17 +73,17 @@ static final class FlatMapIterableObserver<T, R> FlatMapIterableObserver(Subscriber<? super R> actual, Function<? super T, ? extends Iterable<? extends R>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.requested = new AtomicLong(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -97,12 +97,12 @@ public void onSuccess(T value) { has = iterator.hasNext(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } if (!has) { - actual.onComplete(); + downstream.onComplete(); return; } @@ -112,13 +112,13 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override @@ -132,8 +132,8 @@ public void request(long n) { @Override public void cancel() { cancelled = true; - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } void fastPath(Subscriber<? super R> a, Iterator<? extends R> iterator) { @@ -181,7 +181,7 @@ void drain() { return; } - Subscriber<? super R> a = actual; + Subscriber<? super R> a = downstream; Iterator<? extends R> iterator = this.it; if (outputFused && iterator != null) { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java index 1d3ca89756..4e5755fb8f 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java @@ -51,11 +51,11 @@ static final class FlatMapIterableObserver<T, R> extends BasicQueueDisposable<R> implements MaybeObserver<T> { - final Observer<? super R> actual; + final Observer<? super R> downstream; final Function<? super T, ? extends Iterable<? extends R>> mapper; - Disposable d; + Disposable upstream; volatile Iterator<? extends R> it; @@ -65,22 +65,22 @@ static final class FlatMapIterableObserver<T, R> FlatMapIterableObserver(Observer<? super R> actual, Function<? super T, ? extends Iterable<? extends R>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - Observer<? super R> a = actual; + Observer<? super R> a = downstream; Iterator<? extends R> iterator; boolean has; @@ -148,20 +148,20 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { cancelled = true; - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapNotification.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapNotification.java index f5c4ea8084..f5bb71e110 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapNotification.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapNotification.java @@ -59,7 +59,7 @@ static final class FlatMapMaybeObserver<T, R> private static final long serialVersionUID = 4375739915521278546L; - final MaybeObserver<? super R> actual; + final MaybeObserver<? super R> downstream; final Function<? super T, ? extends MaybeSource<? extends R>> onSuccessMapper; @@ -67,13 +67,13 @@ static final class FlatMapMaybeObserver<T, R> final Callable<? extends MaybeSource<? extends R>> onCompleteSupplier; - Disposable d; + Disposable upstream; FlatMapMaybeObserver(MaybeObserver<? super R> actual, Function<? super T, ? extends MaybeSource<? extends R>> onSuccessMapper, Function<? super Throwable, ? extends MaybeSource<? extends R>> onErrorMapper, Callable<? extends MaybeSource<? extends R>> onCompleteSupplier) { - this.actual = actual; + this.downstream = actual; this.onSuccessMapper = onSuccessMapper; this.onErrorMapper = onErrorMapper; this.onCompleteSupplier = onCompleteSupplier; @@ -82,7 +82,7 @@ static final class FlatMapMaybeObserver<T, R> @Override public void dispose() { DisposableHelper.dispose(this); - d.dispose(); + upstream.dispose(); } @Override @@ -92,10 +92,10 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -107,7 +107,7 @@ public void onSuccess(T value) { source = ObjectHelper.requireNonNull(onSuccessMapper.apply(value), "The onSuccessMapper returned a null MaybeSource"); } catch (Exception ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } @@ -122,7 +122,7 @@ public void onError(Throwable e) { source = ObjectHelper.requireNonNull(onErrorMapper.apply(e), "The onErrorMapper returned a null MaybeSource"); } catch (Exception ex) { Exceptions.throwIfFatal(ex); - actual.onError(new CompositeException(e, ex)); + downstream.onError(new CompositeException(e, ex)); return; } @@ -137,7 +137,7 @@ public void onComplete() { source = ObjectHelper.requireNonNull(onCompleteSupplier.call(), "The onCompleteSupplier returned a null MaybeSource"); } catch (Exception ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } @@ -153,17 +153,17 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(R value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingle.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingle.java index 240cfa8015..af55a7a57d 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingle.java @@ -43,8 +43,8 @@ public MaybeFlatMapSingle(MaybeSource<T> source, Function<? super T, ? extends S } @Override - protected void subscribeActual(SingleObserver<? super R> actual) { - source.subscribe(new FlatMapMaybeObserver<T, R>(actual, mapper)); + protected void subscribeActual(SingleObserver<? super R> downstream) { + source.subscribe(new FlatMapMaybeObserver<T, R>(downstream, mapper)); } static final class FlatMapMaybeObserver<T, R> @@ -53,12 +53,12 @@ static final class FlatMapMaybeObserver<T, R> private static final long serialVersionUID = 4827726964688405508L; - final SingleObserver<? super R> actual; + final SingleObserver<? super R> downstream; final Function<? super T, ? extends SingleSource<? extends R>> mapper; FlatMapMaybeObserver(SingleObserver<? super R> actual, Function<? super T, ? extends SingleSource<? extends R>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @@ -75,7 +75,7 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -92,18 +92,18 @@ public void onSuccess(T value) { } if (!isDisposed()) { - ss.subscribe(new FlatMapSingleObserver<R>(this, actual)); + ss.subscribe(new FlatMapSingleObserver<R>(this, downstream)); } } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onError(new NoSuchElementException()); + downstream.onError(new NoSuchElementException()); } } @@ -111,11 +111,11 @@ static final class FlatMapSingleObserver<R> implements SingleObserver<R> { final AtomicReference<Disposable> parent; - final SingleObserver<? super R> actual; + final SingleObserver<? super R> downstream; - FlatMapSingleObserver(AtomicReference<Disposable> parent, SingleObserver<? super R> actual) { + FlatMapSingleObserver(AtomicReference<Disposable> parent, SingleObserver<? super R> downstream) { this.parent = parent; - this.actual = actual; + this.downstream = downstream; } @Override @@ -125,12 +125,12 @@ public void onSubscribe(final Disposable d) { @Override public void onSuccess(final R value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(final Throwable e) { - actual.onError(e); + downstream.onError(e); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingleElement.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingleElement.java index 91e41562d1..37795729b8 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingleElement.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapSingleElement.java @@ -41,8 +41,8 @@ public MaybeFlatMapSingleElement(MaybeSource<T> source, Function<? super T, ? ex } @Override - protected void subscribeActual(MaybeObserver<? super R> actual) { - source.subscribe(new FlatMapMaybeObserver<T, R>(actual, mapper)); + protected void subscribeActual(MaybeObserver<? super R> downstream) { + source.subscribe(new FlatMapMaybeObserver<T, R>(downstream, mapper)); } static final class FlatMapMaybeObserver<T, R> @@ -51,12 +51,12 @@ static final class FlatMapMaybeObserver<T, R> private static final long serialVersionUID = 4827726964688405508L; - final MaybeObserver<? super R> actual; + final MaybeObserver<? super R> downstream; final Function<? super T, ? extends SingleSource<? extends R>> mapper; FlatMapMaybeObserver(MaybeObserver<? super R> actual, Function<? super T, ? extends SingleSource<? extends R>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @@ -73,7 +73,7 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -89,17 +89,17 @@ public void onSuccess(T value) { return; } - ss.subscribe(new FlatMapSingleObserver<R>(this, actual)); + ss.subscribe(new FlatMapSingleObserver<R>(this, downstream)); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } @@ -107,11 +107,11 @@ static final class FlatMapSingleObserver<R> implements SingleObserver<R> { final AtomicReference<Disposable> parent; - final MaybeObserver<? super R> actual; + final MaybeObserver<? super R> downstream; - FlatMapSingleObserver(AtomicReference<Disposable> parent, MaybeObserver<? super R> actual) { + FlatMapSingleObserver(AtomicReference<Disposable> parent, MaybeObserver<? super R> downstream) { this.parent = parent; - this.actual = actual; + this.downstream = downstream; } @Override @@ -121,12 +121,12 @@ public void onSubscribe(final Disposable d) { @Override public void onSuccess(final R value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(final Throwable e) { - actual.onError(e); + downstream.onError(e); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatten.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatten.java index bca244ac4d..b05aebd236 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatten.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatten.java @@ -49,22 +49,22 @@ static final class FlatMapMaybeObserver<T, R> private static final long serialVersionUID = 4375739915521278546L; - final MaybeObserver<? super R> actual; + final MaybeObserver<? super R> downstream; final Function<? super T, ? extends MaybeSource<? extends R>> mapper; - Disposable d; + Disposable upstream; FlatMapMaybeObserver(MaybeObserver<? super R> actual, Function<? super T, ? extends MaybeSource<? extends R>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @Override public void dispose() { DisposableHelper.dispose(this); - d.dispose(); + upstream.dispose(); } @Override @@ -74,10 +74,10 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -89,7 +89,7 @@ public void onSuccess(T value) { source = ObjectHelper.requireNonNull(mapper.apply(value), "The mapper returned a null MaybeSource"); } catch (Exception ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } @@ -100,12 +100,12 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } final class InnerObserver implements MaybeObserver<R> { @@ -117,17 +117,17 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(R value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromCompletable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromCompletable.java index 183588f290..2753d992da 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromCompletable.java @@ -42,44 +42,44 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { } static final class FromCompletableObserver<T> implements CompletableObserver, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - Disposable d; + Disposable upstream; - FromCompletableObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + FromCompletableObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; - actual.onComplete(); + upstream = DisposableHelper.DISPOSED; + downstream.onComplete(); } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromSingle.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromSingle.java index 66dab6d1ab..b610a06a12 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromSingle.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFromSingle.java @@ -42,44 +42,44 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { } static final class FromSingleObserver<T> implements SingleObserver<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - Disposable d; + Disposable upstream; - FromSingleObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + FromSingleObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; - actual.onSuccess(value); + upstream = DisposableHelper.DISPOSED; + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeHide.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeHide.java index 80454b81f8..805f7cdc0d 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeHide.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeHide.java @@ -35,47 +35,47 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class HideMaybeObserver<T> implements MaybeObserver<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - Disposable d; + Disposable upstream; - HideMaybeObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + HideMaybeObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElement.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElement.java index 8b3c40e1f3..000de8cf0e 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElement.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElement.java @@ -35,50 +35,50 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class IgnoreMaybeObserver<T> implements MaybeObserver<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - Disposable d; + Disposable upstream; - IgnoreMaybeObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + IgnoreMaybeObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; - actual.onComplete(); + upstream = DisposableHelper.DISPOSED; + downstream.onComplete(); } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; - actual.onComplete(); + upstream = DisposableHelper.DISPOSED; + downstream.onComplete(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElementCompletable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElementCompletable.java index 10f6b028a3..ac49d66e04 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElementCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElementCompletable.java @@ -44,50 +44,50 @@ public Maybe<T> fuseToMaybe() { static final class IgnoreMaybeObserver<T> implements MaybeObserver<T>, Disposable { - final CompletableObserver actual; + final CompletableObserver downstream; - Disposable d; + Disposable upstream; - IgnoreMaybeObserver(CompletableObserver actual) { - this.actual = actual; + IgnoreMaybeObserver(CompletableObserver downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; - actual.onComplete(); + upstream = DisposableHelper.DISPOSED; + downstream.onComplete(); } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; - actual.onComplete(); + upstream = DisposableHelper.DISPOSED; + downstream.onComplete(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeIsEmpty.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeIsEmpty.java index 284977787a..642dc641ce 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeIsEmpty.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeIsEmpty.java @@ -37,46 +37,46 @@ protected void subscribeActual(MaybeObserver<? super Boolean> observer) { static final class IsEmptyMaybeObserver<T> implements MaybeObserver<T>, Disposable { - final MaybeObserver<? super Boolean> actual; + final MaybeObserver<? super Boolean> downstream; - Disposable d; + Disposable upstream; - IsEmptyMaybeObserver(MaybeObserver<? super Boolean> actual) { - this.actual = actual; + IsEmptyMaybeObserver(MaybeObserver<? super Boolean> downstream) { + this.downstream = downstream; } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(false); + downstream.onSuccess(false); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onSuccess(true); + downstream.onSuccess(true); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeIsEmptySingle.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeIsEmptySingle.java index 84811071f5..c8acdff348 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeIsEmptySingle.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeIsEmptySingle.java @@ -52,50 +52,50 @@ protected void subscribeActual(SingleObserver<? super Boolean> observer) { static final class IsEmptyMaybeObserver<T> implements MaybeObserver<T>, Disposable { - final SingleObserver<? super Boolean> actual; + final SingleObserver<? super Boolean> downstream; - Disposable d; + Disposable upstream; - IsEmptyMaybeObserver(SingleObserver<? super Boolean> actual) { - this.actual = actual; + IsEmptyMaybeObserver(SingleObserver<? super Boolean> downstream) { + this.downstream = downstream; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; - actual.onSuccess(false); + upstream = DisposableHelper.DISPOSED; + downstream.onSuccess(false); } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; - actual.onSuccess(true); + upstream = DisposableHelper.DISPOSED; + downstream.onSuccess(true); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeMap.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeMap.java index 578d9b319d..cda167855c 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeMap.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeMap.java @@ -42,35 +42,35 @@ protected void subscribeActual(MaybeObserver<? super R> observer) { static final class MapMaybeObserver<T, R> implements MaybeObserver<T>, Disposable { - final MaybeObserver<? super R> actual; + final MaybeObserver<? super R> downstream; final Function<? super T, ? extends R> mapper; - Disposable d; + Disposable upstream; MapMaybeObserver(MaybeObserver<? super R> actual, Function<? super T, ? extends R> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @Override public void dispose() { - Disposable d = this.d; - this.d = DisposableHelper.DISPOSED; + Disposable d = this.upstream; + this.upstream = DisposableHelper.DISPOSED; d.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -82,21 +82,21 @@ public void onSuccess(T value) { v = ObjectHelper.requireNonNull(mapper.apply(value), "The mapper returned a null item"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } - actual.onSuccess(v); + downstream.onSuccess(v); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeMergeArray.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeMergeArray.java index a012deecf8..762452ba7a 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeMergeArray.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeMergeArray.java @@ -72,7 +72,7 @@ static final class MergeMaybeObserver<T> private static final long serialVersionUID = -660395290758764731L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final CompositeDisposable set; @@ -91,7 +91,7 @@ static final class MergeMaybeObserver<T> long consumed; MergeMaybeObserver(Subscriber<? super T> actual, int sourceCount, SimpleQueueWithConsumerIndex<Object> queue) { - this.actual = actual; + this.downstream = actual; this.sourceCount = sourceCount; this.set = new CompositeDisposable(); this.requested = new AtomicLong(); @@ -184,7 +184,7 @@ boolean isCancelled() { @SuppressWarnings("unchecked") void drainNormal() { int missed = 1; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; SimpleQueueWithConsumerIndex<Object> q = queue; long e = consumed; @@ -252,7 +252,7 @@ void drainNormal() { void drainFused() { int missed = 1; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; SimpleQueueWithConsumerIndex<Object> q = queue; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeObserveOn.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeObserveOn.java index 3feda9db3e..a3d83612d5 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeObserveOn.java @@ -45,7 +45,7 @@ static final class ObserveOnMaybeObserver<T> private static final long serialVersionUID = 8571289934935992137L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final Scheduler scheduler; @@ -53,7 +53,7 @@ static final class ObserveOnMaybeObserver<T> Throwable error; ObserveOnMaybeObserver(MaybeObserver<? super T> actual, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.scheduler = scheduler; } @@ -70,7 +70,7 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -96,14 +96,14 @@ public void run() { Throwable ex = error; if (ex != null) { error = null; - actual.onError(ex); + downstream.onError(ex); } else { T v = value; if (v != null) { value = null; - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorComplete.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorComplete.java index 54825485d4..10fe0610bc 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorComplete.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorComplete.java @@ -42,29 +42,29 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class OnErrorCompleteMaybeObserver<T> implements MaybeObserver<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final Predicate<? super Throwable> predicate; - Disposable d; + Disposable upstream; OnErrorCompleteMaybeObserver(MaybeObserver<? super T> actual, Predicate<? super Throwable> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override @@ -75,30 +75,30 @@ public void onError(Throwable e) { b = predicate.test(e); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(new CompositeException(e, ex)); + downstream.onError(new CompositeException(e, ex)); return; } if (b) { - actual.onComplete(); + downstream.onComplete(); } else { - actual.onError(e); + downstream.onError(e); } } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorNext.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorNext.java index ebd866c667..5591d41c20 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorNext.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorNext.java @@ -53,7 +53,7 @@ static final class OnErrorNextMaybeObserver<T> private static final long serialVersionUID = 2026620218879969836L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final Function<? super Throwable, ? extends MaybeSource<? extends T>> resumeFunction; @@ -62,7 +62,7 @@ static final class OnErrorNextMaybeObserver<T> OnErrorNextMaybeObserver(MaybeObserver<? super T> actual, Function<? super Throwable, ? extends MaybeSource<? extends T>> resumeFunction, boolean allowFatal) { - this.actual = actual; + this.downstream = actual; this.resumeFunction = resumeFunction; this.allowFatal = allowFatal; } @@ -80,19 +80,19 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { if (!allowFatal && !(e instanceof Exception)) { - actual.onError(e); + downstream.onError(e); return; } MaybeSource<? extends T> m; @@ -101,48 +101,48 @@ public void onError(Throwable e) { m = ObjectHelper.requireNonNull(resumeFunction.apply(e), "The resumeFunction returned a null MaybeSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(new CompositeException(e, ex)); + downstream.onError(new CompositeException(e, ex)); return; } DisposableHelper.replace(this, null); - m.subscribe(new NextMaybeObserver<T>(actual, this)); + m.subscribe(new NextMaybeObserver<T>(downstream, this)); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } static final class NextMaybeObserver<T> implements MaybeObserver<T> { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - final AtomicReference<Disposable> d; + final AtomicReference<Disposable> upstream; NextMaybeObserver(MaybeObserver<? super T> actual, AtomicReference<Disposable> d) { - this.actual = actual; - this.d = d; + this.downstream = actual; + this.upstream = d; } @Override public void onSubscribe(Disposable d) { - DisposableHelper.setOnce(this.d, d); + DisposableHelper.setOnce(this.upstream, d); } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorReturn.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorReturn.java index dda373fdb8..568f15009a 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorReturn.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorReturn.java @@ -41,40 +41,40 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class OnErrorReturnMaybeObserver<T> implements MaybeObserver<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final Function<? super Throwable, ? extends T> valueSupplier; - Disposable d; + Disposable upstream; OnErrorReturnMaybeObserver(MaybeObserver<? super T> actual, Function<? super Throwable, ? extends T> valueSupplier) { - this.actual = actual; + this.downstream = actual; this.valueSupplier = valueSupplier; } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override @@ -85,16 +85,16 @@ public void onError(Throwable e) { v = ObjectHelper.requireNonNull(valueSupplier.apply(e), "The valueSupplier returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(new CompositeException(e, ex)); + downstream.onError(new CompositeException(e, ex)); return; } - actual.onSuccess(v); + downstream.onSuccess(v); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybePeek.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybePeek.java index 46fcf24e01..1d6179abf4 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybePeek.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybePeek.java @@ -57,14 +57,14 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { } static final class MaybePeekObserver<T> implements MaybeObserver<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final MaybePeek<T> parent; - Disposable d; + Disposable upstream; MaybePeekObserver(MaybeObserver<? super T> actual, MaybePeek<T> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } @@ -77,37 +77,37 @@ public void dispose() { RxJavaPlugins.onError(ex); } - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { + if (DisposableHelper.validate(this.upstream, d)) { try { parent.onSubscribeCall.accept(d); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); d.dispose(); - this.d = DisposableHelper.DISPOSED; - EmptyDisposable.error(ex, actual); + this.upstream = DisposableHelper.DISPOSED; + EmptyDisposable.error(ex, downstream); return; } - this.d = d; + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - if (this.d == DisposableHelper.DISPOSED) { + if (this.upstream == DisposableHelper.DISPOSED) { return; } try { @@ -117,16 +117,16 @@ public void onSuccess(T value) { onErrorInner(ex); return; } - this.d = DisposableHelper.DISPOSED; + this.upstream = DisposableHelper.DISPOSED; - actual.onSuccess(value); + downstream.onSuccess(value); onAfterTerminate(); } @Override public void onError(Throwable e) { - if (this.d == DisposableHelper.DISPOSED) { + if (this.upstream == DisposableHelper.DISPOSED) { RxJavaPlugins.onError(e); return; } @@ -142,16 +142,16 @@ void onErrorInner(Throwable e) { e = new CompositeException(e, ex); } - this.d = DisposableHelper.DISPOSED; + this.upstream = DisposableHelper.DISPOSED; - actual.onError(e); + downstream.onError(e); onAfterTerminate(); } @Override public void onComplete() { - if (this.d == DisposableHelper.DISPOSED) { + if (this.upstream == DisposableHelper.DISPOSED) { return; } @@ -162,9 +162,9 @@ public void onComplete() { onErrorInner(ex); return; } - this.d = DisposableHelper.DISPOSED; + this.upstream = DisposableHelper.DISPOSED; - actual.onComplete(); + downstream.onComplete(); onAfterTerminate(); } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeSubscribeOn.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeSubscribeOn.java index 9a7da8dfa0..da2ba08070 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeSubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeSubscribeOn.java @@ -63,10 +63,10 @@ static final class SubscribeOnMaybeObserver<T> private static final long serialVersionUID = 8571289934935992137L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - SubscribeOnMaybeObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + SubscribeOnMaybeObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; this.task = new SequentialDisposable(); } @@ -88,17 +88,17 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmpty.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmpty.java index 396714eb7b..77d2d8f333 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmpty.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmpty.java @@ -44,12 +44,12 @@ static final class SwitchIfEmptyMaybeObserver<T> private static final long serialVersionUID = -2223459372976438024L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final MaybeSource<? extends T> other; SwitchIfEmptyMaybeObserver(MaybeObserver<? super T> actual, MaybeSource<? extends T> other) { - this.actual = actual; + this.downstream = actual; this.other = other; } @@ -66,18 +66,18 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override @@ -85,18 +85,18 @@ public void onComplete() { Disposable d = get(); if (d != DisposableHelper.DISPOSED) { if (compareAndSet(d, null)) { - other.subscribe(new OtherMaybeObserver<T>(actual, this)); + other.subscribe(new OtherMaybeObserver<T>(downstream, this)); } } } static final class OtherMaybeObserver<T> implements MaybeObserver<T> { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final AtomicReference<Disposable> parent; OtherMaybeObserver(MaybeObserver<? super T> actual, AtomicReference<Disposable> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } @Override @@ -105,15 +105,15 @@ public void onSubscribe(Disposable d) { } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingle.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingle.java index 89615edd03..798b3ef24f 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingle.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingle.java @@ -51,12 +51,12 @@ static final class SwitchIfEmptyMaybeObserver<T> private static final long serialVersionUID = 4603919676453758899L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final SingleSource<? extends T> other; SwitchIfEmptyMaybeObserver(SingleObserver<? super T> actual, SingleSource<? extends T> other) { - this.actual = actual; + this.downstream = actual; this.other = other; } @@ -73,18 +73,18 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override @@ -92,18 +92,18 @@ public void onComplete() { Disposable d = get(); if (d != DisposableHelper.DISPOSED) { if (compareAndSet(d, null)) { - other.subscribe(new OtherSingleObserver<T>(actual, this)); + other.subscribe(new OtherSingleObserver<T>(downstream, this)); } } } static final class OtherSingleObserver<T> implements SingleObserver<T> { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final AtomicReference<Disposable> parent; OtherSingleObserver(SingleObserver<? super T> actual, AtomicReference<Disposable> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } @Override @@ -112,11 +112,11 @@ public void onSubscribe(Disposable d) { } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilMaybe.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilMaybe.java index 14f030e5a1..56a5cac4f7 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilMaybe.java @@ -51,12 +51,12 @@ static final class TakeUntilMainMaybeObserver<T, U> private static final long serialVersionUID = -2187421758664251153L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final TakeUntilOtherMaybeObserver<U> other; - TakeUntilMainMaybeObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + TakeUntilMainMaybeObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; this.other = new TakeUntilOtherMaybeObserver<U>(this); } @@ -80,7 +80,7 @@ public void onSubscribe(Disposable d) { public void onSuccess(T value) { DisposableHelper.dispose(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onSuccess(value); + downstream.onSuccess(value); } } @@ -88,7 +88,7 @@ public void onSuccess(T value) { public void onError(Throwable e) { DisposableHelper.dispose(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -98,13 +98,13 @@ public void onError(Throwable e) { public void onComplete() { DisposableHelper.dispose(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onComplete(); + downstream.onComplete(); } } void otherError(Throwable e) { if (DisposableHelper.dispose(this)) { - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -112,7 +112,7 @@ void otherError(Throwable e) { void otherComplete() { if (DisposableHelper.dispose(this)) { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java index 793436526d..656cf473b5 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java @@ -54,12 +54,12 @@ static final class TakeUntilMainMaybeObserver<T, U> private static final long serialVersionUID = -2187421758664251153L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final TakeUntilOtherMaybeObserver<U> other; - TakeUntilMainMaybeObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + TakeUntilMainMaybeObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; this.other = new TakeUntilOtherMaybeObserver<U>(this); } @@ -83,7 +83,7 @@ public void onSubscribe(Disposable d) { public void onSuccess(T value) { SubscriptionHelper.cancel(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onSuccess(value); + downstream.onSuccess(value); } } @@ -91,7 +91,7 @@ public void onSuccess(T value) { public void onError(Throwable e) { SubscriptionHelper.cancel(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -101,13 +101,13 @@ public void onError(Throwable e) { public void onComplete() { SubscriptionHelper.cancel(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onComplete(); + downstream.onComplete(); } } void otherError(Throwable e) { if (DisposableHelper.dispose(this)) { - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -115,7 +115,7 @@ void otherError(Throwable e) { void otherComplete() { if (DisposableHelper.dispose(this)) { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutMaybe.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutMaybe.java index 3e8a9ad050..d162573139 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutMaybe.java @@ -57,7 +57,7 @@ static final class TimeoutMainMaybeObserver<T, U> private static final long serialVersionUID = -5955289211445418871L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final TimeoutOtherMaybeObserver<T, U> other; @@ -66,7 +66,7 @@ static final class TimeoutMainMaybeObserver<T, U> final TimeoutFallbackMaybeObserver<T> otherObserver; TimeoutMainMaybeObserver(MaybeObserver<? super T> actual, MaybeSource<? extends T> fallback) { - this.actual = actual; + this.downstream = actual; this.other = new TimeoutOtherMaybeObserver<T, U>(this); this.fallback = fallback; this.otherObserver = fallback != null ? new TimeoutFallbackMaybeObserver<T>(actual) : null; @@ -96,7 +96,7 @@ public void onSubscribe(Disposable d) { public void onSuccess(T value) { DisposableHelper.dispose(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onSuccess(value); + downstream.onSuccess(value); } } @@ -104,7 +104,7 @@ public void onSuccess(T value) { public void onError(Throwable e) { DisposableHelper.dispose(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -114,13 +114,13 @@ public void onError(Throwable e) { public void onComplete() { DisposableHelper.dispose(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onComplete(); + downstream.onComplete(); } } public void otherError(Throwable e) { if (DisposableHelper.dispose(this)) { - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -129,7 +129,7 @@ public void otherError(Throwable e) { public void otherComplete() { if (DisposableHelper.dispose(this)) { if (fallback == null) { - actual.onError(new TimeoutException()); + downstream.onError(new TimeoutException()); } else { fallback.subscribe(otherObserver); } @@ -177,10 +177,10 @@ static final class TimeoutFallbackMaybeObserver<T> private static final long serialVersionUID = 8663801314800248617L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - TimeoutFallbackMaybeObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + TimeoutFallbackMaybeObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override @@ -190,17 +190,17 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java index 801e646e7b..64ab706f5e 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java @@ -60,7 +60,7 @@ static final class TimeoutMainMaybeObserver<T, U> private static final long serialVersionUID = -5955289211445418871L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final TimeoutOtherMaybeObserver<T, U> other; @@ -69,7 +69,7 @@ static final class TimeoutMainMaybeObserver<T, U> final TimeoutFallbackMaybeObserver<T> otherObserver; TimeoutMainMaybeObserver(MaybeObserver<? super T> actual, MaybeSource<? extends T> fallback) { - this.actual = actual; + this.downstream = actual; this.other = new TimeoutOtherMaybeObserver<T, U>(this); this.fallback = fallback; this.otherObserver = fallback != null ? new TimeoutFallbackMaybeObserver<T>(actual) : null; @@ -99,7 +99,7 @@ public void onSubscribe(Disposable d) { public void onSuccess(T value) { SubscriptionHelper.cancel(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onSuccess(value); + downstream.onSuccess(value); } } @@ -107,7 +107,7 @@ public void onSuccess(T value) { public void onError(Throwable e) { SubscriptionHelper.cancel(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -117,13 +117,13 @@ public void onError(Throwable e) { public void onComplete() { SubscriptionHelper.cancel(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { - actual.onComplete(); + downstream.onComplete(); } } public void otherError(Throwable e) { if (DisposableHelper.dispose(this)) { - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -132,7 +132,7 @@ public void otherError(Throwable e) { public void otherComplete() { if (DisposableHelper.dispose(this)) { if (fallback == null) { - actual.onError(new TimeoutException()); + downstream.onError(new TimeoutException()); } else { fallback.subscribe(otherObserver); } @@ -182,10 +182,10 @@ static final class TimeoutFallbackMaybeObserver<T> private static final long serialVersionUID = 8663801314800248617L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - TimeoutFallbackMaybeObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + TimeoutFallbackMaybeObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override @@ -195,17 +195,17 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimer.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimer.java index 3aaacd98d3..5d2c1c4151 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimer.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimer.java @@ -47,15 +47,15 @@ protected void subscribeActual(final MaybeObserver<? super Long> observer) { static final class TimerDisposable extends AtomicReference<Disposable> implements Disposable, Runnable { private static final long serialVersionUID = 2875964065294031672L; - final MaybeObserver<? super Long> actual; + final MaybeObserver<? super Long> downstream; - TimerDisposable(final MaybeObserver<? super Long> actual) { - this.actual = actual; + TimerDisposable(final MaybeObserver<? super Long> downstream) { + this.downstream = downstream; } @Override public void run() { - actual.onSuccess(0L); + downstream.onSuccess(0L); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToFlowable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToFlowable.java index 7c6fb1e7f8..c477a86b50 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToFlowable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToFlowable.java @@ -50,18 +50,18 @@ static final class MaybeToFlowableSubscriber<T> extends DeferredScalarSubscripti private static final long serialVersionUID = 7603343402964826922L; - Disposable d; + Disposable upstream; - MaybeToFlowableSubscriber(Subscriber<? super T> actual) { - super(actual); + MaybeToFlowableSubscriber(Subscriber<? super T> downstream) { + super(downstream); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -72,18 +72,18 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void cancel() { super.cancel(); - d.dispose(); + upstream.dispose(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java index 9b543c6472..8caa294718 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToObservable.java @@ -60,18 +60,18 @@ static final class MaybeToObservableObserver<T> extends DeferredScalarDisposable private static final long serialVersionUID = 7603343402964826922L; - Disposable d; + Disposable upstream; - MaybeToObservableObserver(Observer<? super T> actual) { - super(actual); + MaybeToObservableObserver(Observer<? super T> downstream) { + super(downstream); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -93,7 +93,7 @@ public void onComplete() { @Override public void dispose() { super.dispose(); - d.dispose(); + upstream.dispose(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToSingle.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToSingle.java index a15eb0f167..146bbb23f8 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeToSingle.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeToSingle.java @@ -47,55 +47,55 @@ protected void subscribeActual(SingleObserver<? super T> observer) { } static final class ToSingleMaybeSubscriber<T> implements MaybeObserver<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final T defaultValue; - Disposable d; + Disposable upstream; ToSingleMaybeSubscriber(SingleObserver<? super T> actual, T defaultValue) { - this.actual = actual; + this.downstream = actual; this.defaultValue = defaultValue; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; - actual.onSuccess(value); + upstream = DisposableHelper.DISPOSED; + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; if (defaultValue != null) { - actual.onSuccess(defaultValue); + downstream.onSuccess(defaultValue); } else { - actual.onError(new NoSuchElementException("The MaybeSource is empty")); + downstream.onError(new NoSuchElementException("The MaybeSource is empty")); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeUnsubscribeOn.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeUnsubscribeOn.java index 2375c01221..a6afe4c51a 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeUnsubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeUnsubscribeOn.java @@ -43,14 +43,14 @@ static final class UnsubscribeOnMaybeObserver<T> extends AtomicReference<Disposa private static final long serialVersionUID = 3256698449646456986L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final Scheduler scheduler; Disposable ds; UnsubscribeOnMaybeObserver(MaybeObserver<? super T> actual, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.scheduler = scheduler; } @@ -76,23 +76,23 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeUsing.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeUsing.java index 130043471f..786772eacf 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeUsing.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeUsing.java @@ -102,25 +102,25 @@ static final class UsingObserver<T, D> private static final long serialVersionUID = -674404550052917487L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final Consumer<? super D> disposer; final boolean eager; - Disposable d; + Disposable upstream; UsingObserver(MaybeObserver<? super T> actual, D resource, Consumer<? super D> disposer, boolean eager) { super(resource); - this.actual = actual; + this.downstream = actual; this.disposer = disposer; this.eager = eager; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; disposeResourceAfter(); } @@ -139,22 +139,22 @@ void disposeResourceAfter() { @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @SuppressWarnings("unchecked") @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; if (eager) { Object resource = getAndSet(this); if (resource != this) { @@ -162,7 +162,7 @@ public void onSuccess(T value) { disposer.accept((D)resource); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } } else { @@ -170,7 +170,7 @@ public void onSuccess(T value) { } } - actual.onSuccess(value); + downstream.onSuccess(value); if (!eager) { disposeResourceAfter(); @@ -180,7 +180,7 @@ public void onSuccess(T value) { @SuppressWarnings("unchecked") @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; if (eager) { Object resource = getAndSet(this); if (resource != this) { @@ -195,7 +195,7 @@ public void onError(Throwable e) { } } - actual.onError(e); + downstream.onError(e); if (!eager) { disposeResourceAfter(); @@ -205,7 +205,7 @@ public void onError(Throwable e) { @SuppressWarnings("unchecked") @Override public void onComplete() { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; if (eager) { Object resource = getAndSet(this); if (resource != this) { @@ -213,7 +213,7 @@ public void onComplete() { disposer.accept((D)resource); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } } else { @@ -221,7 +221,7 @@ public void onComplete() { } } - actual.onComplete(); + downstream.onComplete(); if (!eager) { disposeResourceAfter(); diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeZipArray.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeZipArray.java index eeda31ac19..430d3ff2b6 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeZipArray.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeZipArray.java @@ -69,7 +69,7 @@ static final class ZipCoordinator<T, R> extends AtomicInteger implements Disposa private static final long serialVersionUID = -5556924161382950569L; - final MaybeObserver<? super R> actual; + final MaybeObserver<? super R> downstream; final Function<? super Object[], ? extends R> zipper; @@ -80,7 +80,7 @@ static final class ZipCoordinator<T, R> extends AtomicInteger implements Disposa @SuppressWarnings("unchecked") ZipCoordinator(MaybeObserver<? super R> observer, int n, Function<? super Object[], ? extends R> zipper) { super(n); - this.actual = observer; + this.downstream = observer; this.zipper = zipper; ZipMaybeObserver<T>[] o = new ZipMaybeObserver[n]; for (int i = 0; i < n; i++) { @@ -113,11 +113,11 @@ void innerSuccess(T value, int index) { v = ObjectHelper.requireNonNull(zipper.apply(values), "The zipper returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } - actual.onSuccess(v); + downstream.onSuccess(v); } } @@ -135,7 +135,7 @@ void disposeExcept(int index) { void innerError(Throwable ex, int index) { if (getAndSet(0) > 0) { disposeExcept(index); - actual.onError(ex); + downstream.onError(ex); } else { RxJavaPlugins.onError(ex); } @@ -144,7 +144,7 @@ void innerError(Throwable ex, int index) { void innerComplete(int index) { if (getAndSet(0) > 0) { disposeExcept(index); - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java index 48a503c13c..41fa298128 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java @@ -100,12 +100,12 @@ static final class ConcatMapCompletableObserver<T> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(upstream, s)) { - this.upstream = s; - if (s instanceof QueueDisposable) { + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + this.upstream = d; + if (d instanceof QueueDisposable) { @SuppressWarnings("unchecked") - QueueDisposable<T> qd = (QueueDisposable<T>) s; + QueueDisposable<T> qd = (QueueDisposable<T>) d; int m = qd.requestFusion(QueueDisposable.ANY); if (m == QueueDisposable.SYNC) { diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java index 1a52327c72..32b174a19f 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java @@ -108,9 +108,9 @@ static final class ConcatMapMaybeMainObserver<T, R> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(upstream, s)) { - upstream = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + upstream = d; downstream.onSubscribe(this); } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java index b272f27218..1358e1ed9c 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java @@ -108,9 +108,9 @@ static final class ConcatMapSingleMainObserver<T, R> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(upstream, s)) { - upstream = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + upstream = d; downstream.onSubscribe(this); } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java index 7ffe99b707..1d4e8d247d 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java @@ -82,9 +82,9 @@ static final class SwitchMapCompletableObserver<T> implements Observer<T>, Dispo } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(upstream, s)) { - this.upstream = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + this.upstream = d; downstream.onSubscribe(this); } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java index d6e904cec2..89086255e6 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java @@ -91,9 +91,9 @@ static final class SwitchMapMaybeMainObserver<T, R> extends AtomicInteger } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(upstream, s)) { - upstream = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + upstream = d; downstream.onSubscribe(this); } } diff --git a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java index f739b10161..f9871aa6f9 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java @@ -91,9 +91,9 @@ static final class SwitchMapSingleMainObserver<T, R> extends AtomicInteger } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(upstream, s)) { - upstream = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + upstream = d; downstream.onSubscribe(this); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java b/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java index a9d2e92cb3..776721c84e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java @@ -107,8 +107,8 @@ public T next() { } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAll.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAll.java index 7fffa31214..71d0c32ebf 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAll.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAll.java @@ -32,22 +32,22 @@ protected void subscribeActual(Observer<? super Boolean> t) { } static final class AllObserver<T> implements Observer<T>, Disposable { - final Observer<? super Boolean> actual; + final Observer<? super Boolean> downstream; final Predicate<? super T> predicate; - Disposable s; + Disposable upstream; boolean done; AllObserver(Observer<? super Boolean> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -61,15 +61,15 @@ public void onNext(T t) { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } if (!b) { done = true; - s.dispose(); - actual.onNext(false); - actual.onComplete(); + upstream.dispose(); + downstream.onNext(false); + downstream.onComplete(); } } @@ -80,7 +80,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -89,18 +89,18 @@ public void onComplete() { return; } done = true; - actual.onNext(true); - actual.onComplete(); + downstream.onNext(true); + downstream.onComplete(); } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAllSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAllSingle.java index 59388fe651..3089007d6d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAllSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAllSingle.java @@ -40,22 +40,22 @@ public Observable<Boolean> fuseToObservable() { } static final class AllObserver<T> implements Observer<T>, Disposable { - final SingleObserver<? super Boolean> actual; + final SingleObserver<? super Boolean> downstream; final Predicate<? super T> predicate; - Disposable s; + Disposable upstream; boolean done; AllObserver(SingleObserver<? super Boolean> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -69,14 +69,14 @@ public void onNext(T t) { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } if (!b) { done = true; - s.dispose(); - actual.onSuccess(false); + upstream.dispose(); + downstream.onSuccess(false); } } @@ -87,7 +87,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -96,17 +96,17 @@ public void onComplete() { return; } done = true; - actual.onSuccess(true); + downstream.onSuccess(true); } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java index 65e2493f7e..2ed4fcd93b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java @@ -73,14 +73,14 @@ public void subscribeActual(Observer<? super T> observer) { } static final class AmbCoordinator<T> implements Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final AmbInnerObserver<T>[] observers; final AtomicInteger winner = new AtomicInteger(); @SuppressWarnings("unchecked") AmbCoordinator(Observer<? super T> actual, int count) { - this.actual = actual; + this.downstream = actual; this.observers = new AmbInnerObserver[count]; } @@ -88,10 +88,10 @@ public void subscribe(ObservableSource<? extends T>[] sources) { AmbInnerObserver<T>[] as = observers; int len = as.length; for (int i = 0; i < len; i++) { - as[i] = new AmbInnerObserver<T>(this, i + 1, actual); + as[i] = new AmbInnerObserver<T>(this, i + 1, downstream); } winner.lazySet(0); // release the contents of 'as' - actual.onSubscribe(this); + downstream.onSubscribe(this); for (int i = 0; i < len; i++) { if (winner.get() != 0) { @@ -142,29 +142,29 @@ static final class AmbInnerObserver<T> extends AtomicReference<Disposable> imple private static final long serialVersionUID = -1185974347409665484L; final AmbCoordinator<T> parent; final int index; - final Observer<? super T> actual; + final Observer<? super T> downstream; boolean won; - AmbInnerObserver(AmbCoordinator<T> parent, int index, Observer<? super T> actual) { + AmbInnerObserver(AmbCoordinator<T> parent, int index, Observer<? super T> downstream) { this.parent = parent; this.index = index; - this.actual = actual; + this.downstream = downstream; } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); } @Override public void onNext(T t) { if (won) { - actual.onNext(t); + downstream.onNext(t); } else { if (parent.win(index)) { won = true; - actual.onNext(t); + downstream.onNext(t); } else { get().dispose(); } @@ -174,11 +174,11 @@ public void onNext(T t) { @Override public void onError(Throwable t) { if (won) { - actual.onError(t); + downstream.onError(t); } else { if (parent.win(index)) { won = true; - actual.onError(t); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -188,11 +188,11 @@ public void onError(Throwable t) { @Override public void onComplete() { if (won) { - actual.onComplete(); + downstream.onComplete(); } else { if (parent.win(index)) { won = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAny.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAny.java index a3c919067b..92f3aa02cf 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAny.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAny.java @@ -33,22 +33,22 @@ protected void subscribeActual(Observer<? super Boolean> t) { static final class AnyObserver<T> implements Observer<T>, Disposable { - final Observer<? super Boolean> actual; + final Observer<? super Boolean> downstream; final Predicate<? super T> predicate; - Disposable s; + Disposable upstream; boolean done; AnyObserver(Observer<? super Boolean> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -62,15 +62,15 @@ public void onNext(T t) { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } if (b) { done = true; - s.dispose(); - actual.onNext(true); - actual.onComplete(); + upstream.dispose(); + downstream.onNext(true); + downstream.onComplete(); } } @@ -82,26 +82,26 @@ public void onError(Throwable t) { } done = true; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { if (!done) { done = true; - actual.onNext(false); - actual.onComplete(); + downstream.onNext(false); + downstream.onComplete(); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAnySingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAnySingle.java index 0b9c9db0fb..87f0d7c64c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAnySingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAnySingle.java @@ -42,22 +42,22 @@ public Observable<Boolean> fuseToObservable() { static final class AnyObserver<T> implements Observer<T>, Disposable { - final SingleObserver<? super Boolean> actual; + final SingleObserver<? super Boolean> downstream; final Predicate<? super T> predicate; - Disposable s; + Disposable upstream; boolean done; AnyObserver(SingleObserver<? super Boolean> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -71,14 +71,14 @@ public void onNext(T t) { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } if (b) { done = true; - s.dispose(); - actual.onSuccess(true); + upstream.dispose(); + downstream.onSuccess(true); } } @@ -90,25 +90,25 @@ public void onError(Throwable t) { } done = true; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { if (!done) { done = true; - actual.onSuccess(false); + downstream.onSuccess(false); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java index 9471c0b24a..9cb6ba3de3 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java @@ -49,17 +49,17 @@ protected void subscribeActual(Observer<? super U> t) { } static final class BufferExactObserver<T, U extends Collection<? super T>> implements Observer<T>, Disposable { - final Observer<? super U> actual; + final Observer<? super U> downstream; final int count; final Callable<U> bufferSupplier; U buffer; int size; - Disposable s; + Disposable upstream; BufferExactObserver(Observer<? super U> actual, int count, Callable<U> bufferSupplier) { - this.actual = actual; + this.downstream = actual; this.count = count; this.bufferSupplier = bufferSupplier; } @@ -71,11 +71,11 @@ boolean createBuffer() { } catch (Throwable t) { Exceptions.throwIfFatal(t); buffer = null; - if (s == null) { - EmptyDisposable.error(t, actual); + if (upstream == null) { + EmptyDisposable.error(t, downstream); } else { - s.dispose(); - actual.onError(t); + upstream.dispose(); + downstream.onError(t); } return false; } @@ -86,21 +86,21 @@ boolean createBuffer() { } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override @@ -110,7 +110,7 @@ public void onNext(T t) { b.add(t); if (++size >= count) { - actual.onNext(b); + downstream.onNext(b); size = 0; createBuffer(); @@ -121,7 +121,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { buffer = null; - actual.onError(t); + downstream.onError(t); } @Override @@ -130,9 +130,9 @@ public void onComplete() { if (b != null) { buffer = null; if (!b.isEmpty()) { - actual.onNext(b); + downstream.onNext(b); } - actual.onComplete(); + downstream.onComplete(); } } } @@ -141,19 +141,19 @@ static final class BufferSkipObserver<T, U extends Collection<? super T>> extends AtomicBoolean implements Observer<T>, Disposable { private static final long serialVersionUID = -8223395059921494546L; - final Observer<? super U> actual; + final Observer<? super U> downstream; final int count; final int skip; final Callable<U> bufferSupplier; - Disposable s; + Disposable upstream; final ArrayDeque<U> buffers; long index; BufferSkipObserver(Observer<? super U> actual, int count, int skip, Callable<U> bufferSupplier) { - this.actual = actual; + this.downstream = actual; this.count = count; this.skip = skip; this.bufferSupplier = bufferSupplier; @@ -161,22 +161,22 @@ static final class BufferSkipObserver<T, U extends Collection<? super T>> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override @@ -188,8 +188,8 @@ public void onNext(T t) { b = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources."); } catch (Throwable e) { buffers.clear(); - s.dispose(); - actual.onError(e); + upstream.dispose(); + downstream.onError(e); return; } @@ -203,7 +203,7 @@ public void onNext(T t) { if (count <= b.size()) { it.remove(); - actual.onNext(b); + downstream.onNext(b); } } } @@ -211,15 +211,15 @@ public void onNext(T t) { @Override public void onError(Throwable t) { buffers.clear(); - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { while (!buffers.isEmpty()) { - actual.onNext(buffers.poll()); + downstream.onNext(buffers.poll()); } - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundary.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundary.java index b88bce3477..09f5b2d3d7 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundary.java @@ -57,7 +57,7 @@ static final class BufferBoundaryObserver<T, C extends Collection<? super T>, Op private static final long serialVersionUID = -8466418554264089604L; - final Observer<? super C> actual; + final Observer<? super C> downstream; final Callable<C> bufferSupplier; @@ -86,7 +86,7 @@ static final class BufferBoundaryObserver<T, C extends Collection<? super T>, Op Function<? super Open, ? extends ObservableSource<? extends Close>> bufferClose, Callable<C> bufferSupplier ) { - this.actual = actual; + this.downstream = actual; this.bufferSupplier = bufferSupplier; this.bufferOpen = bufferOpen; this.bufferClose = bufferClose; @@ -98,8 +98,8 @@ static final class BufferBoundaryObserver<T, C extends Collection<? super T>, Op } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.setOnce(this.upstream, s)) { + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(this.upstream, d)) { BufferOpenObserver<Open> open = new BufferOpenObserver<Open>(this); observers.add(open); @@ -240,7 +240,7 @@ void drain() { } int missed = 1; - Observer<? super C> a = actual; + Observer<? super C> a = downstream; SpscLinkedArrayQueue<C> q = queue; for (;;) { @@ -293,8 +293,8 @@ static final class BufferOpenObserver<Open> } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); } @Override @@ -342,16 +342,16 @@ static final class BufferCloseObserver<T, C extends Collection<? super T>> } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); } @Override public void onNext(Object t) { - Disposable s = get(); - if (s != DisposableHelper.DISPOSED) { + Disposable upstream = get(); + if (upstream != DisposableHelper.DISPOSED) { lazySet(DisposableHelper.DISPOSED); - s.dispose(); + upstream.dispose(); parent.close(this, index); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundarySupplier.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundarySupplier.java index 15f0dd0a1c..b642bf1c9c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundarySupplier.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundarySupplier.java @@ -50,7 +50,7 @@ static final class BufferBoundarySupplierObserver<T, U extends Collection<? supe final Callable<U> bufferSupplier; final Callable<? extends ObservableSource<B>> boundarySupplier; - Disposable s; + Disposable upstream; final AtomicReference<Disposable> other = new AtomicReference<Disposable>(); @@ -64,11 +64,11 @@ static final class BufferBoundarySupplierObserver<T, U extends Collection<? supe } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - Observer<? super U> actual = this.actual; + Observer<? super U> actual = this.downstream; U b; @@ -77,7 +77,7 @@ public void onSubscribe(Disposable s) { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancelled = true; - s.dispose(); + d.dispose(); EmptyDisposable.error(e, actual); return; } @@ -91,7 +91,7 @@ public void onSubscribe(Disposable s) { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); cancelled = true; - s.dispose(); + d.dispose(); EmptyDisposable.error(ex, actual); return; } @@ -121,7 +121,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { dispose(); - actual.onError(t); + downstream.onError(t); } @Override @@ -137,7 +137,7 @@ public void onComplete() { queue.offer(b); done = true; if (enter()) { - QueueDrainHelper.drainLoop(queue, actual, false, this, this); + QueueDrainHelper.drainLoop(queue, downstream, false, this, this); } } @@ -145,7 +145,7 @@ public void onComplete() { public void dispose() { if (!cancelled) { cancelled = true; - s.dispose(); + upstream.dispose(); disposeOther(); if (enter()) { @@ -172,7 +172,7 @@ void next() { } catch (Throwable e) { Exceptions.throwIfFatal(e); dispose(); - actual.onError(e); + downstream.onError(e); return; } @@ -183,8 +183,8 @@ void next() { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); cancelled = true; - s.dispose(); - actual.onError(ex); + upstream.dispose(); + downstream.onError(ex); return; } @@ -208,7 +208,7 @@ void next() { @Override public void accept(Observer<? super U> a, U v) { - actual.onNext(v); + downstream.onNext(v); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferExactBoundary.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferExactBoundary.java index 9547e21195..b80d303be2 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferExactBoundary.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferExactBoundary.java @@ -48,7 +48,7 @@ static final class BufferExactBoundaryObserver<T, U extends Collection<? super T final Callable<U> bufferSupplier; final ObservableSource<B> boundary; - Disposable s; + Disposable upstream; Disposable other; @@ -62,9 +62,9 @@ static final class BufferExactBoundaryObserver<T, U extends Collection<? super T } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; U b; @@ -73,8 +73,8 @@ public void onSubscribe(Disposable s) { } catch (Throwable e) { Exceptions.throwIfFatal(e); cancelled = true; - s.dispose(); - EmptyDisposable.error(e, actual); + d.dispose(); + EmptyDisposable.error(e, downstream); return; } @@ -83,7 +83,7 @@ public void onSubscribe(Disposable s) { BufferBoundaryObserver<T, U, B> bs = new BufferBoundaryObserver<T, U, B>(this); other = bs; - actual.onSubscribe(this); + downstream.onSubscribe(this); if (!cancelled) { boundary.subscribe(bs); @@ -105,7 +105,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { dispose(); - actual.onError(t); + downstream.onError(t); } @Override @@ -121,7 +121,7 @@ public void onComplete() { queue.offer(b); done = true; if (enter()) { - QueueDrainHelper.drainLoop(queue, actual, false, this, this); + QueueDrainHelper.drainLoop(queue, downstream, false, this, this); } } @@ -130,7 +130,7 @@ public void dispose() { if (!cancelled) { cancelled = true; other.dispose(); - s.dispose(); + upstream.dispose(); if (enter()) { queue.clear(); @@ -152,7 +152,7 @@ void next() { } catch (Throwable e) { Exceptions.throwIfFatal(e); dispose(); - actual.onError(e); + downstream.onError(e); return; } @@ -170,7 +170,7 @@ void next() { @Override public void accept(Observer<? super U> a, U v) { - actual.onNext(v); + downstream.onNext(v); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java index 2bc4bfbec9..bbfef8ffae 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java @@ -85,7 +85,7 @@ static final class BufferExactUnboundedObserver<T, U extends Collection<? super final TimeUnit unit; final Scheduler scheduler; - Disposable s; + Disposable upstream; U buffer; @@ -102,9 +102,9 @@ static final class BufferExactUnboundedObserver<T, U extends Collection<? super } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; U b; @@ -113,18 +113,18 @@ public void onSubscribe(Disposable s) { } catch (Throwable e) { Exceptions.throwIfFatal(e); dispose(); - EmptyDisposable.error(e, actual); + EmptyDisposable.error(e, downstream); return; } buffer = b; - actual.onSubscribe(this); + downstream.onSubscribe(this); if (!cancelled) { - Disposable d = scheduler.schedulePeriodicallyDirect(this, timespan, timespan, unit); - if (!timer.compareAndSet(null, d)) { - d.dispose(); + Disposable task = scheduler.schedulePeriodicallyDirect(this, timespan, timespan, unit); + if (!timer.compareAndSet(null, task)) { + task.dispose(); } } } @@ -146,7 +146,7 @@ public void onError(Throwable t) { synchronized (this) { buffer = null; } - actual.onError(t); + downstream.onError(t); DisposableHelper.dispose(timer); } @@ -161,7 +161,7 @@ public void onComplete() { queue.offer(b); done = true; if (enter()) { - QueueDrainHelper.drainLoop(queue, actual, false, null, this); + QueueDrainHelper.drainLoop(queue, downstream, false, null, this); } } DisposableHelper.dispose(timer); @@ -170,7 +170,7 @@ public void onComplete() { @Override public void dispose() { DisposableHelper.dispose(timer); - s.dispose(); + upstream.dispose(); } @Override @@ -186,7 +186,7 @@ public void run() { next = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null buffer"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); dispose(); return; } @@ -210,7 +210,7 @@ public void run() { @Override public void accept(Observer<? super U> a, U v) { - actual.onNext(v); + downstream.onNext(v); } } @@ -224,7 +224,7 @@ static final class BufferSkipBoundedObserver<T, U extends Collection<? super T>> final List<U> buffers; - Disposable s; + Disposable upstream; BufferSkipBoundedObserver(Observer<? super U> actual, Callable<U> bufferSupplier, long timespan, @@ -239,9 +239,9 @@ static final class BufferSkipBoundedObserver<T, U extends Collection<? super T>> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; final U b; // NOPMD @@ -249,15 +249,15 @@ public void onSubscribe(Disposable s) { b = ObjectHelper.requireNonNull(bufferSupplier.call(), "The buffer supplied is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); - EmptyDisposable.error(e, actual); + d.dispose(); + EmptyDisposable.error(e, downstream); w.dispose(); return; } buffers.add(b); - actual.onSubscribe(this); + downstream.onSubscribe(this); w.schedulePeriodically(this, timeskip, timeskip, unit); @@ -278,7 +278,7 @@ public void onNext(T t) { public void onError(Throwable t) { done = true; clear(); - actual.onError(t); + downstream.onError(t); w.dispose(); } @@ -295,7 +295,7 @@ public void onComplete() { } done = true; if (enter()) { - QueueDrainHelper.drainLoop(queue, actual, false, w, this); + QueueDrainHelper.drainLoop(queue, downstream, false, w, this); } } @@ -304,7 +304,7 @@ public void dispose() { if (!cancelled) { cancelled = true; clear(); - s.dispose(); + upstream.dispose(); w.dispose(); } } @@ -331,7 +331,7 @@ public void run() { b = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null buffer"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); dispose(); return; } @@ -399,7 +399,7 @@ static final class BufferExactBoundedObserver<T, U extends Collection<? super T> Disposable timer; - Disposable s; + Disposable upstream; long producerIndex; @@ -420,9 +420,9 @@ static final class BufferExactBoundedObserver<T, U extends Collection<? super T> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; U b; @@ -430,15 +430,15 @@ public void onSubscribe(Disposable s) { b = ObjectHelper.requireNonNull(bufferSupplier.call(), "The buffer supplied is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); - EmptyDisposable.error(e, actual); + d.dispose(); + EmptyDisposable.error(e, downstream); w.dispose(); return; } buffer = b; - actual.onSubscribe(this); + downstream.onSubscribe(this); timer = w.schedulePeriodically(this, timespan, timespan, unit); } @@ -472,7 +472,7 @@ public void onNext(T t) { b = ObjectHelper.requireNonNull(bufferSupplier.call(), "The buffer supplied is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); dispose(); return; } @@ -491,7 +491,7 @@ public void onError(Throwable t) { synchronized (this) { buffer = null; } - actual.onError(t); + downstream.onError(t); w.dispose(); } @@ -508,7 +508,7 @@ public void onComplete() { queue.offer(b); done = true; if (enter()) { - QueueDrainHelper.drainLoop(queue, actual, false, this, this); + QueueDrainHelper.drainLoop(queue, downstream, false, this, this); } } @@ -522,7 +522,7 @@ public void accept(Observer<? super U> a, U v) { public void dispose() { if (!cancelled) { cancelled = true; - s.dispose(); + upstream.dispose(); w.dispose(); synchronized (this) { buffer = null; @@ -544,7 +544,7 @@ public void run() { } catch (Throwable e) { Exceptions.throwIfFatal(e); dispose(); - actual.onError(e); + downstream.onError(e); return; } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java index b623bf2182..4d7563608f 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java @@ -204,8 +204,8 @@ public void removeChild(ReplayDisposable<T> p) { } @Override - public void onSubscribe(Disposable s) { - connection.update(s); + public void onSubscribe(Disposable d) { + connection.update(d); } /** diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCollect.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCollect.java index 3d694dba9b..8deff52c47 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCollect.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCollect.java @@ -47,37 +47,37 @@ protected void subscribeActual(Observer<? super U> t) { } static final class CollectObserver<T, U> implements Observer<T>, Disposable { - final Observer<? super U> actual; + final Observer<? super U> downstream; final BiConsumer<? super U, ? super T> collector; final U u; - Disposable s; + Disposable upstream; boolean done; CollectObserver(Observer<? super U> actual, U u, BiConsumer<? super U, ? super T> collector) { - this.actual = actual; + this.downstream = actual; this.collector = collector; this.u = u; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -89,7 +89,7 @@ public void onNext(T t) { try { collector.accept(u, t); } catch (Throwable e) { - s.dispose(); + upstream.dispose(); onError(e); } } @@ -101,7 +101,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -110,8 +110,8 @@ public void onComplete() { return; } done = true; - actual.onNext(u); - actual.onComplete(); + downstream.onNext(u); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCollectSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCollectSingle.java index 92e36a26a7..04753eae0a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCollectSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCollectSingle.java @@ -55,37 +55,37 @@ public Observable<U> fuseToObservable() { } static final class CollectObserver<T, U> implements Observer<T>, Disposable { - final SingleObserver<? super U> actual; + final SingleObserver<? super U> downstream; final BiConsumer<? super U, ? super T> collector; final U u; - Disposable s; + Disposable upstream; boolean done; CollectObserver(SingleObserver<? super U> actual, U u, BiConsumer<? super U, ? super T> collector) { - this.actual = actual; + this.downstream = actual; this.collector = collector; this.u = u; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -97,7 +97,7 @@ public void onNext(T t) { try { collector.accept(u, t); } catch (Throwable e) { - s.dispose(); + upstream.dispose(); onError(e); } } @@ -109,7 +109,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -118,7 +118,7 @@ public void onComplete() { return; } done = true; - actual.onSuccess(u); + downstream.onSuccess(u); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java index d8ed6175f6..27b869439a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java @@ -75,7 +75,7 @@ public void subscribeActual(Observer<? super R> observer) { static final class LatestCoordinator<T, R> extends AtomicInteger implements Disposable { private static final long serialVersionUID = 8567835998786448817L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final Function<? super Object[], ? extends R> combiner; final CombinerObserver<T, R>[] observers; Object[] latest; @@ -95,7 +95,7 @@ static final class LatestCoordinator<T, R> extends AtomicInteger implements Disp LatestCoordinator(Observer<? super R> actual, Function<? super Object[], ? extends R> combiner, int count, int bufferSize, boolean delayError) { - this.actual = actual; + this.downstream = actual; this.combiner = combiner; this.delayError = delayError; this.latest = new Object[count]; @@ -110,7 +110,7 @@ static final class LatestCoordinator<T, R> extends AtomicInteger implements Disp public void subscribe(ObservableSource<? extends T>[] sources) { Observer<T>[] as = observers; int len = as.length; - actual.onSubscribe(this); + downstream.onSubscribe(this); for (int i = 0; i < len; i++) { if (done || cancelled) { return; @@ -154,7 +154,7 @@ void drain() { } final SpscLinkedArrayQueue<Object[]> q = queue; - final Observer<? super R> a = actual; + final Observer<? super R> a = downstream; final boolean delayError = this.delayError; int missed = 1; @@ -298,8 +298,8 @@ static final class CombinerObserver<T, R> extends AtomicReference<Disposable> im } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java index f719e0a842..742661690a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java @@ -58,14 +58,14 @@ public void subscribeActual(Observer<? super U> observer) { static final class SourceObserver<T, U> extends AtomicInteger implements Observer<T>, Disposable { private static final long serialVersionUID = 8828587559905699186L; - final Observer<? super U> actual; + final Observer<? super U> downstream; final Function<? super T, ? extends ObservableSource<? extends U>> mapper; final InnerObserver<U> inner; final int bufferSize; SimpleQueue<T> queue; - Disposable s; + Disposable upstream; volatile boolean active; @@ -77,18 +77,18 @@ static final class SourceObserver<T, U> extends AtomicInteger implements Observe SourceObserver(Observer<? super U> actual, Function<? super T, ? extends ObservableSource<? extends U>> mapper, int bufferSize) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.bufferSize = bufferSize; this.inner = new InnerObserver<U>(actual, this); } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - if (s instanceof QueueDisposable) { + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + if (d instanceof QueueDisposable) { @SuppressWarnings("unchecked") - QueueDisposable<T> qd = (QueueDisposable<T>) s; + QueueDisposable<T> qd = (QueueDisposable<T>) d; int m = qd.requestFusion(QueueDisposable.ANY); if (m == QueueDisposable.SYNC) { @@ -96,7 +96,7 @@ public void onSubscribe(Disposable s) { queue = qd; done = true; - actual.onSubscribe(this); + downstream.onSubscribe(this); drain(); return; @@ -106,7 +106,7 @@ public void onSubscribe(Disposable s) { fusionMode = m; queue = qd; - actual.onSubscribe(this); + downstream.onSubscribe(this); return; } @@ -114,7 +114,7 @@ public void onSubscribe(Disposable s) { queue = new SpscLinkedArrayQueue<T>(bufferSize); - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override @@ -135,7 +135,7 @@ public void onError(Throwable t) { } done = true; dispose(); - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { @@ -160,7 +160,7 @@ public boolean isDisposed() { public void dispose() { disposed = true; inner.dispose(); - s.dispose(); + upstream.dispose(); if (getAndIncrement() == 0) { queue.clear(); @@ -189,7 +189,7 @@ void drain() { Exceptions.throwIfFatal(ex); dispose(); queue.clear(); - actual.onError(ex); + downstream.onError(ex); return; } @@ -197,7 +197,7 @@ void drain() { if (d && empty) { disposed = true; - actual.onComplete(); + downstream.onComplete(); return; } @@ -210,7 +210,7 @@ void drain() { Exceptions.throwIfFatal(ex); dispose(); queue.clear(); - actual.onError(ex); + downstream.onError(ex); return; } @@ -229,27 +229,27 @@ static final class InnerObserver<U> extends AtomicReference<Disposable> implemen private static final long serialVersionUID = -7449079488798789337L; - final Observer<? super U> actual; + final Observer<? super U> downstream; final SourceObserver<?, ?> parent; InnerObserver(Observer<? super U> actual, SourceObserver<?, ?> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.set(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.set(this, d); } @Override public void onNext(U t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { parent.dispose(); - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { @@ -269,7 +269,7 @@ static final class ConcatMapDelayErrorObserver<T, R> private static final long serialVersionUID = -6951100001833242599L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final Function<? super T, ? extends ObservableSource<? extends R>> mapper; @@ -283,7 +283,7 @@ static final class ConcatMapDelayErrorObserver<T, R> SimpleQueue<T> queue; - Disposable d; + Disposable upstream; volatile boolean active; @@ -296,7 +296,7 @@ static final class ConcatMapDelayErrorObserver<T, R> ConcatMapDelayErrorObserver(Observer<? super R> actual, Function<? super T, ? extends ObservableSource<? extends R>> mapper, int bufferSize, boolean tillTheEnd) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.bufferSize = bufferSize; this.tillTheEnd = tillTheEnd; @@ -306,8 +306,8 @@ static final class ConcatMapDelayErrorObserver<T, R> @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; if (d instanceof QueueDisposable) { @SuppressWarnings("unchecked") @@ -319,7 +319,7 @@ public void onSubscribe(Disposable d) { queue = qd; done = true; - actual.onSubscribe(this); + downstream.onSubscribe(this); drain(); return; @@ -328,7 +328,7 @@ public void onSubscribe(Disposable d) { sourceMode = m; queue = qd; - actual.onSubscribe(this); + downstream.onSubscribe(this); return; } @@ -336,7 +336,7 @@ public void onSubscribe(Disposable d) { queue = new SpscLinkedArrayQueue<T>(bufferSize); - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -372,7 +372,7 @@ public boolean isDisposed() { @Override public void dispose() { cancelled = true; - d.dispose(); + upstream.dispose(); observer.dispose(); } @@ -382,7 +382,7 @@ void drain() { return; } - Observer<? super R> actual = this.actual; + Observer<? super R> actual = this.downstream; SimpleQueue<T> queue = this.queue; AtomicThrowable error = this.error; @@ -414,7 +414,7 @@ void drain() { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); cancelled = true; - this.d.dispose(); + this.upstream.dispose(); error.addThrowable(ex); actual.onError(error.terminate()); return; @@ -442,7 +442,7 @@ void drain() { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); cancelled = true; - this.d.dispose(); + this.upstream.dispose(); queue.clear(); error.addThrowable(ex); actual.onError(error.terminate()); @@ -481,12 +481,12 @@ static final class DelayErrorInnerObserver<R> extends AtomicReference<Disposable private static final long serialVersionUID = 2620149119579502636L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final ConcatMapDelayErrorObserver<?, R> parent; DelayErrorInnerObserver(Observer<? super R> actual, ConcatMapDelayErrorObserver<?, R> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } @@ -497,7 +497,7 @@ public void onSubscribe(Disposable d) { @Override public void onNext(R value) { - actual.onNext(value); + downstream.onNext(value); } @Override @@ -505,7 +505,7 @@ public void onError(Throwable e) { ConcatMapDelayErrorObserver<?, R> p = parent; if (p.error.addThrowable(e)) { if (!p.tillTheEnd) { - p.d.dispose(); + p.upstream.dispose(); } p.active = false; p.drain(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapEager.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapEager.java index b19ca9bbdf..cb15b10f65 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapEager.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapEager.java @@ -60,7 +60,7 @@ static final class ConcatMapEagerMainObserver<T, R> private static final long serialVersionUID = 8080567949447303262L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final Function<? super T, ? extends ObservableSource<? extends R>> mapper; @@ -76,7 +76,7 @@ static final class ConcatMapEagerMainObserver<T, R> SimpleQueue<T> queue; - Disposable d; + Disposable upstream; volatile boolean done; @@ -91,7 +91,7 @@ static final class ConcatMapEagerMainObserver<T, R> ConcatMapEagerMainObserver(Observer<? super R> actual, Function<? super T, ? extends ObservableSource<? extends R>> mapper, int maxConcurrency, int prefetch, ErrorMode errorMode) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.maxConcurrency = maxConcurrency; this.prefetch = prefetch; @@ -103,8 +103,8 @@ static final class ConcatMapEagerMainObserver<T, R> @SuppressWarnings("unchecked") @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; if (d instanceof QueueDisposable) { QueueDisposable<T> qd = (QueueDisposable<T>) d; @@ -115,7 +115,7 @@ public void onSubscribe(Disposable d) { queue = qd; done = true; - actual.onSubscribe(this); + downstream.onSubscribe(this); drain(); return; @@ -124,7 +124,7 @@ public void onSubscribe(Disposable d) { sourceMode = m; queue = qd; - actual.onSubscribe(this); + downstream.onSubscribe(this); return; } @@ -132,7 +132,7 @@ public void onSubscribe(Disposable d) { queue = new SpscLinkedArrayQueue<T>(prefetch); - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -203,7 +203,7 @@ public void innerNext(InnerQueuedObserver<R> inner, R value) { public void innerError(InnerQueuedObserver<R> inner, Throwable e) { if (error.addThrowable(e)) { if (errorMode == ErrorMode.IMMEDIATE) { - d.dispose(); + upstream.dispose(); } inner.setDone(); drain(); @@ -228,7 +228,7 @@ public void drain() { SimpleQueue<T> q = queue; ArrayDeque<InnerQueuedObserver<R>> observers = this.observers; - Observer<? super R> a = this.actual; + Observer<? super R> a = this.downstream; ErrorMode errorMode = this.errorMode; outer: @@ -267,7 +267,7 @@ public void drain() { source = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null ObservableSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - d.dispose(); + upstream.dispose(); q.clear(); disposeAll(); error.addThrowable(ex); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java index a80795b370..5609455b33 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithCompletable.java @@ -46,38 +46,38 @@ static final class ConcatWithObserver<T> private static final long serialVersionUID = -1953724749712440952L; - final Observer<? super T> actual; + final Observer<? super T> downstream; CompletableSource other; boolean inCompletable; ConcatWithObserver(Observer<? super T> actual, CompletableSource other) { - this.actual = actual; + this.downstream = actual; this.other = other; } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d) && !inCompletable) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { if (inCompletable) { - actual.onComplete(); + downstream.onComplete(); } else { inCompletable = true; DisposableHelper.replace(this, null); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java index 26af9856eb..ee0f5b9799 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybe.java @@ -46,44 +46,44 @@ static final class ConcatWithObserver<T> private static final long serialVersionUID = -1953724749712440952L; - final Observer<? super T> actual; + final Observer<? super T> downstream; MaybeSource<? extends T> other; boolean inMaybe; ConcatWithObserver(Observer<? super T> actual, MaybeSource<? extends T> other) { - this.actual = actual; + this.downstream = actual; this.other = other; } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d) && !inMaybe) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onSuccess(T t) { - actual.onNext(t); - actual.onComplete(); + downstream.onNext(t); + downstream.onComplete(); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { if (inMaybe) { - actual.onComplete(); + downstream.onComplete(); } else { inMaybe = true; DisposableHelper.replace(this, null); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java index 09b4da0fdb..f3548e68a0 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatWithSingle.java @@ -46,38 +46,38 @@ static final class ConcatWithObserver<T> private static final long serialVersionUID = -1953724749712440952L; - final Observer<? super T> actual; + final Observer<? super T> downstream; SingleSource<? extends T> other; boolean inSingle; ConcatWithObserver(Observer<? super T> actual, SingleSource<? extends T> other) { - this.actual = actual; + this.downstream = actual; this.other = other; } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d) && !inSingle) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onSuccess(T t) { - actual.onNext(t); - actual.onComplete(); + downstream.onNext(t); + downstream.onComplete(); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCount.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCount.java index 41b8cc94a9..bf961d47c0 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCount.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCount.java @@ -28,33 +28,33 @@ public void subscribeActual(Observer<? super Long> t) { } static final class CountObserver implements Observer<Object>, Disposable { - final Observer<? super Long> actual; + final Observer<? super Long> downstream; - Disposable s; + Disposable upstream; long count; - CountObserver(Observer<? super Long> actual) { - this.actual = actual; + CountObserver(Observer<? super Long> downstream) { + this.downstream = downstream; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override @@ -64,13 +64,13 @@ public void onNext(Object t) { @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onNext(count); - actual.onComplete(); + downstream.onNext(count); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCountSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCountSingle.java index 2bc3febf7b..1568e00f97 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCountSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCountSingle.java @@ -36,34 +36,34 @@ public Observable<Long> fuseToObservable() { } static final class CountObserver implements Observer<Object>, Disposable { - final SingleObserver<? super Long> actual; + final SingleObserver<? super Long> downstream; - Disposable d; + Disposable upstream; long count; - CountObserver(SingleObserver<? super Long> actual) { - this.actual = actual; + CountObserver(SingleObserver<? super Long> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; - actual.onSubscribe(this); + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override @@ -73,14 +73,14 @@ public void onNext(Object t) { @Override public void onError(Throwable t) { - d = DisposableHelper.DISPOSED; - actual.onError(t); + upstream = DisposableHelper.DISPOSED; + downstream.onError(t); } @Override public void onComplete() { - d = DisposableHelper.DISPOSED; - actual.onSuccess(count); + upstream = DisposableHelper.DISPOSED; + downstream.onSuccess(count); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java index 68ffd7ed82..1e48bdabee 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java @@ -266,8 +266,8 @@ void drainLoop() { } @Override - public void setDisposable(Disposable s) { - emitter.setDisposable(s); + public void setDisposable(Disposable d) { + emitter.setDisposable(d); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounce.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounce.java index 2a70f8ba4e..2c056eb70e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounce.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounce.java @@ -39,10 +39,10 @@ public void subscribeActual(Observer<? super T> t) { static final class DebounceObserver<T, U> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final Function<? super T, ? extends ObservableSource<U>> debounceSelector; - Disposable s; + Disposable upstream; final AtomicReference<Disposable> debouncer = new AtomicReference<Disposable>(); @@ -52,15 +52,15 @@ static final class DebounceObserver<T, U> DebounceObserver(Observer<? super T> actual, Function<? super T, ? extends ObservableSource<U>> debounceSelector) { - this.actual = actual; + this.downstream = actual; this.debounceSelector = debounceSelector; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -85,7 +85,7 @@ public void onNext(T t) { } catch (Throwable e) { Exceptions.throwIfFatal(e); dispose(); - actual.onError(e); + downstream.onError(e); return; } @@ -99,7 +99,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { DisposableHelper.dispose(debouncer); - actual.onError(t); + downstream.onError(t); } @Override @@ -114,24 +114,24 @@ public void onComplete() { DebounceInnerObserver<T, U> dis = (DebounceInnerObserver<T, U>)d; dis.emit(); DisposableHelper.dispose(debouncer); - actual.onComplete(); + downstream.onComplete(); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); DisposableHelper.dispose(debouncer); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } void emit(long idx, T value) { if (idx == index) { - actual.onNext(value); + downstream.onNext(value); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java index dcc56288a7..d37b99ecfd 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java @@ -44,12 +44,12 @@ public void subscribeActual(Observer<? super T> t) { static final class DebounceTimedObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final long timeout; final TimeUnit unit; final Scheduler.Worker worker; - Disposable s; + Disposable upstream; Disposable timer; @@ -58,17 +58,17 @@ static final class DebounceTimedObserver<T> boolean done; DebounceTimedObserver(Observer<? super T> actual, long timeout, TimeUnit unit, Worker worker) { - this.actual = actual; + this.downstream = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -102,7 +102,7 @@ public void onError(Throwable t) { d.dispose(); } done = true; - actual.onError(t); + downstream.onError(t); worker.dispose(); } @@ -122,13 +122,13 @@ public void onComplete() { if (de != null) { de.run(); } - actual.onComplete(); + downstream.onComplete(); worker.dispose(); } @Override public void dispose() { - s.dispose(); + upstream.dispose(); worker.dispose(); } @@ -139,7 +139,7 @@ public boolean isDisposed() { void emit(long idx, T t, DebounceEmitter<T> emitter) { if (idx == index) { - actual.onNext(t); + downstream.onNext(t); emitter.dispose(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDelay.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDelay.java index 8dff7222eb..8c07ed6878 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDelay.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDelay.java @@ -51,17 +51,17 @@ public void subscribeActual(Observer<? super T> t) { } static final class DelayObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final long delay; final TimeUnit unit; final Scheduler.Worker w; final boolean delayError; - Disposable s; + Disposable upstream; DelayObserver(Observer<? super T> actual, long delay, TimeUnit unit, Worker w, boolean delayError) { super(); - this.actual = actual; + this.downstream = actual; this.delay = delay; this.unit = unit; this.w = w; @@ -69,10 +69,10 @@ static final class DelayObserver<T> implements Observer<T>, Disposable { } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -93,7 +93,7 @@ public void onComplete() { @Override public void dispose() { - s.dispose(); + upstream.dispose(); w.dispose(); } @@ -111,7 +111,7 @@ final class OnNext implements Runnable { @Override public void run() { - actual.onNext(t); + downstream.onNext(t); } } @@ -125,7 +125,7 @@ final class OnError implements Runnable { @Override public void run() { try { - actual.onError(throwable); + downstream.onError(throwable); } finally { w.dispose(); } @@ -136,7 +136,7 @@ final class OnComplete implements Runnable { @Override public void run() { try { - actual.onComplete(); + downstream.onComplete(); } finally { w.dispose(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java index 4fa032db0d..70dd6502b5 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java @@ -30,34 +30,34 @@ public void subscribeActual(Observer<? super T> t) { } static final class DematerializeObserver<T> implements Observer<Notification<T>>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; boolean done; - Disposable s; + Disposable upstream; - DematerializeObserver(Observer<? super T> actual) { - this.actual = actual; + DematerializeObserver(Observer<? super T> downstream) { + this.downstream = downstream; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -70,14 +70,14 @@ public void onNext(Notification<T> t) { return; } if (t.isOnError()) { - s.dispose(); + upstream.dispose(); onError(t.getError()); } else if (t.isOnComplete()) { - s.dispose(); + upstream.dispose(); onComplete(); } else { - actual.onNext(t.getValue()); + downstream.onNext(t.getValue()); } } @@ -89,7 +89,7 @@ public void onError(Throwable t) { } done = true; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { @@ -98,7 +98,7 @@ public void onComplete() { } done = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDetach.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDetach.java index b5093e0972..897ac02ebd 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDetach.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDetach.java @@ -37,54 +37,54 @@ protected void subscribeActual(Observer<? super T> observer) { static final class DetachObserver<T> implements Observer<T>, Disposable { - Observer<? super T> actual; + Observer<? super T> downstream; - Disposable s; + Disposable upstream; - DetachObserver(Observer<? super T> actual) { - this.actual = actual; + DetachObserver(Observer<? super T> downstream) { + this.downstream = downstream; } @Override public void dispose() { - Disposable s = this.s; - this.s = EmptyComponent.INSTANCE; - this.actual = EmptyComponent.asObserver(); - s.dispose(); + Disposable d = this.upstream; + this.upstream = EmptyComponent.INSTANCE; + this.downstream = EmptyComponent.asObserver(); + d.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - Observer<? super T> a = actual; - this.s = EmptyComponent.INSTANCE; - this.actual = EmptyComponent.asObserver(); + Observer<? super T> a = downstream; + this.upstream = EmptyComponent.INSTANCE; + this.downstream = EmptyComponent.asObserver(); a.onError(t); } @Override public void onComplete() { - Observer<? super T> a = actual; - this.s = EmptyComponent.INSTANCE; - this.actual = EmptyComponent.asObserver(); + Observer<? super T> a = downstream; + this.upstream = EmptyComponent.INSTANCE; + this.downstream = EmptyComponent.asObserver(); a.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinct.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinct.java index 4e625ee44c..6ebe127e4e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinct.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinct.java @@ -82,10 +82,10 @@ public void onNext(T value) { } if (b) { - actual.onNext(value); + downstream.onNext(value); } } else { - actual.onNext(null); + downstream.onNext(null); } } @@ -96,7 +96,7 @@ public void onError(Throwable e) { } else { done = true; collection.clear(); - actual.onError(e); + downstream.onError(e); } } @@ -105,7 +105,7 @@ public void onComplete() { if (!done) { done = true; collection.clear(); - actual.onComplete(); + downstream.onComplete(); } } @@ -118,7 +118,7 @@ public int requestFusion(int mode) { @Override public T poll() throws Exception { for (;;) { - T v = qs.poll(); + T v = qd.poll(); if (v == null || collection.add(ObjectHelper.requireNonNull(keySelector.apply(v), "The keySelector returned a null key"))) { return v; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChanged.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChanged.java index 065d121b0a..866efd3210 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChanged.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChanged.java @@ -59,7 +59,7 @@ public void onNext(T t) { return; } if (sourceMode != NONE) { - actual.onNext(t); + downstream.onNext(t); return; } @@ -82,7 +82,7 @@ public void onNext(T t) { return; } - actual.onNext(t); + downstream.onNext(t); } @Override @@ -94,7 +94,7 @@ public int requestFusion(int mode) { @Override public T poll() throws Exception { for (;;) { - T v = qs.poll(); + T v = qd.poll(); if (v == null) { return null; } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java index e2d7760413..c84f3571ab 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java @@ -49,7 +49,7 @@ static final class DoAfterObserver<T> extends BasicFuseableObserver<T, T> { @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); if (sourceMode == NONE) { try { @@ -68,7 +68,7 @@ public int requestFusion(int mode) { @Nullable @Override public T poll() throws Exception { - T v = qs.poll(); + T v = qd.poll(); if (v != null) { onAfterNext.accept(v); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java index 196a8c78e2..bc305afde5 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java @@ -47,60 +47,60 @@ static final class DoFinallyObserver<T> extends BasicIntQueueDisposable<T> imple private static final long serialVersionUID = 4109457741734051389L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final Action onFinally; - Disposable d; + Disposable upstream; QueueDisposable<T> qd; boolean syncFused; DoFinallyObserver(Observer<? super T> actual, Action onFinally) { - this.actual = actual; + this.downstream = actual; this.onFinally = onFinally; } @SuppressWarnings("unchecked") @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; if (d instanceof QueueDisposable) { this.qd = (QueueDisposable<T>)d; } - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); runFinally(); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); runFinally(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); runFinally(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoOnEach.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoOnEach.java index 14ad8fe3df..dc3b4561b2 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoOnEach.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoOnEach.java @@ -43,13 +43,13 @@ public void subscribeActual(Observer<? super T> t) { } static final class DoOnEachObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final Consumer<? super T> onNext; final Consumer<? super Throwable> onError; final Action onComplete; final Action onAfterTerminate; - Disposable s; + Disposable upstream; boolean done; @@ -59,7 +59,7 @@ static final class DoOnEachObserver<T> implements Observer<T>, Disposable { Consumer<? super Throwable> onError, Action onComplete, Action onAfterTerminate) { - this.actual = actual; + this.downstream = actual; this.onNext = onNext; this.onError = onError; this.onComplete = onComplete; @@ -67,22 +67,22 @@ static final class DoOnEachObserver<T> implements Observer<T>, Disposable { } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -95,12 +95,12 @@ public void onNext(T t) { onNext.accept(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } - actual.onNext(t); + downstream.onNext(t); } @Override @@ -116,7 +116,7 @@ public void onError(Throwable t) { Exceptions.throwIfFatal(e); t = new CompositeException(t, e); } - actual.onError(t); + downstream.onError(t); try { onAfterTerminate.run(); @@ -140,7 +140,7 @@ public void onComplete() { } done = true; - actual.onComplete(); + downstream.onComplete(); try { onAfterTerminate.run(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAt.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAt.java index 0870ea812d..7abc421572 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAt.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAt.java @@ -37,41 +37,41 @@ public void subscribeActual(Observer<? super T> t) { } static final class ElementAtObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final long index; final T defaultValue; final boolean errorOnFewer; - Disposable s; + Disposable upstream; long count; boolean done; ElementAtObserver(Observer<? super T> actual, long index, T defaultValue, boolean errorOnFewer) { - this.actual = actual; + this.downstream = actual; this.index = index; this.defaultValue = defaultValue; this.errorOnFewer = errorOnFewer; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -83,9 +83,9 @@ public void onNext(T t) { long c = count; if (c == index) { done = true; - s.dispose(); - actual.onNext(t); - actual.onComplete(); + upstream.dispose(); + downstream.onNext(t); + downstream.onComplete(); return; } count = c + 1; @@ -98,7 +98,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -107,12 +107,12 @@ public void onComplete() { done = true; T v = defaultValue; if (v == null && errorOnFewer) { - actual.onError(new NoSuchElementException()); + downstream.onError(new NoSuchElementException()); } else { if (v != null) { - actual.onNext(v); + downstream.onNext(v); } - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtMaybe.java index 1f7db1e68f..84f8d5baf7 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtMaybe.java @@ -37,37 +37,37 @@ public Observable<T> fuseToObservable() { } static final class ElementAtObserver<T> implements Observer<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final long index; - Disposable s; + Disposable upstream; long count; boolean done; ElementAtObserver(MaybeObserver<? super T> actual, long index) { - this.actual = actual; + this.downstream = actual; this.index = index; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -79,8 +79,8 @@ public void onNext(T t) { long c = count; if (c == index) { done = true; - s.dispose(); - actual.onSuccess(t); + upstream.dispose(); + downstream.onSuccess(t); return; } count = c + 1; @@ -93,14 +93,14 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { if (!done) { done = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtSingle.java index dd7e9973f8..6c73a4e91a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtSingle.java @@ -43,39 +43,39 @@ public Observable<T> fuseToObservable() { } static final class ElementAtObserver<T> implements Observer<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final long index; final T defaultValue; - Disposable s; + Disposable upstream; long count; boolean done; ElementAtObserver(SingleObserver<? super T> actual, long index, T defaultValue) { - this.actual = actual; + this.downstream = actual; this.index = index; this.defaultValue = defaultValue; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -87,8 +87,8 @@ public void onNext(T t) { long c = count; if (c == index) { done = true; - s.dispose(); - actual.onSuccess(t); + upstream.dispose(); + downstream.onSuccess(t); return; } count = c + 1; @@ -101,7 +101,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -112,9 +112,9 @@ public void onComplete() { T v = defaultValue; if (v != null) { - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onError(new NoSuchElementException()); + downstream.onError(new NoSuchElementException()); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFilter.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFilter.java index cbe8fa3849..c9ec142a76 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFilter.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFilter.java @@ -49,10 +49,10 @@ public void onNext(T t) { return; } if (b) { - actual.onNext(t); + downstream.onNext(t); } } else { - actual.onNext(null); + downstream.onNext(null); } } @@ -65,7 +65,7 @@ public int requestFusion(int mode) { @Override public T poll() throws Exception { for (;;) { - T v = qs.poll(); + T v = qd.poll(); if (v == null || filter.test(v)) { return v; } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java index 6df47ffa87..76247e8e08 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java @@ -59,7 +59,7 @@ static final class MergeObserver<T, U> extends AtomicInteger implements Disposab private static final long serialVersionUID = -2117620485640801370L; - final Observer<? super U> actual; + final Observer<? super U> downstream; final Function<? super T, ? extends ObservableSource<? extends U>> mapper; final boolean delayErrors; final int maxConcurrency; @@ -79,7 +79,7 @@ static final class MergeObserver<T, U> extends AtomicInteger implements Disposab static final InnerObserver<?, ?>[] CANCELLED = new InnerObserver<?, ?>[0]; - Disposable s; + Disposable upstream; long uniqueId; long lastId; @@ -91,7 +91,7 @@ static final class MergeObserver<T, U> extends AtomicInteger implements Disposab MergeObserver(Observer<? super U> actual, Function<? super T, ? extends ObservableSource<? extends U>> mapper, boolean delayErrors, int maxConcurrency, int bufferSize) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.delayErrors = delayErrors; this.maxConcurrency = maxConcurrency; @@ -103,10 +103,10 @@ static final class MergeObserver<T, U> extends AtomicInteger implements Disposab } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -121,7 +121,7 @@ public void onNext(T t) { p = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null ObservableSource"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } @@ -234,7 +234,7 @@ boolean tryEmitScalar(Callable<? extends U> value) { if (get() == 0 && compareAndSet(0, 1)) { - actual.onNext(u); + downstream.onNext(u); if (decrementAndGet() == 0) { return true; } @@ -263,7 +263,7 @@ boolean tryEmitScalar(Callable<? extends U> value) { void tryEmit(U value, InnerObserver<T, U> inner) { if (get() == 0 && compareAndSet(0, 1)) { - actual.onNext(value); + downstream.onNext(value); if (decrementAndGet() == 0) { return; } @@ -329,7 +329,7 @@ void drain() { } void drainLoop() { - final Observer<? super U> child = this.actual; + final Observer<? super U> child = this.downstream; int missed = 1; for (;;) { if (checkTerminate()) { @@ -503,7 +503,7 @@ boolean checkTerminate() { disposeAll(); e = errors.terminate(); if (e != ExceptionHelper.TERMINATED) { - actual.onError(e); + downstream.onError(e); } return true; } @@ -511,7 +511,7 @@ boolean checkTerminate() { } boolean disposeAll() { - s.dispose(); + upstream.dispose(); InnerObserver<?, ?>[] a = observers.get(); if (a != CANCELLED) { a = observers.getAndSet(CANCELLED); @@ -543,11 +543,11 @@ static final class InnerObserver<T, U> extends AtomicReference<Disposable> this.parent = parent; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.setOnce(this, s)) { - if (s instanceof QueueDisposable) { + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(this, d)) { + if (d instanceof QueueDisposable) { @SuppressWarnings("unchecked") - QueueDisposable<U> qd = (QueueDisposable<U>) s; + QueueDisposable<U> qd = (QueueDisposable<U>) d; int m = qd.requestFusion(QueueDisposable.ANY | QueueDisposable.BOUNDARY); if (m == QueueDisposable.SYNC) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletable.java index dc6c1e8dd7..727d0bc2de 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletable.java @@ -52,7 +52,7 @@ static final class FlatMapCompletableMainObserver<T> extends BasicIntQueueDispos implements Observer<T> { private static final long serialVersionUID = 8443155186132538303L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final AtomicThrowable errors; @@ -62,12 +62,12 @@ static final class FlatMapCompletableMainObserver<T> extends BasicIntQueueDispos final CompositeDisposable set; - Disposable d; + Disposable upstream; volatile boolean disposed; FlatMapCompletableMainObserver(Observer<? super T> observer, Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors) { - this.actual = observer; + this.downstream = observer; this.mapper = mapper; this.delayErrors = delayErrors; this.errors = new AtomicThrowable(); @@ -77,10 +77,10 @@ static final class FlatMapCompletableMainObserver<T> extends BasicIntQueueDispos @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -92,7 +92,7 @@ public void onNext(T value) { cs = ObjectHelper.requireNonNull(mapper.apply(value), "The mapper returned a null CompletableSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - d.dispose(); + upstream.dispose(); onError(ex); return; } @@ -112,13 +112,13 @@ public void onError(Throwable e) { if (delayErrors) { if (decrementAndGet() == 0) { Throwable ex = errors.terminate(); - actual.onError(ex); + downstream.onError(ex); } } else { dispose(); if (getAndSet(0) > 0) { Throwable ex = errors.terminate(); - actual.onError(ex); + downstream.onError(ex); } } } else { @@ -131,9 +131,9 @@ public void onComplete() { if (decrementAndGet() == 0) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } } } @@ -141,13 +141,13 @@ public void onComplete() { @Override public void dispose() { disposed = true; - d.dispose(); + upstream.dispose(); set.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Nullable diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableCompletable.java index 91734a1196..67691a11f8 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableCompletable.java @@ -57,7 +57,7 @@ public Observable<T> fuseToObservable() { static final class FlatMapCompletableMainObserver<T> extends AtomicInteger implements Disposable, Observer<T> { private static final long serialVersionUID = 8443155186132538303L; - final CompletableObserver actual; + final CompletableObserver downstream; final AtomicThrowable errors; @@ -67,12 +67,12 @@ static final class FlatMapCompletableMainObserver<T> extends AtomicInteger imple final CompositeDisposable set; - Disposable d; + Disposable upstream; volatile boolean disposed; FlatMapCompletableMainObserver(CompletableObserver observer, Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors) { - this.actual = observer; + this.downstream = observer; this.mapper = mapper; this.delayErrors = delayErrors; this.errors = new AtomicThrowable(); @@ -82,10 +82,10 @@ static final class FlatMapCompletableMainObserver<T> extends AtomicInteger imple @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -97,7 +97,7 @@ public void onNext(T value) { cs = ObjectHelper.requireNonNull(mapper.apply(value), "The mapper returned a null CompletableSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - d.dispose(); + upstream.dispose(); onError(ex); return; } @@ -117,13 +117,13 @@ public void onError(Throwable e) { if (delayErrors) { if (decrementAndGet() == 0) { Throwable ex = errors.terminate(); - actual.onError(ex); + downstream.onError(ex); } } else { dispose(); if (getAndSet(0) > 0) { Throwable ex = errors.terminate(); - actual.onError(ex); + downstream.onError(ex); } } } else { @@ -136,9 +136,9 @@ public void onComplete() { if (decrementAndGet() == 0) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } } } @@ -146,13 +146,13 @@ public void onComplete() { @Override public void dispose() { disposed = true; - d.dispose(); + upstream.dispose(); set.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } void innerComplete(InnerObserver inner) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybe.java index 51815b4c1e..122572ac50 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybe.java @@ -54,7 +54,7 @@ static final class FlatMapMaybeObserver<T, R> private static final long serialVersionUID = 8600231336733376951L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final boolean delayErrors; @@ -68,13 +68,13 @@ static final class FlatMapMaybeObserver<T, R> final AtomicReference<SpscLinkedArrayQueue<R>> queue; - Disposable d; + Disposable upstream; volatile boolean cancelled; FlatMapMaybeObserver(Observer<? super R> actual, Function<? super T, ? extends MaybeSource<? extends R>> mapper, boolean delayErrors) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.delayErrors = delayErrors; this.set = new CompositeDisposable(); @@ -85,10 +85,10 @@ static final class FlatMapMaybeObserver<T, R> @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -100,7 +100,7 @@ public void onNext(T t) { ms = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null MaybeSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - d.dispose(); + upstream.dispose(); onError(ex); return; } @@ -136,7 +136,7 @@ public void onComplete() { @Override public void dispose() { cancelled = true; - d.dispose(); + upstream.dispose(); set.dispose(); } @@ -148,7 +148,7 @@ public boolean isDisposed() { void innerSuccess(InnerObserver inner, R value) { set.delete(inner); if (get() == 0 && compareAndSet(0, 1)) { - actual.onNext(value); + downstream.onNext(value); boolean d = active.decrementAndGet() == 0; SpscLinkedArrayQueue<R> q = queue.get(); @@ -156,9 +156,9 @@ void innerSuccess(InnerObserver inner, R value) { if (d && (q == null || q.isEmpty())) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } return; } @@ -195,7 +195,7 @@ void innerError(InnerObserver inner, Throwable e) { set.delete(inner); if (errors.addThrowable(e)) { if (!delayErrors) { - d.dispose(); + upstream.dispose(); set.dispose(); } active.decrementAndGet(); @@ -215,9 +215,9 @@ void innerComplete(InnerObserver inner) { if (d && (q == null || q.isEmpty())) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } return; } @@ -246,7 +246,7 @@ void clear() { void drainLoop() { int missed = 1; - Observer<? super R> a = actual; + Observer<? super R> a = downstream; AtomicInteger n = active; AtomicReference<SpscLinkedArrayQueue<R>> qr = queue; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingle.java index 4697d8e106..bedda3cb49 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingle.java @@ -54,7 +54,7 @@ static final class FlatMapSingleObserver<T, R> private static final long serialVersionUID = 8600231336733376951L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final boolean delayErrors; @@ -68,13 +68,13 @@ static final class FlatMapSingleObserver<T, R> final AtomicReference<SpscLinkedArrayQueue<R>> queue; - Disposable d; + Disposable upstream; volatile boolean cancelled; FlatMapSingleObserver(Observer<? super R> actual, Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean delayErrors) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.delayErrors = delayErrors; this.set = new CompositeDisposable(); @@ -85,10 +85,10 @@ static final class FlatMapSingleObserver<T, R> @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -100,7 +100,7 @@ public void onNext(T t) { ms = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - d.dispose(); + upstream.dispose(); onError(ex); return; } @@ -136,7 +136,7 @@ public void onComplete() { @Override public void dispose() { cancelled = true; - d.dispose(); + upstream.dispose(); set.dispose(); } @@ -148,7 +148,7 @@ public boolean isDisposed() { void innerSuccess(InnerObserver inner, R value) { set.delete(inner); if (get() == 0 && compareAndSet(0, 1)) { - actual.onNext(value); + downstream.onNext(value); boolean d = active.decrementAndGet() == 0; SpscLinkedArrayQueue<R> q = queue.get(); @@ -156,9 +156,9 @@ void innerSuccess(InnerObserver inner, R value) { if (d && (q == null || q.isEmpty())) { Throwable ex = errors.terminate(); if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } return; } @@ -195,7 +195,7 @@ void innerError(InnerObserver inner, Throwable e) { set.delete(inner); if (errors.addThrowable(e)) { if (!delayErrors) { - d.dispose(); + upstream.dispose(); set.dispose(); } active.decrementAndGet(); @@ -220,7 +220,7 @@ void clear() { void drainLoop() { int missed = 1; - Observer<? super R> a = actual; + Observer<? super R> a = downstream; AtomicInteger n = active; AtomicReference<SpscLinkedArrayQueue<R>> qr = queue; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlattenIterable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlattenIterable.java index 1781f0a03d..74b1839bb8 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlattenIterable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlattenIterable.java @@ -45,29 +45,29 @@ protected void subscribeActual(Observer<? super R> observer) { } static final class FlattenIterableObserver<T, R> implements Observer<T>, Disposable { - final Observer<? super R> actual; + final Observer<? super R> downstream; final Function<? super T, ? extends Iterable<? extends R>> mapper; - Disposable d; + Disposable upstream; FlattenIterableObserver(Observer<? super R> actual, Function<? super T, ? extends Iterable<? extends R>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T value) { - if (d == DisposableHelper.DISPOSED) { + if (upstream == DisposableHelper.DISPOSED) { return; } @@ -77,12 +77,12 @@ public void onNext(T value) { it = mapper.apply(value).iterator(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - d.dispose(); + upstream.dispose(); onError(ex); return; } - Observer<? super R> a = actual; + Observer<? super R> a = downstream; for (;;) { boolean b; @@ -91,7 +91,7 @@ public void onNext(T value) { b = it.hasNext(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - d.dispose(); + upstream.dispose(); onError(ex); return; } @@ -103,7 +103,7 @@ public void onNext(T value) { v = ObjectHelper.requireNonNull(it.next(), "The iterator returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - d.dispose(); + upstream.dispose(); onError(ex); return; } @@ -117,32 +117,32 @@ public void onNext(T value) { @Override public void onError(Throwable e) { - if (d == DisposableHelper.DISPOSED) { + if (upstream == DisposableHelper.DISPOSED) { RxJavaPlugins.onError(e); return; } - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override public void onComplete() { - if (d == DisposableHelper.DISPOSED) { + if (upstream == DisposableHelper.DISPOSED) { return; } - d = DisposableHelper.DISPOSED; - actual.onComplete(); + upstream = DisposableHelper.DISPOSED; + downstream.onComplete(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java index bd12bec41c..0633d59726 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java @@ -38,7 +38,7 @@ public void subscribeActual(Observer<? super T> observer) { static final class FromArrayDisposable<T> extends BasicQueueDisposable<T> { - final Observer<? super T> actual; + final Observer<? super T> downstream; final T[] array; @@ -49,7 +49,7 @@ static final class FromArrayDisposable<T> extends BasicQueueDisposable<T> { volatile boolean disposed; FromArrayDisposable(Observer<? super T> actual, T[] array) { - this.actual = actual; + this.downstream = actual; this.array = array; } @@ -101,13 +101,13 @@ void run() { for (int i = 0; i < n && !isDisposed(); i++) { T value = a[i]; if (value == null) { - actual.onError(new NullPointerException("The " + i + "th element is null")); + downstream.onError(new NullPointerException("The " + i + "th element is null")); return; } - actual.onNext(value); + downstream.onNext(value); } if (!isDisposed()) { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromIterable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromIterable.java index ae7638e142..f937f4ded5 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromIterable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromIterable.java @@ -61,7 +61,7 @@ public void subscribeActual(Observer<? super T> observer) { static final class FromIterableDisposable<T> extends BasicQueueDisposable<T> { - final Observer<? super T> actual; + final Observer<? super T> downstream; final Iterator<? extends T> it; @@ -74,7 +74,7 @@ static final class FromIterableDisposable<T> extends BasicQueueDisposable<T> { boolean checkNext; FromIterableDisposable(Observer<? super T> actual, Iterator<? extends T> it) { - this.actual = actual; + this.downstream = actual; this.it = it; } @@ -91,11 +91,11 @@ void run() { v = ObjectHelper.requireNonNull(it.next(), "The iterator returned a null value"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } - actual.onNext(v); + downstream.onNext(v); if (isDisposed()) { return; @@ -104,13 +104,13 @@ void run() { hasNext = it.hasNext(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } } while (hasNext); if (!isDisposed()) { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromPublisher.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromPublisher.java index 3de1735670..27b4305c89 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromPublisher.java @@ -34,46 +34,46 @@ protected void subscribeActual(final Observer<? super T> o) { static final class PublisherSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final Observer<? super T> actual; - Subscription s; + final Observer<? super T> downstream; + Subscription upstream; PublisherSubscriber(Observer<? super T> o) { - this.actual = o; + this.downstream = o; } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } } @Override public void dispose() { - s.cancel(); - s = SubscriptionHelper.CANCELLED; + upstream.cancel(); + upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { - return s == SubscriptionHelper.CANCELLED; + return upstream == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java index ac33e689ac..c74f697b7d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java @@ -54,7 +54,7 @@ public void subscribeActual(Observer<? super T> observer) { static final class GeneratorDisposable<T, S> implements Emitter<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final BiFunction<S, ? super Emitter<T>, S> generator; final Consumer<? super S> disposeState; @@ -69,7 +69,7 @@ static final class GeneratorDisposable<T, S> GeneratorDisposable(Observer<? super T> actual, BiFunction<S, ? super Emitter<T>, S> generator, Consumer<? super S> disposeState, S initialState) { - this.actual = actual; + this.downstream = actual; this.generator = generator; this.disposeState = disposeState; this.state = initialState; @@ -147,7 +147,7 @@ public void onNext(T t) { onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); } else { hasNext = true; - actual.onNext(t); + downstream.onNext(t); } } } @@ -162,7 +162,7 @@ public void onError(Throwable t) { t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); } terminate = true; - actual.onError(t); + downstream.onError(t); } } @@ -170,7 +170,7 @@ public void onError(Throwable t) { public void onComplete() { if (!terminate) { terminate = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupBy.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupBy.java index 2667401199..0c0390a107 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupBy.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupBy.java @@ -52,7 +52,7 @@ public static final class GroupByObserver<T, K, V> extends AtomicInteger impleme private static final long serialVersionUID = -3688291656102519502L; - final Observer<? super GroupedObservable<K, V>> actual; + final Observer<? super GroupedObservable<K, V>> downstream; final Function<? super T, ? extends K> keySelector; final Function<? super T, ? extends V> valueSelector; final int bufferSize; @@ -61,12 +61,12 @@ public static final class GroupByObserver<T, K, V> extends AtomicInteger impleme static final Object NULL_KEY = new Object(); - Disposable s; + Disposable upstream; final AtomicBoolean cancelled = new AtomicBoolean(); public GroupByObserver(Observer<? super GroupedObservable<K, V>> actual, Function<? super T, ? extends K> keySelector, Function<? super T, ? extends V> valueSelector, int bufferSize, boolean delayError) { - this.actual = actual; + this.downstream = actual; this.keySelector = keySelector; this.valueSelector = valueSelector; this.bufferSize = bufferSize; @@ -76,10 +76,10 @@ public GroupByObserver(Observer<? super GroupedObservable<K, V>> actual, Functio } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -90,7 +90,7 @@ public void onNext(T t) { key = keySelector.apply(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } @@ -109,7 +109,7 @@ public void onNext(T t) { getAndIncrement(); - actual.onNext(group); + downstream.onNext(group); } V v; @@ -117,7 +117,7 @@ public void onNext(T t) { v = ObjectHelper.requireNonNull(valueSelector.apply(t), "The value supplied is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } @@ -134,7 +134,7 @@ public void onError(Throwable t) { e.onError(t); } - actual.onError(t); + downstream.onError(t); } @Override @@ -146,7 +146,7 @@ public void onComplete() { e.onComplete(); } - actual.onComplete(); + downstream.onComplete(); } @Override @@ -155,7 +155,7 @@ public void dispose() { // but running groups still require new values if (cancelled.compareAndSet(false, true)) { if (decrementAndGet() == 0) { - s.dispose(); + upstream.dispose(); } } } @@ -169,7 +169,7 @@ public void cancel(K key) { Object mapKey = key != null ? key : NULL_KEY; groups.remove(mapKey); if (decrementAndGet() == 0) { - s.dispose(); + upstream.dispose(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java index bf012297cd..3b4baaa78a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java @@ -91,7 +91,7 @@ static final class GroupJoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R> private static final long serialVersionUID = -6071216598687999801L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final SpscLinkedArrayQueue<Object> queue; @@ -130,7 +130,7 @@ static final class GroupJoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R> Function<? super TLeft, ? extends ObservableSource<TLeftEnd>> leftEnd, Function<? super TRight, ? extends ObservableSource<TRightEnd>> rightEnd, BiFunction<? super TLeft, ? super Observable<TRight>, ? extends R> resultSelector) { - this.actual = actual; + this.downstream = actual; this.disposables = new CompositeDisposable(); this.queue = new SpscLinkedArrayQueue<Object>(bufferSize()); this.lefts = new LinkedHashMap<Integer, UnicastSubject<TRight>>(); @@ -191,7 +191,7 @@ void drain() { int missed = 1; SpscLinkedArrayQueue<Object> q = queue; - Observer<? super R> a = actual; + Observer<? super R> a = downstream; for (;;) { for (;;) { @@ -405,8 +405,8 @@ public boolean isDisposed() { } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); } @Override @@ -456,8 +456,8 @@ public boolean isDisposed() { } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableHide.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableHide.java index f85b92c173..6685146fcb 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableHide.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableHide.java @@ -36,45 +36,45 @@ protected void subscribeActual(Observer<? super T> o) { static final class HideDisposable<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; - Disposable d; + Disposable upstream; - HideDisposable(Observer<? super T> actual) { - this.actual = actual; + HideDisposable(Observer<? super T> downstream) { + this.downstream = downstream; } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; - actual.onSubscribe(this); + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableIgnoreElements.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableIgnoreElements.java index 58de57c635..b609cdee0c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableIgnoreElements.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableIgnoreElements.java @@ -28,18 +28,18 @@ public void subscribeActual(final Observer<? super T> t) { } static final class IgnoreObservable<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; - Disposable d; + Disposable upstream; IgnoreObservable(Observer<? super T> t) { - this.actual = t; + this.downstream = t; } @Override - public void onSubscribe(Disposable s) { - this.d = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + this.upstream = d; + downstream.onSubscribe(this); } @Override @@ -49,22 +49,22 @@ public void onNext(T v) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableIgnoreElementsCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableIgnoreElementsCompletable.java index 792dd4f456..15b3789e18 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableIgnoreElementsCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableIgnoreElementsCompletable.java @@ -37,18 +37,18 @@ public Observable<T> fuseToObservable() { } static final class IgnoreObservable<T> implements Observer<T>, Disposable { - final CompletableObserver actual; + final CompletableObserver downstream; - Disposable d; + Disposable upstream; IgnoreObservable(CompletableObserver t) { - this.actual = t; + this.downstream = t; } @Override - public void onSubscribe(Disposable s) { - this.d = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + this.upstream = d; + downstream.onSubscribe(this); } @Override @@ -58,22 +58,22 @@ public void onNext(T v) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java index ae5038b525..f786cffaba 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java @@ -59,12 +59,12 @@ static final class IntervalObserver private static final long serialVersionUID = 346773832286157679L; - final Observer<? super Long> actual; + final Observer<? super Long> downstream; long count; - IntervalObserver(Observer<? super Long> actual) { - this.actual = actual; + IntervalObserver(Observer<? super Long> downstream) { + this.downstream = downstream; } @Override @@ -80,7 +80,7 @@ public boolean isDisposed() { @Override public void run() { if (get() != DisposableHelper.DISPOSED) { - actual.onNext(count++); + downstream.onNext(count++); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java index 9d011b3b6b..2e69495e66 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java @@ -63,13 +63,13 @@ static final class IntervalRangeObserver private static final long serialVersionUID = 1891866368734007884L; - final Observer<? super Long> actual; + final Observer<? super Long> downstream; final long end; long count; IntervalRangeObserver(Observer<? super Long> actual, long start, long end) { - this.actual = actual; + this.downstream = actual; this.count = start; this.end = end; } @@ -88,11 +88,11 @@ public boolean isDisposed() { public void run() { if (!isDisposed()) { long c = count; - actual.onNext(c); + downstream.onNext(c); if (c == end) { DisposableHelper.dispose(this); - actual.onComplete(); + downstream.onComplete(); return; } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java index 5cbde302bb..b8393e3f78 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java @@ -77,7 +77,7 @@ static final class JoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R> private static final long serialVersionUID = -6071216598687999801L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final SpscLinkedArrayQueue<Object> queue; @@ -115,7 +115,7 @@ static final class JoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R> Function<? super TLeft, ? extends ObservableSource<TLeftEnd>> leftEnd, Function<? super TRight, ? extends ObservableSource<TRightEnd>> rightEnd, BiFunction<? super TLeft, ? super TRight, ? extends R> resultSelector) { - this.actual = actual; + this.downstream = actual; this.disposables = new CompositeDisposable(); this.queue = new SpscLinkedArrayQueue<Object>(bufferSize()); this.lefts = new LinkedHashMap<Integer, TLeft>(); @@ -171,7 +171,7 @@ void drain() { int missed = 1; SpscLinkedArrayQueue<Object> q = queue; - Observer<? super R> a = actual; + Observer<? super R> a = downstream; for (;;) { for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableLastMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableLastMaybe.java index a5abffc1bd..d6b0da18d0 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableLastMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableLastMaybe.java @@ -40,33 +40,33 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class LastObserver<T> implements Observer<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - Disposable s; + Disposable upstream; T item; - LastObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + LastObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void dispose() { - s.dispose(); - s = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return s == DisposableHelper.DISPOSED; + return upstream == DisposableHelper.DISPOSED; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -77,20 +77,20 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - s = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; item = null; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - s = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; T v = item; if (v != null) { item = null; - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableLastSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableLastSingle.java index 324bccc04d..b1355f2ca5 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableLastSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableLastSingle.java @@ -45,36 +45,36 @@ protected void subscribeActual(SingleObserver<? super T> observer) { static final class LastObserver<T> implements Observer<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final T defaultItem; - Disposable s; + Disposable upstream; T item; LastObserver(SingleObserver<? super T> actual, T defaultItem) { - this.actual = actual; + this.downstream = actual; this.defaultItem = defaultItem; } @Override public void dispose() { - s.dispose(); - s = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return s == DisposableHelper.DISPOSED; + return upstream == DisposableHelper.DISPOSED; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -85,24 +85,24 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - s = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; item = null; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - s = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; T v = item; if (v != null) { item = null; - actual.onSuccess(v); + downstream.onSuccess(v); } else { v = defaultItem; if (v != null) { - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onError(new NoSuchElementException()); + downstream.onError(new NoSuchElementException()); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMap.java index caed356c01..5df2a6c341 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMap.java @@ -49,7 +49,7 @@ public void onNext(T t) { } if (sourceMode != NONE) { - actual.onNext(null); + downstream.onNext(null); return; } @@ -61,7 +61,7 @@ public void onNext(T t) { fail(ex); return; } - actual.onNext(v); + downstream.onNext(v); } @Override @@ -72,7 +72,7 @@ public int requestFusion(int mode) { @Nullable @Override public U poll() throws Exception { - T t = qs.poll(); + T t = qd.poll(); return t != null ? ObjectHelper.<U>requireNonNull(mapper.apply(t), "The mapper function returned a null value.") : null; } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMapNotification.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMapNotification.java index 1fb5f94451..d6b6e39f47 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMapNotification.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMapNotification.java @@ -46,40 +46,40 @@ public void subscribeActual(Observer<? super ObservableSource<? extends R>> t) { static final class MapNotificationObserver<T, R> implements Observer<T>, Disposable { - final Observer<? super ObservableSource<? extends R>> actual; + final Observer<? super ObservableSource<? extends R>> downstream; final Function<? super T, ? extends ObservableSource<? extends R>> onNextMapper; final Function<? super Throwable, ? extends ObservableSource<? extends R>> onErrorMapper; final Callable<? extends ObservableSource<? extends R>> onCompleteSupplier; - Disposable s; + Disposable upstream; MapNotificationObserver(Observer<? super ObservableSource<? extends R>> actual, Function<? super T, ? extends ObservableSource<? extends R>> onNextMapper, Function<? super Throwable, ? extends ObservableSource<? extends R>> onErrorMapper, Callable<? extends ObservableSource<? extends R>> onCompleteSupplier) { - this.actual = actual; + this.downstream = actual; this.onNextMapper = onNextMapper; this.onErrorMapper = onErrorMapper; this.onCompleteSupplier = onCompleteSupplier; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -91,11 +91,11 @@ public void onNext(T t) { p = ObjectHelper.requireNonNull(onNextMapper.apply(t), "The onNext ObservableSource returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } - actual.onNext(p); + downstream.onNext(p); } @Override @@ -106,12 +106,12 @@ public void onError(Throwable t) { p = ObjectHelper.requireNonNull(onErrorMapper.apply(t), "The onError ObservableSource returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); return; } - actual.onNext(p); - actual.onComplete(); + downstream.onNext(p); + downstream.onComplete(); } @Override @@ -122,12 +122,12 @@ public void onComplete() { p = ObjectHelper.requireNonNull(onCompleteSupplier.call(), "The onComplete ObservableSource returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } - actual.onNext(p); - actual.onComplete(); + downstream.onNext(p); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java index f2db8cc3df..3a89194e97 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java @@ -30,51 +30,51 @@ public void subscribeActual(Observer<? super Notification<T>> t) { } static final class MaterializeObserver<T> implements Observer<T>, Disposable { - final Observer<? super Notification<T>> actual; + final Observer<? super Notification<T>> downstream; - Disposable s; + Disposable upstream; - MaterializeObserver(Observer<? super Notification<T>> actual) { - this.actual = actual; + MaterializeObserver(Observer<? super Notification<T>> downstream) { + this.downstream = downstream; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override public void onNext(T t) { - actual.onNext(Notification.createOnNext(t)); + downstream.onNext(Notification.createOnNext(t)); } @Override public void onError(Throwable t) { Notification<T> v = Notification.createOnError(t); - actual.onNext(v); - actual.onComplete(); + downstream.onNext(v); + downstream.onComplete(); } @Override public void onComplete() { Notification<T> v = Notification.createOnComplete(); - actual.onNext(v); - actual.onComplete(); + downstream.onNext(v); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java index 8fa2f7e2cd..fa020b6ae4 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java @@ -49,7 +49,7 @@ static final class MergeWithObserver<T> extends AtomicInteger private static final long serialVersionUID = -4592979584110982903L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final AtomicReference<Disposable> mainDisposable; @@ -61,8 +61,8 @@ static final class MergeWithObserver<T> extends AtomicInteger volatile boolean otherDone; - MergeWithObserver(Observer<? super T> actual) { - this.actual = actual; + MergeWithObserver(Observer<? super T> downstream) { + this.downstream = downstream; this.mainDisposable = new AtomicReference<Disposable>(); this.otherObserver = new OtherObserver(this); this.error = new AtomicThrowable(); @@ -75,20 +75,20 @@ public void onSubscribe(Disposable d) { @Override public void onNext(T t) { - HalfSerializer.onNext(actual, t, this, error); + HalfSerializer.onNext(downstream, t, this, error); } @Override public void onError(Throwable ex) { DisposableHelper.dispose(mainDisposable); - HalfSerializer.onError(actual, ex, this, error); + HalfSerializer.onError(downstream, ex, this, error); } @Override public void onComplete() { mainDone = true; if (otherDone) { - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } } @@ -105,13 +105,13 @@ public void dispose() { void otherError(Throwable ex) { DisposableHelper.dispose(mainDisposable); - HalfSerializer.onError(actual, ex, this, error); + HalfSerializer.onError(downstream, ex, this, error); } void otherComplete() { otherDone = true; if (mainDone) { - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java index cefa778ebd..23b2532d9b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java @@ -52,7 +52,7 @@ static final class MergeWithObserver<T> extends AtomicInteger private static final long serialVersionUID = -4592979584110982903L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final AtomicReference<Disposable> mainDisposable; @@ -74,8 +74,8 @@ static final class MergeWithObserver<T> extends AtomicInteger static final int OTHER_STATE_CONSUMED_OR_EMPTY = 2; - MergeWithObserver(Observer<? super T> actual) { - this.actual = actual; + MergeWithObserver(Observer<? super T> downstream) { + this.downstream = downstream; this.mainDisposable = new AtomicReference<Disposable>(); this.otherObserver = new OtherObserver<T>(this); this.error = new AtomicThrowable(); @@ -89,7 +89,7 @@ public void onSubscribe(Disposable d) { @Override public void onNext(T t) { if (compareAndSet(0, 1)) { - actual.onNext(t); + downstream.onNext(t); if (decrementAndGet() == 0) { return; } @@ -137,7 +137,7 @@ public void dispose() { void otherSuccess(T value) { if (compareAndSet(0, 1)) { - actual.onNext(value); + downstream.onNext(value); otherState = OTHER_STATE_CONSUMED_OR_EMPTY; } else { singleItem = value; @@ -179,7 +179,7 @@ void drain() { } void drainLoop() { - Observer<? super T> actual = this.actual; + Observer<? super T> actual = this.downstream; int missed = 1; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java index 28f6596915..20c4d21b5c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java @@ -52,7 +52,7 @@ static final class MergeWithObserver<T> extends AtomicInteger private static final long serialVersionUID = -4592979584110982903L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final AtomicReference<Disposable> mainDisposable; @@ -74,8 +74,8 @@ static final class MergeWithObserver<T> extends AtomicInteger static final int OTHER_STATE_CONSUMED_OR_EMPTY = 2; - MergeWithObserver(Observer<? super T> actual) { - this.actual = actual; + MergeWithObserver(Observer<? super T> downstream) { + this.downstream = downstream; this.mainDisposable = new AtomicReference<Disposable>(); this.otherObserver = new OtherObserver<T>(this); this.error = new AtomicThrowable(); @@ -89,7 +89,7 @@ public void onSubscribe(Disposable d) { @Override public void onNext(T t) { if (compareAndSet(0, 1)) { - actual.onNext(t); + downstream.onNext(t); if (decrementAndGet() == 0) { return; } @@ -137,7 +137,7 @@ public void dispose() { void otherSuccess(T value) { if (compareAndSet(0, 1)) { - actual.onNext(value); + downstream.onNext(value); otherState = OTHER_STATE_CONSUMED_OR_EMPTY; } else { singleItem = value; @@ -174,7 +174,7 @@ void drain() { } void drainLoop() { - Observer<? super T> actual = this.actual; + Observer<? super T> actual = this.downstream; int missed = 1; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java index b54b671a86..f415e7016f 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java @@ -50,14 +50,14 @@ static final class ObserveOnObserver<T> extends BasicIntQueueDisposable<T> implements Observer<T>, Runnable { private static final long serialVersionUID = 6576896619930983584L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final Scheduler.Worker worker; final boolean delayError; final int bufferSize; SimpleQueue<T> queue; - Disposable s; + Disposable upstream; Throwable error; volatile boolean done; @@ -69,19 +69,19 @@ static final class ObserveOnObserver<T> extends BasicIntQueueDisposable<T> boolean outputFused; ObserveOnObserver(Observer<? super T> actual, Scheduler.Worker worker, boolean delayError, int bufferSize) { - this.actual = actual; + this.downstream = actual; this.worker = worker; this.delayError = delayError; this.bufferSize = bufferSize; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - if (s instanceof QueueDisposable) { + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + if (d instanceof QueueDisposable) { @SuppressWarnings("unchecked") - QueueDisposable<T> qd = (QueueDisposable<T>) s; + QueueDisposable<T> qd = (QueueDisposable<T>) d; int m = qd.requestFusion(QueueDisposable.ANY | QueueDisposable.BOUNDARY); @@ -89,21 +89,21 @@ public void onSubscribe(Disposable s) { sourceMode = m; queue = qd; done = true; - actual.onSubscribe(this); + downstream.onSubscribe(this); schedule(); return; } if (m == QueueDisposable.ASYNC) { sourceMode = m; queue = qd; - actual.onSubscribe(this); + downstream.onSubscribe(this); return; } } queue = new SpscLinkedArrayQueue<T>(bufferSize); - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -143,7 +143,7 @@ public void onComplete() { public void dispose() { if (!cancelled) { cancelled = true; - s.dispose(); + upstream.dispose(); worker.dispose(); if (getAndIncrement() == 0) { queue.clear(); @@ -166,7 +166,7 @@ void drainNormal() { int missed = 1; final SimpleQueue<T> q = queue; - final Observer<? super T> a = actual; + final Observer<? super T> a = downstream; for (;;) { if (checkTerminated(done, q.isEmpty(), a)) { @@ -181,7 +181,7 @@ void drainNormal() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.dispose(); + upstream.dispose(); q.clear(); a.onError(ex); worker.dispose(); @@ -219,19 +219,19 @@ void drainFused() { Throwable ex = error; if (!delayError && d && ex != null) { - actual.onError(error); + downstream.onError(error); worker.dispose(); return; } - actual.onNext(null); + downstream.onNext(null); if (d) { ex = error; if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onComplete(); + downstream.onComplete(); } worker.dispose(); return; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorNext.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorNext.java index 93df2a0548..649831d59f 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorNext.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorNext.java @@ -39,7 +39,7 @@ public void subscribeActual(Observer<? super T> t) { } static final class OnErrorNextObserver<T> implements Observer<T> { - final Observer<? super T> actual; + final Observer<? super T> downstream; final Function<? super Throwable, ? extends ObservableSource<? extends T>> nextSupplier; final boolean allowFatal; final SequentialDisposable arbiter; @@ -49,15 +49,15 @@ static final class OnErrorNextObserver<T> implements Observer<T> { boolean done; OnErrorNextObserver(Observer<? super T> actual, Function<? super Throwable, ? extends ObservableSource<? extends T>> nextSupplier, boolean allowFatal) { - this.actual = actual; + this.downstream = actual; this.nextSupplier = nextSupplier; this.allowFatal = allowFatal; this.arbiter = new SequentialDisposable(); } @Override - public void onSubscribe(Disposable s) { - arbiter.replace(s); + public void onSubscribe(Disposable d) { + arbiter.replace(d); } @Override @@ -65,7 +65,7 @@ public void onNext(T t) { if (done) { return; } - actual.onNext(t); + downstream.onNext(t); } @Override @@ -75,13 +75,13 @@ public void onError(Throwable t) { RxJavaPlugins.onError(t); return; } - actual.onError(t); + downstream.onError(t); return; } once = true; if (allowFatal && !(t instanceof Exception)) { - actual.onError(t); + downstream.onError(t); return; } @@ -91,14 +91,14 @@ public void onError(Throwable t) { p = nextSupplier.apply(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); return; } if (p == null) { NullPointerException npe = new NullPointerException("Observable is null"); npe.initCause(t); - actual.onError(npe); + downstream.onError(npe); return; } @@ -112,7 +112,7 @@ public void onComplete() { } done = true; once = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturn.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturn.java index 087aa47b24..2ed68d48e9 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturn.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturn.java @@ -32,38 +32,38 @@ public void subscribeActual(Observer<? super T> t) { } static final class OnErrorReturnObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final Function<? super Throwable, ? extends T> valueSupplier; - Disposable s; + Disposable upstream; OnErrorReturnObserver(Observer<? super T> actual, Function<? super Throwable, ? extends T> valueSupplier) { - this.actual = actual; + this.downstream = actual; this.valueSupplier = valueSupplier; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override @@ -73,24 +73,24 @@ public void onError(Throwable t) { v = valueSupplier.apply(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); return; } if (v == null) { NullPointerException e = new NullPointerException("The supplied value is null"); e.initCause(t); - actual.onError(e); + downstream.onError(e); return; } - actual.onNext(v); - actual.onComplete(); + downstream.onNext(v); + downstream.onComplete(); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java index d5fa94eb76..39975af10b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java @@ -136,7 +136,7 @@ static final class PublishObserver<T> */ final AtomicBoolean shouldConnect; - final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); @SuppressWarnings("unchecked") PublishObserver(AtomicReference<PublishObserver<T>> current) { @@ -152,7 +152,7 @@ public void dispose() { if (ps != TERMINATED) { current.compareAndSet(PublishObserver.this, null); - DisposableHelper.dispose(s); + DisposableHelper.dispose(upstream); } } @@ -162,8 +162,8 @@ public boolean isDisposed() { } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this.s, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this.upstream, d); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishSelector.java b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishSelector.java index 05abfd6181..17824fb4ca 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishSelector.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishSelector.java @@ -95,49 +95,49 @@ static final class TargetObserver<T, R> extends AtomicReference<Disposable> implements Observer<R>, Disposable { private static final long serialVersionUID = 854110278590336484L; - final Observer<? super R> actual; + final Observer<? super R> downstream; - Disposable d; + Disposable upstream; - TargetObserver(Observer<? super R> actual) { - this.actual = actual; + TargetObserver(Observer<? super R> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(R value) { - actual.onNext(value); + downstream.onNext(value); } @Override public void onError(Throwable e) { DisposableHelper.dispose(this); - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { DisposableHelper.dispose(this); - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); DisposableHelper.dispose(this); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRange.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRange.java index 2718ef6c8e..19cb08cc21 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRange.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRange.java @@ -40,7 +40,7 @@ static final class RangeDisposable private static final long serialVersionUID = 396518478098735504L; - final Observer<? super Integer> actual; + final Observer<? super Integer> downstream; final long end; @@ -49,7 +49,7 @@ static final class RangeDisposable boolean fused; RangeDisposable(Observer<? super Integer> actual, long start, long end) { - this.actual = actual; + this.downstream = actual; this.index = start; this.end = end; } @@ -58,7 +58,7 @@ void run() { if (fused) { return; } - Observer<? super Integer> actual = this.actual; + Observer<? super Integer> actual = this.downstream; long e = end; for (long i = index; i != e && get() == 0; i++) { actual.onNext((int)i); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRangeLong.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRangeLong.java index 851a5ecea3..55d23d28f1 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRangeLong.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRangeLong.java @@ -37,7 +37,7 @@ static final class RangeDisposable private static final long serialVersionUID = 396518478098735504L; - final Observer<? super Long> actual; + final Observer<? super Long> downstream; final long end; @@ -46,7 +46,7 @@ static final class RangeDisposable boolean fused; RangeDisposable(Observer<? super Long> actual, long start, long end) { - this.actual = actual; + this.downstream = actual; this.index = start; this.end = end; } @@ -55,7 +55,7 @@ void run() { if (fused) { return; } - Observer<? super Long> actual = this.actual; + Observer<? super Long> actual = this.downstream; long e = end; for (long i = index; i != e && get() == 0; i++) { actual.onNext(i); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceMaybe.java index 0215e73fb4..63d0e6c2d1 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceMaybe.java @@ -45,7 +45,7 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { static final class ReduceObserver<T> implements Observer<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; final BiFunction<T, T, T> reducer; @@ -53,19 +53,19 @@ static final class ReduceObserver<T> implements Observer<T>, Disposable { T value; - Disposable d; + Disposable upstream; ReduceObserver(MaybeObserver<? super T> observer, BiFunction<T, T, T> reducer) { - this.actual = observer; + this.downstream = observer; this.reducer = reducer; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -81,7 +81,7 @@ public void onNext(T value) { this.value = ObjectHelper.requireNonNull(reducer.apply(v, value), "The reducer returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - d.dispose(); + upstream.dispose(); onError(ex); } } @@ -96,7 +96,7 @@ public void onError(Throwable e) { } done = true; value = null; - actual.onError(e); + downstream.onError(e); } @Override @@ -108,20 +108,20 @@ public void onComplete() { T v = value; value = null; if (v != null) { - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onComplete(); + downstream.onComplete(); } } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceSeedSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceSeedSingle.java index 9006957348..6a11b91631 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceSeedSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableReduceSeedSingle.java @@ -49,26 +49,26 @@ protected void subscribeActual(SingleObserver<? super R> observer) { static final class ReduceSeedObserver<T, R> implements Observer<T>, Disposable { - final SingleObserver<? super R> actual; + final SingleObserver<? super R> downstream; final BiFunction<R, ? super T, R> reducer; R value; - Disposable d; + Disposable upstream; ReduceSeedObserver(SingleObserver<? super R> actual, BiFunction<R, ? super T, R> reducer, R value) { - this.actual = actual; + this.downstream = actual; this.value = value; this.reducer = reducer; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -80,7 +80,7 @@ public void onNext(T value) { this.value = ObjectHelper.requireNonNull(reducer.apply(v, value), "The reducer returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - d.dispose(); + upstream.dispose(); onError(ex); } } @@ -91,7 +91,7 @@ public void onError(Throwable e) { R v = value; if (v != null) { value = null; - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } @@ -102,18 +102,18 @@ public void onComplete() { R v = value; if (v != null) { value = null; - actual.onSuccess(v); + downstream.onSuccess(v); } } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java index 73b1e0c1db..59b571640d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java @@ -170,7 +170,7 @@ static final class RefCountObserver<T> private static final long serialVersionUID = -7419642935409022375L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final ObservableRefCount<T> parent; @@ -178,22 +178,22 @@ static final class RefCountObserver<T> Disposable upstream; - RefCountObserver(Observer<? super T> actual, ObservableRefCount<T> parent, RefConnection connection) { - this.actual = actual; + RefCountObserver(Observer<? super T> downstream, ObservableRefCount<T> parent, RefConnection connection) { + this.downstream = downstream; this.parent = parent; this.connection = connection; } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { if (compareAndSet(false, true)) { parent.terminated(connection); - actual.onError(t); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -203,7 +203,7 @@ public void onError(Throwable t) { public void onComplete() { if (compareAndSet(false, true)) { parent.terminated(connection); - actual.onComplete(); + downstream.onComplete(); } } @@ -225,7 +225,7 @@ public void onSubscribe(Disposable d) { if (DisposableHelper.validate(upstream, d)) { this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java index c5ce8d1763..426bed7dd9 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java @@ -39,29 +39,29 @@ static final class RepeatObserver<T> extends AtomicInteger implements Observer<T private static final long serialVersionUID = -7098360935104053232L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final SequentialDisposable sd; final ObservableSource<? extends T> source; long remaining; RepeatObserver(Observer<? super T> actual, long count, SequentialDisposable sd, ObservableSource<? extends T> source) { - this.actual = actual; + this.downstream = actual; this.sd = sd; this.source = source; this.remaining = count; } @Override - public void onSubscribe(Disposable s) { - sd.replace(s); + public void onSubscribe(Disposable d) { + sd.replace(d); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override @@ -73,7 +73,7 @@ public void onComplete() { if (r != 0L) { subscribeNext(); } else { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java index 595c5e3b03..8d8b9e29ac 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java @@ -41,29 +41,29 @@ static final class RepeatUntilObserver<T> extends AtomicInteger implements Obser private static final long serialVersionUID = -7098360935104053232L; - final Observer<? super T> actual; - final SequentialDisposable sd; + final Observer<? super T> downstream; + final SequentialDisposable upstream; final ObservableSource<? extends T> source; final BooleanSupplier stop; RepeatUntilObserver(Observer<? super T> actual, BooleanSupplier until, SequentialDisposable sd, ObservableSource<? extends T> source) { - this.actual = actual; - this.sd = sd; + this.downstream = actual; + this.upstream = sd; this.source = source; this.stop = until; } @Override - public void onSubscribe(Disposable s) { - sd.replace(s); + public void onSubscribe(Disposable d) { + upstream.replace(d); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override @@ -73,11 +73,11 @@ public void onComplete() { b = stop.getAsBoolean(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } if (b) { - actual.onComplete(); + downstream.onComplete(); } else { subscribeNext(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java index 36143ebc00..4b8e194973 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java @@ -64,7 +64,7 @@ static final class RepeatWhenObserver<T> extends AtomicInteger implements Observ private static final long serialVersionUID = 802743776666017014L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final AtomicInteger wip; @@ -74,36 +74,36 @@ static final class RepeatWhenObserver<T> extends AtomicInteger implements Observ final InnerRepeatObserver inner; - final AtomicReference<Disposable> d; + final AtomicReference<Disposable> upstream; final ObservableSource<T> source; volatile boolean active; RepeatWhenObserver(Observer<? super T> actual, Subject<Object> signaller, ObservableSource<T> source) { - this.actual = actual; + this.downstream = actual; this.signaller = signaller; this.source = source; this.wip = new AtomicInteger(); this.error = new AtomicThrowable(); this.inner = new InnerRepeatObserver(); - this.d = new AtomicReference<Disposable>(); + this.upstream = new AtomicReference<Disposable>(); } @Override public void onSubscribe(Disposable d) { - DisposableHelper.replace(this.d, d); + DisposableHelper.replace(this.upstream, d); } @Override public void onNext(T t) { - HalfSerializer.onNext(actual, t, this, error); + HalfSerializer.onNext(downstream, t, this, error); } @Override public void onError(Throwable e) { DisposableHelper.dispose(inner); - HalfSerializer.onError(actual, e, this, error); + HalfSerializer.onError(downstream, e, this, error); } @Override @@ -114,12 +114,12 @@ public void onComplete() { @Override public boolean isDisposed() { - return DisposableHelper.isDisposed(d.get()); + return DisposableHelper.isDisposed(upstream.get()); } @Override public void dispose() { - DisposableHelper.dispose(d); + DisposableHelper.dispose(upstream); DisposableHelper.dispose(inner); } @@ -128,13 +128,13 @@ void innerNext() { } void innerError(Throwable ex) { - DisposableHelper.dispose(d); - HalfSerializer.onError(actual, ex, this, error); + DisposableHelper.dispose(upstream); + HalfSerializer.onError(downstream, ex, this, error); } void innerComplete() { - DisposableHelper.dispose(d); - HalfSerializer.onComplete(actual, this, error); + DisposableHelper.dispose(upstream); + HalfSerializer.onComplete(downstream, this, error); } void subscribeNext() { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java index cbf1111400..a743ae55c6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java @@ -43,27 +43,27 @@ static final class RetryBiObserver<T> extends AtomicInteger implements Observer< private static final long serialVersionUID = -7098360935104053232L; - final Observer<? super T> actual; - final SequentialDisposable sa; + final Observer<? super T> downstream; + final SequentialDisposable upstream; final ObservableSource<? extends T> source; final BiPredicate<? super Integer, ? super Throwable> predicate; int retries; RetryBiObserver(Observer<? super T> actual, BiPredicate<? super Integer, ? super Throwable> predicate, SequentialDisposable sa, ObservableSource<? extends T> source) { - this.actual = actual; - this.sa = sa; + this.downstream = actual; + this.upstream = sa; this.source = source; this.predicate = predicate; } @Override - public void onSubscribe(Disposable s) { - sa.update(s); + public void onSubscribe(Disposable d) { + upstream.update(d); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { @@ -72,11 +72,11 @@ public void onError(Throwable t) { b = predicate.test(++retries, t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); return; } if (!b) { - actual.onError(t); + downstream.onError(t); return; } subscribeNext(); @@ -84,7 +84,7 @@ public void onError(Throwable t) { @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } /** @@ -94,7 +94,7 @@ void subscribeNext() { if (getAndIncrement() == 0) { int missed = 1; for (;;) { - if (sa.isDisposed()) { + if (upstream.isDisposed()) { return; } source.subscribe(this); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java index 9c22024a7e..3f98549c1d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java @@ -45,28 +45,28 @@ static final class RepeatObserver<T> extends AtomicInteger implements Observer<T private static final long serialVersionUID = -7098360935104053232L; - final Observer<? super T> actual; - final SequentialDisposable sa; + final Observer<? super T> downstream; + final SequentialDisposable upstream; final ObservableSource<? extends T> source; final Predicate<? super Throwable> predicate; long remaining; RepeatObserver(Observer<? super T> actual, long count, Predicate<? super Throwable> predicate, SequentialDisposable sa, ObservableSource<? extends T> source) { - this.actual = actual; - this.sa = sa; + this.downstream = actual; + this.upstream = sa; this.source = source; this.predicate = predicate; this.remaining = count; } @Override - public void onSubscribe(Disposable s) { - sa.update(s); + public void onSubscribe(Disposable d) { + upstream.update(d); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { @@ -75,18 +75,18 @@ public void onError(Throwable t) { remaining = r - 1; } if (r == 0) { - actual.onError(t); + downstream.onError(t); } else { boolean b; try { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(new CompositeException(t, e)); + downstream.onError(new CompositeException(t, e)); return; } if (!b) { - actual.onError(t); + downstream.onError(t); return; } subscribeNext(); @@ -95,7 +95,7 @@ public void onError(Throwable t) { @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } /** @@ -105,7 +105,7 @@ void subscribeNext() { if (getAndIncrement() == 0) { int missed = 1; for (;;) { - if (sa.isDisposed()) { + if (upstream.isDisposed()) { return; } source.subscribe(this); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryWhen.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryWhen.java index 8c8a780b04..65a17fe269 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryWhen.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryWhen.java @@ -64,7 +64,7 @@ static final class RepeatWhenObserver<T> extends AtomicInteger implements Observ private static final long serialVersionUID = 802743776666017014L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final AtomicInteger wip; @@ -74,30 +74,30 @@ static final class RepeatWhenObserver<T> extends AtomicInteger implements Observ final InnerRepeatObserver inner; - final AtomicReference<Disposable> d; + final AtomicReference<Disposable> upstream; final ObservableSource<T> source; volatile boolean active; RepeatWhenObserver(Observer<? super T> actual, Subject<Throwable> signaller, ObservableSource<T> source) { - this.actual = actual; + this.downstream = actual; this.signaller = signaller; this.source = source; this.wip = new AtomicInteger(); this.error = new AtomicThrowable(); this.inner = new InnerRepeatObserver(); - this.d = new AtomicReference<Disposable>(); + this.upstream = new AtomicReference<Disposable>(); } @Override public void onSubscribe(Disposable d) { - DisposableHelper.replace(this.d, d); + DisposableHelper.replace(this.upstream, d); } @Override public void onNext(T t) { - HalfSerializer.onNext(actual, t, this, error); + HalfSerializer.onNext(downstream, t, this, error); } @Override @@ -109,17 +109,17 @@ public void onError(Throwable e) { @Override public void onComplete() { DisposableHelper.dispose(inner); - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } @Override public boolean isDisposed() { - return DisposableHelper.isDisposed(d.get()); + return DisposableHelper.isDisposed(upstream.get()); } @Override public void dispose() { - DisposableHelper.dispose(d); + DisposableHelper.dispose(upstream); DisposableHelper.dispose(inner); } @@ -128,13 +128,13 @@ void innerNext() { } void innerError(Throwable ex) { - DisposableHelper.dispose(d); - HalfSerializer.onError(actual, ex, this, error); + DisposableHelper.dispose(upstream); + HalfSerializer.onError(downstream, ex, this, error); } void innerComplete() { - DisposableHelper.dispose(d); - HalfSerializer.onComplete(actual, this, error); + DisposableHelper.dispose(upstream); + HalfSerializer.onComplete(downstream, this, error); } void subscribeNext() { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleTimed.java index 9a420fa186..9397438e09 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleTimed.java @@ -51,30 +51,30 @@ abstract static class SampleTimedObserver<T> extends AtomicReference<T> implemen private static final long serialVersionUID = -3517602651313910099L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final long period; final TimeUnit unit; final Scheduler scheduler; final AtomicReference<Disposable> timer = new AtomicReference<Disposable>(); - Disposable s; + Disposable upstream; SampleTimedObserver(Observer<? super T> actual, long period, TimeUnit unit, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.period = period; this.unit = unit; this.scheduler = scheduler; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); - Disposable d = scheduler.schedulePeriodicallyDirect(this, period, period, unit); - DisposableHelper.replace(timer, d); + Disposable task = scheduler.schedulePeriodicallyDirect(this, period, period, unit); + DisposableHelper.replace(timer, task); } } @@ -86,7 +86,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { cancelTimer(); - actual.onError(t); + downstream.onError(t); } @Override @@ -102,18 +102,18 @@ void cancelTimer() { @Override public void dispose() { cancelTimer(); - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } void emit() { T value = getAndSet(null); if (value != null) { - actual.onNext(value); + downstream.onNext(value); } } @@ -130,7 +130,7 @@ static final class SampleTimedNoLast<T> extends SampleTimedObserver<T> { @Override void complete() { - actual.onComplete(); + downstream.onComplete(); } @Override @@ -154,7 +154,7 @@ static final class SampleTimedEmitLast<T> extends SampleTimedObserver<T> { void complete() { emit(); if (wip.decrementAndGet() == 0) { - actual.onComplete(); + downstream.onComplete(); } } @@ -163,7 +163,7 @@ public void run() { if (wip.incrementAndGet() == 2) { emit(); if (wip.decrementAndGet() == 0) { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleWithObservable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleWithObservable.java index 5a6f092ce1..fcb0f33a00 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleWithObservable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleWithObservable.java @@ -47,23 +47,23 @@ abstract static class SampleMainObserver<T> extends AtomicReference<T> private static final long serialVersionUID = -3517602651313910099L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final ObservableSource<?> sampler; final AtomicReference<Disposable> other = new AtomicReference<Disposable>(); - Disposable s; + Disposable upstream; SampleMainObserver(Observer<? super T> actual, ObservableSource<?> other) { - this.actual = actual; + this.downstream = actual; this.sampler = other; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); if (other.get() == null) { sampler.subscribe(new SamplerObserver<T>(this)); } @@ -78,7 +78,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { DisposableHelper.dispose(other); - actual.onError(t); + downstream.onError(t); } @Override @@ -94,7 +94,7 @@ boolean setOther(Disposable o) { @Override public void dispose() { DisposableHelper.dispose(other); - s.dispose(); + upstream.dispose(); } @Override @@ -103,19 +103,19 @@ public boolean isDisposed() { } public void error(Throwable e) { - s.dispose(); - actual.onError(e); + upstream.dispose(); + downstream.onError(e); } public void complete() { - s.dispose(); + upstream.dispose(); completeOther(); } void emit() { T value = getAndSet(null); if (value != null) { - actual.onNext(value); + downstream.onNext(value); } } @@ -134,8 +134,8 @@ static final class SamplerObserver<T> implements Observer<Object> { } @Override - public void onSubscribe(Disposable s) { - parent.setOther(s); + public void onSubscribe(Disposable d) { + parent.setOther(d); } @Override @@ -164,12 +164,12 @@ static final class SampleMainNoLast<T> extends SampleMainObserver<T> { @Override void completeMain() { - actual.onComplete(); + downstream.onComplete(); } @Override void completeOther() { - actual.onComplete(); + downstream.onComplete(); } @Override @@ -196,7 +196,7 @@ void completeMain() { done = true; if (wip.getAndIncrement() == 0) { emit(); - actual.onComplete(); + downstream.onComplete(); } } @@ -205,7 +205,7 @@ void completeOther() { done = true; if (wip.getAndIncrement() == 0) { emit(); - actual.onComplete(); + downstream.onComplete(); } } @@ -216,7 +216,7 @@ void run() { boolean d = done; emit(); if (d) { - actual.onComplete(); + downstream.onComplete(); return; } } while (wip.decrementAndGet() != 0); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableScan.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableScan.java index 2e3a6b4fda..13fd31fa1a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableScan.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableScan.java @@ -34,37 +34,37 @@ public void subscribeActual(Observer<? super T> t) { } static final class ScanObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final BiFunction<T, T, T> accumulator; - Disposable s; + Disposable upstream; T value; boolean done; ScanObserver(Observer<? super T> actual, BiFunction<T, T, T> accumulator) { - this.actual = actual; + this.downstream = actual; this.accumulator = accumulator; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -73,7 +73,7 @@ public void onNext(T t) { if (done) { return; } - final Observer<? super T> a = actual; + final Observer<? super T> a = downstream; T v = value; if (v == null) { value = t; @@ -85,7 +85,7 @@ public void onNext(T t) { u = ObjectHelper.requireNonNull(accumulator.apply(v, t), "The value returned by the accumulator is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } @@ -102,7 +102,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -111,7 +111,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableScanSeed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableScanSeed.java index 6eda15b035..6f9222fbee 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableScanSeed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableScanSeed.java @@ -48,41 +48,41 @@ public void subscribeActual(Observer<? super R> t) { } static final class ScanSeedObserver<T, R> implements Observer<T>, Disposable { - final Observer<? super R> actual; + final Observer<? super R> downstream; final BiFunction<R, ? super T, R> accumulator; R value; - Disposable s; + Disposable upstream; boolean done; ScanSeedObserver(Observer<? super R> actual, BiFunction<R, ? super T, R> accumulator, R value) { - this.actual = actual; + this.downstream = actual; this.accumulator = accumulator; this.value = value; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); - actual.onNext(value); + downstream.onNext(value); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override @@ -99,14 +99,14 @@ public void onNext(T t) { u = ObjectHelper.requireNonNull(accumulator.apply(v, t), "The accumulator returned a null value"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } value = u; - actual.onNext(u); + downstream.onNext(u); } @Override @@ -116,7 +116,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -125,7 +125,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqual.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqual.java index aab9dcab05..07da31f3f0 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqual.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqual.java @@ -46,7 +46,7 @@ public void subscribeActual(Observer<? super Boolean> observer) { static final class EqualCoordinator<T> extends AtomicInteger implements Disposable { private static final long serialVersionUID = -6178010334400373240L; - final Observer<? super Boolean> actual; + final Observer<? super Boolean> downstream; final BiPredicate<? super T, ? super T> comparer; final ArrayCompositeDisposable resources; final ObservableSource<? extends T> first; @@ -62,7 +62,7 @@ static final class EqualCoordinator<T> extends AtomicInteger implements Disposab EqualCoordinator(Observer<? super Boolean> actual, int bufferSize, ObservableSource<? extends T> first, ObservableSource<? extends T> second, BiPredicate<? super T, ? super T> comparer) { - this.actual = actual; + this.downstream = actual; this.first = first; this.second = second; this.comparer = comparer; @@ -74,8 +74,8 @@ static final class EqualCoordinator<T> extends AtomicInteger implements Disposab this.resources = new ArrayCompositeDisposable(2); } - boolean setDisposable(Disposable s, int index) { - return resources.setResource(index, s); + boolean setDisposable(Disposable d, int index) { + return resources.setResource(index, d); } void subscribe() { @@ -138,7 +138,7 @@ void drain() { if (e != null) { cancel(q1, q2); - actual.onError(e); + downstream.onError(e); return; } } @@ -149,7 +149,7 @@ void drain() { if (e != null) { cancel(q1, q2); - actual.onError(e); + downstream.onError(e); return; } } @@ -165,15 +165,15 @@ void drain() { boolean e2 = v2 == null; if (d1 && d2 && e1 && e2) { - actual.onNext(true); - actual.onComplete(); + downstream.onNext(true); + downstream.onComplete(); return; } if ((d1 && d2) && (e1 != e2)) { cancel(q1, q2); - actual.onNext(false); - actual.onComplete(); + downstream.onNext(false); + downstream.onComplete(); return; } @@ -186,15 +186,15 @@ void drain() { Exceptions.throwIfFatal(ex); cancel(q1, q2); - actual.onError(ex); + downstream.onError(ex); return; } if (!c) { cancel(q1, q2); - actual.onNext(false); - actual.onComplete(); + downstream.onNext(false); + downstream.onComplete(); return; } @@ -230,8 +230,8 @@ static final class EqualObserver<T> implements Observer<T> { } @Override - public void onSubscribe(Disposable s) { - parent.setDisposable(s, index); + public void onSubscribe(Disposable d) { + parent.setDisposable(d, index); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualSingle.java index 742b7fb39c..88e059a5cb 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualSingle.java @@ -53,7 +53,7 @@ public Observable<Boolean> fuseToObservable() { static final class EqualCoordinator<T> extends AtomicInteger implements Disposable { private static final long serialVersionUID = -6178010334400373240L; - final SingleObserver<? super Boolean> actual; + final SingleObserver<? super Boolean> downstream; final BiPredicate<? super T, ? super T> comparer; final ArrayCompositeDisposable resources; final ObservableSource<? extends T> first; @@ -69,7 +69,7 @@ static final class EqualCoordinator<T> extends AtomicInteger implements Disposab EqualCoordinator(SingleObserver<? super Boolean> actual, int bufferSize, ObservableSource<? extends T> first, ObservableSource<? extends T> second, BiPredicate<? super T, ? super T> comparer) { - this.actual = actual; + this.downstream = actual; this.first = first; this.second = second; this.comparer = comparer; @@ -81,8 +81,8 @@ static final class EqualCoordinator<T> extends AtomicInteger implements Disposab this.resources = new ArrayCompositeDisposable(2); } - boolean setDisposable(Disposable s, int index) { - return resources.setResource(index, s); + boolean setDisposable(Disposable d, int index) { + return resources.setResource(index, d); } void subscribe() { @@ -145,7 +145,7 @@ void drain() { if (e != null) { cancel(q1, q2); - actual.onError(e); + downstream.onError(e); return; } } @@ -156,7 +156,7 @@ void drain() { if (e != null) { cancel(q1, q2); - actual.onError(e); + downstream.onError(e); return; } } @@ -172,13 +172,13 @@ void drain() { boolean e2 = v2 == null; if (d1 && d2 && e1 && e2) { - actual.onSuccess(true); + downstream.onSuccess(true); return; } if ((d1 && d2) && (e1 != e2)) { cancel(q1, q2); - actual.onSuccess(false); + downstream.onSuccess(false); return; } @@ -191,14 +191,14 @@ void drain() { Exceptions.throwIfFatal(ex); cancel(q1, q2); - actual.onError(ex); + downstream.onError(ex); return; } if (!c) { cancel(q1, q2); - actual.onSuccess(false); + downstream.onSuccess(false); return; } @@ -234,8 +234,8 @@ static final class EqualObserver<T> implements Observer<T> { } @Override - public void onSubscribe(Disposable s) { - parent.setDisposable(s, index); + public void onSubscribe(Disposable d) { + parent.setDisposable(d, index); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleMaybe.java index 3dc75441bf..ab45f7b29f 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleMaybe.java @@ -31,35 +31,35 @@ public void subscribeActual(MaybeObserver<? super T> t) { } static final class SingleElementObserver<T> implements Observer<T>, Disposable { - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; - Disposable s; + Disposable upstream; T value; boolean done; - SingleElementObserver(MaybeObserver<? super T> actual) { - this.actual = actual; + SingleElementObserver(MaybeObserver<? super T> downstream) { + this.downstream = downstream; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -70,8 +70,8 @@ public void onNext(T t) { } if (value != null) { done = true; - s.dispose(); - actual.onError(new IllegalArgumentException("Sequence contains more than one element!")); + upstream.dispose(); + downstream.onError(new IllegalArgumentException("Sequence contains more than one element!")); return; } value = t; @@ -84,7 +84,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -96,9 +96,9 @@ public void onComplete() { T v = value; value = null; if (v == null) { - actual.onComplete(); + downstream.onComplete(); } else { - actual.onSuccess(v); + downstream.onSuccess(v); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleSingle.java index 40ac65da57..79f7aaa4b2 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleSingle.java @@ -36,38 +36,38 @@ public void subscribeActual(SingleObserver<? super T> t) { } static final class SingleElementObserver<T> implements Observer<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final T defaultValue; - Disposable s; + Disposable upstream; T value; boolean done; SingleElementObserver(SingleObserver<? super T> actual, T defaultValue) { - this.actual = actual; + this.downstream = actual; this.defaultValue = defaultValue; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -78,8 +78,8 @@ public void onNext(T t) { } if (value != null) { done = true; - s.dispose(); - actual.onError(new IllegalArgumentException("Sequence contains more than one element!")); + upstream.dispose(); + downstream.onError(new IllegalArgumentException("Sequence contains more than one element!")); return; } value = t; @@ -92,7 +92,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -108,9 +108,9 @@ public void onComplete() { } if (v != null) { - actual.onSuccess(v); + downstream.onSuccess(v); } else { - actual.onError(new NoSuchElementException()); + downstream.onError(new NoSuchElementException()); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java index 570c4e8877..a03bca541f 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java @@ -30,21 +30,21 @@ public void subscribeActual(Observer<? super T> observer) { } static final class SkipObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; long remaining; - Disposable d; + Disposable upstream; SkipObserver(Observer<? super T> actual, long n) { - this.actual = actual; + this.downstream = actual; this.remaining = n; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; - actual.onSubscribe(this); + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -53,28 +53,28 @@ public void onNext(T t) { if (remaining != 0L) { remaining--; } else { - actual.onNext(t); + downstream.onNext(t); } } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java index f22df6fdf7..3c6de3847a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java @@ -35,52 +35,52 @@ public void subscribeActual(Observer<? super T> observer) { static final class SkipLastObserver<T> extends ArrayDeque<T> implements Observer<T>, Disposable { private static final long serialVersionUID = -3807491841935125653L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final int skip; - Disposable s; + Disposable upstream; SkipLastObserver(Observer<? super T> actual, int skip) { super(skip); - this.actual = actual; + this.downstream = actual; this.skip = skip; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override public void onNext(T t) { if (skip == size()) { - actual.onNext(poll()); + downstream.onNext(poll()); } offer(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimed.java index b24d341245..3c9eb40261 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimed.java @@ -46,14 +46,14 @@ public void subscribeActual(Observer<? super T> t) { static final class SkipLastTimedObserver<T> extends AtomicInteger implements Observer<T>, Disposable { private static final long serialVersionUID = -5677354903406201275L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final long time; final TimeUnit unit; final Scheduler scheduler; final SpscLinkedArrayQueue<Object> queue; final boolean delayError; - Disposable s; + Disposable upstream; volatile boolean cancelled; @@ -61,7 +61,7 @@ static final class SkipLastTimedObserver<T> extends AtomicInteger implements Obs Throwable error; SkipLastTimedObserver(Observer<? super T> actual, long time, TimeUnit unit, Scheduler scheduler, int bufferSize, boolean delayError) { - this.actual = actual; + this.downstream = actual; this.time = time; this.unit = unit; this.scheduler = scheduler; @@ -70,10 +70,10 @@ static final class SkipLastTimedObserver<T> extends AtomicInteger implements Obs } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -105,7 +105,7 @@ public void onComplete() { public void dispose() { if (!cancelled) { cancelled = true; - s.dispose(); + upstream.dispose(); if (getAndIncrement() == 0) { queue.clear(); @@ -125,7 +125,7 @@ void drain() { int missed = 1; - final Observer<? super T> a = actual; + final Observer<? super T> a = downstream; final SpscLinkedArrayQueue<Object> q = queue; final boolean delayError = this.delayError; final TimeUnit unit = this.unit; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipUntil.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipUntil.java index c9f711ff3e..f02edecf0e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipUntil.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipUntil.java @@ -43,56 +43,56 @@ public void subscribeActual(Observer<? super T> child) { static final class SkipUntilObserver<T> implements Observer<T> { - final Observer<? super T> actual; + final Observer<? super T> downstream; final ArrayCompositeDisposable frc; - Disposable s; + Disposable upstream; volatile boolean notSkipping; boolean notSkippingLocal; SkipUntilObserver(Observer<? super T> actual, ArrayCompositeDisposable frc) { - this.actual = actual; + this.downstream = actual; this.frc = frc; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - frc.setResource(0, s); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + frc.setResource(0, d); } } @Override public void onNext(T t) { if (notSkippingLocal) { - actual.onNext(t); + downstream.onNext(t); } else if (notSkipping) { notSkippingLocal = true; - actual.onNext(t); + downstream.onNext(t); } } @Override public void onError(Throwable t) { frc.dispose(); - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { frc.dispose(); - actual.onComplete(); + downstream.onComplete(); } } final class SkipUntil implements Observer<U> { - private final ArrayCompositeDisposable frc; - private final SkipUntilObserver<T> sus; - private final SerializedObserver<T> serial; - Disposable s; + final ArrayCompositeDisposable frc; + final SkipUntilObserver<T> sus; + final SerializedObserver<T> serial; + Disposable upstream; SkipUntil(ArrayCompositeDisposable frc, SkipUntilObserver<T> sus, SerializedObserver<T> serial) { this.frc = frc; @@ -101,16 +101,16 @@ final class SkipUntil implements Observer<U> { } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - frc.setResource(1, s); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + frc.setResource(1, d); } } @Override public void onNext(U t) { - s.dispose(); + upstream.dispose(); sus.notSkipping = true; } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java index dfe5fd1d9c..a39b553563 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java @@ -32,64 +32,64 @@ public void subscribeActual(Observer<? super T> observer) { } static final class SkipWhileObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final Predicate<? super T> predicate; - Disposable s; + Disposable upstream; boolean notSkipping; SkipWhileObserver(Observer<? super T> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override public void onNext(T t) { if (notSkipping) { - actual.onNext(t); + downstream.onNext(t); } else { boolean b; try { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); - actual.onError(e); + upstream.dispose(); + downstream.onError(e); return; } if (!b) { notSkipping = true; - actual.onNext(t); + downstream.onNext(t); } } } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSubscribeOn.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSubscribeOn.java index c55a224155..7e697d379a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSubscribeOn.java @@ -39,38 +39,38 @@ public void subscribeActual(final Observer<? super T> observer) { static final class SubscribeOnObserver<T> extends AtomicReference<Disposable> implements Observer<T>, Disposable { private static final long serialVersionUID = 8094547886072529208L; - final Observer<? super T> actual; + final Observer<? super T> downstream; - final AtomicReference<Disposable> s; + final AtomicReference<Disposable> upstream; - SubscribeOnObserver(Observer<? super T> actual) { - this.actual = actual; - this.s = new AtomicReference<Disposable>(); + SubscribeOnObserver(Observer<? super T> downstream) { + this.downstream = downstream; + this.upstream = new AtomicReference<Disposable>(); } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this.s, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this.upstream, d); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { - DisposableHelper.dispose(s); + DisposableHelper.dispose(upstream); DisposableHelper.dispose(this); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmpty.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmpty.java index aa97b7f18a..6eec37f7a1 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmpty.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmpty.java @@ -32,22 +32,22 @@ public void subscribeActual(Observer<? super T> t) { } static final class SwitchIfEmptyObserver<T> implements Observer<T> { - final Observer<? super T> actual; + final Observer<? super T> downstream; final ObservableSource<? extends T> other; final SequentialDisposable arbiter; boolean empty; SwitchIfEmptyObserver(Observer<? super T> actual, ObservableSource<? extends T> other) { - this.actual = actual; + this.downstream = actual; this.other = other; this.empty = true; this.arbiter = new SequentialDisposable(); } @Override - public void onSubscribe(Disposable s) { - arbiter.update(s); + public void onSubscribe(Disposable d) { + arbiter.update(d); } @Override @@ -55,12 +55,12 @@ public void onNext(T t) { if (empty) { empty = false; } - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override @@ -69,7 +69,7 @@ public void onComplete() { empty = false; other.subscribe(this); } else { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java index 032f84dbc6..8c5aa371dc 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java @@ -54,7 +54,7 @@ public void subscribeActual(Observer<? super R> t) { static final class SwitchMapObserver<T, R> extends AtomicInteger implements Observer<T>, Disposable { private static final long serialVersionUID = -3491074160481096299L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final Function<? super T, ? extends ObservableSource<? extends R>> mapper; final int bufferSize; @@ -66,7 +66,7 @@ static final class SwitchMapObserver<T, R> extends AtomicInteger implements Obse volatile boolean cancelled; - Disposable s; + Disposable upstream; final AtomicReference<SwitchMapInnerObserver<T, R>> active = new AtomicReference<SwitchMapInnerObserver<T, R>>(); @@ -81,7 +81,7 @@ static final class SwitchMapObserver<T, R> extends AtomicInteger implements Obse SwitchMapObserver(Observer<? super R> actual, Function<? super T, ? extends ObservableSource<? extends R>> mapper, int bufferSize, boolean delayErrors) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.bufferSize = bufferSize; this.delayErrors = delayErrors; @@ -89,10 +89,10 @@ static final class SwitchMapObserver<T, R> extends AtomicInteger implements Obse } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -111,7 +111,7 @@ public void onNext(T t) { p = ObjectHelper.requireNonNull(mapper.apply(t), "The ObservableSource returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } @@ -155,7 +155,7 @@ public void onComplete() { public void dispose() { if (!cancelled) { cancelled = true; - s.dispose(); + upstream.dispose(); disposeInner(); } } @@ -181,7 +181,7 @@ void drain() { return; } - final Observer<? super R> a = actual; + final Observer<? super R> a = downstream; final AtomicReference<SwitchMapInnerObserver<T, R>> active = this.active; final boolean delayErrors = this.delayErrors; @@ -274,7 +274,7 @@ void drain() { active.compareAndSet(inner, null); if (!delayErrors) { disposeInner(); - s.dispose(); + upstream.dispose(); done = true; } else { inner.cancel(); @@ -313,7 +313,7 @@ void drain() { void innerError(SwitchMapInnerObserver<T, R> inner, Throwable ex) { if (inner.index == unique && errors.addThrowable(ex)) { if (!delayErrors) { - s.dispose(); + upstream.dispose(); } inner.done = true; drain(); @@ -342,11 +342,11 @@ static final class SwitchMapInnerObserver<T, R> extends AtomicReference<Disposab } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.setOnce(this, s)) { - if (s instanceof QueueDisposable) { + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(this, d)) { + if (d instanceof QueueDisposable) { @SuppressWarnings("unchecked") - QueueDisposable<R> qd = (QueueDisposable<R>) s; + QueueDisposable<R> qd = (QueueDisposable<R>) d; int m = qd.requestFusion(QueueDisposable.ANY | QueueDisposable.BOUNDARY); if (m == QueueDisposable.SYNC) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTake.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTake.java index 418ec23e7a..7bda3017d5 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTake.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTake.java @@ -31,27 +31,27 @@ protected void subscribeActual(Observer<? super T> observer) { } static final class TakeObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; boolean done; - Disposable subscription; + Disposable upstream; long remaining; TakeObserver(Observer<? super T> actual, long limit) { - this.actual = actual; + this.downstream = actual; this.remaining = limit; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.subscription, s)) { - subscription = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + upstream = d; if (remaining == 0) { done = true; - s.dispose(); - EmptyDisposable.complete(actual); + d.dispose(); + EmptyDisposable.complete(downstream); } else { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } } @@ -59,7 +59,7 @@ public void onSubscribe(Disposable s) { public void onNext(T t) { if (!done && remaining-- > 0) { boolean stop = remaining == 0; - actual.onNext(t); + downstream.onNext(t); if (stop) { onComplete(); } @@ -73,26 +73,26 @@ public void onError(Throwable t) { } done = true; - subscription.dispose(); - actual.onError(t); + upstream.dispose(); + downstream.onError(t); } @Override public void onComplete() { if (!done) { done = true; - subscription.dispose(); - actual.onComplete(); + upstream.dispose(); + downstream.onComplete(); } } @Override public void dispose() { - subscription.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return subscription.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLast.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLast.java index 239ec3dea2..92f0510f11 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLast.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLast.java @@ -35,23 +35,23 @@ public void subscribeActual(Observer<? super T> t) { static final class TakeLastObserver<T> extends ArrayDeque<T> implements Observer<T>, Disposable { private static final long serialVersionUID = 7240042530241604978L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final int count; - Disposable s; + Disposable upstream; volatile boolean cancelled; TakeLastObserver(Observer<? super T> actual, int count) { - this.actual = actual; + this.downstream = actual; this.count = count; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -65,12 +65,12 @@ public void onNext(T t) { @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - Observer<? super T> a = actual; + Observer<? super T> a = downstream; for (;;) { if (cancelled) { return; @@ -90,7 +90,7 @@ public void onComplete() { public void dispose() { if (!cancelled) { cancelled = true; - s.dispose(); + upstream.dispose(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastOne.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastOne.java index 04ad923c28..353f51fcf9 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastOne.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastOne.java @@ -28,21 +28,21 @@ public void subscribeActual(Observer<? super T> observer) { } static final class TakeLastOneObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; - Disposable s; + Disposable upstream; T value; - TakeLastOneObserver(Observer<? super T> actual) { - this.actual = actual; + TakeLastOneObserver(Observer<? super T> downstream) { + this.downstream = downstream; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -54,7 +54,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { value = null; - actual.onError(t); + downstream.onError(t); } @Override @@ -66,20 +66,20 @@ void emit() { T v = value; if (v != null) { value = null; - actual.onNext(v); + downstream.onNext(v); } - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { value = null; - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimed.java index d72d4c2171..7bd29092b4 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimed.java @@ -49,7 +49,7 @@ static final class TakeLastTimedObserver<T> extends AtomicBoolean implements Observer<T>, Disposable { private static final long serialVersionUID = -5677354903406201275L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final long count; final long time; final TimeUnit unit; @@ -57,14 +57,14 @@ static final class TakeLastTimedObserver<T> final SpscLinkedArrayQueue<Object> queue; final boolean delayError; - Disposable d; + Disposable upstream; volatile boolean cancelled; Throwable error; TakeLastTimedObserver(Observer<? super T> actual, long count, long time, TimeUnit unit, Scheduler scheduler, int bufferSize, boolean delayError) { - this.actual = actual; + this.downstream = actual; this.count = count; this.time = time; this.unit = unit; @@ -75,9 +75,9 @@ static final class TakeLastTimedObserver<T> @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; - actual.onSubscribe(this); + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -118,7 +118,7 @@ public void onComplete() { public void dispose() { if (!cancelled) { cancelled = true; - d.dispose(); + upstream.dispose(); if (compareAndSet(false, true)) { queue.clear(); @@ -136,7 +136,7 @@ void drain() { return; } - final Observer<? super T> a = actual; + final Observer<? super T> a = downstream; final SpscLinkedArrayQueue<Object> q = queue; final boolean delayError = this.delayError; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicate.java index 43cdaf05bd..cd984f2e07 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicate.java @@ -33,50 +33,50 @@ public void subscribeActual(Observer<? super T> observer) { } static final class TakeUntilPredicateObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final Predicate<? super T> predicate; - Disposable s; + Disposable upstream; boolean done; - TakeUntilPredicateObserver(Observer<? super T> actual, Predicate<? super T> predicate) { - this.actual = actual; + TakeUntilPredicateObserver(Observer<? super T> downstream, Predicate<? super T> predicate) { + this.downstream = downstream; this.predicate = predicate; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override public void onNext(T t) { if (!done) { - actual.onNext(t); + downstream.onNext(t); boolean b; try { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } if (b) { done = true; - s.dispose(); - actual.onComplete(); + upstream.dispose(); + downstream.onComplete(); } } } @@ -85,7 +85,7 @@ public void onNext(T t) { public void onError(Throwable t) { if (!done) { done = true; - actual.onError(t); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -95,7 +95,7 @@ public void onError(Throwable t) { public void onComplete() { if (!done) { done = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeWhile.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeWhile.java index b91898a652..1b41c6e86b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeWhile.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeWhile.java @@ -33,35 +33,35 @@ public void subscribeActual(Observer<? super T> t) { } static final class TakeWhileObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final Predicate<? super T> predicate; - Disposable s; + Disposable upstream; boolean done; TakeWhileObserver(Observer<? super T> actual, Predicate<? super T> predicate) { - this.actual = actual; + this.downstream = actual; this.predicate = predicate; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -75,19 +75,19 @@ public void onNext(T t) { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); - s.dispose(); + upstream.dispose(); onError(e); return; } if (!b) { done = true; - s.dispose(); - actual.onComplete(); + upstream.dispose(); + downstream.onComplete(); return; } - actual.onNext(t); + downstream.onNext(t); } @Override @@ -97,7 +97,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -106,7 +106,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleFirstTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleFirstTimed.java index f2512180da..54e94ab0b7 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleFirstTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleFirstTimed.java @@ -48,29 +48,29 @@ static final class DebounceTimedObserver<T> implements Observer<T>, Disposable, Runnable { private static final long serialVersionUID = 786994795061867455L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final long timeout; final TimeUnit unit; final Scheduler.Worker worker; - Disposable s; + Disposable upstream; volatile boolean gate; boolean done; DebounceTimedObserver(Observer<? super T> actual, long timeout, TimeUnit unit, Worker worker) { - this.actual = actual; + this.downstream = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @@ -79,7 +79,7 @@ public void onNext(T t) { if (!gate && !done) { gate = true; - actual.onNext(t); + downstream.onNext(t); Disposable d = get(); if (d != null) { @@ -102,7 +102,7 @@ public void onError(Throwable t) { RxJavaPlugins.onError(t); } else { done = true; - actual.onError(t); + downstream.onError(t); worker.dispose(); } } @@ -111,14 +111,14 @@ public void onError(Throwable t) { public void onComplete() { if (!done) { done = true; - actual.onComplete(); + downstream.onComplete(); worker.dispose(); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); worker.dispose(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java index 00dda7ad6b..39e0f0bfc3 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleLatest.java @@ -97,9 +97,9 @@ static final class ThrottleLatestObserver<T> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(upstream, s)) { - upstream = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + upstream = d; downstream.onSubscribe(this); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeInterval.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeInterval.java index a9449ecd89..0cc1a2c018 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeInterval.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeInterval.java @@ -36,37 +36,37 @@ public void subscribeActual(Observer<? super Timed<T>> t) { } static final class TimeIntervalObserver<T> implements Observer<T>, Disposable { - final Observer<? super Timed<T>> actual; + final Observer<? super Timed<T>> downstream; final TimeUnit unit; final Scheduler scheduler; long lastTime; - Disposable s; + Disposable upstream; TimeIntervalObserver(Observer<? super Timed<T>> actual, TimeUnit unit, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.scheduler = scheduler; this.unit = unit; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; lastTime = scheduler.now(unit); - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -76,17 +76,17 @@ public void onNext(T t) { long last = lastTime; lastTime = now; long delta = now - last; - actual.onNext(new Timed<T>(t, delta, unit)); + downstream.onNext(new Timed<T>(t, delta, unit)); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java index eeacf6d555..2aeb9051a2 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeout.java @@ -65,7 +65,7 @@ static final class TimeoutObserver<T> extends AtomicLong private static final long serialVersionUID = 3764492702657003550L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final Function<? super T, ? extends ObservableSource<?>> itemTimeoutIndicator; @@ -74,15 +74,15 @@ static final class TimeoutObserver<T> extends AtomicLong final AtomicReference<Disposable> upstream; TimeoutObserver(Observer<? super T> actual, Function<? super T, ? extends ObservableSource<?>> itemTimeoutIndicator) { - this.actual = actual; + this.downstream = actual; this.itemTimeoutIndicator = itemTimeoutIndicator; this.task = new SequentialDisposable(); this.upstream = new AtomicReference<Disposable>(); } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(upstream, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(upstream, d); } @Override @@ -97,7 +97,7 @@ public void onNext(T t) { d.dispose(); } - actual.onNext(t); + downstream.onNext(t); ObservableSource<?> itemTimeoutObservableSource; @@ -109,7 +109,7 @@ public void onNext(T t) { Exceptions.throwIfFatal(ex); upstream.get().dispose(); getAndSet(Long.MAX_VALUE); - actual.onError(ex); + downstream.onError(ex); return; } @@ -133,7 +133,7 @@ public void onError(Throwable t) { if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onError(t); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -144,7 +144,7 @@ public void onComplete() { if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onComplete(); + downstream.onComplete(); } } @@ -153,7 +153,7 @@ public void onTimeout(long idx) { if (compareAndSet(idx, Long.MAX_VALUE)) { DisposableHelper.dispose(upstream); - actual.onError(new TimeoutException()); + downstream.onError(new TimeoutException()); } } @@ -162,7 +162,7 @@ public void onTimeoutError(long idx, Throwable ex) { if (compareAndSet(idx, Long.MAX_VALUE)) { DisposableHelper.dispose(upstream); - actual.onError(ex); + downstream.onError(ex); } else { RxJavaPlugins.onError(ex); } @@ -186,7 +186,7 @@ static final class TimeoutFallbackObserver<T> private static final long serialVersionUID = -7508389464265974549L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final Function<? super T, ? extends ObservableSource<?>> itemTimeoutIndicator; @@ -201,7 +201,7 @@ static final class TimeoutFallbackObserver<T> TimeoutFallbackObserver(Observer<? super T> actual, Function<? super T, ? extends ObservableSource<?>> itemTimeoutIndicator, ObservableSource<? extends T> fallback) { - this.actual = actual; + this.downstream = actual; this.itemTimeoutIndicator = itemTimeoutIndicator; this.task = new SequentialDisposable(); this.fallback = fallback; @@ -210,8 +210,8 @@ static final class TimeoutFallbackObserver<T> } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(upstream, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(upstream, d); } @Override @@ -226,7 +226,7 @@ public void onNext(T t) { d.dispose(); } - actual.onNext(t); + downstream.onNext(t); ObservableSource<?> itemTimeoutObservableSource; @@ -238,7 +238,7 @@ public void onNext(T t) { Exceptions.throwIfFatal(ex); upstream.get().dispose(); index.getAndSet(Long.MAX_VALUE); - actual.onError(ex); + downstream.onError(ex); return; } @@ -262,7 +262,7 @@ public void onError(Throwable t) { if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onError(t); + downstream.onError(t); task.dispose(); } else { @@ -275,7 +275,7 @@ public void onComplete() { if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onComplete(); + downstream.onComplete(); task.dispose(); } @@ -289,7 +289,7 @@ public void onTimeout(long idx) { ObservableSource<? extends T> f = fallback; fallback = null; - f.subscribe(new ObservableTimeoutTimed.FallbackObserver<T>(actual, this)); + f.subscribe(new ObservableTimeoutTimed.FallbackObserver<T>(downstream, this)); } } @@ -298,7 +298,7 @@ public void onTimeoutError(long idx, Throwable ex) { if (index.compareAndSet(idx, Long.MAX_VALUE)) { DisposableHelper.dispose(this); - actual.onError(ex); + downstream.onError(ex); } else { RxJavaPlugins.onError(ex); } @@ -332,8 +332,8 @@ static final class TimeoutConsumer extends AtomicReference<Disposable> } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this, d); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java index 45416b9344..7c955939c0 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java @@ -56,7 +56,7 @@ static final class TimeoutObserver<T> extends AtomicLong private static final long serialVersionUID = 3764492702657003550L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final long timeout; @@ -69,7 +69,7 @@ static final class TimeoutObserver<T> extends AtomicLong final AtomicReference<Disposable> upstream; TimeoutObserver(Observer<? super T> actual, long timeout, TimeUnit unit, Scheduler.Worker worker) { - this.actual = actual; + this.downstream = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; @@ -78,8 +78,8 @@ static final class TimeoutObserver<T> extends AtomicLong } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(upstream, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(upstream, d); } @Override @@ -91,7 +91,7 @@ public void onNext(T t) { task.get().dispose(); - actual.onNext(t); + downstream.onNext(t); startTimeout(idx + 1); } @@ -105,7 +105,7 @@ public void onError(Throwable t) { if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onError(t); + downstream.onError(t); worker.dispose(); } else { @@ -118,7 +118,7 @@ public void onComplete() { if (getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onComplete(); + downstream.onComplete(); worker.dispose(); } @@ -129,7 +129,7 @@ public void onTimeout(long idx) { if (compareAndSet(idx, Long.MAX_VALUE)) { DisposableHelper.dispose(upstream); - actual.onError(new TimeoutException()); + downstream.onError(new TimeoutException()); worker.dispose(); } @@ -170,7 +170,7 @@ static final class TimeoutFallbackObserver<T> extends AtomicReference<Disposable private static final long serialVersionUID = 3764492702657003550L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final long timeout; @@ -188,7 +188,7 @@ static final class TimeoutFallbackObserver<T> extends AtomicReference<Disposable TimeoutFallbackObserver(Observer<? super T> actual, long timeout, TimeUnit unit, Scheduler.Worker worker, ObservableSource<? extends T> fallback) { - this.actual = actual; + this.downstream = actual; this.timeout = timeout; this.unit = unit; this.worker = worker; @@ -199,8 +199,8 @@ static final class TimeoutFallbackObserver<T> extends AtomicReference<Disposable } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(upstream, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(upstream, d); } @Override @@ -212,7 +212,7 @@ public void onNext(T t) { task.get().dispose(); - actual.onNext(t); + downstream.onNext(t); startTimeout(idx + 1); } @@ -226,7 +226,7 @@ public void onError(Throwable t) { if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onError(t); + downstream.onError(t); worker.dispose(); } else { @@ -239,7 +239,7 @@ public void onComplete() { if (index.getAndSet(Long.MAX_VALUE) != Long.MAX_VALUE) { task.dispose(); - actual.onComplete(); + downstream.onComplete(); worker.dispose(); } @@ -253,7 +253,7 @@ public void onTimeout(long idx) { ObservableSource<? extends T> f = fallback; fallback = null; - f.subscribe(new FallbackObserver<T>(actual, this)); + f.subscribe(new FallbackObserver<T>(downstream, this)); worker.dispose(); } @@ -274,33 +274,33 @@ public boolean isDisposed() { static final class FallbackObserver<T> implements Observer<T> { - final Observer<? super T> actual; + final Observer<? super T> downstream; final AtomicReference<Disposable> arbiter; FallbackObserver(Observer<? super T> actual, AtomicReference<Disposable> arbiter) { - this.actual = actual; + this.downstream = actual; this.arbiter = arbiter; } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.replace(arbiter, s); + public void onSubscribe(Disposable d) { + DisposableHelper.replace(arbiter, d); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimer.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimer.java index 01a6a52743..c635ccb9db 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimer.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimer.java @@ -45,10 +45,10 @@ static final class TimerObserver extends AtomicReference<Disposable> private static final long serialVersionUID = -2809475196591179431L; - final Observer<? super Long> actual; + final Observer<? super Long> downstream; - TimerObserver(Observer<? super Long> actual) { - this.actual = actual; + TimerObserver(Observer<? super Long> downstream) { + this.downstream = downstream; } @Override @@ -64,9 +64,9 @@ public boolean isDisposed() { @Override public void run() { if (!isDisposed()) { - actual.onNext(0L); + downstream.onNext(0L); lazySet(EmptyDisposable.INSTANCE); - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableToList.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableToList.java index 8181c00563..53dd99fd2b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableToList.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableToList.java @@ -52,33 +52,34 @@ public void subscribeActual(Observer<? super U> t) { } static final class ToListObserver<T, U extends Collection<? super T>> implements Observer<T>, Disposable { - U collection; - final Observer<? super U> actual; + final Observer<? super U> downstream; + + Disposable upstream; - Disposable s; + U collection; ToListObserver(Observer<? super U> actual, U collection) { - this.actual = actual; + this.downstream = actual; this.collection = collection; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -90,15 +91,15 @@ public void onNext(T t) { @Override public void onError(Throwable t) { collection = null; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { U c = collection; collection = null; - actual.onNext(c); - actual.onComplete(); + downstream.onNext(c); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableToListSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableToListSingle.java index dc38c76dfd..4358229f53 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableToListSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableToListSingle.java @@ -64,34 +64,34 @@ public Observable<U> fuseToObservable() { } static final class ToListObserver<T, U extends Collection<? super T>> implements Observer<T>, Disposable { - final SingleObserver<? super U> actual; + final SingleObserver<? super U> downstream; U collection; - Disposable s; + Disposable upstream; ToListObserver(SingleObserver<? super U> actual, U collection) { - this.actual = actual; + this.downstream = actual; this.collection = collection; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -103,14 +103,14 @@ public void onNext(T t) { @Override public void onError(Throwable t) { collection = null; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { U c = collection; collection = null; - actual.onSuccess(c); + downstream.onSuccess(c); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOn.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOn.java index bfcc33308e..5f4ecad8a6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOn.java @@ -36,28 +36,28 @@ static final class UnsubscribeObserver<T> extends AtomicBoolean implements Obser private static final long serialVersionUID = 1015244841293359600L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final Scheduler scheduler; - Disposable s; + Disposable upstream; UnsubscribeObserver(Observer<? super T> actual, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.scheduler = scheduler; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { if (!get()) { - actual.onNext(t); + downstream.onNext(t); } } @@ -67,13 +67,13 @@ public void onError(Throwable t) { RxJavaPlugins.onError(t); return; } - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { if (!get()) { - actual.onComplete(); + downstream.onComplete(); } } @@ -92,7 +92,7 @@ public boolean isDisposed() { final class DisposeTask implements Runnable { @Override public void run() { - s.dispose(); + upstream.dispose(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableUsing.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableUsing.java index 039da6f67c..46806ae0dc 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableUsing.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableUsing.java @@ -77,31 +77,31 @@ static final class UsingObserver<T, D> extends AtomicBoolean implements Observer private static final long serialVersionUID = 5904473792286235046L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final D resource; final Consumer<? super D> disposer; final boolean eager; - Disposable s; + Disposable upstream; UsingObserver(Observer<? super T> actual, D resource, Consumer<? super D> disposer, boolean eager) { - this.actual = actual; + this.downstream = actual; this.resource = resource; this.disposer = disposer; this.eager = eager; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override @@ -116,11 +116,11 @@ public void onError(Throwable t) { } } - s.dispose(); - actual.onError(t); + upstream.dispose(); + downstream.onError(t); } else { - actual.onError(t); - s.dispose(); + downstream.onError(t); + upstream.dispose(); disposeAfter(); } } @@ -133,16 +133,16 @@ public void onComplete() { disposer.accept(resource); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } } - s.dispose(); - actual.onComplete(); + upstream.dispose(); + downstream.onComplete(); } else { - actual.onComplete(); - s.dispose(); + downstream.onComplete(); + upstream.dispose(); disposeAfter(); } } @@ -150,7 +150,7 @@ public void onComplete() { @Override public void dispose() { disposeAfter(); - s.dispose(); + upstream.dispose(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindow.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindow.java index dae684bc9a..0c5c50d407 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindow.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindow.java @@ -47,30 +47,30 @@ static final class WindowExactObserver<T> implements Observer<T>, Disposable, Runnable { private static final long serialVersionUID = -7481782523886138128L; - final Observer<? super Observable<T>> actual; + final Observer<? super Observable<T>> downstream; final long count; final int capacityHint; long size; - Disposable s; + Disposable upstream; UnicastSubject<T> window; volatile boolean cancelled; WindowExactObserver(Observer<? super Observable<T>> actual, long count, int capacityHint) { - this.actual = actual; + this.downstream = actual; this.count = count; this.capacityHint = capacityHint; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -80,7 +80,7 @@ public void onNext(T t) { if (w == null && !cancelled) { w = UnicastSubject.create(capacityHint, this); window = w; - actual.onNext(w); + downstream.onNext(w); } if (w != null) { @@ -90,7 +90,7 @@ public void onNext(T t) { window = null; w.onComplete(); if (cancelled) { - s.dispose(); + upstream.dispose(); } } } @@ -103,7 +103,7 @@ public void onError(Throwable t) { window = null; w.onError(t); } - actual.onError(t); + downstream.onError(t); } @Override @@ -113,7 +113,7 @@ public void onComplete() { window = null; w.onComplete(); } - actual.onComplete(); + downstream.onComplete(); } @Override @@ -129,7 +129,7 @@ public boolean isDisposed() { @Override public void run() { if (cancelled) { - s.dispose(); + upstream.dispose(); } } } @@ -138,7 +138,7 @@ static final class WindowSkipObserver<T> extends AtomicBoolean implements Observer<T>, Disposable, Runnable { private static final long serialVersionUID = 3366976432059579510L; - final Observer<? super Observable<T>> actual; + final Observer<? super Observable<T>> downstream; final long count; final long skip; final int capacityHint; @@ -151,12 +151,12 @@ static final class WindowSkipObserver<T> extends AtomicBoolean /** Counts how many elements were emitted to the very first window in windows. */ long firstEmission; - Disposable s; + Disposable upstream; final AtomicInteger wip = new AtomicInteger(); WindowSkipObserver(Observer<? super Observable<T>> actual, long count, long skip, int capacityHint) { - this.actual = actual; + this.downstream = actual; this.count = count; this.skip = skip; this.capacityHint = capacityHint; @@ -164,11 +164,11 @@ static final class WindowSkipObserver<T> extends AtomicBoolean } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -184,7 +184,7 @@ public void onNext(T t) { wip.getAndIncrement(); UnicastSubject<T> w = UnicastSubject.create(capacityHint, this); ws.offer(w); - actual.onNext(w); + downstream.onNext(w); } long c = firstEmission + 1; @@ -196,7 +196,7 @@ public void onNext(T t) { if (c >= count) { ws.poll().onComplete(); if (ws.isEmpty() && cancelled) { - this.s.dispose(); + this.upstream.dispose(); return; } firstEmission = c - s; @@ -213,7 +213,7 @@ public void onError(Throwable t) { while (!ws.isEmpty()) { ws.poll().onError(t); } - actual.onError(t); + downstream.onError(t); } @Override @@ -222,7 +222,7 @@ public void onComplete() { while (!ws.isEmpty()) { ws.poll().onComplete(); } - actual.onComplete(); + downstream.onComplete(); } @Override @@ -239,7 +239,7 @@ public boolean isDisposed() { public void run() { if (wip.decrementAndGet() == 0) { if (cancelled) { - s.dispose(); + upstream.dispose(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java index d0da7e2b0a..b15d4ee140 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java @@ -61,7 +61,7 @@ static final class WindowBoundaryMainObserver<T, B, V> final int bufferSize; final CompositeDisposable resources; - Disposable s; + Disposable upstream; final AtomicReference<Disposable> boundary = new AtomicReference<Disposable>(); @@ -81,11 +81,11 @@ static final class WindowBoundaryMainObserver<T, B, V> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); if (cancelled) { return; @@ -135,7 +135,7 @@ public void onError(Throwable t) { resources.dispose(); } - actual.onError(t); + downstream.onError(t); } @Override @@ -153,11 +153,11 @@ public void onComplete() { resources.dispose(); } - actual.onComplete(); + downstream.onComplete(); } void error(Throwable t) { - s.dispose(); + upstream.dispose(); resources.dispose(); onError(t); } @@ -179,7 +179,7 @@ void disposeBoundary() { void drainLoop() { final MpscLinkedQueue<Object> q = (MpscLinkedQueue<Object>)queue; - final Observer<? super Observable<T>> a = actual; + final Observer<? super Observable<T>> a = downstream; final List<UnicastSubject<T>> ws = this.ws; int missed = 1; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java index 73676bf698..5b76d067e7 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java @@ -81,7 +81,7 @@ static final class WindowExactUnboundedObserver<T> final Scheduler scheduler; final int bufferSize; - Disposable s; + Disposable upstream; UnicastSubject<T> window; @@ -101,20 +101,20 @@ static final class WindowExactUnboundedObserver<T> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; window = UnicastSubject.<T>create(bufferSize); - Observer<? super Observable<T>> a = actual; + Observer<? super Observable<T>> a = downstream; a.onSubscribe(this); a.onNext(window); if (!cancelled) { - Disposable d = scheduler.schedulePeriodicallyDirect(this, timespan, timespan, unit); - DisposableHelper.replace(timer, d); + Disposable task = scheduler.schedulePeriodicallyDirect(this, timespan, timespan, unit); + DisposableHelper.replace(timer, task); } } } @@ -147,7 +147,7 @@ public void onError(Throwable t) { } disposeTimer(); - actual.onError(t); + downstream.onError(t); } @Override @@ -158,7 +158,7 @@ public void onComplete() { } disposeTimer(); - actual.onComplete(); + downstream.onComplete(); } @Override @@ -190,7 +190,7 @@ public void run() { void drainLoop() { final MpscLinkedQueue<Object> q = (MpscLinkedQueue<Object>)queue; - final Observer<? super Observable<T>> a = actual; + final Observer<? super Observable<T>> a = downstream; UnicastSubject<T> w = window; int missed = 1; @@ -228,7 +228,7 @@ void drainLoop() { a.onNext(w); } else { - s.dispose(); + upstream.dispose(); } continue; } @@ -260,7 +260,7 @@ static final class WindowExactBoundedObserver<T> long producerIndex; - Disposable s; + Disposable upstream; UnicastSubject<T> window; @@ -288,11 +288,11 @@ static final class WindowExactBoundedObserver<T> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - Observer<? super Observable<T>> a = actual; + Observer<? super Observable<T>> a = downstream; a.onSubscribe(this); @@ -305,15 +305,15 @@ public void onSubscribe(Disposable s) { a.onNext(w); - Disposable d; + Disposable task; ConsumerIndexHolder consumerIndexHolder = new ConsumerIndexHolder(producerIndex, this); if (restartTimerOnMaxSize) { - d = worker.schedulePeriodically(consumerIndexHolder, timespan, timespan, unit); + task = worker.schedulePeriodically(consumerIndexHolder, timespan, timespan, unit); } else { - d = scheduler.schedulePeriodicallyDirect(consumerIndexHolder, timespan, timespan, unit); + task = scheduler.schedulePeriodicallyDirect(consumerIndexHolder, timespan, timespan, unit); } - DisposableHelper.replace(timer, d); + DisposableHelper.replace(timer, task); } } @@ -337,7 +337,7 @@ public void onNext(T t) { w = UnicastSubject.create(bufferSize); window = w; - actual.onNext(w); + downstream.onNext(w); if (restartTimerOnMaxSize) { Disposable tm = timer.get(); tm.dispose(); @@ -370,7 +370,7 @@ public void onError(Throwable t) { drainLoop(); } - actual.onError(t); + downstream.onError(t); disposeTimer(); } @@ -381,7 +381,7 @@ public void onComplete() { drainLoop(); } - actual.onComplete(); + downstream.onComplete(); disposeTimer(); } @@ -405,7 +405,7 @@ void disposeTimer() { void drainLoop() { final MpscLinkedQueue<Object> q = (MpscLinkedQueue<Object>)queue; - final Observer<? super Observable<T>> a = actual; + final Observer<? super Observable<T>> a = downstream; UnicastSubject<T> w = window; int missed = 1; @@ -413,7 +413,7 @@ void drainLoop() { for (;;) { if (terminated) { - s.dispose(); + upstream.dispose(); q.clear(); disposeTimer(); return; @@ -467,7 +467,7 @@ void drainLoop() { w = UnicastSubject.create(bufferSize); window = w; - actual.onNext(w); + downstream.onNext(w); if (restartTimerOnMaxSize) { Disposable tm = timer.get(); @@ -528,7 +528,7 @@ static final class WindowSkipObserver<T> final List<UnicastSubject<T>> windows; - Disposable s; + Disposable upstream; volatile boolean terminated; @@ -545,11 +545,11 @@ static final class WindowSkipObserver<T> } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); if (cancelled) { return; @@ -558,7 +558,7 @@ public void onSubscribe(Disposable s) { final UnicastSubject<T> w = UnicastSubject.create(bufferSize); windows.add(w); - actual.onNext(w); + downstream.onNext(w); worker.schedule(new CompletionTask(w), timespan, unit); worker.schedulePeriodically(this, timeskip, timeskip, unit); @@ -592,7 +592,7 @@ public void onError(Throwable t) { drainLoop(); } - actual.onError(t); + downstream.onError(t); disposeWorker(); } @@ -603,7 +603,7 @@ public void onComplete() { drainLoop(); } - actual.onComplete(); + downstream.onComplete(); disposeWorker(); } @@ -631,7 +631,7 @@ void complete(UnicastSubject<T> w) { @SuppressWarnings("unchecked") void drainLoop() { final MpscLinkedQueue<Object> q = (MpscLinkedQueue<Object>)queue; - final Observer<? super Observable<T>> a = actual; + final Observer<? super Observable<T>> a = downstream; final List<UnicastSubject<T>> ws = windows; int missed = 1; @@ -640,7 +640,7 @@ void drainLoop() { for (;;) { if (terminated) { - s.dispose(); + upstream.dispose(); disposeWorker(); q.clear(); ws.clear(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFrom.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFrom.java index d60a086687..9bc7984dd6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFrom.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFrom.java @@ -40,7 +40,7 @@ public void subscribeActual(Observer<? super R> t) { serial.onSubscribe(wlf); - other.subscribe(new WithLastFrom(wlf)); + other.subscribe(new WithLatestFromOtherObserver(wlf)); source.subscribe(wlf); } @@ -49,21 +49,21 @@ static final class WithLatestFromObserver<T, U, R> extends AtomicReference<U> im private static final long serialVersionUID = -312246233408980075L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final BiFunction<? super T, ? super U, ? extends R> combiner; - final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); final AtomicReference<Disposable> other = new AtomicReference<Disposable>(); WithLatestFromObserver(Observer<? super R> actual, BiFunction<? super T, ? super U, ? extends R> combiner) { - this.actual = actual; + this.downstream = actual; this.combiner = combiner; } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this.s, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this.upstream, d); } @Override @@ -76,34 +76,34 @@ public void onNext(T t) { } catch (Throwable e) { Exceptions.throwIfFatal(e); dispose(); - actual.onError(e); + downstream.onError(e); return; } - actual.onNext(r); + downstream.onNext(r); } } @Override public void onError(Throwable t) { DisposableHelper.dispose(other); - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { DisposableHelper.dispose(other); - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { - DisposableHelper.dispose(s); + DisposableHelper.dispose(upstream); DisposableHelper.dispose(other); } @Override public boolean isDisposed() { - return DisposableHelper.isDisposed(s.get()); + return DisposableHelper.isDisposed(upstream.get()); } public boolean setOther(Disposable o) { @@ -111,31 +111,31 @@ public boolean setOther(Disposable o) { } public void otherError(Throwable e) { - DisposableHelper.dispose(s); - actual.onError(e); + DisposableHelper.dispose(upstream); + downstream.onError(e); } } - final class WithLastFrom implements Observer<U> { - private final WithLatestFromObserver<T, U, R> wlf; + final class WithLatestFromOtherObserver implements Observer<U> { + private final WithLatestFromObserver<T, U, R> parent; - WithLastFrom(WithLatestFromObserver<T, U, R> wlf) { - this.wlf = wlf; + WithLatestFromOtherObserver(WithLatestFromObserver<T, U, R> parent) { + this.parent = parent; } @Override - public void onSubscribe(Disposable s) { - wlf.setOther(s); + public void onSubscribe(Disposable d) { + parent.setOther(d); } @Override public void onNext(U t) { - wlf.lazySet(t); + parent.lazySet(t); } @Override public void onError(Throwable t) { - wlf.otherError(t); + parent.otherError(t); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromMany.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromMany.java index b460ad58b1..194d33c61c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromMany.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromMany.java @@ -100,7 +100,7 @@ static final class WithLatestFromObserver<T, R> private static final long serialVersionUID = 1577321883966341961L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final Function<? super Object[], R> combiner; @@ -108,14 +108,14 @@ static final class WithLatestFromObserver<T, R> final AtomicReferenceArray<Object> values; - final AtomicReference<Disposable> d; + final AtomicReference<Disposable> upstream; final AtomicThrowable error; volatile boolean done; WithLatestFromObserver(Observer<? super R> actual, Function<? super Object[], R> combiner, int n) { - this.actual = actual; + this.downstream = actual; this.combiner = combiner; WithLatestInnerObserver[] s = new WithLatestInnerObserver[n]; for (int i = 0; i < n; i++) { @@ -123,15 +123,15 @@ static final class WithLatestFromObserver<T, R> } this.observers = s; this.values = new AtomicReferenceArray<Object>(n); - this.d = new AtomicReference<Disposable>(); + this.upstream = new AtomicReference<Disposable>(); this.error = new AtomicThrowable(); } void subscribe(ObservableSource<?>[] others, int n) { WithLatestInnerObserver[] observers = this.observers; - AtomicReference<Disposable> s = this.d; + AtomicReference<Disposable> upstream = this.upstream; for (int i = 0; i < n; i++) { - if (DisposableHelper.isDisposed(s.get()) || done) { + if (DisposableHelper.isDisposed(upstream.get()) || done) { return; } others[i].subscribe(observers[i]); @@ -140,7 +140,7 @@ void subscribe(ObservableSource<?>[] others, int n) { @Override public void onSubscribe(Disposable d) { - DisposableHelper.setOnce(this.d, d); + DisposableHelper.setOnce(this.upstream, d); } @Override @@ -173,7 +173,7 @@ public void onNext(T t) { return; } - HalfSerializer.onNext(actual, v, this, error); + HalfSerializer.onNext(downstream, v, this, error); } @Override @@ -184,7 +184,7 @@ public void onError(Throwable t) { } done = true; cancelAllBut(-1); - HalfSerializer.onError(actual, t, this, error); + HalfSerializer.onError(downstream, t, this, error); } @Override @@ -192,18 +192,18 @@ public void onComplete() { if (!done) { done = true; cancelAllBut(-1); - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } } @Override public boolean isDisposed() { - return DisposableHelper.isDisposed(d.get()); + return DisposableHelper.isDisposed(upstream.get()); } @Override public void dispose() { - DisposableHelper.dispose(d); + DisposableHelper.dispose(upstream); for (WithLatestInnerObserver observer : observers) { observer.dispose(); } @@ -215,16 +215,16 @@ void innerNext(int index, Object o) { void innerError(int index, Throwable t) { done = true; - DisposableHelper.dispose(d); + DisposableHelper.dispose(upstream); cancelAllBut(index); - HalfSerializer.onError(actual, t, this, error); + HalfSerializer.onError(downstream, t, this, error); } void innerComplete(int index, boolean nonEmpty) { if (!nonEmpty) { done = true; cancelAllBut(index); - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java index 923c1a062d..5ac0027aeb 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java @@ -75,7 +75,7 @@ public void subscribeActual(Observer<? super R> observer) { static final class ZipCoordinator<T, R> extends AtomicInteger implements Disposable { private static final long serialVersionUID = 2983708048395377667L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final Function<? super Object[], ? extends R> zipper; final ZipObserver<T, R>[] observers; final T[] row; @@ -87,7 +87,7 @@ static final class ZipCoordinator<T, R> extends AtomicInteger implements Disposa ZipCoordinator(Observer<? super R> actual, Function<? super Object[], ? extends R> zipper, int count, boolean delayError) { - this.actual = actual; + this.downstream = actual; this.zipper = zipper; this.observers = new ZipObserver[count]; this.row = (T[])new Object[count]; @@ -102,7 +102,7 @@ public void subscribe(ObservableSource<? extends T>[] sources, int bufferSize) { } // this makes sure the contents of the observers array is visible this.lazySet(0); - actual.onSubscribe(this); + downstream.onSubscribe(this); for (int i = 0; i < len; i++) { if (cancelled) { return; @@ -152,7 +152,7 @@ public void drain() { int missing = 1; final ZipObserver<T, R>[] zs = observers; - final Observer<? super R> a = actual; + final Observer<? super R> a = downstream; final T[] os = row; final boolean delayError = this.delayError; @@ -259,15 +259,15 @@ static final class ZipObserver<T, R> implements Observer<T> { volatile boolean done; Throwable error; - final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); ZipObserver(ZipCoordinator<T, R> parent, int bufferSize) { this.parent = parent; this.queue = new SpscLinkedArrayQueue<T>(bufferSize); } @Override - public void onSubscribe(Disposable s) { - DisposableHelper.setOnce(this.s, s); + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(this.upstream, d); } @Override @@ -290,7 +290,7 @@ public void onComplete() { } public void dispose() { - DisposableHelper.dispose(s); + DisposableHelper.dispose(upstream); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableZipIterable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableZipIterable.java index 4e01080759..8db76ed428 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableZipIterable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableZipIterable.java @@ -67,38 +67,38 @@ public void subscribeActual(Observer<? super V> t) { } static final class ZipIterableObserver<T, U, V> implements Observer<T>, Disposable { - final Observer<? super V> actual; + final Observer<? super V> downstream; final Iterator<U> iterator; final BiFunction<? super T, ? super U, ? extends V> zipper; - Disposable s; + Disposable upstream; boolean done; ZipIterableObserver(Observer<? super V> actual, Iterator<U> iterator, BiFunction<? super T, ? super U, ? extends V> zipper) { - this.actual = actual; + this.downstream = actual; this.iterator = iterator; this.zipper = zipper; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -127,7 +127,7 @@ public void onNext(T t) { return; } - actual.onNext(v); + downstream.onNext(v); boolean b; @@ -141,15 +141,15 @@ public void onNext(T t) { if (!b) { done = true; - s.dispose(); - actual.onComplete(); + upstream.dispose(); + downstream.onComplete(); } } void error(Throwable e) { done = true; - s.dispose(); - actual.onError(e); + upstream.dispose(); + downstream.onError(e); } @Override @@ -159,7 +159,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -168,7 +168,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObserverResourceWrapper.java b/src/main/java/io/reactivex/internal/operators/observable/ObserverResourceWrapper.java index 6da2c5d377..80034928be 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObserverResourceWrapper.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObserverResourceWrapper.java @@ -23,48 +23,48 @@ public final class ObserverResourceWrapper<T> extends AtomicReference<Disposable private static final long serialVersionUID = -8612022020200669122L; - final Observer<? super T> actual; + final Observer<? super T> downstream; - final AtomicReference<Disposable> subscription = new AtomicReference<Disposable>(); + final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); - public ObserverResourceWrapper(Observer<? super T> actual) { - this.actual = actual; + public ObserverResourceWrapper(Observer<? super T> downstream) { + this.downstream = downstream; } @Override - public void onSubscribe(Disposable s) { - if (DisposableHelper.setOnce(subscription, s)) { - actual.onSubscribe(this); + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(upstream, d)) { + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { dispose(); - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { dispose(); - actual.onComplete(); + downstream.onComplete(); } @Override public void dispose() { - DisposableHelper.dispose(subscription); + DisposableHelper.dispose(upstream); DisposableHelper.dispose(this); } @Override public boolean isDisposed() { - return subscription.get() == DisposableHelper.DISPOSED; + return upstream.get() == DisposableHelper.DISPOSED; } public void setResource(Disposable resource) { diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelCollect.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelCollect.java index 47c55f5d08..4f7b53ed94 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelCollect.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelCollect.java @@ -105,10 +105,10 @@ static final class ParallelCollectSubscriber<T, C> extends DeferredScalarSubscri @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -137,7 +137,7 @@ public void onError(Throwable t) { } done = true; collection = null; - actual.onError(t); + downstream.onError(t); } @Override @@ -154,7 +154,7 @@ public void onComplete() { @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelDoOnNextTry.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelDoOnNextTry.java index ae74461419..23fae57a80 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelDoOnNextTry.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelDoOnNextTry.java @@ -74,46 +74,46 @@ public int parallelism() { static final class ParallelDoOnNextSubscriber<T> implements ConditionalSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Consumer<? super T> onNext; final BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler; - Subscription s; + Subscription upstream; boolean done; ParallelDoOnNextSubscriber(Subscriber<? super T> actual, Consumer<? super T> onNext, BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { - this.actual = actual; + this.downstream = actual; this.onNext = onNext; this.errorHandler = errorHandler; } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { if (!tryOnNext(t)) { - s.request(1); + upstream.request(1); } } @@ -157,7 +157,7 @@ public boolean tryOnNext(T t) { } } - actual.onNext(t); + downstream.onNext(t); return true; } } @@ -169,7 +169,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -178,52 +178,53 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } } static final class ParallelDoOnNextConditionalSubscriber<T> implements ConditionalSubscriber<T>, Subscription { - final ConditionalSubscriber<? super T> actual; + final ConditionalSubscriber<? super T> downstream; final Consumer<? super T> onNext; final BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler; - Subscription s; + + Subscription upstream; boolean done; ParallelDoOnNextConditionalSubscriber(ConditionalSubscriber<? super T> actual, Consumer<? super T> onNext, BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { - this.actual = actual; + this.downstream = actual; this.onNext = onNext; this.errorHandler = errorHandler; } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { if (!tryOnNext(t) && !done) { - s.request(1); + upstream.request(1); } } @@ -267,7 +268,7 @@ public boolean tryOnNext(T t) { } } - return actual.tryOnNext(t); + return downstream.tryOnNext(t); } } @@ -278,7 +279,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -287,7 +288,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelFilter.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelFilter.java index 5dab623306..1a775d54ae 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelFilter.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelFilter.java @@ -68,7 +68,7 @@ public int parallelism() { abstract static class BaseFilterSubscriber<T> implements ConditionalSubscriber<T>, Subscription { final Predicate<? super T> predicate; - Subscription s; + Subscription upstream; boolean done; @@ -78,37 +78,37 @@ abstract static class BaseFilterSubscriber<T> implements ConditionalSubscriber<T @Override public final void request(long n) { - s.request(n); + upstream.request(n); } @Override public final void cancel() { - s.cancel(); + upstream.cancel(); } @Override public final void onNext(T t) { if (!tryOnNext(t) && !done) { - s.request(1); + upstream.request(1); } } } static final class ParallelFilterSubscriber<T> extends BaseFilterSubscriber<T> { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; ParallelFilterSubscriber(Subscriber<? super T> actual, Predicate<? super T> predicate) { super(predicate); - this.actual = actual; + this.downstream = actual; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -127,7 +127,7 @@ public boolean tryOnNext(T t) { } if (b) { - actual.onNext(t); + downstream.onNext(t); return true; } } @@ -141,33 +141,33 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { if (!done) { done = true; - actual.onComplete(); + downstream.onComplete(); } } } static final class ParallelFilterConditionalSubscriber<T> extends BaseFilterSubscriber<T> { - final ConditionalSubscriber<? super T> actual; + final ConditionalSubscriber<? super T> downstream; ParallelFilterConditionalSubscriber(ConditionalSubscriber<? super T> actual, Predicate<? super T> predicate) { super(predicate); - this.actual = actual; + this.downstream = actual; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -186,7 +186,7 @@ public boolean tryOnNext(T t) { } if (b) { - return actual.tryOnNext(t); + return downstream.tryOnNext(t); } } return false; @@ -199,14 +199,14 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { if (!done) { done = true; - actual.onComplete(); + downstream.onComplete(); } } }} diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelFilterTry.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelFilterTry.java index e6aa32f867..bd0923fb70 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelFilterTry.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelFilterTry.java @@ -75,7 +75,7 @@ abstract static class BaseFilterSubscriber<T> implements ConditionalSubscriber<T final BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler; - Subscription s; + Subscription upstream; boolean done; @@ -86,37 +86,37 @@ abstract static class BaseFilterSubscriber<T> implements ConditionalSubscriber<T @Override public final void request(long n) { - s.request(n); + upstream.request(n); } @Override public final void cancel() { - s.cancel(); + upstream.cancel(); } @Override public final void onNext(T t) { if (!tryOnNext(t) && !done) { - s.request(1); + upstream.request(1); } } } static final class ParallelFilterSubscriber<T> extends BaseFilterSubscriber<T> { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; ParallelFilterSubscriber(Subscriber<? super T> actual, Predicate<? super T> predicate, BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { super(predicate, errorHandler); - this.actual = actual; + this.downstream = actual; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -161,7 +161,7 @@ public boolean tryOnNext(T t) { } if (b) { - actual.onNext(t); + downstream.onNext(t); return true; } return false; @@ -177,35 +177,35 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { if (!done) { done = true; - actual.onComplete(); + downstream.onComplete(); } } } static final class ParallelFilterConditionalSubscriber<T> extends BaseFilterSubscriber<T> { - final ConditionalSubscriber<? super T> actual; + final ConditionalSubscriber<? super T> downstream; ParallelFilterConditionalSubscriber(ConditionalSubscriber<? super T> actual, Predicate<? super T> predicate, BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { super(predicate, errorHandler); - this.actual = actual; + this.downstream = actual; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -249,7 +249,7 @@ public boolean tryOnNext(T t) { } } - return b && actual.tryOnNext(t); + return b && downstream.tryOnNext(t); } } return false; @@ -262,14 +262,14 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { if (!done) { done = true; - actual.onComplete(); + downstream.onComplete(); } } }} diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java index 5eb11d3e4e..fc7288a1a1 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java @@ -75,7 +75,7 @@ static final class ParallelDispatcher<T> final int limit; - Subscription s; + Subscription upstream; SimpleQueue<T> queue; @@ -109,8 +109,8 @@ static final class ParallelDispatcher<T> @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; if (s instanceof QueueSubscription) { @SuppressWarnings("unchecked") @@ -204,7 +204,7 @@ public void cancel() { public void onNext(T t) { if (sourceMode == QueueSubscription.NONE) { if (!queue.offer(t)) { - s.cancel(); + upstream.cancel(); onError(new MissingBackpressureException("Queue is full?")); return; } @@ -228,7 +228,7 @@ public void onComplete() { void cancel(int m) { if (requests.decrementAndGet(m) == 0L) { cancelled = true; - this.s.cancel(); + this.upstream.cancel(); if (getAndIncrement() == 0) { queue.clear(); @@ -292,7 +292,7 @@ void drainAsync() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); for (Subscriber<? super T> s : a) { s.onError(ex); } @@ -310,7 +310,7 @@ void drainAsync() { int c = ++consumed; if (c == limit) { consumed = 0; - s.request(c); + upstream.request(c); } notReady = 0; } else { @@ -380,7 +380,7 @@ void drainSync() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.cancel(); + upstream.cancel(); for (Subscriber<? super T> s : a) { s.onError(ex); } diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java index 7a29e1bed4..b248cde69f 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java @@ -63,7 +63,7 @@ abstract static class JoinSubscriptionBase<T> extends AtomicInteger private static final long serialVersionUID = 3100232009247827843L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final JoinInnerSubscriber<T>[] subscribers; @@ -76,7 +76,7 @@ abstract static class JoinSubscriptionBase<T> extends AtomicInteger final AtomicInteger done = new AtomicInteger(); JoinSubscriptionBase(Subscriber<? super T> actual, int n, int prefetch) { - this.actual = actual; + this.downstream = actual; @SuppressWarnings("unchecked") JoinInnerSubscriber<T>[] a = new JoinInnerSubscriber[n]; @@ -144,7 +144,7 @@ static final class JoinSubscription<T> extends JoinSubscriptionBase<T> { public void onNext(JoinInnerSubscriber<T> inner, T value) { if (get() == 0 && compareAndSet(0, 1)) { if (requested.get() != 0) { - actual.onNext(value); + downstream.onNext(value); if (requested.get() != Long.MAX_VALUE) { requested.decrementAndGet(); } @@ -156,7 +156,7 @@ public void onNext(JoinInnerSubscriber<T> inner, T value) { cancelAll(); Throwable mbe = new MissingBackpressureException("Queue full?!"); if (errors.compareAndSet(null, mbe)) { - actual.onError(mbe); + downstream.onError(mbe); } else { RxJavaPlugins.onError(mbe); } @@ -215,7 +215,7 @@ void drainLoop() { JoinInnerSubscriber<T>[] s = this.subscribers; int n = s.length; - Subscriber<? super T> a = this.actual; + Subscriber<? super T> a = this.downstream; for (;;) { @@ -329,7 +329,7 @@ static final class JoinSubscriptionDelayError<T> extends JoinSubscriptionBase<T> void onNext(JoinInnerSubscriber<T> inner, T value) { if (get() == 0 && compareAndSet(0, 1)) { if (requested.get() != 0) { - actual.onNext(value); + downstream.onNext(value); if (requested.get() != Long.MAX_VALUE) { requested.decrementAndGet(); } @@ -393,7 +393,7 @@ void drainLoop() { JoinInnerSubscriber<T>[] s = this.subscribers; int n = s.length; - Subscriber<? super T> a = this.actual; + Subscriber<? super T> a = this.downstream; for (;;) { diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelMap.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelMap.java index 6786621f5f..18a627d6ad 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelMap.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelMap.java @@ -70,35 +70,35 @@ public int parallelism() { static final class ParallelMapSubscriber<T, R> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final Function<? super T, ? extends R> mapper; - Subscription s; + Subscription upstream; boolean done; ParallelMapSubscriber(Subscriber<? super R> actual, Function<? super T, ? extends R> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -118,7 +118,7 @@ public void onNext(T t) { return; } - actual.onNext(v); + downstream.onNext(v); } @Override @@ -128,7 +128,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -137,41 +137,41 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } } static final class ParallelMapConditionalSubscriber<T, R> implements ConditionalSubscriber<T>, Subscription { - final ConditionalSubscriber<? super R> actual; + final ConditionalSubscriber<? super R> downstream; final Function<? super T, ? extends R> mapper; - Subscription s; + Subscription upstream; boolean done; ParallelMapConditionalSubscriber(ConditionalSubscriber<? super R> actual, Function<? super T, ? extends R> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -191,7 +191,7 @@ public void onNext(T t) { return; } - actual.onNext(v); + downstream.onNext(v); } @Override @@ -210,7 +210,7 @@ public boolean tryOnNext(T t) { return false; } - return actual.tryOnNext(v); + return downstream.tryOnNext(v); } @Override @@ -220,7 +220,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -229,7 +229,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelMapTry.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelMapTry.java index 493b5f5dc3..73c19733bd 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelMapTry.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelMapTry.java @@ -75,46 +75,46 @@ public int parallelism() { static final class ParallelMapTrySubscriber<T, R> implements ConditionalSubscriber<T>, Subscription { - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final Function<? super T, ? extends R> mapper; final BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler; - Subscription s; + Subscription upstream; boolean done; ParallelMapTrySubscriber(Subscriber<? super R> actual, Function<? super T, ? extends R> mapper, BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.errorHandler = errorHandler; } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { if (!tryOnNext(t) && !done) { - s.request(1); + upstream.request(1); } } @@ -160,7 +160,7 @@ public boolean tryOnNext(T t) { } } - actual.onNext(v); + downstream.onNext(v); return true; } } @@ -172,7 +172,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -181,52 +181,53 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } } static final class ParallelMapTryConditionalSubscriber<T, R> implements ConditionalSubscriber<T>, Subscription { - final ConditionalSubscriber<? super R> actual; + final ConditionalSubscriber<? super R> downstream; final Function<? super T, ? extends R> mapper; final BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler; - Subscription s; + + Subscription upstream; boolean done; ParallelMapTryConditionalSubscriber(ConditionalSubscriber<? super R> actual, Function<? super T, ? extends R> mapper, BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.errorHandler = errorHandler; } @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onNext(T t) { if (!tryOnNext(t) && !done) { - s.request(1); + upstream.request(1); } } @@ -272,7 +273,7 @@ public boolean tryOnNext(T t) { } } - return actual.tryOnNext(v); + return downstream.tryOnNext(v); } } @@ -283,7 +284,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } @Override @@ -292,7 +293,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelPeek.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelPeek.java index ebcc3c91a4..3e7914c02a 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelPeek.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelPeek.java @@ -87,16 +87,16 @@ public int parallelism() { static final class ParallelPeekSubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final ParallelPeek<T> parent; - Subscription s; + Subscription upstream; boolean done; ParallelPeekSubscriber(Subscriber<? super T> actual, ParallelPeek<T> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } @@ -108,7 +108,7 @@ public void request(long n) { Exceptions.throwIfFatal(ex); RxJavaPlugins.onError(ex); } - s.request(n); + upstream.request(n); } @Override @@ -119,25 +119,25 @@ public void cancel() { Exceptions.throwIfFatal(ex); RxJavaPlugins.onError(ex); } - s.cancel(); + upstream.cancel(); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; try { parent.onSubscribe.accept(s); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); s.cancel(); - actual.onSubscribe(EmptySubscription.INSTANCE); + downstream.onSubscribe(EmptySubscription.INSTANCE); onError(ex); return; } - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -152,7 +152,7 @@ public void onNext(T t) { return; } - actual.onNext(t); + downstream.onNext(t); try { parent.onAfterNext.accept(t); @@ -177,7 +177,7 @@ public void onError(Throwable t) { Exceptions.throwIfFatal(ex); t = new CompositeException(t, ex); } - actual.onError(t); + downstream.onError(t); try { parent.onAfterTerminated.run(); @@ -195,10 +195,10 @@ public void onComplete() { parent.onComplete.run(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } - actual.onComplete(); + downstream.onComplete(); try { parent.onAfterTerminated.run(); diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduce.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduce.java index f747e8c83c..8e421ef112 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduce.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduce.java @@ -103,10 +103,10 @@ static final class ParallelReduceSubscriber<T, R> extends DeferredScalarSubscrib @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -138,7 +138,7 @@ public void onError(Throwable t) { } done = true; accumulator = null; - actual.onError(t); + downstream.onError(t); } @Override @@ -155,7 +155,7 @@ public void onComplete() { @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java index 1505ea0ff3..347ce2ead9 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java @@ -117,7 +117,7 @@ public void cancel() { void innerError(Throwable ex) { if (error.compareAndSet(null, ex)) { cancel(); - actual.onError(ex); + downstream.onError(ex); } else { if (ex != error.get()) { RxJavaPlugins.onError(ex); @@ -153,7 +153,7 @@ void innerComplete(T value) { if (sp != null) { complete(sp.first); } else { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelRunOn.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelRunOn.java index bf52698359..8643cc6d2b 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelRunOn.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelRunOn.java @@ -120,7 +120,7 @@ abstract static class BaseRunOnSubscriber<T> extends AtomicInteger final Worker worker; - Subscription s; + Subscription upstream; volatile boolean done; @@ -145,7 +145,7 @@ public final void onNext(T t) { return; } if (!queue.offer(t)) { - s.cancel(); + upstream.cancel(); onError(new MissingBackpressureException("Queue is full?!")); return; } @@ -184,7 +184,7 @@ public final void request(long n) { public final void cancel() { if (!cancelled) { cancelled = true; - s.cancel(); + upstream.cancel(); worker.dispose(); if (getAndIncrement() == 0) { @@ -204,19 +204,19 @@ static final class RunOnSubscriber<T> extends BaseRunOnSubscriber<T> { private static final long serialVersionUID = 1075119423897941642L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; RunOnSubscriber(Subscriber<? super T> actual, int prefetch, SpscArrayQueue<T> queue, Worker worker) { super(prefetch, queue, worker); - this.actual = actual; + this.downstream = actual; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(prefetch); } @@ -227,7 +227,7 @@ public void run() { int missed = 1; int c = consumed; SpscArrayQueue<T> q = queue; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; int lim = limit; for (;;) { @@ -277,7 +277,7 @@ public void run() { int p = ++c; if (p == lim) { c = 0; - s.request(p); + upstream.request(p); } } @@ -328,19 +328,19 @@ static final class RunOnConditionalSubscriber<T> extends BaseRunOnSubscriber<T> private static final long serialVersionUID = 1075119423897941642L; - final ConditionalSubscriber<? super T> actual; + final ConditionalSubscriber<? super T> downstream; RunOnConditionalSubscriber(ConditionalSubscriber<? super T> actual, int prefetch, SpscArrayQueue<T> queue, Worker worker) { super(prefetch, queue, worker); - this.actual = actual; + this.downstream = actual; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(prefetch); } @@ -351,7 +351,7 @@ public void run() { int missed = 1; int c = consumed; SpscArrayQueue<T> q = queue; - ConditionalSubscriber<? super T> a = actual; + ConditionalSubscriber<? super T> a = downstream; int lim = limit; for (;;) { @@ -401,7 +401,7 @@ public void run() { int p = ++c; if (p == lim) { c = 0; - s.request(p); + upstream.request(p); } } diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java index 43ef716d1a..1151716fff 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java @@ -58,7 +58,7 @@ static final class SortedJoinSubscription<T> private static final long serialVersionUID = 3481980673745556697L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final SortedJoinInnerSubscriber<T>[] subscribers; @@ -78,7 +78,7 @@ static final class SortedJoinSubscription<T> @SuppressWarnings("unchecked") SortedJoinSubscription(Subscriber<? super T> actual, int n, Comparator<? super T> comparator) { - this.actual = actual; + this.downstream = actual; this.comparator = comparator; SortedJoinInnerSubscriber<T>[] s = new SortedJoinInnerSubscriber[n]; @@ -142,7 +142,7 @@ void drain() { } int missed = 1; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; List<T>[] lists = this.lists; int[] indexes = this.indexes; int n = indexes.length; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleCache.java b/src/main/java/io/reactivex/internal/operators/single/SingleCache.java index de237efc84..1752a283b0 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleCache.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleCache.java @@ -131,7 +131,7 @@ public void onSuccess(T value) { for (CacheDisposable<T> d : observers.getAndSet(TERMINATED)) { if (!d.isDisposed()) { - d.actual.onSuccess(value); + d.downstream.onSuccess(value); } } } @@ -143,7 +143,7 @@ public void onError(Throwable e) { for (CacheDisposable<T> d : observers.getAndSet(TERMINATED)) { if (!d.isDisposed()) { - d.actual.onError(e); + d.downstream.onError(e); } } } @@ -154,12 +154,12 @@ static final class CacheDisposable<T> private static final long serialVersionUID = 7514387411091976596L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final SingleCache<T> parent; CacheDisposable(SingleObserver<? super T> actual, SingleCache<T> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java b/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java index fd52840f89..2b0dcfae85 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleCreate.java @@ -47,14 +47,13 @@ static final class Emitter<T> extends AtomicReference<Disposable> implements SingleEmitter<T>, Disposable { - final SingleObserver<? super T> actual; - - Emitter(SingleObserver<? super T> actual) { - this.actual = actual; - } + private static final long serialVersionUID = -2467358622224974244L; + final SingleObserver<? super T> downstream; - private static final long serialVersionUID = -2467358622224974244L; + Emitter(SingleObserver<? super T> downstream) { + this.downstream = downstream; + } @Override public void onSuccess(T value) { @@ -63,9 +62,9 @@ public void onSuccess(T value) { if (d != DisposableHelper.DISPOSED) { try { if (value == null) { - actual.onError(new NullPointerException("onSuccess called with null. Null values are generally not allowed in 2.x operators and sources.")); + downstream.onError(new NullPointerException("onSuccess called with null. Null values are generally not allowed in 2.x operators and sources.")); } else { - actual.onSuccess(value); + downstream.onSuccess(value); } } finally { if (d != null) { @@ -92,7 +91,7 @@ public boolean tryOnError(Throwable t) { Disposable d = getAndSet(DisposableHelper.DISPOSED); if (d != DisposableHelper.DISPOSED) { try { - actual.onError(t); + downstream.onError(t); } finally { if (d != null) { d.dispose(); diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java index 4307f4197c..ba5beeec9d 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java @@ -43,12 +43,12 @@ static final class OtherObserver<T> private static final long serialVersionUID = -8565274649390031272L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final SingleSource<T> source; OtherObserver(SingleObserver<? super T> actual, SingleSource<T> source) { - this.actual = actual; + this.downstream = actual; this.source = source; } @@ -56,18 +56,18 @@ static final class OtherObserver<T> public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - source.subscribe(new ResumeSingleObserver<T>(this, actual)); + source.subscribe(new ResumeSingleObserver<T>(this, downstream)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java index d9ec740604..0614c091c0 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java @@ -44,14 +44,14 @@ static final class OtherSubscriber<T, U> private static final long serialVersionUID = -8565274649390031272L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final SingleSource<T> source; boolean done; OtherSubscriber(SingleObserver<? super T> actual, SingleSource<T> source) { - this.actual = actual; + this.downstream = actual; this.source = source; } @@ -59,7 +59,7 @@ static final class OtherSubscriber<T, U> public void onSubscribe(Disposable d) { if (DisposableHelper.set(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -76,7 +76,7 @@ public void onError(Throwable e) { return; } done = true; - actual.onError(e); + downstream.onError(e); } @Override @@ -85,7 +85,7 @@ public void onComplete() { return; } done = true; - source.subscribe(new ResumeSingleObserver<T>(this, actual)); + source.subscribe(new ResumeSingleObserver<T>(this, downstream)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java index 0928bab13d..bbc8a9e460 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java @@ -47,25 +47,25 @@ static final class OtherSubscriber<T, U> private static final long serialVersionUID = -8565274649390031272L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final SingleSource<T> source; boolean done; - Subscription s; + Subscription upstream; OtherSubscriber(SingleObserver<? super T> actual, SingleSource<T> source) { - this.actual = actual; + this.downstream = actual; this.source = source; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -73,7 +73,7 @@ public void onSubscribe(Subscription s) { @Override public void onNext(U value) { - s.cancel(); + upstream.cancel(); onComplete(); } @@ -84,7 +84,7 @@ public void onError(Throwable e) { return; } done = true; - actual.onError(e); + downstream.onError(e); } @Override @@ -93,12 +93,12 @@ public void onComplete() { return; } done = true; - source.subscribe(new ResumeSingleObserver<T>(this, actual)); + source.subscribe(new ResumeSingleObserver<T>(this, downstream)); } @Override public void dispose() { - s.cancel(); + upstream.cancel(); DisposableHelper.dispose(this); } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java index 3adc4f9333..1c1b4aabe3 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java @@ -43,12 +43,12 @@ static final class OtherObserver<T, U> private static final long serialVersionUID = -8565274649390031272L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final SingleSource<T> source; OtherObserver(SingleObserver<? super T> actual, SingleSource<T> source) { - this.actual = actual; + this.downstream = actual; this.source = source; } @@ -56,18 +56,18 @@ static final class OtherObserver<T, U> public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(U value) { - source.subscribe(new ResumeSingleObserver<T>(this, actual)); + source.subscribe(new ResumeSingleObserver<T>(this, downstream)); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java b/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java index dd077d259e..ad9883a1a2 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDetach.java @@ -38,51 +38,51 @@ protected void subscribeActual(SingleObserver<? super T> observer) { static final class DetachSingleObserver<T> implements SingleObserver<T>, Disposable { - SingleObserver<? super T> actual; + SingleObserver<? super T> downstream; - Disposable d; + Disposable upstream; - DetachSingleObserver(SingleObserver<? super T> actual) { - this.actual = actual; + DetachSingleObserver(SingleObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void dispose() { - actual = null; - d.dispose(); - d = DisposableHelper.DISPOSED; + downstream = null; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; - SingleObserver<? super T> a = actual; + upstream = DisposableHelper.DISPOSED; + SingleObserver<? super T> a = downstream; if (a != null) { - actual = null; + downstream = null; a.onSuccess(value); } } @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - SingleObserver<? super T> a = actual; + upstream = DisposableHelper.DISPOSED; + SingleObserver<? super T> a = downstream; if (a != null) { - actual = null; + downstream = null; a.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java index bf2e557c36..208bb0ecba 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterSuccess.java @@ -44,29 +44,29 @@ protected void subscribeActual(SingleObserver<? super T> observer) { static final class DoAfterObserver<T> implements SingleObserver<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final Consumer<? super T> onAfterSuccess; - Disposable d; + Disposable upstream; DoAfterObserver(SingleObserver<? super T> actual, Consumer<? super T> onAfterSuccess) { - this.actual = actual; + this.downstream = actual; this.onAfterSuccess = onAfterSuccess; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T t) { - actual.onSuccess(t); + downstream.onSuccess(t); try { onAfterSuccess.accept(t); @@ -79,17 +79,17 @@ public void onSuccess(T t) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java index 269902cdc7..eed7993231 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java @@ -46,48 +46,48 @@ protected void subscribeActual(SingleObserver<? super T> observer) { static final class DoAfterTerminateObserver<T> implements SingleObserver<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final Action onAfterTerminate; - Disposable d; + Disposable upstream; DoAfterTerminateObserver(SingleObserver<? super T> actual, Action onAfterTerminate) { - this.actual = actual; + this.downstream = actual; this.onAfterTerminate = onAfterTerminate; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T t) { - actual.onSuccess(t); + downstream.onSuccess(t); onAfterTerminate(); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); onAfterTerminate(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } private void onAfterTerminate() { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java index f7e6cc3fee..7a6bc67258 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoFinally.java @@ -48,47 +48,47 @@ static final class DoFinallyObserver<T> extends AtomicInteger implements SingleO private static final long serialVersionUID = 4109457741734051389L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final Action onFinally; - Disposable d; + Disposable upstream; DoFinallyObserver(SingleObserver<? super T> actual, Action onFinally) { - this.actual = actual; + this.downstream = actual; this.onFinally = onFinally; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T t) { - actual.onSuccess(t); + downstream.onSuccess(t); runFinally(); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); runFinally(); } @Override public void dispose() { - d.dispose(); + upstream.dispose(); runFinally(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } void runFinally() { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnDispose.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnDispose.java index 8515d99887..29cd86d6b7 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnDispose.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnDispose.java @@ -43,12 +43,12 @@ static final class DoOnDisposeObserver<T> implements SingleObserver<T>, Disposable { private static final long serialVersionUID = -8583764624474935784L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; - Disposable d; + Disposable upstream; DoOnDisposeObserver(SingleObserver<? super T> actual, Action onDispose) { - this.actual = actual; + this.downstream = actual; this.lazySet(onDispose); } @@ -62,31 +62,31 @@ public void dispose() { Exceptions.throwIfFatal(ex); RxJavaPlugins.onError(ex); } - d.dispose(); + upstream.dispose(); } } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; - actual.onSubscribe(this); + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSubscribe.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSubscribe.java index c46c2d819b..4103ad6c79 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSubscribe.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnSubscribe.java @@ -43,14 +43,14 @@ protected void subscribeActual(final SingleObserver<? super T> observer) { static final class DoOnSubscribeSingleObserver<T> implements SingleObserver<T> { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final Consumer<? super Disposable> onSubscribe; boolean done; DoOnSubscribeSingleObserver(SingleObserver<? super T> actual, Consumer<? super Disposable> onSubscribe) { - this.actual = actual; + this.downstream = actual; this.onSubscribe = onSubscribe; } @@ -62,11 +62,11 @@ public void onSubscribe(Disposable d) { Exceptions.throwIfFatal(ex); done = true; d.dispose(); - EmptyDisposable.error(ex, actual); + EmptyDisposable.error(ex, downstream); return; } - actual.onSubscribe(d); + downstream.onSubscribe(d); } @Override @@ -74,7 +74,7 @@ public void onSuccess(T value) { if (done) { return; } - actual.onSuccess(value); + downstream.onSuccess(value); } @Override @@ -83,7 +83,7 @@ public void onError(Throwable e) { RxJavaPlugins.onError(e); return; } - actual.onError(e); + downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMap.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMap.java index 29dc3433e4..2913ff79d7 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMap.java @@ -32,8 +32,8 @@ public SingleFlatMap(SingleSource<? extends T> source, Function<? super T, ? ext } @Override - protected void subscribeActual(SingleObserver<? super R> actual) { - source.subscribe(new SingleFlatMapCallback<T, R>(actual, mapper)); + protected void subscribeActual(SingleObserver<? super R> downstream) { + source.subscribe(new SingleFlatMapCallback<T, R>(downstream, mapper)); } static final class SingleFlatMapCallback<T, R> @@ -41,13 +41,13 @@ static final class SingleFlatMapCallback<T, R> implements SingleObserver<T>, Disposable { private static final long serialVersionUID = 3258103020495908596L; - final SingleObserver<? super R> actual; + final SingleObserver<? super R> downstream; final Function<? super T, ? extends SingleSource<? extends R>> mapper; SingleFlatMapCallback(SingleObserver<? super R> actual, Function<? super T, ? extends SingleSource<? extends R>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @@ -64,7 +64,7 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -76,29 +76,29 @@ public void onSuccess(T value) { o = ObjectHelper.requireNonNull(mapper.apply(value), "The single returned by the mapper is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } if (!isDisposed()) { - o.subscribe(new FlatMapSingleObserver<R>(this, actual)); + o.subscribe(new FlatMapSingleObserver<R>(this, downstream)); } } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } static final class FlatMapSingleObserver<R> implements SingleObserver<R> { final AtomicReference<Disposable> parent; - final SingleObserver<? super R> actual; + final SingleObserver<? super R> downstream; - FlatMapSingleObserver(AtomicReference<Disposable> parent, SingleObserver<? super R> actual) { + FlatMapSingleObserver(AtomicReference<Disposable> parent, SingleObserver<? super R> downstream) { this.parent = parent; - this.actual = actual; + this.downstream = downstream; } @Override @@ -108,12 +108,12 @@ public void onSubscribe(final Disposable d) { @Override public void onSuccess(final R value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(final Throwable e) { - actual.onError(e); + downstream.onError(e); } } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapCompletable.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapCompletable.java index 986a831f94..31b9ac2c99 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapCompletable.java @@ -50,13 +50,13 @@ static final class FlatMapCompletableObserver<T> private static final long serialVersionUID = -2177128922851101253L; - final CompletableObserver actual; + final CompletableObserver downstream; final Function<? super T, ? extends CompletableSource> mapper; FlatMapCompletableObserver(CompletableObserver actual, Function<? super T, ? extends CompletableSource> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @@ -94,12 +94,12 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowable.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowable.java index 7267fad95c..1243413dff 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowable.java @@ -57,13 +57,13 @@ static final class FlatMapIterableObserver<T, R> private static final long serialVersionUID = -8938804753851907758L; - final Subscriber<? super R> actual; + final Subscriber<? super R> downstream; final Function<? super T, ? extends Iterable<? extends R>> mapper; final AtomicLong requested; - Disposable d; + Disposable upstream; volatile Iterator<? extends R> it; @@ -73,17 +73,17 @@ static final class FlatMapIterableObserver<T, R> FlatMapIterableObserver(Subscriber<? super R> actual, Function<? super T, ? extends Iterable<? extends R>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.requested = new AtomicLong(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -97,12 +97,12 @@ public void onSuccess(T value) { has = iterator.hasNext(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } if (!has) { - actual.onComplete(); + downstream.onComplete(); return; } @@ -112,8 +112,8 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override @@ -127,8 +127,8 @@ public void request(long n) { @Override public void cancel() { cancelled = true; - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } void drain() { @@ -136,7 +136,7 @@ void drain() { return; } - Subscriber<? super R> a = actual; + Subscriber<? super R> a = downstream; Iterator<? extends R> iterator = this.it; if (outputFused && iterator != null) { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java index 541e5063ed..760a052278 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java @@ -53,11 +53,11 @@ static final class FlatMapIterableObserver<T, R> private static final long serialVersionUID = -8938804753851907758L; - final Observer<? super R> actual; + final Observer<? super R> downstream; final Function<? super T, ? extends Iterable<? extends R>> mapper; - Disposable d; + Disposable upstream; volatile Iterator<? extends R> it; @@ -67,22 +67,22 @@ static final class FlatMapIterableObserver<T, R> FlatMapIterableObserver(Observer<? super R> actual, Function<? super T, ? extends Iterable<? extends R>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - Observer<? super R> a = actual; + Observer<? super R> a = downstream; Iterator<? extends R> iterator; boolean has; try { @@ -91,7 +91,7 @@ public void onSuccess(T value) { has = iterator.hasNext(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } @@ -147,15 +147,15 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; - actual.onError(e); + upstream = DisposableHelper.DISPOSED; + downstream.onError(e); } @Override public void dispose() { cancelled = true; - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; } @Override diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapMaybe.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapMaybe.java index 2b9030ce19..dfe6b60143 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapMaybe.java @@ -37,8 +37,8 @@ public SingleFlatMapMaybe(SingleSource<? extends T> source, Function<? super T, } @Override - protected void subscribeActual(MaybeObserver<? super R> actual) { - source.subscribe(new FlatMapSingleObserver<T, R>(actual, mapper)); + protected void subscribeActual(MaybeObserver<? super R> downstream) { + source.subscribe(new FlatMapSingleObserver<T, R>(downstream, mapper)); } static final class FlatMapSingleObserver<T, R> @@ -47,12 +47,12 @@ static final class FlatMapSingleObserver<T, R> private static final long serialVersionUID = -5843758257109742742L; - final MaybeObserver<? super R> actual; + final MaybeObserver<? super R> downstream; final Function<? super T, ? extends MaybeSource<? extends R>> mapper; FlatMapSingleObserver(MaybeObserver<? super R> actual, Function<? super T, ? extends MaybeSource<? extends R>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; } @@ -69,7 +69,7 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -86,13 +86,13 @@ public void onSuccess(T value) { } if (!isDisposed()) { - ms.subscribe(new FlatMapMaybeObserver<R>(this, actual)); + ms.subscribe(new FlatMapMaybeObserver<R>(this, downstream)); } } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } } @@ -100,11 +100,11 @@ static final class FlatMapMaybeObserver<R> implements MaybeObserver<R> { final AtomicReference<Disposable> parent; - final MaybeObserver<? super R> actual; + final MaybeObserver<? super R> downstream; - FlatMapMaybeObserver(AtomicReference<Disposable> parent, MaybeObserver<? super R> actual) { + FlatMapMaybeObserver(AtomicReference<Disposable> parent, MaybeObserver<? super R> downstream) { this.parent = parent; - this.actual = actual; + this.downstream = downstream; } @Override @@ -114,17 +114,17 @@ public void onSubscribe(final Disposable d) { @Override public void onSuccess(final R value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(final Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapPublisher.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapPublisher.java index bdb7d166cd..be090bd20b 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapPublisher.java @@ -62,8 +62,8 @@ public SingleFlatMapPublisher(SingleSource<T> source, } @Override - protected void subscribeActual(Subscriber<? super R> actual) { - source.subscribe(new SingleFlatMapPublisherObserver<T, R>(actual, mapper)); + protected void subscribeActual(Subscriber<? super R> downstream) { + source.subscribe(new SingleFlatMapPublisherObserver<T, R>(downstream, mapper)); } static final class SingleFlatMapPublisherObserver<S, T> extends AtomicLong @@ -71,14 +71,14 @@ static final class SingleFlatMapPublisherObserver<S, T> extends AtomicLong private static final long serialVersionUID = 7759721921468635667L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final Function<? super S, ? extends Publisher<? extends T>> mapper; final AtomicReference<Subscription> parent; Disposable disposable; SingleFlatMapPublisherObserver(Subscriber<? super T> actual, Function<? super S, ? extends Publisher<? extends T>> mapper) { - this.actual = actual; + this.downstream = actual; this.mapper = mapper; this.parent = new AtomicReference<Subscription>(); } @@ -86,7 +86,7 @@ static final class SingleFlatMapPublisherObserver<S, T> extends AtomicLong @Override public void onSubscribe(Disposable d) { this.disposable = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } @Override @@ -96,7 +96,7 @@ public void onSuccess(S value) { f = ObjectHelper.requireNonNull(mapper.apply(value), "the mapper returned a null Publisher"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - actual.onError(e); + downstream.onError(e); return; } f.subscribe(this); @@ -109,17 +109,17 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFromPublisher.java b/src/main/java/io/reactivex/internal/operators/single/SingleFromPublisher.java index 9543c494c9..5709f3c6d4 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFromPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFromPublisher.java @@ -36,9 +36,9 @@ protected void subscribeActual(final SingleObserver<? super T> observer) { } static final class ToSingleObserver<T> implements FlowableSubscriber<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; - Subscription s; + Subscription upstream; T value; @@ -46,16 +46,16 @@ static final class ToSingleObserver<T> implements FlowableSubscriber<T>, Disposa volatile boolean disposed; - ToSingleObserver(SingleObserver<? super T> actual) { - this.actual = actual; + ToSingleObserver(SingleObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -67,10 +67,10 @@ public void onNext(T t) { return; } if (value != null) { - s.cancel(); + upstream.cancel(); done = true; this.value = null; - actual.onError(new IndexOutOfBoundsException("Too many elements in the Publisher")); + downstream.onError(new IndexOutOfBoundsException("Too many elements in the Publisher")); } else { value = t; } @@ -84,7 +84,7 @@ public void onError(Throwable t) { } done = true; this.value = null; - actual.onError(t); + downstream.onError(t); } @Override @@ -96,9 +96,9 @@ public void onComplete() { T v = this.value; this.value = null; if (v == null) { - actual.onError(new NoSuchElementException("The source Publisher is empty")); + downstream.onError(new NoSuchElementException("The source Publisher is empty")); } else { - actual.onSuccess(v); + downstream.onSuccess(v); } } @@ -110,7 +110,7 @@ public boolean isDisposed() { @Override public void dispose() { disposed = true; - s.cancel(); + upstream.cancel(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleHide.java b/src/main/java/io/reactivex/internal/operators/single/SingleHide.java index 27cf6205b2..7ec7390e20 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleHide.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleHide.java @@ -32,40 +32,40 @@ protected void subscribeActual(SingleObserver<? super T> observer) { static final class HideSingleObserver<T> implements SingleObserver<T>, Disposable { - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; - Disposable d; + Disposable upstream; - HideSingleObserver(SingleObserver<? super T> actual) { - this.actual = actual; + HideSingleObserver(SingleObserver<? super T> downstream) { + this.downstream = downstream; } @Override public void dispose() { - d.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; - actual.onSubscribe(this); + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleObserveOn.java b/src/main/java/io/reactivex/internal/operators/single/SingleObserveOn.java index 494fa2c896..7c8a6c1977 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleObserveOn.java @@ -39,7 +39,7 @@ static final class ObserveOnSingleObserver<T> extends AtomicReference<Disposable implements SingleObserver<T>, Disposable, Runnable { private static final long serialVersionUID = 3528003840217436037L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final Scheduler scheduler; @@ -47,14 +47,14 @@ static final class ObserveOnSingleObserver<T> extends AtomicReference<Disposable Throwable error; ObserveOnSingleObserver(SingleObserver<? super T> actual, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.scheduler = scheduler; } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -76,9 +76,9 @@ public void onError(Throwable e) { public void run() { Throwable ex = error; if (ex != null) { - actual.onError(ex); + downstream.onError(ex); } else { - actual.onSuccess(value); + downstream.onSuccess(value); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleResumeNext.java b/src/main/java/io/reactivex/internal/operators/single/SingleResumeNext.java index 42133c05f4..325365f8f4 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleResumeNext.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleResumeNext.java @@ -43,26 +43,26 @@ static final class ResumeMainSingleObserver<T> extends AtomicReference<Disposabl implements SingleObserver<T>, Disposable { private static final long serialVersionUID = -5314538511045349925L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final Function<? super Throwable, ? extends SingleSource<? extends T>> nextFunction; ResumeMainSingleObserver(SingleObserver<? super T> actual, Function<? super Throwable, ? extends SingleSource<? extends T>> nextFunction) { - this.actual = actual; + this.downstream = actual; this.nextFunction = nextFunction; } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override @@ -73,11 +73,11 @@ public void onError(Throwable e) { source = ObjectHelper.requireNonNull(nextFunction.apply(e), "The nextFunction returned a null SingleSource."); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(new CompositeException(e, ex)); + downstream.onError(new CompositeException(e, ex)); return; } - source.subscribe(new ResumeSingleObserver<T>(this, actual)); + source.subscribe(new ResumeSingleObserver<T>(this, downstream)); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleSubscribeOn.java b/src/main/java/io/reactivex/internal/operators/single/SingleSubscribeOn.java index 68299fef2c..9b29e6253f 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleSubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleSubscribeOn.java @@ -46,14 +46,14 @@ static final class SubscribeOnObserver<T> private static final long serialVersionUID = 7000911171163930287L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final SequentialDisposable task; final SingleSource<? extends T> source; SubscribeOnObserver(SingleObserver<? super T> actual, SingleSource<? extends T> source) { - this.actual = actual; + this.downstream = actual; this.source = source; this.task = new SequentialDisposable(); } @@ -65,12 +65,12 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java b/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java index 2a4bb1b4b7..8db5e40a03 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java @@ -57,12 +57,12 @@ static final class TakeUntilMainObserver<T> private static final long serialVersionUID = -622603812305745221L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final TakeUntilOtherSubscriber other; - TakeUntilMainObserver(SingleObserver<? super T> actual) { - this.actual = actual; + TakeUntilMainObserver(SingleObserver<? super T> downstream) { + this.downstream = downstream; this.other = new TakeUntilOtherSubscriber(this); } @@ -88,7 +88,7 @@ public void onSuccess(T value) { Disposable a = getAndSet(DisposableHelper.DISPOSED); if (a != DisposableHelper.DISPOSED) { - actual.onSuccess(value); + downstream.onSuccess(value); } } @@ -100,7 +100,7 @@ public void onError(Throwable e) { if (a != DisposableHelper.DISPOSED) { a = getAndSet(DisposableHelper.DISPOSED); if (a != DisposableHelper.DISPOSED) { - actual.onError(e); + downstream.onError(e); return; } } @@ -115,7 +115,7 @@ void otherError(Throwable e) { if (a != null) { a.dispose(); } - actual.onError(e); + downstream.onError(e); return; } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java b/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java index 575d47732a..4c97882d62 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java @@ -58,7 +58,7 @@ static final class TimeoutMainObserver<T> extends AtomicReference<Disposable> private static final long serialVersionUID = 37497744973048446L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final AtomicReference<Disposable> task; @@ -70,10 +70,10 @@ static final class TimeoutFallbackObserver<T> extends AtomicReference<Disposable implements SingleObserver<T> { private static final long serialVersionUID = 2071387740092105509L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; - TimeoutFallbackObserver(SingleObserver<? super T> actual) { - this.actual = actual; + TimeoutFallbackObserver(SingleObserver<? super T> downstream) { + this.downstream = downstream; } @Override @@ -83,17 +83,17 @@ public void onSubscribe(Disposable d) { @Override public void onSuccess(T t) { - actual.onSuccess(t); + downstream.onSuccess(t); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } } TimeoutMainObserver(SingleObserver<? super T> actual, SingleSource<? extends T> other) { - this.actual = actual; + this.downstream = actual; this.other = other; this.task = new AtomicReference<Disposable>(); if (other != null) { @@ -112,7 +112,7 @@ public void run() { } SingleSource<? extends T> other = this.other; if (other == null) { - actual.onError(new TimeoutException()); + downstream.onError(new TimeoutException()); } else { this.other = null; other.subscribe(fallback); @@ -130,7 +130,7 @@ public void onSuccess(T t) { Disposable d = get(); if (d != DisposableHelper.DISPOSED && compareAndSet(d, DisposableHelper.DISPOSED)) { DisposableHelper.dispose(task); - actual.onSuccess(t); + downstream.onSuccess(t); } } @@ -139,7 +139,7 @@ public void onError(Throwable e) { Disposable d = get(); if (d != DisposableHelper.DISPOSED && compareAndSet(d, DisposableHelper.DISPOSED)) { DisposableHelper.dispose(task); - actual.onError(e); + downstream.onError(e); } else { RxJavaPlugins.onError(e); } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleTimer.java b/src/main/java/io/reactivex/internal/operators/single/SingleTimer.java index 638a8894c5..68b4c9c3b7 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleTimer.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleTimer.java @@ -45,15 +45,15 @@ protected void subscribeActual(final SingleObserver<? super Long> observer) { static final class TimerDisposable extends AtomicReference<Disposable> implements Disposable, Runnable { private static final long serialVersionUID = 8465401857522493082L; - final SingleObserver<? super Long> actual; + final SingleObserver<? super Long> downstream; - TimerDisposable(final SingleObserver<? super Long> actual) { - this.actual = actual; + TimerDisposable(final SingleObserver<? super Long> downstream) { + this.downstream = downstream; } @Override public void run() { - actual.onSuccess(0L); + downstream.onSuccess(0L); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleToFlowable.java b/src/main/java/io/reactivex/internal/operators/single/SingleToFlowable.java index a33d36df98..f48aa4659b 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleToFlowable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleToFlowable.java @@ -43,18 +43,18 @@ static final class SingleToFlowableObserver<T> extends DeferredScalarSubscriptio private static final long serialVersionUID = 187782011903685568L; - Disposable d; + Disposable upstream; - SingleToFlowableObserver(Subscriber<? super T> actual) { - super(actual); + SingleToFlowableObserver(Subscriber<? super T> downstream) { + super(downstream); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -65,13 +65,13 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } @Override public void cancel() { super.cancel(); - d.dispose(); + upstream.dispose(); } } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java index 56d78e0774..2c4126a837 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleToObservable.java @@ -52,18 +52,18 @@ static final class SingleToObservableObserver<T> implements SingleObserver<T> { private static final long serialVersionUID = 3786543492451018833L; - Disposable d; + Disposable upstream; - SingleToObservableObserver(Observer<? super T> actual) { - super(actual); + SingleToObservableObserver(Observer<? super T> downstream) { + super(downstream); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @@ -80,7 +80,7 @@ public void onError(Throwable e) { @Override public void dispose() { super.dispose(); - d.dispose(); + upstream.dispose(); } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleUnsubscribeOn.java b/src/main/java/io/reactivex/internal/operators/single/SingleUnsubscribeOn.java index 27c4200d8a..dc7962ba8e 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleUnsubscribeOn.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleUnsubscribeOn.java @@ -45,14 +45,14 @@ static final class UnsubscribeOnSingleObserver<T> extends AtomicReference<Dispos private static final long serialVersionUID = 3256698449646456986L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final Scheduler scheduler; Disposable ds; UnsubscribeOnSingleObserver(SingleObserver<? super T> actual, Scheduler scheduler) { - this.actual = actual; + this.downstream = actual; this.scheduler = scheduler; } @@ -78,18 +78,18 @@ public boolean isDisposed() { @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { - actual.onSuccess(value); + downstream.onSuccess(value); } @Override public void onError(Throwable e) { - actual.onError(e); + downstream.onError(e); } } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleUsing.java b/src/main/java/io/reactivex/internal/operators/single/SingleUsing.java index e2f93a9110..0352bddb63 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleUsing.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleUsing.java @@ -89,47 +89,47 @@ static final class UsingSingleObserver<T, U> extends private static final long serialVersionUID = -5331524057054083935L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; final Consumer<? super U> disposer; final boolean eager; - Disposable d; + Disposable upstream; UsingSingleObserver(SingleObserver<? super T> actual, U resource, boolean eager, Consumer<? super U> disposer) { super(resource); - this.actual = actual; + this.downstream = actual; this.eager = eager; this.disposer = disposer; } @Override public void dispose() { - d.dispose(); - d = DisposableHelper.DISPOSED; + upstream.dispose(); + upstream = DisposableHelper.DISPOSED; disposeAfter(); } @Override public boolean isDisposed() { - return d.isDisposed(); + return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { - if (DisposableHelper.validate(this.d, d)) { - this.d = d; + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @SuppressWarnings("unchecked") @Override public void onSuccess(T value) { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; if (eager) { Object u = getAndSet(this); @@ -138,7 +138,7 @@ public void onSuccess(T value) { disposer.accept((U)u); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } } else { @@ -146,7 +146,7 @@ public void onSuccess(T value) { } } - actual.onSuccess(value); + downstream.onSuccess(value); if (!eager) { disposeAfter(); @@ -156,7 +156,7 @@ public void onSuccess(T value) { @SuppressWarnings("unchecked") @Override public void onError(Throwable e) { - d = DisposableHelper.DISPOSED; + upstream = DisposableHelper.DISPOSED; if (eager) { Object u = getAndSet(this); @@ -172,7 +172,7 @@ public void onError(Throwable e) { } } - actual.onError(e); + downstream.onError(e); if (!eager) { disposeAfter(); diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleZipArray.java b/src/main/java/io/reactivex/internal/operators/single/SingleZipArray.java index e98917b511..e9ba27d755 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleZipArray.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleZipArray.java @@ -70,7 +70,7 @@ static final class ZipCoordinator<T, R> extends AtomicInteger implements Disposa private static final long serialVersionUID = -5556924161382950569L; - final SingleObserver<? super R> actual; + final SingleObserver<? super R> downstream; final Function<? super Object[], ? extends R> zipper; @@ -81,7 +81,7 @@ static final class ZipCoordinator<T, R> extends AtomicInteger implements Disposa @SuppressWarnings("unchecked") ZipCoordinator(SingleObserver<? super R> observer, int n, Function<? super Object[], ? extends R> zipper) { super(n); - this.actual = observer; + this.downstream = observer; this.zipper = zipper; ZipSingleObserver<T>[] o = new ZipSingleObserver[n]; for (int i = 0; i < n; i++) { @@ -114,11 +114,11 @@ void innerSuccess(T value, int index) { v = ObjectHelper.requireNonNull(zipper.apply(values), "The zipper returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - actual.onError(ex); + downstream.onError(ex); return; } - actual.onSuccess(v); + downstream.onSuccess(v); } } @@ -136,7 +136,7 @@ void disposeExcept(int index) { void innerError(Throwable ex, int index) { if (getAndSet(0) > 0) { disposeExcept(index); - actual.onError(ex); + downstream.onError(ex); } else { RxJavaPlugins.onError(ex); } diff --git a/src/main/java/io/reactivex/internal/schedulers/DisposeOnCancel.java b/src/main/java/io/reactivex/internal/schedulers/DisposeOnCancel.java index ef7dfedd02..c79eaeb149 100644 --- a/src/main/java/io/reactivex/internal/schedulers/DisposeOnCancel.java +++ b/src/main/java/io/reactivex/internal/schedulers/DisposeOnCancel.java @@ -22,15 +22,16 @@ * the other methods are not implemented. */ final class DisposeOnCancel implements Future<Object> { - final Disposable d; + + final Disposable upstream; DisposeOnCancel(Disposable d) { - this.d = d; + this.upstream = d; } @Override public boolean cancel(boolean mayInterruptIfRunning) { - d.dispose(); + upstream.dispose(); return false; } diff --git a/src/main/java/io/reactivex/internal/subscribers/BasicFuseableConditionalSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/BasicFuseableConditionalSubscriber.java index c9d2f98b46..f665d48a49 100644 --- a/src/main/java/io/reactivex/internal/subscribers/BasicFuseableConditionalSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/BasicFuseableConditionalSubscriber.java @@ -28,10 +28,10 @@ public abstract class BasicFuseableConditionalSubscriber<T, R> implements ConditionalSubscriber<T>, QueueSubscription<R> { /** The downstream subscriber. */ - protected final ConditionalSubscriber<? super R> actual; + protected final ConditionalSubscriber<? super R> downstream; /** The upstream subscription. */ - protected Subscription s; + protected Subscription upstream; /** The upstream's QueueSubscription if not null. */ protected QueueSubscription<T> qs; @@ -44,26 +44,26 @@ public abstract class BasicFuseableConditionalSubscriber<T, R> implements Condit /** * Construct a BasicFuseableSubscriber by wrapping the given subscriber. - * @param actual the subscriber, not null (not verified) + * @param downstream the subscriber, not null (not verified) */ - public BasicFuseableConditionalSubscriber(ConditionalSubscriber<? super R> actual) { - this.actual = actual; + public BasicFuseableConditionalSubscriber(ConditionalSubscriber<? super R> downstream) { + this.downstream = downstream; } // final: fixed protocol steps to support fuseable and non-fuseable upstream @SuppressWarnings("unchecked") @Override public final void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { + if (SubscriptionHelper.validate(this.upstream, s)) { - this.s = s; + this.upstream = s; if (s instanceof QueueSubscription) { this.qs = (QueueSubscription<T>)s; } if (beforeDownstream()) { - actual.onSubscribe(this); + downstream.onSubscribe(this); afterDownstream(); } @@ -97,7 +97,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } /** @@ -106,7 +106,7 @@ public void onError(Throwable t) { */ protected final void fail(Throwable t) { Exceptions.throwIfFatal(t); - s.cancel(); + upstream.cancel(); onError(t); } @@ -116,7 +116,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } /** @@ -149,12 +149,12 @@ protected final int transitiveBoundaryFusion(int mode) { @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override diff --git a/src/main/java/io/reactivex/internal/subscribers/BasicFuseableSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/BasicFuseableSubscriber.java index 6af9b49fc1..945d311b29 100644 --- a/src/main/java/io/reactivex/internal/subscribers/BasicFuseableSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/BasicFuseableSubscriber.java @@ -29,10 +29,10 @@ public abstract class BasicFuseableSubscriber<T, R> implements FlowableSubscriber<T>, QueueSubscription<R> { /** The downstream subscriber. */ - protected final Subscriber<? super R> actual; + protected final Subscriber<? super R> downstream; /** The upstream subscription. */ - protected Subscription s; + protected Subscription upstream; /** The upstream's QueueSubscription if not null. */ protected QueueSubscription<T> qs; @@ -45,26 +45,26 @@ public abstract class BasicFuseableSubscriber<T, R> implements FlowableSubscribe /** * Construct a BasicFuseableSubscriber by wrapping the given subscriber. - * @param actual the subscriber, not null (not verified) + * @param downstream the subscriber, not null (not verified) */ - public BasicFuseableSubscriber(Subscriber<? super R> actual) { - this.actual = actual; + public BasicFuseableSubscriber(Subscriber<? super R> downstream) { + this.downstream = downstream; } // final: fixed protocol steps to support fuseable and non-fuseable upstream @SuppressWarnings("unchecked") @Override public final void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { + if (SubscriptionHelper.validate(this.upstream, s)) { - this.s = s; + this.upstream = s; if (s instanceof QueueSubscription) { this.qs = (QueueSubscription<T>)s; } if (beforeDownstream()) { - actual.onSubscribe(this); + downstream.onSubscribe(this); afterDownstream(); } @@ -98,7 +98,7 @@ public void onError(Throwable t) { return; } done = true; - actual.onError(t); + downstream.onError(t); } /** @@ -107,7 +107,7 @@ public void onError(Throwable t) { */ protected final void fail(Throwable t) { Exceptions.throwIfFatal(t); - s.cancel(); + upstream.cancel(); onError(t); } @@ -117,7 +117,7 @@ public void onComplete() { return; } done = true; - actual.onComplete(); + downstream.onComplete(); } /** @@ -150,12 +150,12 @@ protected final int transitiveBoundaryFusion(int mode) { @Override public void request(long n) { - s.request(n); + upstream.request(n); } @Override public void cancel() { - s.cancel(); + upstream.cancel(); } @Override diff --git a/src/main/java/io/reactivex/internal/subscribers/BlockingBaseSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/BlockingBaseSubscriber.java index 6ab208cc27..72a1374420 100644 --- a/src/main/java/io/reactivex/internal/subscribers/BlockingBaseSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/BlockingBaseSubscriber.java @@ -26,7 +26,7 @@ public abstract class BlockingBaseSubscriber<T> extends CountDownLatch T value; Throwable error; - Subscription s; + Subscription upstream; volatile boolean cancelled; @@ -36,12 +36,12 @@ public BlockingBaseSubscriber() { @Override public final void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; if (!cancelled) { s.request(Long.MAX_VALUE); if (cancelled) { - this.s = SubscriptionHelper.CANCELLED; + this.upstream = SubscriptionHelper.CANCELLED; s.cancel(); } } @@ -64,8 +64,8 @@ public final T blockingGet() { BlockingHelper.verifyNonBlocking(); await(); } catch (InterruptedException ex) { - Subscription s = this.s; - this.s = SubscriptionHelper.CANCELLED; + Subscription s = this.upstream; + this.upstream = SubscriptionHelper.CANCELLED; if (s != null) { s.cancel(); } diff --git a/src/main/java/io/reactivex/internal/subscribers/BlockingFirstSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/BlockingFirstSubscriber.java index 55e8e8c0a2..57fd44623f 100644 --- a/src/main/java/io/reactivex/internal/subscribers/BlockingFirstSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/BlockingFirstSubscriber.java @@ -26,7 +26,7 @@ public final class BlockingFirstSubscriber<T> extends BlockingBaseSubscriber<T> public void onNext(T t) { if (value == null) { value = t; - s.cancel(); + upstream.cancel(); countDown(); } } diff --git a/src/main/java/io/reactivex/internal/subscribers/DeferredScalarSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/DeferredScalarSubscriber.java index 910a898214..701b4a44bc 100644 --- a/src/main/java/io/reactivex/internal/subscribers/DeferredScalarSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/DeferredScalarSubscriber.java @@ -30,25 +30,25 @@ public abstract class DeferredScalarSubscriber<T, R> extends DeferredScalarSubsc private static final long serialVersionUID = 2984505488220891551L; /** The upstream subscription. */ - protected Subscription s; + protected Subscription upstream; /** Can indicate if there was at least on onNext call. */ protected boolean hasValue; /** * Creates a DeferredScalarSubscriber instance and wraps a downstream Subscriber. - * @param actual the downstream subscriber, not null (not verified) + * @param downstream the downstream subscriber, not null (not verified) */ - public DeferredScalarSubscriber(Subscriber<? super R> actual) { - super(actual); + public DeferredScalarSubscriber(Subscriber<? super R> downstream) { + super(downstream); } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); s.request(Long.MAX_VALUE); } @@ -57,7 +57,7 @@ public void onSubscribe(Subscription s) { @Override public void onError(Throwable t) { value = null; - actual.onError(t); + downstream.onError(t); } @Override @@ -65,13 +65,13 @@ public void onComplete() { if (hasValue) { complete(value); } else { - actual.onComplete(); + downstream.onComplete(); } } @Override public void cancel() { super.cancel(); - s.cancel(); + upstream.cancel(); } } diff --git a/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java index 9537556008..1cc2eb2e09 100644 --- a/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java @@ -36,22 +36,22 @@ public final class FutureSubscriber<T> extends CountDownLatch T value; Throwable error; - final AtomicReference<Subscription> s; + final AtomicReference<Subscription> upstream; public FutureSubscriber() { super(1); - this.s = new AtomicReference<Subscription>(); + this.upstream = new AtomicReference<Subscription>(); } @Override public boolean cancel(boolean mayInterruptIfRunning) { for (;;) { - Subscription a = s.get(); + Subscription a = upstream.get(); if (a == this || a == SubscriptionHelper.CANCELLED) { return false; } - if (s.compareAndSet(a, SubscriptionHelper.CANCELLED)) { + if (upstream.compareAndSet(a, SubscriptionHelper.CANCELLED)) { if (a != null) { a.cancel(); } @@ -63,7 +63,7 @@ public boolean cancel(boolean mayInterruptIfRunning) { @Override public boolean isCancelled() { - return SubscriptionHelper.isCancelled(s.get()); + return SubscriptionHelper.isCancelled(upstream.get()); } @Override @@ -110,13 +110,13 @@ public T get(long timeout, TimeUnit unit) throws InterruptedException, Execution @Override public void onSubscribe(Subscription s) { - SubscriptionHelper.setOnce(this.s, s, Long.MAX_VALUE); + SubscriptionHelper.setOnce(this.upstream, s, Long.MAX_VALUE); } @Override public void onNext(T t) { if (value != null) { - s.get().cancel(); + upstream.get().cancel(); onError(new IndexOutOfBoundsException("More than one element received")); return; } @@ -126,13 +126,13 @@ public void onNext(T t) { @Override public void onError(Throwable t) { for (;;) { - Subscription a = s.get(); + Subscription a = upstream.get(); if (a == this || a == SubscriptionHelper.CANCELLED) { RxJavaPlugins.onError(t); return; } error = t; - if (s.compareAndSet(a, this)) { + if (upstream.compareAndSet(a, this)) { countDown(); return; } @@ -146,11 +146,11 @@ public void onComplete() { return; } for (;;) { - Subscription a = s.get(); + Subscription a = upstream.get(); if (a == this || a == SubscriptionHelper.CANCELLED) { return; } - if (s.compareAndSet(a, this)) { + if (upstream.compareAndSet(a, this)) { countDown(); return; } diff --git a/src/main/java/io/reactivex/internal/subscribers/QueueDrainSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/QueueDrainSubscriber.java index 31d97833c2..d07f748999 100644 --- a/src/main/java/io/reactivex/internal/subscribers/QueueDrainSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/QueueDrainSubscriber.java @@ -33,7 +33,9 @@ * @param <V> the value type the child subscriber accepts */ public abstract class QueueDrainSubscriber<T, U, V> extends QueueDrainSubscriberPad4 implements FlowableSubscriber<T>, QueueDrain<U, V> { - protected final Subscriber<? super V> actual; + + protected final Subscriber<? super V> downstream; + protected final SimplePlainQueue<U> queue; protected volatile boolean cancelled; @@ -42,7 +44,7 @@ public abstract class QueueDrainSubscriber<T, U, V> extends QueueDrainSubscriber protected Throwable error; public QueueDrainSubscriber(Subscriber<? super V> actual, SimplePlainQueue<U> queue) { - this.actual = actual; + this.downstream = actual; this.queue = queue; } @@ -66,7 +68,7 @@ public final boolean fastEnter() { } protected final void fastPathEmitMax(U value, boolean delayError, Disposable dispose) { - final Subscriber<? super V> s = actual; + final Subscriber<? super V> s = downstream; final SimplePlainQueue<U> q = queue; if (fastEnter()) { @@ -95,7 +97,7 @@ protected final void fastPathEmitMax(U value, boolean delayError, Disposable dis } protected final void fastPathOrderedEmitMax(U value, boolean delayError, Disposable dispose) { - final Subscriber<? super V> s = actual; + final Subscriber<? super V> s = downstream; final SimplePlainQueue<U> q = queue; if (fastEnter()) { diff --git a/src/main/java/io/reactivex/internal/subscribers/SinglePostCompleteSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/SinglePostCompleteSubscriber.java index 8d7efc37aa..4ea2ac2368 100644 --- a/src/main/java/io/reactivex/internal/subscribers/SinglePostCompleteSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/SinglePostCompleteSubscriber.java @@ -32,10 +32,10 @@ public abstract class SinglePostCompleteSubscriber<T, R> extends AtomicLong impl private static final long serialVersionUID = 7917814472626990048L; /** The downstream consumer. */ - protected final Subscriber<? super R> actual; + protected final Subscriber<? super R> downstream; /** The upstream subscription. */ - protected Subscription s; + protected Subscription upstream; /** The last value stored in case there is no request for it. */ protected R value; @@ -48,15 +48,15 @@ public abstract class SinglePostCompleteSubscriber<T, R> extends AtomicLong impl /** Masks out the lower 63 bit holding the current request amount. */ static final long REQUEST_MASK = Long.MAX_VALUE; - public SinglePostCompleteSubscriber(Subscriber<? super R> actual) { - this.actual = actual; + public SinglePostCompleteSubscriber(Subscriber<? super R> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -78,8 +78,8 @@ protected final void complete(R n) { } if ((r & REQUEST_MASK) != 0) { lazySet(COMPLETE_MASK + 1); - actual.onNext(n); - actual.onComplete(); + downstream.onNext(n); + downstream.onComplete(); return; } value = n; @@ -105,14 +105,14 @@ public final void request(long n) { long r = get(); if ((r & COMPLETE_MASK) != 0) { if (compareAndSet(COMPLETE_MASK, COMPLETE_MASK + 1)) { - actual.onNext(value); - actual.onComplete(); + downstream.onNext(value); + downstream.onComplete(); } break; } long u = BackpressureHelper.addCap(r, n); if (compareAndSet(r, u)) { - s.request(n); + upstream.request(n); break; } } @@ -121,6 +121,6 @@ public final void request(long n) { @Override public void cancel() { - s.cancel(); + upstream.cancel(); } } diff --git a/src/main/java/io/reactivex/internal/subscribers/StrictSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/StrictSubscriber.java index 6d6c7514c2..0fb9d5666c 100644 --- a/src/main/java/io/reactivex/internal/subscribers/StrictSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/StrictSubscriber.java @@ -41,23 +41,23 @@ public class StrictSubscriber<T> private static final long serialVersionUID = -4945028590049415624L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final AtomicThrowable error; final AtomicLong requested; - final AtomicReference<Subscription> s; + final AtomicReference<Subscription> upstream; final AtomicBoolean once; volatile boolean done; - public StrictSubscriber(Subscriber<? super T> actual) { - this.actual = actual; + public StrictSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; this.error = new AtomicThrowable(); this.requested = new AtomicLong(); - this.s = new AtomicReference<Subscription>(); + this.upstream = new AtomicReference<Subscription>(); this.once = new AtomicBoolean(); } @@ -67,14 +67,14 @@ public void request(long n) { cancel(); onError(new IllegalArgumentException("§3.9 violated: positive request amount required but it was " + n)); } else { - SubscriptionHelper.deferredRequest(s, requested, n); + SubscriptionHelper.deferredRequest(upstream, requested, n); } } @Override public void cancel() { if (!done) { - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); } } @@ -82,9 +82,9 @@ public void cancel() { public void onSubscribe(Subscription s) { if (once.compareAndSet(false, true)) { - actual.onSubscribe(this); + downstream.onSubscribe(this); - SubscriptionHelper.deferredSetOnce(this.s, requested, s); + SubscriptionHelper.deferredSetOnce(this.upstream, requested, s); } else { s.cancel(); cancel(); @@ -94,18 +94,18 @@ public void onSubscribe(Subscription s) { @Override public void onNext(T t) { - HalfSerializer.onNext(actual, t, this, error); + HalfSerializer.onNext(downstream, t, this, error); } @Override public void onError(Throwable t) { done = true; - HalfSerializer.onError(actual, t, this, error); + HalfSerializer.onError(downstream, t, this, error); } @Override public void onComplete() { done = true; - HalfSerializer.onComplete(actual, this, error); + HalfSerializer.onComplete(downstream, this, error); } } diff --git a/src/main/java/io/reactivex/internal/subscribers/SubscriberResourceWrapper.java b/src/main/java/io/reactivex/internal/subscribers/SubscriberResourceWrapper.java index bb8061b610..807430bb7b 100644 --- a/src/main/java/io/reactivex/internal/subscribers/SubscriberResourceWrapper.java +++ b/src/main/java/io/reactivex/internal/subscribers/SubscriberResourceWrapper.java @@ -26,55 +26,55 @@ public final class SubscriberResourceWrapper<T> extends AtomicReference<Disposab private static final long serialVersionUID = -8612022020200669122L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; - final AtomicReference<Subscription> subscription = new AtomicReference<Subscription>(); + final AtomicReference<Subscription> upstream = new AtomicReference<Subscription>(); - public SubscriberResourceWrapper(Subscriber<? super T> actual) { - this.actual = actual; + public SubscriberResourceWrapper(Subscriber<? super T> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(subscription, s)) { - actual.onSubscribe(this); + if (SubscriptionHelper.setOnce(upstream, s)) { + downstream.onSubscribe(this); } } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { DisposableHelper.dispose(this); - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { DisposableHelper.dispose(this); - actual.onComplete(); + downstream.onComplete(); } @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { - subscription.get().request(n); + upstream.get().request(n); } } @Override public void dispose() { - SubscriptionHelper.cancel(subscription); + SubscriptionHelper.cancel(upstream); DisposableHelper.dispose(this); } @Override public boolean isDisposed() { - return subscription.get() == SubscriptionHelper.CANCELLED; + return upstream.get() == SubscriptionHelper.CANCELLED; } @Override diff --git a/src/main/java/io/reactivex/internal/subscriptions/DeferredScalarSubscription.java b/src/main/java/io/reactivex/internal/subscriptions/DeferredScalarSubscription.java index 3e0406f4fe..536ddf4c00 100644 --- a/src/main/java/io/reactivex/internal/subscriptions/DeferredScalarSubscription.java +++ b/src/main/java/io/reactivex/internal/subscriptions/DeferredScalarSubscription.java @@ -38,7 +38,7 @@ public class DeferredScalarSubscription<T> extends BasicIntQueueSubscription<T> private static final long serialVersionUID = -2151279923272604993L; /** The Subscriber to emit the value to. */ - protected final Subscriber<? super T> actual; + protected final Subscriber<? super T> downstream; /** The value is stored here if there is no request yet or in fusion mode. */ protected T value; @@ -64,10 +64,10 @@ public class DeferredScalarSubscription<T> extends BasicIntQueueSubscription<T> /** * Creates a DeferredScalarSubscription by wrapping the given Subscriber. - * @param actual the Subscriber to wrap, not null (not verified) + * @param downstream the Subscriber to wrap, not null (not verified) */ - public DeferredScalarSubscription(Subscriber<? super T> actual) { - this.actual = actual; + public DeferredScalarSubscription(Subscriber<? super T> downstream) { + this.downstream = downstream; } @Override @@ -85,7 +85,7 @@ public final void request(long n) { T v = value; if (v != null) { value = null; - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; a.onNext(v); if (get() != CANCELLED) { a.onComplete(); @@ -114,7 +114,7 @@ public final void complete(T v) { value = v; lazySet(FUSED_READY); - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; a.onNext(v); if (get() != CANCELLED) { a.onComplete(); @@ -129,7 +129,7 @@ public final void complete(T v) { if (state == HAS_REQUEST_NO_VALUE) { lazySet(HAS_REQUEST_HAS_VALUE); - Subscriber<? super T> a = actual; + Subscriber<? super T> a = downstream; a.onNext(v); if (get() != CANCELLED) { a.onComplete(); diff --git a/src/main/java/io/reactivex/internal/util/NotificationLite.java b/src/main/java/io/reactivex/internal/util/NotificationLite.java index 68aeb8492e..2359141e5e 100644 --- a/src/main/java/io/reactivex/internal/util/NotificationLite.java +++ b/src/main/java/io/reactivex/internal/util/NotificationLite.java @@ -64,14 +64,14 @@ public boolean equals(Object obj) { static final class SubscriptionNotification implements Serializable { private static final long serialVersionUID = -1322257508628817540L; - final Subscription s; + final Subscription upstream; SubscriptionNotification(Subscription s) { - this.s = s; + this.upstream = s; } @Override public String toString() { - return "NotificationLite.Subscription[" + s + "]"; + return "NotificationLite.Subscription[" + upstream + "]"; } } @@ -81,15 +81,15 @@ public String toString() { static final class DisposableNotification implements Serializable { private static final long serialVersionUID = -7482590109178395495L; - final Disposable d; + final Disposable upstream; DisposableNotification(Disposable d) { - this.d = d; + this.upstream = d; } @Override public String toString() { - return "NotificationLite.Disposable[" + d + "]"; + return "NotificationLite.Disposable[" + upstream + "]"; } } @@ -195,11 +195,11 @@ public static Throwable getError(Object o) { * @return the extracted Subscription */ public static Subscription getSubscription(Object o) { - return ((SubscriptionNotification)o).s; + return ((SubscriptionNotification)o).upstream; } public static Disposable getDisposable(Object o) { - return ((DisposableNotification)o).d; + return ((DisposableNotification)o).upstream; } /** @@ -266,7 +266,7 @@ public static <T> boolean acceptFull(Object o, Subscriber<? super T> s) { return true; } else if (o instanceof SubscriptionNotification) { - s.onSubscribe(((SubscriptionNotification)o).s); + s.onSubscribe(((SubscriptionNotification)o).upstream); return false; } s.onNext((T)o); @@ -292,7 +292,7 @@ public static <T> boolean acceptFull(Object o, Observer<? super T> observer) { return true; } else if (o instanceof DisposableNotification) { - observer.onSubscribe(((DisposableNotification)o).d); + observer.onSubscribe(((DisposableNotification)o).upstream); return false; } observer.onNext((T)o); diff --git a/src/main/java/io/reactivex/observers/DefaultObserver.java b/src/main/java/io/reactivex/observers/DefaultObserver.java index b09f8b7e89..144cea72ae 100644 --- a/src/main/java/io/reactivex/observers/DefaultObserver.java +++ b/src/main/java/io/reactivex/observers/DefaultObserver.java @@ -62,11 +62,13 @@ * @param <T> the value type */ public abstract class DefaultObserver<T> implements Observer<T> { - private Disposable s; + + private Disposable upstream; + @Override - public final void onSubscribe(@NonNull Disposable s) { - if (EndConsumerHelper.validate(this.s, s, getClass())) { - this.s = s; + public final void onSubscribe(@NonNull Disposable d) { + if (EndConsumerHelper.validate(this.upstream, d, getClass())) { + this.upstream = d; onStart(); } } @@ -75,9 +77,9 @@ public final void onSubscribe(@NonNull Disposable s) { * Cancels the upstream's disposable. */ protected final void cancel() { - Disposable s = this.s; - this.s = DisposableHelper.DISPOSED; - s.dispose(); + Disposable upstream = this.upstream; + this.upstream = DisposableHelper.DISPOSED; + upstream.dispose(); } /** * Called once the subscription has been set on this observer; override this diff --git a/src/main/java/io/reactivex/observers/DisposableCompletableObserver.java b/src/main/java/io/reactivex/observers/DisposableCompletableObserver.java index e07cb508c7..5ec519492c 100644 --- a/src/main/java/io/reactivex/observers/DisposableCompletableObserver.java +++ b/src/main/java/io/reactivex/observers/DisposableCompletableObserver.java @@ -52,11 +52,12 @@ * </code></pre> */ public abstract class DisposableCompletableObserver implements CompletableObserver, Disposable { - final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + + final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); @Override - public final void onSubscribe(@NonNull Disposable s) { - if (EndConsumerHelper.setOnce(this.s, s, getClass())) { + public final void onSubscribe(@NonNull Disposable d) { + if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) { onStart(); } } @@ -69,11 +70,11 @@ protected void onStart() { @Override public final boolean isDisposed() { - return s.get() == DisposableHelper.DISPOSED; + return upstream.get() == DisposableHelper.DISPOSED; } @Override public final void dispose() { - DisposableHelper.dispose(s); + DisposableHelper.dispose(upstream); } } diff --git a/src/main/java/io/reactivex/observers/DisposableMaybeObserver.java b/src/main/java/io/reactivex/observers/DisposableMaybeObserver.java index ebf8a579f2..6cff241c22 100644 --- a/src/main/java/io/reactivex/observers/DisposableMaybeObserver.java +++ b/src/main/java/io/reactivex/observers/DisposableMaybeObserver.java @@ -62,11 +62,11 @@ */ public abstract class DisposableMaybeObserver<T> implements MaybeObserver<T>, Disposable { - final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); @Override - public final void onSubscribe(@NonNull Disposable s) { - if (EndConsumerHelper.setOnce(this.s, s, getClass())) { + public final void onSubscribe(@NonNull Disposable d) { + if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) { onStart(); } } @@ -79,11 +79,11 @@ protected void onStart() { @Override public final boolean isDisposed() { - return s.get() == DisposableHelper.DISPOSED; + return upstream.get() == DisposableHelper.DISPOSED; } @Override public final void dispose() { - DisposableHelper.dispose(s); + DisposableHelper.dispose(upstream); } } diff --git a/src/main/java/io/reactivex/observers/DisposableObserver.java b/src/main/java/io/reactivex/observers/DisposableObserver.java index c835b853a2..dccd973549 100644 --- a/src/main/java/io/reactivex/observers/DisposableObserver.java +++ b/src/main/java/io/reactivex/observers/DisposableObserver.java @@ -66,11 +66,11 @@ */ public abstract class DisposableObserver<T> implements Observer<T>, Disposable { - final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); @Override - public final void onSubscribe(@NonNull Disposable s) { - if (EndConsumerHelper.setOnce(this.s, s, getClass())) { + public final void onSubscribe(@NonNull Disposable d) { + if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) { onStart(); } } @@ -83,11 +83,11 @@ protected void onStart() { @Override public final boolean isDisposed() { - return s.get() == DisposableHelper.DISPOSED; + return upstream.get() == DisposableHelper.DISPOSED; } @Override public final void dispose() { - DisposableHelper.dispose(s); + DisposableHelper.dispose(upstream); } } diff --git a/src/main/java/io/reactivex/observers/DisposableSingleObserver.java b/src/main/java/io/reactivex/observers/DisposableSingleObserver.java index 2d339e3400..38224e0668 100644 --- a/src/main/java/io/reactivex/observers/DisposableSingleObserver.java +++ b/src/main/java/io/reactivex/observers/DisposableSingleObserver.java @@ -55,11 +55,11 @@ */ public abstract class DisposableSingleObserver<T> implements SingleObserver<T>, Disposable { - final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); @Override - public final void onSubscribe(@NonNull Disposable s) { - if (EndConsumerHelper.setOnce(this.s, s, getClass())) { + public final void onSubscribe(@NonNull Disposable d) { + if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) { onStart(); } } @@ -72,11 +72,11 @@ protected void onStart() { @Override public final boolean isDisposed() { - return s.get() == DisposableHelper.DISPOSED; + return upstream.get() == DisposableHelper.DISPOSED; } @Override public final void dispose() { - DisposableHelper.dispose(s); + DisposableHelper.dispose(upstream); } } diff --git a/src/main/java/io/reactivex/observers/ResourceCompletableObserver.java b/src/main/java/io/reactivex/observers/ResourceCompletableObserver.java index f4b4261807..ead4570ff9 100644 --- a/src/main/java/io/reactivex/observers/ResourceCompletableObserver.java +++ b/src/main/java/io/reactivex/observers/ResourceCompletableObserver.java @@ -74,7 +74,7 @@ */ public abstract class ResourceCompletableObserver implements CompletableObserver, Disposable { /** The active subscription. */ - private final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + private final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); /** The resource composite, can never be null. */ private final ListCompositeDisposable resources = new ListCompositeDisposable(); @@ -92,8 +92,8 @@ public final void add(@NonNull Disposable resource) { } @Override - public final void onSubscribe(@NonNull Disposable s) { - if (EndConsumerHelper.setOnce(this.s, s, getClass())) { + public final void onSubscribe(@NonNull Disposable d) { + if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) { onStart(); } } @@ -116,7 +116,7 @@ protected void onStart() { */ @Override public final void dispose() { - if (DisposableHelper.dispose(s)) { + if (DisposableHelper.dispose(upstream)) { resources.dispose(); } } @@ -127,6 +127,6 @@ public final void dispose() { */ @Override public final boolean isDisposed() { - return DisposableHelper.isDisposed(s.get()); + return DisposableHelper.isDisposed(upstream.get()); } } diff --git a/src/main/java/io/reactivex/observers/ResourceMaybeObserver.java b/src/main/java/io/reactivex/observers/ResourceMaybeObserver.java index a48fb06872..ca603cf3b0 100644 --- a/src/main/java/io/reactivex/observers/ResourceMaybeObserver.java +++ b/src/main/java/io/reactivex/observers/ResourceMaybeObserver.java @@ -84,7 +84,7 @@ */ public abstract class ResourceMaybeObserver<T> implements MaybeObserver<T>, Disposable { /** The active subscription. */ - private final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + private final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); /** The resource composite, can never be null. */ private final ListCompositeDisposable resources = new ListCompositeDisposable(); @@ -102,8 +102,8 @@ public final void add(@NonNull Disposable resource) { } @Override - public final void onSubscribe(@NonNull Disposable s) { - if (EndConsumerHelper.setOnce(this.s, s, getClass())) { + public final void onSubscribe(@NonNull Disposable d) { + if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) { onStart(); } } @@ -126,7 +126,7 @@ protected void onStart() { */ @Override public final void dispose() { - if (DisposableHelper.dispose(s)) { + if (DisposableHelper.dispose(upstream)) { resources.dispose(); } } @@ -137,6 +137,6 @@ public final void dispose() { */ @Override public final boolean isDisposed() { - return DisposableHelper.isDisposed(s.get()); + return DisposableHelper.isDisposed(upstream.get()); } } diff --git a/src/main/java/io/reactivex/observers/ResourceObserver.java b/src/main/java/io/reactivex/observers/ResourceObserver.java index f42353db13..f30d4475df 100644 --- a/src/main/java/io/reactivex/observers/ResourceObserver.java +++ b/src/main/java/io/reactivex/observers/ResourceObserver.java @@ -82,7 +82,7 @@ */ public abstract class ResourceObserver<T> implements Observer<T>, Disposable { /** The active subscription. */ - private final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + private final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); /** The resource composite, can never be null. */ private final ListCompositeDisposable resources = new ListCompositeDisposable(); @@ -100,8 +100,8 @@ public final void add(@NonNull Disposable resource) { } @Override - public final void onSubscribe(Disposable s) { - if (EndConsumerHelper.setOnce(this.s, s, getClass())) { + public final void onSubscribe(Disposable d) { + if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) { onStart(); } } @@ -124,7 +124,7 @@ protected void onStart() { */ @Override public final void dispose() { - if (DisposableHelper.dispose(s)) { + if (DisposableHelper.dispose(upstream)) { resources.dispose(); } } @@ -135,6 +135,6 @@ public final void dispose() { */ @Override public final boolean isDisposed() { - return DisposableHelper.isDisposed(s.get()); + return DisposableHelper.isDisposed(upstream.get()); } } diff --git a/src/main/java/io/reactivex/observers/ResourceSingleObserver.java b/src/main/java/io/reactivex/observers/ResourceSingleObserver.java index 9f28fd0791..2f533b8d99 100644 --- a/src/main/java/io/reactivex/observers/ResourceSingleObserver.java +++ b/src/main/java/io/reactivex/observers/ResourceSingleObserver.java @@ -77,7 +77,7 @@ */ public abstract class ResourceSingleObserver<T> implements SingleObserver<T>, Disposable { /** The active subscription. */ - private final AtomicReference<Disposable> s = new AtomicReference<Disposable>(); + private final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); /** The resource composite, can never be null. */ private final ListCompositeDisposable resources = new ListCompositeDisposable(); @@ -95,8 +95,8 @@ public final void add(@NonNull Disposable resource) { } @Override - public final void onSubscribe(@NonNull Disposable s) { - if (EndConsumerHelper.setOnce(this.s, s, getClass())) { + public final void onSubscribe(@NonNull Disposable d) { + if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) { onStart(); } } @@ -119,7 +119,7 @@ protected void onStart() { */ @Override public final void dispose() { - if (DisposableHelper.dispose(s)) { + if (DisposableHelper.dispose(upstream)) { resources.dispose(); } } @@ -130,6 +130,6 @@ public final void dispose() { */ @Override public final boolean isDisposed() { - return DisposableHelper.isDisposed(s.get()); + return DisposableHelper.isDisposed(upstream.get()); } } diff --git a/src/main/java/io/reactivex/observers/SafeObserver.java b/src/main/java/io/reactivex/observers/SafeObserver.java index a370f3799b..8dddcf1d9e 100644 --- a/src/main/java/io/reactivex/observers/SafeObserver.java +++ b/src/main/java/io/reactivex/observers/SafeObserver.java @@ -27,32 +27,32 @@ */ public final class SafeObserver<T> implements Observer<T>, Disposable { /** The actual Subscriber. */ - final Observer<? super T> actual; + final Observer<? super T> downstream; /** The subscription. */ - Disposable s; + Disposable upstream; /** Indicates a terminal state. */ boolean done; /** * Constructs a SafeObserver by wrapping the given actual Observer. - * @param actual the actual Observer to wrap, not null (not validated) + * @param downstream the actual Observer to wrap, not null (not validated) */ - public SafeObserver(@NonNull Observer<? super T> actual) { - this.actual = actual; + public SafeObserver(@NonNull Observer<? super T> downstream) { + this.downstream = downstream; } @Override - public void onSubscribe(@NonNull Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(@NonNull Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; try { - actual.onSubscribe(this); + downstream.onSubscribe(this); } catch (Throwable e) { Exceptions.throwIfFatal(e); done = true; // can't call onError because the actual's state may be corrupt at this point try { - s.dispose(); + d.dispose(); } catch (Throwable e1) { Exceptions.throwIfFatal(e1); RxJavaPlugins.onError(new CompositeException(e, e1)); @@ -66,12 +66,12 @@ public void onSubscribe(@NonNull Disposable s) { @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @Override @@ -79,7 +79,7 @@ public void onNext(@NonNull T t) { if (done) { return; } - if (s == null) { + if (upstream == null) { onNextNoSubscription(); return; } @@ -87,7 +87,7 @@ public void onNext(@NonNull T t) { if (t == null) { Throwable ex = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); try { - s.dispose(); + upstream.dispose(); } catch (Throwable e1) { Exceptions.throwIfFatal(e1); onError(new CompositeException(ex, e1)); @@ -98,11 +98,11 @@ public void onNext(@NonNull T t) { } try { - actual.onNext(t); + downstream.onNext(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); try { - s.dispose(); + upstream.dispose(); } catch (Throwable e1) { Exceptions.throwIfFatal(e1); onError(new CompositeException(e, e1)); @@ -118,7 +118,7 @@ void onNextNoSubscription() { Throwable ex = new NullPointerException("Subscription not set!"); try { - actual.onSubscribe(EmptyDisposable.INSTANCE); + downstream.onSubscribe(EmptyDisposable.INSTANCE); } catch (Throwable e) { Exceptions.throwIfFatal(e); // can't call onError because the actual's state may be corrupt at this point @@ -126,7 +126,7 @@ void onNextNoSubscription() { return; } try { - actual.onError(ex); + downstream.onError(ex); } catch (Throwable e) { Exceptions.throwIfFatal(e); // if onError failed, all that's left is to report the error to plugins @@ -142,11 +142,11 @@ public void onError(@NonNull Throwable t) { } done = true; - if (s == null) { + if (upstream == null) { Throwable npe = new NullPointerException("Subscription not set!"); try { - actual.onSubscribe(EmptyDisposable.INSTANCE); + downstream.onSubscribe(EmptyDisposable.INSTANCE); } catch (Throwable e) { Exceptions.throwIfFatal(e); // can't call onError because the actual's state may be corrupt at this point @@ -154,7 +154,7 @@ public void onError(@NonNull Throwable t) { return; } try { - actual.onError(new CompositeException(t, npe)); + downstream.onError(new CompositeException(t, npe)); } catch (Throwable e) { Exceptions.throwIfFatal(e); // if onError failed, all that's left is to report the error to plugins @@ -168,7 +168,7 @@ public void onError(@NonNull Throwable t) { } try { - actual.onError(t); + downstream.onError(t); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); @@ -184,13 +184,13 @@ public void onComplete() { done = true; - if (s == null) { + if (upstream == null) { onCompleteNoSubscription(); return; } try { - actual.onComplete(); + downstream.onComplete(); } catch (Throwable e) { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(e); @@ -202,7 +202,7 @@ void onCompleteNoSubscription() { Throwable ex = new NullPointerException("Subscription not set!"); try { - actual.onSubscribe(EmptyDisposable.INSTANCE); + downstream.onSubscribe(EmptyDisposable.INSTANCE); } catch (Throwable e) { Exceptions.throwIfFatal(e); // can't call onError because the actual's state may be corrupt at this point @@ -210,7 +210,7 @@ void onCompleteNoSubscription() { return; } try { - actual.onError(ex); + downstream.onError(ex); } catch (Throwable e) { Exceptions.throwIfFatal(e); // if onError failed, all that's left is to report the error to plugins diff --git a/src/main/java/io/reactivex/observers/SerializedObserver.java b/src/main/java/io/reactivex/observers/SerializedObserver.java index ec2061ba97..d0cdd4eeab 100644 --- a/src/main/java/io/reactivex/observers/SerializedObserver.java +++ b/src/main/java/io/reactivex/observers/SerializedObserver.java @@ -31,12 +31,12 @@ * @param <T> the value type */ public final class SerializedObserver<T> implements Observer<T>, Disposable { - final Observer<? super T> actual; + final Observer<? super T> downstream; final boolean delayError; static final int QUEUE_LINK_SIZE = 4; - Disposable s; + Disposable upstream; boolean emitting; AppendOnlyLinkedArrayList<Object> queue; @@ -45,10 +45,10 @@ public final class SerializedObserver<T> implements Observer<T>, Disposable { /** * Construct a SerializedObserver by wrapping the given actual Observer. - * @param actual the actual Observer, not null (not verified) + * @param downstream the actual Observer, not null (not verified) */ - public SerializedObserver(@NonNull Observer<? super T> actual) { - this(actual, false); + public SerializedObserver(@NonNull Observer<? super T> downstream) { + this(downstream, false); } /** @@ -59,28 +59,28 @@ public SerializedObserver(@NonNull Observer<? super T> actual) { * @param delayError if true, errors are emitted after regular values have been emitted */ public SerializedObserver(@NonNull Observer<? super T> actual, boolean delayError) { - this.actual = actual; + this.downstream = actual; this.delayError = delayError; } @Override - public void onSubscribe(@NonNull Disposable s) { - if (DisposableHelper.validate(this.s, s)) { - this.s = s; + public void onSubscribe(@NonNull Disposable d) { + if (DisposableHelper.validate(this.upstream, d)) { + this.upstream = d; - actual.onSubscribe(this); + downstream.onSubscribe(this); } } @Override public void dispose() { - s.dispose(); + upstream.dispose(); } @Override public boolean isDisposed() { - return s.isDisposed(); + return upstream.isDisposed(); } @@ -90,7 +90,7 @@ public void onNext(@NonNull T t) { return; } if (t == null) { - s.dispose(); + upstream.dispose(); onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); return; } @@ -110,7 +110,7 @@ public void onNext(@NonNull T t) { emitting = true; } - actual.onNext(t); + downstream.onNext(t); emitLoop(); } @@ -152,7 +152,7 @@ public void onError(@NonNull Throwable t) { return; } - actual.onError(t); + downstream.onError(t); // no need to loop because this onError is the last event } @@ -178,7 +178,7 @@ public void onComplete() { emitting = true; } - actual.onComplete(); + downstream.onComplete(); // no need to loop because this onComplete is the last event } @@ -194,7 +194,7 @@ void emitLoop() { queue = null; } - if (q.accept(actual)) { + if (q.accept(downstream)) { return; } } diff --git a/src/main/java/io/reactivex/observers/TestObserver.java b/src/main/java/io/reactivex/observers/TestObserver.java index 18d9b41faf..3909059b27 100644 --- a/src/main/java/io/reactivex/observers/TestObserver.java +++ b/src/main/java/io/reactivex/observers/TestObserver.java @@ -35,12 +35,12 @@ public class TestObserver<T> extends BaseTestConsumer<T, TestObserver<T>> implements Observer<T>, Disposable, MaybeObserver<T>, SingleObserver<T>, CompletableObserver { /** The actual observer to forward events to. */ - private final Observer<? super T> actual; + private final Observer<? super T> downstream; /** Holds the current subscription if any. */ - private final AtomicReference<Disposable> subscription = new AtomicReference<Disposable>(); + private final AtomicReference<Disposable> upstream = new AtomicReference<Disposable>(); - private QueueDisposable<T> qs; + private QueueDisposable<T> qd; /** * Constructs a non-forwarding TestObserver. @@ -70,34 +70,34 @@ public TestObserver() { /** * Constructs a forwarding TestObserver. - * @param actual the actual Observer to forward events to + * @param downstream the actual Observer to forward events to */ - public TestObserver(Observer<? super T> actual) { - this.actual = actual; + public TestObserver(Observer<? super T> downstream) { + this.downstream = downstream; } @SuppressWarnings("unchecked") @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { lastThread = Thread.currentThread(); - if (s == null) { + if (d == null) { errors.add(new NullPointerException("onSubscribe received a null Subscription")); return; } - if (!subscription.compareAndSet(null, s)) { - s.dispose(); - if (subscription.get() != DisposableHelper.DISPOSED) { - errors.add(new IllegalStateException("onSubscribe received multiple subscriptions: " + s)); + if (!upstream.compareAndSet(null, d)) { + d.dispose(); + if (upstream.get() != DisposableHelper.DISPOSED) { + errors.add(new IllegalStateException("onSubscribe received multiple subscriptions: " + d)); } return; } if (initialFusionMode != 0) { - if (s instanceof QueueDisposable) { - qs = (QueueDisposable<T>)s; + if (d instanceof QueueDisposable) { + qd = (QueueDisposable<T>)d; - int m = qs.requestFusion(initialFusionMode); + int m = qd.requestFusion(initialFusionMode); establishedFusionMode = m; if (m == QueueDisposable.SYNC) { @@ -105,12 +105,12 @@ public void onSubscribe(Disposable s) { lastThread = Thread.currentThread(); try { T t; - while ((t = qs.poll()) != null) { + while ((t = qd.poll()) != null) { values.add(t); } completions++; - subscription.lazySet(DisposableHelper.DISPOSED); + upstream.lazySet(DisposableHelper.DISPOSED); } catch (Throwable ex) { // Exceptions.throwIfFatal(e); TODO add fatal exceptions? errors.add(ex); @@ -120,14 +120,14 @@ public void onSubscribe(Disposable s) { } } - actual.onSubscribe(s); + downstream.onSubscribe(d); } @Override public void onNext(T t) { if (!checkSubscriptionOnce) { checkSubscriptionOnce = true; - if (subscription.get() == null) { + if (upstream.get() == null) { errors.add(new IllegalStateException("onSubscribe not called in proper order")); } } @@ -136,13 +136,13 @@ public void onNext(T t) { if (establishedFusionMode == QueueDisposable.ASYNC) { try { - while ((t = qs.poll()) != null) { + while ((t = qd.poll()) != null) { values.add(t); } } catch (Throwable ex) { // Exceptions.throwIfFatal(e); TODO add fatal exceptions? errors.add(ex); - qs.dispose(); + qd.dispose(); } return; } @@ -153,14 +153,14 @@ public void onNext(T t) { errors.add(new NullPointerException("onNext received a null value")); } - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { if (!checkSubscriptionOnce) { checkSubscriptionOnce = true; - if (subscription.get() == null) { + if (upstream.get() == null) { errors.add(new IllegalStateException("onSubscribe not called in proper order")); } } @@ -173,7 +173,7 @@ public void onError(Throwable t) { errors.add(t); } - actual.onError(t); + downstream.onError(t); } finally { done.countDown(); } @@ -183,7 +183,7 @@ public void onError(Throwable t) { public void onComplete() { if (!checkSubscriptionOnce) { checkSubscriptionOnce = true; - if (subscription.get() == null) { + if (upstream.get() == null) { errors.add(new IllegalStateException("onSubscribe not called in proper order")); } } @@ -192,7 +192,7 @@ public void onComplete() { lastThread = Thread.currentThread(); completions++; - actual.onComplete(); + downstream.onComplete(); } finally { done.countDown(); } @@ -217,12 +217,12 @@ public final void cancel() { @Override public final void dispose() { - DisposableHelper.dispose(subscription); + DisposableHelper.dispose(upstream); } @Override public final boolean isDisposed() { - return DisposableHelper.isDisposed(subscription.get()); + return DisposableHelper.isDisposed(upstream.get()); } // state retrieval methods @@ -231,7 +231,7 @@ public final boolean isDisposed() { * @return true if this TestObserver received a subscription */ public final boolean hasSubscription() { - return subscription.get() != null; + return upstream.get() != null; } /** @@ -240,7 +240,7 @@ public final boolean hasSubscription() { */ @Override public final TestObserver<T> assertSubscribed() { - if (subscription.get() == null) { + if (upstream.get() == null) { throw fail("Not subscribed!"); } return this; @@ -252,7 +252,7 @@ public final TestObserver<T> assertSubscribed() { */ @Override public final TestObserver<T> assertNotSubscribed() { - if (subscription.get() != null) { + if (upstream.get() != null) { throw fail("Subscribed!"); } else if (!errors.isEmpty()) { @@ -297,7 +297,7 @@ final TestObserver<T> setInitialFusionMode(int mode) { final TestObserver<T> assertFusionMode(int mode) { int m = establishedFusionMode; if (m != mode) { - if (qs != null) { + if (qd != null) { throw new AssertionError("Fusion mode different. Expected: " + fusionModeToString(mode) + ", actual: " + fusionModeToString(m)); } else { @@ -323,7 +323,7 @@ static String fusionModeToString(int mode) { * @return this */ final TestObserver<T> assertFuseable() { - if (qs == null) { + if (qd == null) { throw new AssertionError("Upstream is not fuseable."); } return this; @@ -336,7 +336,7 @@ final TestObserver<T> assertFuseable() { * @return this */ final TestObserver<T> assertNotFuseable() { - if (qs != null) { + if (qd != null) { throw new AssertionError("Upstream is fuseable."); } return this; diff --git a/src/main/java/io/reactivex/processors/AsyncProcessor.java b/src/main/java/io/reactivex/processors/AsyncProcessor.java index 6ef3044d6d..e360d17eb3 100644 --- a/src/main/java/io/reactivex/processors/AsyncProcessor.java +++ b/src/main/java/io/reactivex/processors/AsyncProcessor.java @@ -390,7 +390,7 @@ public void cancel() { void onComplete() { if (!isCancelled()) { - actual.onComplete(); + downstream.onComplete(); } } @@ -398,7 +398,7 @@ void onError(Throwable t) { if (isCancelled()) { RxJavaPlugins.onError(t); } else { - actual.onError(t); + downstream.onError(t); } } } diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index 0c4af463e0..ff69ef4273 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -525,7 +525,7 @@ static final class BehaviorSubscription<T> extends AtomicLong implements Subscri private static final long serialVersionUID = 3293175281126227086L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final BehaviorProcessor<T> state; boolean next; @@ -539,7 +539,7 @@ static final class BehaviorSubscription<T> extends AtomicLong implements Subscri long index; BehaviorSubscription(Subscriber<? super T> actual, BehaviorProcessor<T> state) { - this.actual = actual; + this.downstream = actual; this.state = state; } @@ -629,24 +629,24 @@ public boolean test(Object o) { } if (NotificationLite.isComplete(o)) { - actual.onComplete(); + downstream.onComplete(); return true; } else if (NotificationLite.isError(o)) { - actual.onError(NotificationLite.getError(o)); + downstream.onError(NotificationLite.getError(o)); return true; } long r = get(); if (r != 0L) { - actual.onNext(NotificationLite.<T>getValue(o)); + downstream.onNext(NotificationLite.<T>getValue(o)); if (r != Long.MAX_VALUE) { decrementAndGet(); } return false; } cancel(); - actual.onError(new MissingBackpressureException("Could not deliver value due to lack of requests")); + downstream.onError(new MissingBackpressureException("Could not deliver value due to lack of requests")); return true; } diff --git a/src/main/java/io/reactivex/processors/MulticastProcessor.java b/src/main/java/io/reactivex/processors/MulticastProcessor.java index 3d0923a8ab..317244313f 100644 --- a/src/main/java/io/reactivex/processors/MulticastProcessor.java +++ b/src/main/java/io/reactivex/processors/MulticastProcessor.java @@ -580,14 +580,14 @@ static final class MulticastSubscription<T> extends AtomicLong implements Subscr private static final long serialVersionUID = -363282618957264509L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final MulticastProcessor<T> parent; long emitted; MulticastSubscription(Subscriber<? super T> actual, MulticastProcessor<T> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } @@ -621,19 +621,19 @@ public void cancel() { void onNext(T t) { if (get() != Long.MIN_VALUE) { emitted++; - actual.onNext(t); + downstream.onNext(t); } } void onError(Throwable t) { if (get() != Long.MIN_VALUE) { - actual.onError(t); + downstream.onError(t); } } void onComplete() { if (get() != Long.MIN_VALUE) { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index 38f0aa874c..713fc4190f 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -338,7 +338,7 @@ static final class PublishSubscription<T> extends AtomicLong implements Subscrip private static final long serialVersionUID = 3562861878281475070L; /** The actual subscriber. */ - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; /** The parent processor servicing this subscriber. */ final PublishProcessor<T> parent; @@ -348,7 +348,7 @@ static final class PublishSubscription<T> extends AtomicLong implements Subscrip * @param parent the parent PublishProcessor */ PublishSubscription(Subscriber<? super T> actual, PublishProcessor<T> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } @@ -358,17 +358,17 @@ public void onNext(T t) { return; } if (r != 0L) { - actual.onNext(t); + downstream.onNext(t); BackpressureHelper.producedCancel(this, 1); } else { cancel(); - actual.onError(new MissingBackpressureException("Could not emit value due to lack of requests")); + downstream.onError(new MissingBackpressureException("Could not emit value due to lack of requests")); } } public void onError(Throwable t) { if (get() != Long.MIN_VALUE) { - actual.onError(t); + downstream.onError(t); } else { RxJavaPlugins.onError(t); } @@ -376,7 +376,7 @@ public void onError(Throwable t) { public void onComplete() { if (get() != Long.MIN_VALUE) { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index 95bcf5d263..868d465748 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -589,7 +589,7 @@ interface ReplayBuffer<T> { static final class ReplaySubscription<T> extends AtomicInteger implements Subscription { private static final long serialVersionUID = 466549804534799122L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final ReplayProcessor<T> state; Object index; @@ -601,7 +601,7 @@ static final class ReplaySubscription<T> extends AtomicInteger implements Subscr long emitted; ReplaySubscription(Subscriber<? super T> actual, ReplayProcessor<T> state) { - this.actual = actual; + this.downstream = actual; this.state = state; this.requested = new AtomicLong(); } @@ -701,7 +701,7 @@ public void replay(ReplaySubscription<T> rs) { int missed = 1; final List<T> b = buffer; - final Subscriber<? super T> a = rs.actual; + final Subscriber<? super T> a = rs.downstream; Integer indexObject = (Integer)rs.index; int index; @@ -940,7 +940,7 @@ public void replay(ReplaySubscription<T> rs) { } int missed = 1; - final Subscriber<? super T> a = rs.actual; + final Subscriber<? super T> a = rs.downstream; Node<T> index = (Node<T>)rs.index; if (index == null) { @@ -1227,7 +1227,7 @@ public void replay(ReplaySubscription<T> rs) { } int missed = 1; - final Subscriber<? super T> a = rs.actual; + final Subscriber<? super T> a = rs.downstream; TimedNode<T> index = (TimedNode<T>)rs.index; if (index == null) { diff --git a/src/main/java/io/reactivex/processors/UnicastProcessor.java b/src/main/java/io/reactivex/processors/UnicastProcessor.java index c9fb44f7eb..c754629374 100644 --- a/src/main/java/io/reactivex/processors/UnicastProcessor.java +++ b/src/main/java/io/reactivex/processors/UnicastProcessor.java @@ -160,7 +160,7 @@ public final class UnicastProcessor<T> extends FlowableProcessor<T> { Throwable error; - final AtomicReference<Subscriber<? super T>> actual; + final AtomicReference<Subscriber<? super T>> downstream; volatile boolean cancelled; @@ -282,7 +282,7 @@ public static <T> UnicastProcessor<T> create(int capacityHint, Runnable onCancel this.queue = new SpscLinkedArrayQueue<T>(ObjectHelper.verifyPositive(capacityHint, "capacityHint")); this.onTerminate = new AtomicReference<Runnable>(onTerminate); this.delayError = delayError; - this.actual = new AtomicReference<Subscriber<? super T>>(); + this.downstream = new AtomicReference<Subscriber<? super T>>(); this.once = new AtomicBoolean(); this.wip = new UnicastQueueSubscription(); this.requested = new AtomicLong(); @@ -348,7 +348,7 @@ void drainFused(Subscriber<? super T> a) { if (cancelled) { q.clear(); - actual.lazySet(null); + downstream.lazySet(null); return; } @@ -356,14 +356,14 @@ void drainFused(Subscriber<? super T> a) { if (failFast && d && error != null) { q.clear(); - actual.lazySet(null); + downstream.lazySet(null); a.onError(error); return; } a.onNext(null); if (d) { - actual.lazySet(null); + downstream.lazySet(null); Throwable ex = error; if (ex != null) { @@ -388,7 +388,7 @@ void drain() { int missed = 1; - Subscriber<? super T> a = actual.get(); + Subscriber<? super T> a = downstream.get(); for (;;) { if (a != null) { @@ -404,27 +404,27 @@ void drain() { if (missed == 0) { break; } - a = actual.get(); + a = downstream.get(); } } boolean checkTerminated(boolean failFast, boolean d, boolean empty, Subscriber<? super T> a, SpscLinkedArrayQueue<T> q) { if (cancelled) { q.clear(); - actual.lazySet(null); + downstream.lazySet(null); return true; } if (d) { if (failFast && error != null) { q.clear(); - actual.lazySet(null); + downstream.lazySet(null); a.onError(error); return true; } if (empty) { Throwable e = error; - actual.lazySet(null); + downstream.lazySet(null); if (e != null) { a.onError(e); } else { @@ -493,9 +493,9 @@ protected void subscribeActual(Subscriber<? super T> s) { if (!once.get() && once.compareAndSet(false, true)) { s.onSubscribe(wip); - actual.set(s); + downstream.set(s); if (cancelled) { - actual.lazySet(null); + downstream.lazySet(null); } else { drain(); } @@ -554,7 +554,7 @@ public void cancel() { if (!enableOperatorFusion) { if (wip.getAndIncrement() == 0) { queue.clear(); - actual.lazySet(null); + downstream.lazySet(null); } } } @@ -562,7 +562,7 @@ public void cancel() { @Override public boolean hasSubscribers() { - return actual.get() != null; + return downstream.get() != null; } @Override diff --git a/src/main/java/io/reactivex/subjects/AsyncSubject.java b/src/main/java/io/reactivex/subjects/AsyncSubject.java index 335b183e1a..ce9b2dcedb 100644 --- a/src/main/java/io/reactivex/subjects/AsyncSubject.java +++ b/src/main/java/io/reactivex/subjects/AsyncSubject.java @@ -145,9 +145,9 @@ public static <T> AsyncSubject<T> create() { } @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { if (subscribers.get() == TERMINATED) { - s.dispose(); + d.dispose(); } } @@ -380,7 +380,7 @@ public void dispose() { void onComplete() { if (!isDisposed()) { - actual.onComplete(); + downstream.onComplete(); } } @@ -388,7 +388,7 @@ void onError(Throwable t) { if (isDisposed()) { RxJavaPlugins.onError(t); } else { - actual.onError(t); + downstream.onError(t); } } } diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java index d147f24b85..7f13dfb432 100644 --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java @@ -249,9 +249,9 @@ protected void subscribeActual(Observer<? super T> observer) { } @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { if (terminalEvent.get() != null) { - s.dispose(); + d.dispose(); } } @@ -470,7 +470,7 @@ void setCurrent(Object o) { static final class BehaviorDisposable<T> implements Disposable, NonThrowingPredicate<Object> { - final Observer<? super T> actual; + final Observer<? super T> downstream; final BehaviorSubject<T> state; boolean next; @@ -484,7 +484,7 @@ static final class BehaviorDisposable<T> implements Disposable, NonThrowingPredi long index; BehaviorDisposable(Observer<? super T> actual, BehaviorSubject<T> state) { - this.actual = actual; + this.downstream = actual; this.state = state; } @@ -567,7 +567,7 @@ void emitNext(Object value, long stateIndex) { @Override public boolean test(Object o) { - return cancelled || NotificationLite.accept(o, actual); + return cancelled || NotificationLite.accept(o, downstream); } void emitLoop() { diff --git a/src/main/java/io/reactivex/subjects/CompletableSubject.java b/src/main/java/io/reactivex/subjects/CompletableSubject.java index 2e1b72ec9c..328e35175f 100644 --- a/src/main/java/io/reactivex/subjects/CompletableSubject.java +++ b/src/main/java/io/reactivex/subjects/CompletableSubject.java @@ -125,7 +125,7 @@ public void onError(Throwable e) { if (once.compareAndSet(false, true)) { this.error = e; for (CompletableDisposable md : observers.getAndSet(TERMINATED)) { - md.actual.onError(e); + md.downstream.onError(e); } } else { RxJavaPlugins.onError(e); @@ -136,7 +136,7 @@ public void onError(Throwable e) { public void onComplete() { if (once.compareAndSet(false, true)) { for (CompletableDisposable md : observers.getAndSet(TERMINATED)) { - md.actual.onComplete(); + md.downstream.onComplete(); } } } @@ -260,10 +260,10 @@ static final class CompletableDisposable extends AtomicReference<CompletableSubject> implements Disposable { private static final long serialVersionUID = -7650903191002190468L; - final CompletableObserver actual; + final CompletableObserver downstream; CompletableDisposable(CompletableObserver actual, CompletableSubject parent) { - this.actual = actual; + this.downstream = actual; lazySet(parent); } diff --git a/src/main/java/io/reactivex/subjects/MaybeSubject.java b/src/main/java/io/reactivex/subjects/MaybeSubject.java index 61b80445af..ef9128c4f6 100644 --- a/src/main/java/io/reactivex/subjects/MaybeSubject.java +++ b/src/main/java/io/reactivex/subjects/MaybeSubject.java @@ -154,7 +154,7 @@ public void onSuccess(T value) { if (once.compareAndSet(false, true)) { this.value = value; for (MaybeDisposable<T> md : observers.getAndSet(TERMINATED)) { - md.actual.onSuccess(value); + md.downstream.onSuccess(value); } } } @@ -166,7 +166,7 @@ public void onError(Throwable e) { if (once.compareAndSet(false, true)) { this.error = e; for (MaybeDisposable<T> md : observers.getAndSet(TERMINATED)) { - md.actual.onError(e); + md.downstream.onError(e); } } else { RxJavaPlugins.onError(e); @@ -178,7 +178,7 @@ public void onError(Throwable e) { public void onComplete() { if (once.compareAndSet(false, true)) { for (MaybeDisposable<T> md : observers.getAndSet(TERMINATED)) { - md.actual.onComplete(); + md.downstream.onComplete(); } } } @@ -328,10 +328,10 @@ static final class MaybeDisposable<T> extends AtomicReference<MaybeSubject<T>> implements Disposable { private static final long serialVersionUID = -7650903191002190468L; - final MaybeObserver<? super T> actual; + final MaybeObserver<? super T> downstream; MaybeDisposable(MaybeObserver<? super T> actual, MaybeSubject<T> parent) { - this.actual = actual; + this.downstream = actual; lazySet(parent); } diff --git a/src/main/java/io/reactivex/subjects/PublishSubject.java b/src/main/java/io/reactivex/subjects/PublishSubject.java index b99fe9f6cc..b97af134ca 100644 --- a/src/main/java/io/reactivex/subjects/PublishSubject.java +++ b/src/main/java/io/reactivex/subjects/PublishSubject.java @@ -216,17 +216,17 @@ void remove(PublishDisposable<T> ps) { } @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { if (subscribers.get() == TERMINATED) { - s.dispose(); + d.dispose(); } } @Override public void onNext(T t) { ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); - for (PublishDisposable<T> s : subscribers.get()) { - s.onNext(t); + for (PublishDisposable<T> pd : subscribers.get()) { + pd.onNext(t); } } @@ -240,8 +240,8 @@ public void onError(Throwable t) { } error = t; - for (PublishDisposable<T> s : subscribers.getAndSet(TERMINATED)) { - s.onError(t); + for (PublishDisposable<T> pd : subscribers.getAndSet(TERMINATED)) { + pd.onError(t); } } @@ -251,8 +251,8 @@ public void onComplete() { if (subscribers.get() == TERMINATED) { return; } - for (PublishDisposable<T> s : subscribers.getAndSet(TERMINATED)) { - s.onComplete(); + for (PublishDisposable<T> pd : subscribers.getAndSet(TERMINATED)) { + pd.onComplete(); } } @@ -290,7 +290,7 @@ static final class PublishDisposable<T> extends AtomicBoolean implements Disposa private static final long serialVersionUID = 3562861878281475070L; /** The actual subscriber. */ - final Observer<? super T> actual; + final Observer<? super T> downstream; /** The subject state. */ final PublishSubject<T> parent; @@ -300,13 +300,13 @@ static final class PublishDisposable<T> extends AtomicBoolean implements Disposa * @param parent the parent PublishProcessor */ PublishDisposable(Observer<? super T> actual, PublishSubject<T> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } public void onNext(T t) { if (!get()) { - actual.onNext(t); + downstream.onNext(t); } } @@ -314,13 +314,13 @@ public void onError(Throwable t) { if (get()) { RxJavaPlugins.onError(t); } else { - actual.onError(t); + downstream.onError(t); } } public void onComplete() { if (!get()) { - actual.onComplete(); + downstream.onComplete(); } } diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java index 9454de50d0..344ef99fee 100644 --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java @@ -332,9 +332,9 @@ protected void subscribeActual(Observer<? super T> observer) { } @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { if (done) { - s.dispose(); + d.dispose(); } } @@ -597,7 +597,7 @@ interface ReplayBuffer<T> { static final class ReplayDisposable<T> extends AtomicInteger implements Disposable { private static final long serialVersionUID = 466549804534799122L; - final Observer<? super T> actual; + final Observer<? super T> downstream; final ReplaySubject<T> state; Object index; @@ -605,7 +605,7 @@ static final class ReplayDisposable<T> extends AtomicInteger implements Disposab volatile boolean cancelled; ReplayDisposable(Observer<? super T> actual, ReplaySubject<T> state) { - this.actual = actual; + this.downstream = actual; this.state = state; } @@ -723,7 +723,7 @@ public void replay(ReplayDisposable<T> rs) { int missed = 1; final List<Object> b = buffer; - final Observer<? super T> a = rs.actual; + final Observer<? super T> a = rs.downstream; Integer indexObject = (Integer)rs.index; int index; @@ -957,7 +957,7 @@ public void replay(ReplayDisposable<T> rs) { } int missed = 1; - final Observer<? super T> a = rs.actual; + final Observer<? super T> a = rs.downstream; Node<Object> index = (Node<Object>)rs.index; if (index == null) { @@ -1247,7 +1247,7 @@ public void replay(ReplayDisposable<T> rs) { } int missed = 1; - final Observer<? super T> a = rs.actual; + final Observer<? super T> a = rs.downstream; TimedNode<Object> index = (TimedNode<Object>)rs.index; if (index == null) { diff --git a/src/main/java/io/reactivex/subjects/SerializedSubject.java b/src/main/java/io/reactivex/subjects/SerializedSubject.java index 54ffb596a5..5b8bc16204 100644 --- a/src/main/java/io/reactivex/subjects/SerializedSubject.java +++ b/src/main/java/io/reactivex/subjects/SerializedSubject.java @@ -51,7 +51,7 @@ protected void subscribeActual(Observer<? super T> observer) { @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { boolean cancel; if (!done) { synchronized (this) { @@ -64,7 +64,7 @@ public void onSubscribe(Disposable s) { q = new AppendOnlyLinkedArrayList<Object>(4); queue = q; } - q.add(NotificationLite.disposable(s)); + q.add(NotificationLite.disposable(d)); return; } emitting = true; @@ -75,9 +75,9 @@ public void onSubscribe(Disposable s) { cancel = true; } if (cancel) { - s.dispose(); + d.dispose(); } else { - actual.onSubscribe(s); + actual.onSubscribe(d); emitLoop(); } } diff --git a/src/main/java/io/reactivex/subjects/SingleSubject.java b/src/main/java/io/reactivex/subjects/SingleSubject.java index ff07b75845..cd9e3a2cd4 100644 --- a/src/main/java/io/reactivex/subjects/SingleSubject.java +++ b/src/main/java/io/reactivex/subjects/SingleSubject.java @@ -138,7 +138,7 @@ public void onSuccess(@NonNull T value) { if (once.compareAndSet(false, true)) { this.value = value; for (SingleDisposable<T> md : observers.getAndSet(TERMINATED)) { - md.actual.onSuccess(value); + md.downstream.onSuccess(value); } } } @@ -150,7 +150,7 @@ public void onError(@NonNull Throwable e) { if (once.compareAndSet(false, true)) { this.error = e; for (SingleDisposable<T> md : observers.getAndSet(TERMINATED)) { - md.actual.onError(e); + md.downstream.onError(e); } } else { RxJavaPlugins.onError(e); @@ -289,10 +289,10 @@ static final class SingleDisposable<T> extends AtomicReference<SingleSubject<T>> implements Disposable { private static final long serialVersionUID = -7650903191002190468L; - final SingleObserver<? super T> actual; + final SingleObserver<? super T> downstream; SingleDisposable(SingleObserver<? super T> actual, SingleSubject<T> parent) { - this.actual = actual; + this.downstream = actual; lazySet(parent); } diff --git a/src/main/java/io/reactivex/subjects/UnicastSubject.java b/src/main/java/io/reactivex/subjects/UnicastSubject.java index e6cc271073..72f0563637 100644 --- a/src/main/java/io/reactivex/subjects/UnicastSubject.java +++ b/src/main/java/io/reactivex/subjects/UnicastSubject.java @@ -146,7 +146,7 @@ public final class UnicastSubject<T> extends Subject<T> { final SpscLinkedArrayQueue<T> queue; /** The single Observer. */ - final AtomicReference<Observer<? super T>> actual; + final AtomicReference<Observer<? super T>> downstream; /** The optional callback when the Subject gets cancelled or terminates. */ final AtomicReference<Runnable> onTerminate; @@ -263,7 +263,7 @@ public static <T> UnicastSubject<T> create(boolean delayError) { this.queue = new SpscLinkedArrayQueue<T>(ObjectHelper.verifyPositive(capacityHint, "capacityHint")); this.onTerminate = new AtomicReference<Runnable>(); this.delayError = delayError; - this.actual = new AtomicReference<Observer<? super T>>(); + this.downstream = new AtomicReference<Observer<? super T>>(); this.once = new AtomicBoolean(); this.wip = new UnicastQueueDisposable(); } @@ -293,7 +293,7 @@ public static <T> UnicastSubject<T> create(boolean delayError) { this.queue = new SpscLinkedArrayQueue<T>(ObjectHelper.verifyPositive(capacityHint, "capacityHint")); this.onTerminate = new AtomicReference<Runnable>(ObjectHelper.requireNonNull(onTerminate, "onTerminate")); this.delayError = delayError; - this.actual = new AtomicReference<Observer<? super T>>(); + this.downstream = new AtomicReference<Observer<? super T>>(); this.once = new AtomicBoolean(); this.wip = new UnicastQueueDisposable(); } @@ -302,9 +302,9 @@ public static <T> UnicastSubject<T> create(boolean delayError) { protected void subscribeActual(Observer<? super T> observer) { if (!once.get() && once.compareAndSet(false, true)) { observer.onSubscribe(wip); - actual.lazySet(observer); // full barrier in drain + downstream.lazySet(observer); // full barrier in drain if (disposed) { - actual.lazySet(null); + downstream.lazySet(null); return; } drain(); @@ -321,9 +321,9 @@ void doTerminate() { } @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { if (done || disposed) { - s.dispose(); + d.dispose(); } } @@ -373,7 +373,7 @@ void drainNormal(Observer<? super T> a) { for (;;) { if (disposed) { - actual.lazySet(null); + downstream.lazySet(null); q.clear(); return; } @@ -420,7 +420,7 @@ void drainFused(Observer<? super T> a) { for (;;) { if (disposed) { - actual.lazySet(null); + downstream.lazySet(null); q.clear(); return; } @@ -447,7 +447,7 @@ void drainFused(Observer<? super T> a) { } void errorOrComplete(Observer<? super T> a) { - actual.lazySet(null); + downstream.lazySet(null); Throwable ex = error; if (ex != null) { a.onError(ex); @@ -459,7 +459,7 @@ void errorOrComplete(Observer<? super T> a) { boolean failedFast(final SimpleQueue<T> q, Observer<? super T> a) { Throwable ex = error; if (ex != null) { - actual.lazySet(null); + downstream.lazySet(null); q.clear(); a.onError(ex); return true; @@ -473,7 +473,7 @@ void drain() { return; } - Observer<? super T> a = actual.get(); + Observer<? super T> a = downstream.get(); int missed = 1; for (;;) { @@ -492,13 +492,13 @@ void drain() { break; } - a = actual.get(); + a = downstream.get(); } } @Override public boolean hasObservers() { - return actual.get() != null; + return downstream.get() != null; } @Override @@ -557,9 +557,9 @@ public void dispose() { doTerminate(); - actual.lazySet(null); + downstream.lazySet(null); if (wip.getAndIncrement() == 0) { - actual.lazySet(null); + downstream.lazySet(null); queue.clear(); } } diff --git a/src/main/java/io/reactivex/subscribers/DefaultSubscriber.java b/src/main/java/io/reactivex/subscribers/DefaultSubscriber.java index 0b6c538cf9..3038a955fd 100644 --- a/src/main/java/io/reactivex/subscribers/DefaultSubscriber.java +++ b/src/main/java/io/reactivex/subscribers/DefaultSubscriber.java @@ -73,11 +73,13 @@ * </code></pre> */ public abstract class DefaultSubscriber<T> implements FlowableSubscriber<T> { - private Subscription s; + + Subscription upstream; + @Override public final void onSubscribe(Subscription s) { - if (EndConsumerHelper.validate(this.s, s, getClass())) { - this.s = s; + if (EndConsumerHelper.validate(this.upstream, s, getClass())) { + this.upstream = s; onStart(); } } @@ -87,7 +89,7 @@ public final void onSubscribe(Subscription s) { * @param n the request amount, positive */ protected final void request(long n) { - Subscription s = this.s; + Subscription s = this.upstream; if (s != null) { s.request(n); } @@ -97,8 +99,8 @@ protected final void request(long n) { * Cancels the upstream's Subscription. */ protected final void cancel() { - Subscription s = this.s; - this.s = SubscriptionHelper.CANCELLED; + Subscription s = this.upstream; + this.upstream = SubscriptionHelper.CANCELLED; s.cancel(); } /** diff --git a/src/main/java/io/reactivex/subscribers/SafeSubscriber.java b/src/main/java/io/reactivex/subscribers/SafeSubscriber.java index 7c17a472d2..a7c1fb3ad6 100644 --- a/src/main/java/io/reactivex/subscribers/SafeSubscriber.java +++ b/src/main/java/io/reactivex/subscribers/SafeSubscriber.java @@ -27,26 +27,26 @@ */ public final class SafeSubscriber<T> implements FlowableSubscriber<T>, Subscription { /** The actual Subscriber. */ - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; /** The subscription. */ - Subscription s; + Subscription upstream; /** Indicates a terminal state. */ boolean done; /** * Constructs a SafeSubscriber by wrapping the given actual Subscriber. - * @param actual the actual Subscriber to wrap, not null (not validated) + * @param downstream the actual Subscriber to wrap, not null (not validated) */ - public SafeSubscriber(Subscriber<? super T> actual) { - this.actual = actual; + public SafeSubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.s, s)) { - this.s = s; + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; try { - actual.onSubscribe(this); + downstream.onSubscribe(this); } catch (Throwable e) { Exceptions.throwIfFatal(e); done = true; @@ -68,7 +68,7 @@ public void onNext(T t) { if (done) { return; } - if (s == null) { + if (upstream == null) { onNextNoSubscription(); return; } @@ -76,7 +76,7 @@ public void onNext(T t) { if (t == null) { Throwable ex = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); try { - s.cancel(); + upstream.cancel(); } catch (Throwable e1) { Exceptions.throwIfFatal(e1); onError(new CompositeException(ex, e1)); @@ -87,11 +87,11 @@ public void onNext(T t) { } try { - actual.onNext(t); + downstream.onNext(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); try { - s.cancel(); + upstream.cancel(); } catch (Throwable e1) { Exceptions.throwIfFatal(e1); onError(new CompositeException(e, e1)); @@ -106,7 +106,7 @@ void onNextNoSubscription() { Throwable ex = new NullPointerException("Subscription not set!"); try { - actual.onSubscribe(EmptySubscription.INSTANCE); + downstream.onSubscribe(EmptySubscription.INSTANCE); } catch (Throwable e) { Exceptions.throwIfFatal(e); // can't call onError because the actual's state may be corrupt at this point @@ -114,7 +114,7 @@ void onNextNoSubscription() { return; } try { - actual.onError(ex); + downstream.onError(ex); } catch (Throwable e) { Exceptions.throwIfFatal(e); // if onError failed, all that's left is to report the error to plugins @@ -130,11 +130,11 @@ public void onError(Throwable t) { } done = true; - if (s == null) { + if (upstream == null) { Throwable npe = new NullPointerException("Subscription not set!"); try { - actual.onSubscribe(EmptySubscription.INSTANCE); + downstream.onSubscribe(EmptySubscription.INSTANCE); } catch (Throwable e) { Exceptions.throwIfFatal(e); // can't call onError because the actual's state may be corrupt at this point @@ -142,7 +142,7 @@ public void onError(Throwable t) { return; } try { - actual.onError(new CompositeException(t, npe)); + downstream.onError(new CompositeException(t, npe)); } catch (Throwable e) { Exceptions.throwIfFatal(e); // if onError failed, all that's left is to report the error to plugins @@ -156,7 +156,7 @@ public void onError(Throwable t) { } try { - actual.onError(t); + downstream.onError(t); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); @@ -171,14 +171,14 @@ public void onComplete() { } done = true; - if (s == null) { + if (upstream == null) { onCompleteNoSubscription(); return; } try { - actual.onComplete(); + downstream.onComplete(); } catch (Throwable e) { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(e); @@ -190,7 +190,7 @@ void onCompleteNoSubscription() { Throwable ex = new NullPointerException("Subscription not set!"); try { - actual.onSubscribe(EmptySubscription.INSTANCE); + downstream.onSubscribe(EmptySubscription.INSTANCE); } catch (Throwable e) { Exceptions.throwIfFatal(e); // can't call onError because the actual's state may be corrupt at this point @@ -198,7 +198,7 @@ void onCompleteNoSubscription() { return; } try { - actual.onError(ex); + downstream.onError(ex); } catch (Throwable e) { Exceptions.throwIfFatal(e); // if onError failed, all that's left is to report the error to plugins @@ -209,11 +209,11 @@ void onCompleteNoSubscription() { @Override public void request(long n) { try { - s.request(n); + upstream.request(n); } catch (Throwable e) { Exceptions.throwIfFatal(e); try { - s.cancel(); + upstream.cancel(); } catch (Throwable e1) { Exceptions.throwIfFatal(e1); RxJavaPlugins.onError(new CompositeException(e, e1)); @@ -226,7 +226,7 @@ public void request(long n) { @Override public void cancel() { try { - s.cancel(); + upstream.cancel(); } catch (Throwable e1) { Exceptions.throwIfFatal(e1); RxJavaPlugins.onError(e1); diff --git a/src/main/java/io/reactivex/subscribers/SerializedSubscriber.java b/src/main/java/io/reactivex/subscribers/SerializedSubscriber.java index 9743518eea..4e1b147d8e 100644 --- a/src/main/java/io/reactivex/subscribers/SerializedSubscriber.java +++ b/src/main/java/io/reactivex/subscribers/SerializedSubscriber.java @@ -31,12 +31,12 @@ * @param <T> the value type */ public final class SerializedSubscriber<T> implements FlowableSubscriber<T>, Subscription { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final boolean delayError; static final int QUEUE_LINK_SIZE = 4; - Subscription subscription; + Subscription upstream; boolean emitting; AppendOnlyLinkedArrayList<Object> queue; @@ -45,10 +45,10 @@ public final class SerializedSubscriber<T> implements FlowableSubscriber<T>, Sub /** * Construct a SerializedSubscriber by wrapping the given actual Subscriber. - * @param actual the actual Subscriber, not null (not verified) + * @param downstream the actual Subscriber, not null (not verified) */ - public SerializedSubscriber(Subscriber<? super T> actual) { - this(actual, false); + public SerializedSubscriber(Subscriber<? super T> downstream) { + this(downstream, false); } /** @@ -59,15 +59,15 @@ public SerializedSubscriber(Subscriber<? super T> actual) { * @param delayError if true, errors are emitted after regular values have been emitted */ public SerializedSubscriber(Subscriber<? super T> actual, boolean delayError) { - this.actual = actual; + this.downstream = actual; this.delayError = delayError; } @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.validate(this.subscription, s)) { - this.subscription = s; - actual.onSubscribe(this); + if (SubscriptionHelper.validate(this.upstream, s)) { + this.upstream = s; + downstream.onSubscribe(this); } } @@ -77,7 +77,7 @@ public void onNext(T t) { return; } if (t == null) { - subscription.cancel(); + upstream.cancel(); onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); return; } @@ -97,7 +97,7 @@ public void onNext(T t) { emitting = true; } - actual.onNext(t); + downstream.onNext(t); emitLoop(); } @@ -139,7 +139,7 @@ public void onError(Throwable t) { return; } - actual.onError(t); + downstream.onError(t); // no need to loop because this onError is the last event } @@ -165,7 +165,7 @@ public void onComplete() { emitting = true; } - actual.onComplete(); + downstream.onComplete(); // no need to loop because this onComplete is the last event } @@ -181,7 +181,7 @@ void emitLoop() { queue = null; } - if (q.accept(actual)) { + if (q.accept(downstream)) { return; } } @@ -189,11 +189,11 @@ void emitLoop() { @Override public void request(long n) { - subscription.request(n); + upstream.request(n); } @Override public void cancel() { - subscription.cancel(); + upstream.cancel(); } } diff --git a/src/main/java/io/reactivex/subscribers/TestSubscriber.java b/src/main/java/io/reactivex/subscribers/TestSubscriber.java index 07a63a4753..30c1a22b03 100644 --- a/src/main/java/io/reactivex/subscribers/TestSubscriber.java +++ b/src/main/java/io/reactivex/subscribers/TestSubscriber.java @@ -41,13 +41,13 @@ public class TestSubscriber<T> extends BaseTestConsumer<T, TestSubscriber<T>> implements FlowableSubscriber<T>, Subscription, Disposable { /** The actual subscriber to forward events to. */ - private final Subscriber<? super T> actual; + private final Subscriber<? super T> downstream; /** Makes sure the incoming Subscriptions get cancelled immediately. */ private volatile boolean cancelled; /** Holds the current subscription if any. */ - private final AtomicReference<Subscription> subscription; + private final AtomicReference<Subscription> upstream; /** Holds the requested amount until a subscription arrives. */ private final AtomicLong missedRequested; @@ -102,10 +102,10 @@ public TestSubscriber(long initialRequest) { /** * Constructs a forwarding TestSubscriber but leaves the requesting to the wrapped subscriber. - * @param actual the actual Subscriber to forward events to + * @param downstream the actual Subscriber to forward events to */ - public TestSubscriber(Subscriber<? super T> actual) { - this(actual, Long.MAX_VALUE); + public TestSubscriber(Subscriber<? super T> downstream) { + this(downstream, Long.MAX_VALUE); } /** @@ -120,8 +120,8 @@ public TestSubscriber(Subscriber<? super T> actual, long initialRequest) { if (initialRequest < 0) { throw new IllegalArgumentException("Negative initial request not allowed"); } - this.actual = actual; - this.subscription = new AtomicReference<Subscription>(); + this.downstream = actual; + this.upstream = new AtomicReference<Subscription>(); this.missedRequested = new AtomicLong(initialRequest); } @@ -134,9 +134,9 @@ public void onSubscribe(Subscription s) { errors.add(new NullPointerException("onSubscribe received a null Subscription")); return; } - if (!subscription.compareAndSet(null, s)) { + if (!upstream.compareAndSet(null, s)) { s.cancel(); - if (subscription.get() != SubscriptionHelper.CANCELLED) { + if (upstream.get() != SubscriptionHelper.CANCELLED) { errors.add(new IllegalStateException("onSubscribe received multiple subscriptions: " + s)); } return; @@ -168,7 +168,7 @@ public void onSubscribe(Subscription s) { } - actual.onSubscribe(s); + downstream.onSubscribe(s); long mr = missedRequested.getAndSet(0L); if (mr != 0L) { @@ -189,7 +189,7 @@ protected void onStart() { public void onNext(T t) { if (!checkSubscriptionOnce) { checkSubscriptionOnce = true; - if (subscription.get() == null) { + if (upstream.get() == null) { errors.add(new IllegalStateException("onSubscribe not called in proper order")); } } @@ -214,14 +214,14 @@ public void onNext(T t) { errors.add(new NullPointerException("onNext received a null value")); } - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { if (!checkSubscriptionOnce) { checkSubscriptionOnce = true; - if (subscription.get() == null) { + if (upstream.get() == null) { errors.add(new NullPointerException("onSubscribe not called in proper order")); } } @@ -233,7 +233,7 @@ public void onError(Throwable t) { errors.add(new IllegalStateException("onError received a null Throwable")); } - actual.onError(t); + downstream.onError(t); } finally { done.countDown(); } @@ -243,7 +243,7 @@ public void onError(Throwable t) { public void onComplete() { if (!checkSubscriptionOnce) { checkSubscriptionOnce = true; - if (subscription.get() == null) { + if (upstream.get() == null) { errors.add(new IllegalStateException("onSubscribe not called in proper order")); } } @@ -251,7 +251,7 @@ public void onComplete() { lastThread = Thread.currentThread(); completions++; - actual.onComplete(); + downstream.onComplete(); } finally { done.countDown(); } @@ -259,14 +259,14 @@ public void onComplete() { @Override public final void request(long n) { - SubscriptionHelper.deferredRequest(subscription, missedRequested, n); + SubscriptionHelper.deferredRequest(upstream, missedRequested, n); } @Override public final void cancel() { if (!cancelled) { cancelled = true; - SubscriptionHelper.cancel(subscription); + SubscriptionHelper.cancel(upstream); } } @@ -295,7 +295,7 @@ public final boolean isDisposed() { * @return true if this TestSubscriber received a subscription */ public final boolean hasSubscription() { - return subscription.get() != null; + return upstream.get() != null; } // assertion methods @@ -306,7 +306,7 @@ public final boolean hasSubscription() { */ @Override public final TestSubscriber<T> assertSubscribed() { - if (subscription.get() == null) { + if (upstream.get() == null) { throw fail("Not subscribed!"); } return this; @@ -318,7 +318,7 @@ public final TestSubscriber<T> assertSubscribed() { */ @Override public final TestSubscriber<T> assertNotSubscribed() { - if (subscription.get() != null) { + if (upstream.get() != null) { throw fail("Subscribed!"); } else if (!errors.isEmpty()) { diff --git a/src/test/java/io/reactivex/TestHelper.java b/src/test/java/io/reactivex/TestHelper.java index cba835fcbd..7d19b95b35 100644 --- a/src/test/java/io/reactivex/TestHelper.java +++ b/src/test/java/io/reactivex/TestHelper.java @@ -1425,16 +1425,16 @@ public static <T, R> void checkDoubleOnSubscribeFlowable(Function<Flowable<T>, ? @Override protected void subscribeActual(Subscriber<? super T> subscriber) { try { - BooleanSubscription d1 = new BooleanSubscription(); + BooleanSubscription bs1 = new BooleanSubscription(); - subscriber.onSubscribe(d1); + subscriber.onSubscribe(bs1); - BooleanSubscription d2 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); - subscriber.onSubscribe(d2); + subscriber.onSubscribe(bs2); - b[0] = d1.isCancelled(); - b[1] = d2.isCancelled(); + b[0] = bs1.isCancelled(); + b[1] = bs2.isCancelled(); } finally { cdl.countDown(); } @@ -1694,16 +1694,16 @@ public static <T, R> void checkDoubleOnSubscribeFlowableToObservable(Function<Fl @Override protected void subscribeActual(Subscriber<? super T> subscriber) { try { - BooleanSubscription d1 = new BooleanSubscription(); + BooleanSubscription bs1 = new BooleanSubscription(); - subscriber.onSubscribe(d1); + subscriber.onSubscribe(bs1); - BooleanSubscription d2 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); - subscriber.onSubscribe(d2); + subscriber.onSubscribe(bs2); - b[0] = d1.isCancelled(); - b[1] = d2.isCancelled(); + b[0] = bs1.isCancelled(); + b[1] = bs2.isCancelled(); } finally { cdl.countDown(); } @@ -1748,16 +1748,16 @@ public static <T, R> void checkDoubleOnSubscribeFlowableToSingle(Function<Flowab @Override protected void subscribeActual(Subscriber<? super T> subscriber) { try { - BooleanSubscription d1 = new BooleanSubscription(); + BooleanSubscription bs1 = new BooleanSubscription(); - subscriber.onSubscribe(d1); + subscriber.onSubscribe(bs1); - BooleanSubscription d2 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); - subscriber.onSubscribe(d2); + subscriber.onSubscribe(bs2); - b[0] = d1.isCancelled(); - b[1] = d2.isCancelled(); + b[0] = bs1.isCancelled(); + b[1] = bs2.isCancelled(); } finally { cdl.countDown(); } @@ -1802,16 +1802,16 @@ public static <T, R> void checkDoubleOnSubscribeFlowableToMaybe(Function<Flowabl @Override protected void subscribeActual(Subscriber<? super T> subscriber) { try { - BooleanSubscription d1 = new BooleanSubscription(); + BooleanSubscription bs1 = new BooleanSubscription(); - subscriber.onSubscribe(d1); + subscriber.onSubscribe(bs1); - BooleanSubscription d2 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); - subscriber.onSubscribe(d2); + subscriber.onSubscribe(bs2); - b[0] = d1.isCancelled(); - b[1] = d2.isCancelled(); + b[0] = bs1.isCancelled(); + b[1] = bs2.isCancelled(); } finally { cdl.countDown(); } @@ -1855,16 +1855,16 @@ public static <T> void checkDoubleOnSubscribeFlowableToCompletable(Function<Flow @Override protected void subscribeActual(Subscriber<? super T> subscriber) { try { - BooleanSubscription d1 = new BooleanSubscription(); + BooleanSubscription bs1 = new BooleanSubscription(); - subscriber.onSubscribe(d1); + subscriber.onSubscribe(bs1); - BooleanSubscription d2 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); - subscriber.onSubscribe(d2); + subscriber.onSubscribe(bs2); - b[0] = d1.isCancelled(); - b[1] = d2.isCancelled(); + b[0] = bs1.isCancelled(); + b[1] = bs2.isCancelled(); } finally { cdl.countDown(); } @@ -2416,28 +2416,28 @@ public static <T> void checkFusedIsEmptyClear(Flowable<T> source) { source.subscribe(new FlowableSubscriber<T>() { @Override - public void onSubscribe(Subscription d) { + public void onSubscribe(Subscription s) { try { - if (d instanceof QueueSubscription) { + if (s instanceof QueueSubscription) { @SuppressWarnings("unchecked") - QueueSubscription<Object> qd = (QueueSubscription<Object>) d; + QueueSubscription<Object> qs = (QueueSubscription<Object>) s; state[0] = true; - int m = qd.requestFusion(QueueFuseable.ANY); + int m = qs.requestFusion(QueueFuseable.ANY); if (m != QueueFuseable.NONE) { state[1] = true; - state[2] = qd.isEmpty(); + state[2] = qs.isEmpty(); - qd.clear(); + qs.clear(); - state[3] = qd.isEmpty(); + state[3] = qs.isEmpty(); } } cdl.countDown(); } finally { - d.cancel(); + s.cancel(); } } @@ -2943,14 +2943,14 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class StripBoundarySubscriber<T> implements FlowableSubscriber<T>, QueueSubscription<T> { - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; Subscription upstream; QueueSubscription<T> qs; - StripBoundarySubscriber(Subscriber<? super T> actual) { - this.actual = actual; + StripBoundarySubscriber(Subscriber<? super T> downstream) { + this.downstream = downstream; } @SuppressWarnings("unchecked") @@ -2960,22 +2960,22 @@ public void onSubscribe(Subscription subscription) { if (subscription instanceof QueueSubscription) { qs = (QueueSubscription<T>)subscription; } - actual.onSubscribe(this); + downstream.onSubscribe(this); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable throwable) { - actual.onError(throwable); + downstream.onError(throwable); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override @@ -3048,14 +3048,14 @@ protected void subscribeActual(Observer<? super T> observer) { static final class StripBoundaryObserver<T> implements Observer<T>, QueueDisposable<T> { - final Observer<? super T> actual; + final Observer<? super T> downstream; Disposable upstream; QueueDisposable<T> qd; - StripBoundaryObserver(Observer<? super T> actual) { - this.actual = actual; + StripBoundaryObserver(Observer<? super T> downstream) { + this.downstream = downstream; } @SuppressWarnings("unchecked") @@ -3065,22 +3065,22 @@ public void onSubscribe(Disposable d) { if (d instanceof QueueDisposable) { qd = (QueueDisposable<T>)d; } - actual.onSubscribe(this); + downstream.onSubscribe(this); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable throwable) { - actual.onError(throwable); + downstream.onError(throwable); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } @Override diff --git a/src/test/java/io/reactivex/completable/CompletableTest.java b/src/test/java/io/reactivex/completable/CompletableTest.java index dd4bdfc9e3..32461d5d41 100644 --- a/src/test/java/io/reactivex/completable/CompletableTest.java +++ b/src/test/java/io/reactivex/completable/CompletableTest.java @@ -1899,7 +1899,7 @@ public void doOnSubscribeNormal() { Completable c = normal.completable.doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { calls.getAndIncrement(); } }); @@ -3651,21 +3651,21 @@ public void subscribeActionReportsUnsubscribedAfter() { PublishSubject<String> stringSubject = PublishSubject.create(); Completable completable = stringSubject.ignoreElements(); - final AtomicReference<Disposable> subscriptionRef = new AtomicReference<Disposable>(); + final AtomicReference<Disposable> disposableRef = new AtomicReference<Disposable>(); Disposable completableSubscription = completable.subscribe(new Action() { @Override public void run() { - if (subscriptionRef.get().isDisposed()) { - subscriptionRef.set(null); + if (disposableRef.get().isDisposed()) { + disposableRef.set(null); } } }); - subscriptionRef.set(completableSubscription); + disposableRef.set(completableSubscription); stringSubject.onComplete(); assertTrue("Not unsubscribed?", completableSubscription.isDisposed()); - assertNotNull("Unsubscribed before the call to onComplete", subscriptionRef.get()); + assertNotNull("Unsubscribed before the call to onComplete", disposableRef.get()); } @Test @@ -4180,7 +4180,7 @@ public void onError(Throwable e) { } @Override - public void onSubscribe(Subscription d) { + public void onSubscribe(Subscription s) { } @@ -4212,7 +4212,7 @@ public void onError(Throwable e) { } @Override - public void onSubscribe(Subscription d) { + public void onSubscribe(Subscription s) { } @@ -4333,21 +4333,21 @@ public void subscribeAction2ReportsUnsubscribedAfter() { PublishSubject<String> stringSubject = PublishSubject.create(); Completable completable = stringSubject.ignoreElements(); - final AtomicReference<Disposable> subscriptionRef = new AtomicReference<Disposable>(); + final AtomicReference<Disposable> disposableRef = new AtomicReference<Disposable>(); Disposable completableSubscription = completable.subscribe(new Action() { @Override public void run() { - if (subscriptionRef.get().isDisposed()) { - subscriptionRef.set(null); + if (disposableRef.get().isDisposed()) { + disposableRef.set(null); } } }, Functions.emptyConsumer()); - subscriptionRef.set(completableSubscription); + disposableRef.set(completableSubscription); stringSubject.onComplete(); assertTrue("Not unsubscribed?", completableSubscription.isDisposed()); - assertNotNull("Unsubscribed before the call to onComplete", subscriptionRef.get()); + assertNotNull("Unsubscribed before the call to onComplete", disposableRef.get()); } @Test @@ -4355,22 +4355,22 @@ public void subscribeAction2ReportsUnsubscribedOnErrorAfter() { PublishSubject<String> stringSubject = PublishSubject.create(); Completable completable = stringSubject.ignoreElements(); - final AtomicReference<Disposable> subscriptionRef = new AtomicReference<Disposable>(); + final AtomicReference<Disposable> disposableRef = new AtomicReference<Disposable>(); Disposable completableSubscription = completable.subscribe(Functions.EMPTY_ACTION, new Consumer<Throwable>() { @Override public void accept(Throwable e) { - if (subscriptionRef.get().isDisposed()) { - subscriptionRef.set(null); + if (disposableRef.get().isDisposed()) { + disposableRef.set(null); } } }); - subscriptionRef.set(completableSubscription); + disposableRef.set(completableSubscription); stringSubject.onError(new TestException()); assertTrue("Not unsubscribed?", completableSubscription.isDisposed()); - assertNotNull("Unsubscribed before the call to onError", subscriptionRef.get()); + assertNotNull("Unsubscribed before the call to onError", disposableRef.get()); } @Ignore("onXXX methods are not allowed to throw") @@ -4478,9 +4478,9 @@ public void andThenError() { final Exception e = new Exception(); Completable.unsafeCreate(new CompletableSource() { @Override - public void subscribe(CompletableObserver cs) { - cs.onSubscribe(Disposables.empty()); - cs.onError(e); + public void subscribe(CompletableObserver co) { + co.onSubscribe(Disposables.empty()); + co.onError(e); } }) .andThen(Flowable.<String>unsafeCreate(new Publisher<String>() { diff --git a/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java b/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java index 78e73bf047..ce8cd412b2 100644 --- a/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java +++ b/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java @@ -31,8 +31,8 @@ public class CompositeDisposableTest { @Test public void testSuccess() { final AtomicInteger counter = new AtomicInteger(); - CompositeDisposable s = new CompositeDisposable(); - s.add(Disposables.fromRunnable(new Runnable() { + CompositeDisposable cd = new CompositeDisposable(); + cd.add(Disposables.fromRunnable(new Runnable() { @Override public void run() { @@ -41,7 +41,7 @@ public void run() { })); - s.add(Disposables.fromRunnable(new Runnable() { + cd.add(Disposables.fromRunnable(new Runnable() { @Override public void run() { @@ -49,7 +49,7 @@ public void run() { } })); - s.dispose(); + cd.dispose(); assertEquals(2, counter.get()); } @@ -57,12 +57,12 @@ public void run() { @Test(timeout = 1000) public void shouldUnsubscribeAll() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); - final CompositeDisposable s = new CompositeDisposable(); + final CompositeDisposable cd = new CompositeDisposable(); final int count = 10; final CountDownLatch start = new CountDownLatch(1); for (int i = 0; i < count; i++) { - s.add(Disposables.fromRunnable(new Runnable() { + cd.add(Disposables.fromRunnable(new Runnable() { @Override public void run() { @@ -78,7 +78,7 @@ public void run() { public void run() { try { start.await(); - s.dispose(); + cd.dispose(); } catch (final InterruptedException e) { fail(e.getMessage()); } @@ -99,8 +99,8 @@ public void run() { @Test public void testException() { final AtomicInteger counter = new AtomicInteger(); - CompositeDisposable s = new CompositeDisposable(); - s.add(Disposables.fromRunnable(new Runnable() { + CompositeDisposable cd = new CompositeDisposable(); + cd.add(Disposables.fromRunnable(new Runnable() { @Override public void run() { @@ -109,7 +109,7 @@ public void run() { })); - s.add(Disposables.fromRunnable(new Runnable() { + cd.add(Disposables.fromRunnable(new Runnable() { @Override public void run() { @@ -119,7 +119,7 @@ public void run() { })); try { - s.dispose(); + cd.dispose(); fail("Expecting an exception"); } catch (RuntimeException e) { // we expect this @@ -133,8 +133,8 @@ public void run() { @Test public void testCompositeException() { final AtomicInteger counter = new AtomicInteger(); - CompositeDisposable s = new CompositeDisposable(); - s.add(Disposables.fromRunnable(new Runnable() { + CompositeDisposable cd = new CompositeDisposable(); + cd.add(Disposables.fromRunnable(new Runnable() { @Override public void run() { @@ -143,7 +143,7 @@ public void run() { })); - s.add(Disposables.fromRunnable(new Runnable() { + cd.add(Disposables.fromRunnable(new Runnable() { @Override public void run() { @@ -151,7 +151,7 @@ public void run() { } })); - s.add(Disposables.fromRunnable(new Runnable() { + cd.add(Disposables.fromRunnable(new Runnable() { @Override public void run() { @@ -161,7 +161,7 @@ public void run() { })); try { - s.dispose(); + cd.dispose(); fail("Expecting an exception"); } catch (CompositeException e) { // we expect this @@ -174,51 +174,51 @@ public void run() { @Test public void testRemoveUnsubscribes() { - Disposable s1 = Disposables.empty(); - Disposable s2 = Disposables.empty(); + Disposable d1 = Disposables.empty(); + Disposable d2 = Disposables.empty(); - CompositeDisposable s = new CompositeDisposable(); - s.add(s1); - s.add(s2); + CompositeDisposable cd = new CompositeDisposable(); + cd.add(d1); + cd.add(d2); - s.remove(s1); + cd.remove(d1); - assertTrue(s1.isDisposed()); - assertFalse(s2.isDisposed()); + assertTrue(d1.isDisposed()); + assertFalse(d2.isDisposed()); } @Test public void testClear() { - Disposable s1 = Disposables.empty(); - Disposable s2 = Disposables.empty(); + Disposable d1 = Disposables.empty(); + Disposable d2 = Disposables.empty(); - CompositeDisposable s = new CompositeDisposable(); - s.add(s1); - s.add(s2); + CompositeDisposable cd = new CompositeDisposable(); + cd.add(d1); + cd.add(d2); - assertFalse(s1.isDisposed()); - assertFalse(s2.isDisposed()); + assertFalse(d1.isDisposed()); + assertFalse(d2.isDisposed()); - s.clear(); + cd.clear(); - assertTrue(s1.isDisposed()); - assertTrue(s2.isDisposed()); - assertFalse(s.isDisposed()); + assertTrue(d1.isDisposed()); + assertTrue(d2.isDisposed()); + assertFalse(cd.isDisposed()); - Disposable s3 = Disposables.empty(); + Disposable d3 = Disposables.empty(); - s.add(s3); - s.dispose(); + cd.add(d3); + cd.dispose(); - assertTrue(s3.isDisposed()); - assertTrue(s.isDisposed()); + assertTrue(d3.isDisposed()); + assertTrue(cd.isDisposed()); } @Test public void testUnsubscribeIdempotence() { final AtomicInteger counter = new AtomicInteger(); - CompositeDisposable s = new CompositeDisposable(); - s.add(Disposables.fromRunnable(new Runnable() { + CompositeDisposable cd = new CompositeDisposable(); + cd.add(Disposables.fromRunnable(new Runnable() { @Override public void run() { @@ -227,9 +227,9 @@ public void run() { })); - s.dispose(); - s.dispose(); - s.dispose(); + cd.dispose(); + cd.dispose(); + cd.dispose(); // we should have only disposed once assertEquals(1, counter.get()); @@ -239,11 +239,11 @@ public void run() { public void testUnsubscribeIdempotenceConcurrently() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); - final CompositeDisposable s = new CompositeDisposable(); + final CompositeDisposable cd = new CompositeDisposable(); final int count = 10; final CountDownLatch start = new CountDownLatch(1); - s.add(Disposables.fromRunnable(new Runnable() { + cd.add(Disposables.fromRunnable(new Runnable() { @Override public void run() { @@ -259,7 +259,7 @@ public void run() { public void run() { try { start.await(); - s.dispose(); + cd.dispose(); } catch (final InterruptedException e) { fail(e.getMessage()); } @@ -279,22 +279,22 @@ public void run() { } @Test public void testTryRemoveIfNotIn() { - CompositeDisposable csub = new CompositeDisposable(); + CompositeDisposable cd = new CompositeDisposable(); - CompositeDisposable csub1 = new CompositeDisposable(); - CompositeDisposable csub2 = new CompositeDisposable(); + CompositeDisposable cd1 = new CompositeDisposable(); + CompositeDisposable cd2 = new CompositeDisposable(); - csub.add(csub1); - csub.remove(csub1); - csub.add(csub2); + cd.add(cd1); + cd.remove(cd1); + cd.add(cd2); - csub.remove(csub1); // try removing agian + cd.remove(cd1); // try removing agian } @Test(expected = NullPointerException.class) public void testAddingNullDisposableIllegal() { - CompositeDisposable csub = new CompositeDisposable(); - csub.add(null); + CompositeDisposable cd = new CompositeDisposable(); + cd.add(null); } @Test diff --git a/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java b/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java index 9ad78fd1e4..9db71ac805 100644 --- a/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java @@ -36,13 +36,13 @@ public class FlowableBackpressureTests { static final class FirehoseNoBackpressure extends AtomicBoolean implements Subscription { private static final long serialVersionUID = -669931580197884015L; - final Subscriber<? super Integer> s; - private final AtomicInteger counter; + final Subscriber<? super Integer> downstream; + final AtomicInteger counter; volatile boolean cancelled; private FirehoseNoBackpressure(AtomicInteger counter, Subscriber<? super Integer> s) { this.counter = counter; - this.s = s; + this.downstream = s; } @Override @@ -52,7 +52,7 @@ public void request(long n) { } if (compareAndSet(false, true)) { int i = 0; - final Subscriber<? super Integer> a = s; + final Subscriber<? super Integer> a = downstream; final AtomicInteger c = counter; while (!cancelled) { diff --git a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java index b01c2886ac..b72df7a98c 100644 --- a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java @@ -589,10 +589,10 @@ public boolean test(Integer v) throws Exception { try { s.onSubscribe(new BooleanSubscription()); - BooleanSubscription d = new BooleanSubscription(); - s.onSubscribe(d); + BooleanSubscription bs = new BooleanSubscription(); + s.onSubscribe(bs); - assertTrue(d.isCancelled()); + assertTrue(bs.isCancelled()); TestHelper.assertError(list, 0, IllegalStateException.class, "Subscription already set!"); } finally { diff --git a/src/test/java/io/reactivex/flowable/FlowableTests.java b/src/test/java/io/reactivex/flowable/FlowableTests.java index 8f45ce3689..f3b7d2b371 100644 --- a/src/test/java/io/reactivex/flowable/FlowableTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableTests.java @@ -549,7 +549,7 @@ public void run() { }).replay(); // we connect immediately and it will emit the value - Disposable s = f.connect(); + Disposable connection = f.connect(); try { // we then expect the following 2 subscriptions to get that same value @@ -578,7 +578,7 @@ public void accept(String v) { } assertEquals(1, counter.get()); } finally { - s.dispose(); + connection.dispose(); } } diff --git a/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java b/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java index 07d279d162..8defb098ef 100644 --- a/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java @@ -32,13 +32,13 @@ static final class TakeFirst extends DeferredScalarObserver<Integer, Integer> { private static final long serialVersionUID = -2793723002312330530L; - TakeFirst(Observer<? super Integer> actual) { - super(actual); + TakeFirst(Observer<? super Integer> downstream) { + super(downstream); } @Override public void onNext(Integer value) { - s.dispose(); + upstream.dispose(); complete(value); complete(value); } @@ -177,8 +177,8 @@ static final class TakeLast extends DeferredScalarObserver<Integer, Integer> { private static final long serialVersionUID = -2793723002312330530L; - TakeLast(Observer<? super Integer> actual) { - super(actual); + TakeLast(Observer<? super Integer> downstream) { + super(downstream); } @@ -312,18 +312,18 @@ public void disposedAfterOnNext() { final TestObserver<Integer> to = new TestObserver<Integer>(); TakeLast source = new TakeLast(new Observer<Integer>() { - Disposable d; + Disposable upstream; @Override public void onSubscribe(Disposable d) { - this.d = d; + this.upstream = d; to.onSubscribe(d); } @Override public void onNext(Integer value) { to.onNext(value); - d.dispose(); + upstream.dispose(); } @Override diff --git a/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java b/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java index 90fe6c3910..bf91a78a4e 100644 --- a/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java @@ -135,16 +135,16 @@ public void onSubscribe() throws Exception { try { - Disposable s = Disposables.empty(); + Disposable d1 = Disposables.empty(); - fo.onSubscribe(s); + fo.onSubscribe(d1); - Disposable s2 = Disposables.empty(); + Disposable d2 = Disposables.empty(); - fo.onSubscribe(s2); + fo.onSubscribe(d2); - assertFalse(s.isDisposed()); - assertTrue(s2.isDisposed()); + assertFalse(d1.isDisposed()); + assertTrue(d2.isDisposed()); TestHelper.assertError(errors, 0, IllegalStateException.class, "Disposable already set!"); } finally { diff --git a/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java b/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java index 3171f8e8df..8e520fd402 100644 --- a/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java @@ -54,7 +54,7 @@ public void run() throws Exception { } }, new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { throw new TestException(); } }); @@ -91,7 +91,7 @@ public void run() throws Exception { } }, new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { } }); @@ -130,7 +130,7 @@ public void run() throws Exception { } }, new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { } }); @@ -176,7 +176,7 @@ public void run() throws Exception { } }, new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { } }); @@ -201,13 +201,13 @@ public void badSourceOnSubscribe() { Observable<Integer> source = new Observable<Integer>() { @Override public void subscribeActual(Observer<? super Integer> observer) { - Disposable s1 = Disposables.empty(); - observer.onSubscribe(s1); - Disposable s2 = Disposables.empty(); - observer.onSubscribe(s2); + Disposable d1 = Disposables.empty(); + observer.onSubscribe(d1); + Disposable d2 = Disposables.empty(); + observer.onSubscribe(d2); - assertFalse(s1.isDisposed()); - assertTrue(s2.isDisposed()); + assertFalse(d1.isDisposed()); + assertTrue(d2.isDisposed()); observer.onNext(1); observer.onComplete(); @@ -234,7 +234,7 @@ public void run() throws Exception { } }, new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { } }); @@ -284,7 +284,7 @@ public void run() throws Exception { } }, new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { } }); @@ -348,7 +348,7 @@ public void run() throws Exception { } }, new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { throw new TestException(); } }); diff --git a/src/test/java/io/reactivex/internal/observers/QueueDrainObserverTest.java b/src/test/java/io/reactivex/internal/observers/QueueDrainObserverTest.java index 12959cb898..1f9fffd356 100644 --- a/src/test/java/io/reactivex/internal/observers/QueueDrainObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/QueueDrainObserverTest.java @@ -38,7 +38,7 @@ public void onComplete() { } @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { } @Override @@ -65,7 +65,7 @@ public void onComplete() { } @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { } @Override diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableDoOnTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableDoOnTest.java index 91f904ce56..5d38ba126f 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableDoOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableDoOnTest.java @@ -93,7 +93,7 @@ protected void subscribeActual(CompletableObserver observer) { } .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { throw new TestException("First"); } }) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java index 2ed817df9a..636d7bcd28 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBlockingTest.java @@ -289,8 +289,8 @@ public void blockingSubscribeObserver() { .blockingSubscribe(new FlowableSubscriber<Object>() { @Override - public void onSubscribe(Subscription d) { - d.request(Long.MAX_VALUE); + public void onSubscribe(Subscription s) { + s.request(Long.MAX_VALUE); } @Override @@ -324,8 +324,8 @@ public void blockingSubscribeObserverError() { .blockingSubscribe(new FlowableSubscriber<Object>() { @Override - public void onSubscribe(Subscription d) { - d.request(Long.MAX_VALUE); + public void onSubscribe(Subscription s) { + s.request(Long.MAX_VALUE); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java index 0599234015..2934084b0d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java @@ -1382,7 +1382,7 @@ public void dontSubscribeIfDone() { Flowable.error(new TestException()) .doOnSubscribe(new Consumer<Subscription>() { @Override - public void accept(Subscription d) throws Exception { + public void accept(Subscription s) throws Exception { count[0]++; } }), @@ -1415,7 +1415,7 @@ public void dontSubscribeIfDone2() { Flowable.error(new TestException()) .doOnSubscribe(new Consumer<Subscription>() { @Override - public void accept(Subscription d) throws Exception { + public void accept(Subscription s) throws Exception { count[0]++; } }) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java index ba4c9933a9..8aeef598c8 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java @@ -792,7 +792,7 @@ public void subscribe(FlowableEmitter<Object> e) throws Exception { }, m) .subscribe(new FlowableSubscriber<Object>() { @Override - public void onSubscribe(Subscription d) { + public void onSubscribe(Subscription s) { } @Override @@ -830,7 +830,7 @@ public void subscribe(FlowableEmitter<Object> e) throws Exception { }, m) .subscribe(new FlowableSubscriber<Object>() { @Override - public void onSubscribe(Subscription d) { + public void onSubscribe(Subscription s) { } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java index fd79f56b9c..448e963d49 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java @@ -175,14 +175,14 @@ public void fusedClear() { .distinct() .subscribe(new FlowableSubscriber<Integer>() { @Override - public void onSubscribe(Subscription d) { - QueueSubscription<?> qd = (QueueSubscription<?>)d; + public void onSubscribe(Subscription s) { + QueueSubscription<?> qs = (QueueSubscription<?>)s; - assertFalse(qd.isEmpty()); + assertFalse(qs.isEmpty()); - qd.clear(); + qs.clear(); - assertTrue(qd.isEmpty()); + assertTrue(qs.isEmpty()); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java index c0ddc1f302..01309ff55c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java @@ -422,15 +422,15 @@ public CompletableSource apply(Integer v) throws Exception { .toFlowable() .subscribe(new FlowableSubscriber<Object>() { @Override - public void onSubscribe(Subscription d) { - QueueSubscription<?> qd = (QueueSubscription<?>)d; + public void onSubscribe(Subscription s) { + QueueSubscription<?> qs = (QueueSubscription<?>)s; try { - assertNull(qd.poll()); + assertNull(qs.poll()); } catch (Throwable ex) { throw new RuntimeException(ex); } - assertTrue(qd.isEmpty()); - qd.clear(); + assertTrue(qs.isEmpty()); + qs.clear(); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java index 421cd9e4c7..fdedc6577c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java @@ -882,21 +882,21 @@ public void fusionClear() { Flowable.fromIterable(Arrays.asList(1, 2, 3)) .subscribe(new FlowableSubscriber<Integer>() { @Override - public void onSubscribe(Subscription d) { + public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") - QueueSubscription<Integer> qd = (QueueSubscription<Integer>)d; + QueueSubscription<Integer> qs = (QueueSubscription<Integer>)s; - qd.requestFusion(QueueFuseable.ANY); + qs.requestFusion(QueueFuseable.ANY); try { - assertEquals(1, qd.poll().intValue()); + assertEquals(1, qs.poll().intValue()); } catch (Throwable ex) { fail(ex.toString()); } - qd.clear(); + qs.clear(); try { - assertNull(qd.poll()); + assertNull(qs.poll()); } catch (Throwable ex) { fail(ex.toString()); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java index 10c6f5bd47..10c1facc16 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java @@ -1306,19 +1306,19 @@ public void outputFusedCancelReentrant() throws Exception { us.observeOn(Schedulers.single()) .subscribe(new FlowableSubscriber<Integer>() { - Subscription d; + Subscription upstream; int count; @Override - public void onSubscribe(Subscription d) { - this.d = d; - ((QueueSubscription<?>)d).requestFusion(QueueFuseable.ANY); + public void onSubscribe(Subscription s) { + this.upstream = s; + ((QueueSubscription<?>)s).requestFusion(QueueFuseable.ANY); } @Override public void onNext(Integer value) { if (++count == 1) { us.onNext(2); - d.cancel(); + upstream.cancel(); cdl.countDown(); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java index ed8b3b6aba..140ca333ac 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java @@ -148,19 +148,19 @@ public void subscribe(Subscriber<? super String> t1) { static final class TestObservable implements Publisher<String> { - final Subscription s; + final Subscription upstream; final String[] values; Thread t; TestObservable(Subscription s, String... values) { - this.s = s; + this.upstream = s; this.values = values; } @Override public void subscribe(final Subscriber<? super String> subscriber) { System.out.println("TestObservable subscribed to ..."); - subscriber.onSubscribe(s); + subscriber.onSubscribe(upstream); t = new Thread(new Runnable() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java index 32c906a692..bf8b269196 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java @@ -81,14 +81,14 @@ public void accept(String v) { } }); - Disposable s = f.connect(); + Disposable connection = f.connect(); try { if (!latch.await(1000, TimeUnit.MILLISECONDS)) { fail("subscriptions did not receive values"); } assertEquals(1, counter.get()); } finally { - s.dispose(); + connection.dispose(); } } @@ -275,7 +275,7 @@ public void testSubscribeAfterDisconnectThenConnect() { source.subscribe(ts1); - Disposable s = source.connect(); + Disposable connection = source.connect(); ts1.assertValue(1); ts1.assertNoErrors(); @@ -285,14 +285,14 @@ public void testSubscribeAfterDisconnectThenConnect() { source.subscribe(ts2); - Disposable s2 = source.connect(); + Disposable connection2 = source.connect(); ts2.assertValue(1); ts2.assertNoErrors(); ts2.assertTerminated(); - System.out.println(s); - System.out.println(s2); + System.out.println(connection); + System.out.println(connection2); } @Test @@ -328,18 +328,18 @@ public void testNonNullConnection() { public void testNoDisconnectSomeoneElse() { ConnectableFlowable<Object> source = Flowable.never().publish(); - Disposable s1 = source.connect(); - Disposable s2 = source.connect(); + Disposable connection1 = source.connect(); + Disposable connection2 = source.connect(); - s1.dispose(); + connection1.dispose(); - Disposable s3 = source.connect(); + Disposable connection3 = source.connect(); - s2.dispose(); + connection2.dispose(); - assertTrue(checkPublishDisposed(s1)); - assertTrue(checkPublishDisposed(s2)); - assertFalse(checkPublishDisposed(s3)); + assertTrue(checkPublishDisposed(connection1)); + assertTrue(checkPublishDisposed(connection2)); + assertFalse(checkPublishDisposed(connection3)); } @SuppressWarnings("unchecked") @@ -412,7 +412,7 @@ public void syncFusedObserveOn() { obs.subscribe(ts); } - Disposable s = cf.connect(); + Disposable connection = cf.connect(); for (TestSubscriber<Integer> ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) @@ -421,7 +421,7 @@ public void syncFusedObserveOn() { .assertNoErrors() .assertComplete(); } - s.dispose(); + connection.dispose(); } } } @@ -439,7 +439,7 @@ public void syncFusedObserveOn2() { obs.subscribe(ts); } - Disposable s = cf.connect(); + Disposable connection = cf.connect(); for (TestSubscriber<Integer> ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) @@ -448,7 +448,7 @@ public void syncFusedObserveOn2() { .assertNoErrors() .assertComplete(); } - s.dispose(); + connection.dispose(); } } } @@ -465,7 +465,7 @@ public void asyncFusedObserveOn() { cf.subscribe(ts); } - Disposable s = cf.connect(); + Disposable connection = cf.connect(); for (TestSubscriber<Integer> ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) @@ -474,7 +474,7 @@ public void asyncFusedObserveOn() { .assertNoErrors() .assertComplete(); } - s.dispose(); + connection.dispose(); } } } @@ -492,7 +492,7 @@ public void testObserveOn() { obs.subscribe(ts); } - Disposable s = cf.connect(); + Disposable connection = cf.connect(); for (TestSubscriber<Integer> ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) @@ -501,7 +501,7 @@ public void testObserveOn() { .assertNoErrors() .assertComplete(); } - s.dispose(); + connection.dispose(); } } } @@ -519,7 +519,7 @@ public void connectThrows() { try { cf.connect(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { throw new TestException(); } }); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index acb93684d6..8eefc701e3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -63,14 +63,14 @@ public void accept(Long l) { .publish().refCount(); final AtomicInteger receivedCount = new AtomicInteger(); - Disposable s1 = r.subscribe(new Consumer<Long>() { + Disposable d1 = r.subscribe(new Consumer<Long>() { @Override public void accept(Long l) { receivedCount.incrementAndGet(); } }); - Disposable s2 = r.subscribe(); + Disposable d2 = r.subscribe(); try { Thread.sleep(10); @@ -94,8 +94,8 @@ public void accept(Long l) { // give time to emit // now unsubscribe - s2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one subscriber getting a value but not the other - s1.dispose(); + d2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one subscriber getting a value but not the other + d1.dispose(); System.out.println("onNext: " + nextCount.get()); @@ -125,14 +125,14 @@ public void accept(Integer l) { .publish().refCount(); final AtomicInteger receivedCount = new AtomicInteger(); - Disposable s1 = r.subscribe(new Consumer<Integer>() { + Disposable d1 = r.subscribe(new Consumer<Integer>() { @Override public void accept(Integer l) { receivedCount.incrementAndGet(); } }); - Disposable s2 = r.subscribe(); + Disposable d2 = r.subscribe(); // give time to emit try { @@ -141,8 +141,8 @@ public void accept(Integer l) { } // now unsubscribe - s2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one subscriber getting a value but not the other - s1.dispose(); + d2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one subscriber getting a value but not the other + d1.dispose(); System.out.println("onNext Count: " + nextCount.get()); @@ -386,7 +386,7 @@ public void testRefCount() { // subscribe list1 final List<Long> list1 = new ArrayList<Long>(); - Disposable s1 = interval.subscribe(new Consumer<Long>() { + Disposable d1 = interval.subscribe(new Consumer<Long>() { @Override public void accept(Long t1) { list1.add(t1); @@ -401,7 +401,7 @@ public void accept(Long t1) { // subscribe list2 final List<Long> list2 = new ArrayList<Long>(); - Disposable s2 = interval.subscribe(new Consumer<Long>() { + Disposable d2 = interval.subscribe(new Consumer<Long>() { @Override public void accept(Long t1) { list2.add(t1); @@ -423,7 +423,7 @@ public void accept(Long t1) { assertEquals(4L, list2.get(2).longValue()); // unsubscribe list1 - s1.dispose(); + d1.dispose(); // advance further s.advanceTimeBy(300, TimeUnit.MILLISECONDS); @@ -438,7 +438,7 @@ public void accept(Long t1) { assertEquals(7L, list2.get(5).longValue()); // unsubscribe list2 - s2.dispose(); + d2.dispose(); // advance further s.advanceTimeBy(1000, TimeUnit.MILLISECONDS); @@ -694,14 +694,14 @@ public Object call() throws Exception { .replay(1) .refCount(); - Disposable s1 = source.subscribe(); - Disposable s2 = source.subscribe(); + Disposable d1 = source.subscribe(); + Disposable d2 = source.subscribe(); - s1.dispose(); - s2.dispose(); + d1.dispose(); + d2.dispose(); - s1 = null; - s2 = null; + d1 = null; + d2 = null; System.gc(); Thread.sleep(100); @@ -765,14 +765,14 @@ public Object call() throws Exception { .publish() .refCount(); - Disposable s1 = source.test(); - Disposable s2 = source.test(); + Disposable d1 = source.test(); + Disposable d2 = source.test(); - s1.dispose(); - s2.dispose(); + d1.dispose(); + d2.dispose(); - s1 = null; - s2 = null; + d1 = null; + d2 = null; System.gc(); Thread.sleep(100); @@ -790,11 +790,11 @@ public void replayIsUnsubscribed() { assertTrue(((Disposable)cf).isDisposed()); - Disposable s = cf.connect(); + Disposable connection = cf.connect(); assertFalse(((Disposable)cf).isDisposed()); - s.dispose(); + connection.dispose(); assertTrue(((Disposable)cf).isDisposed()); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java index 428eefa467..702f4660e1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java @@ -156,10 +156,10 @@ public void testTakeUntilOtherCompleted() { private static class TestObservable implements Publisher<String> { Subscriber<? super String> subscriber; - Subscription s; + Subscription upstream; TestObservable(Subscription s) { - this.s = s; + this.upstream = s; } /* used to simulate subscription */ @@ -180,7 +180,7 @@ public void sendOnError(Throwable e) { @Override public void subscribe(Subscriber<? super String> subscriber) { this.subscriber = subscriber; - subscriber.onSubscribe(s); + subscriber.onSubscribe(upstream); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java index f05b8e9fae..97eac27982 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java @@ -191,19 +191,19 @@ public boolean test(String s) { private static class TestFlowable implements Publisher<String> { - final Subscription s; + final Subscription upstream; final String[] values; Thread t; TestFlowable(Subscription s, String... values) { - this.s = s; + this.upstream = s; this.values = values; } @Override public void subscribe(final Subscriber<? super String> subscriber) { System.out.println("TestFlowable subscribed to ..."); - subscriber.onSubscribe(s); + subscriber.onSubscribe(upstream); t = new Thread(new Runnable() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java index ad3869f4ac..b67437e7a9 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java @@ -53,8 +53,8 @@ public void accept(Resource r) { private final Consumer<Disposable> disposeSubscription = new Consumer<Disposable>() { @Override - public void accept(Disposable s) { - s.dispose(); + public void accept(Disposable d) { + d.dispose(); } }; @@ -186,7 +186,7 @@ public Disposable call() { Function<Disposable, Flowable<Integer>> observableFactory = new Function<Disposable, Flowable<Integer>>() { @Override - public Flowable<Integer> apply(Disposable s) { + public Flowable<Integer> apply(Disposable d) { return Flowable.empty(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnEventTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnEventTest.java index 81930eb12c..19389db622 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnEventTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnEventTest.java @@ -70,7 +70,7 @@ protected void subscribeActual(MaybeObserver<? super Integer> observer) { } .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { throw new TestException("First"); } }) diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java index c44782fa3c..450129d175 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowableTest.java @@ -299,24 +299,24 @@ public Iterable<Integer> apply(Object v) throws Exception { return Arrays.asList(1, 2, 3); } }).subscribe(new FlowableSubscriber<Integer>() { - QueueSubscription<Integer> qd; + QueueSubscription<Integer> qs; @SuppressWarnings("unchecked") @Override - public void onSubscribe(Subscription d) { - qd = (QueueSubscription<Integer>)d; + public void onSubscribe(Subscription s) { + qs = (QueueSubscription<Integer>)s; - assertEquals(QueueFuseable.ASYNC, qd.requestFusion(QueueFuseable.ANY)); + assertEquals(QueueFuseable.ASYNC, qs.requestFusion(QueueFuseable.ANY)); } @Override public void onNext(Integer value) { - assertFalse(qd.isEmpty()); + assertFalse(qs.isEmpty()); - qd.clear(); + qs.clear(); - assertTrue(qd.isEmpty()); + assertTrue(qs.isEmpty()); - qd.cancel(); + qs.cancel(); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java index b5833c1941..38ce04fdf0 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMergeArrayTest.java @@ -62,23 +62,23 @@ public void fusedPollMixed() { public void fusedEmptyCheck() { Maybe.mergeArray(Maybe.just(1), Maybe.<Integer>empty(), Maybe.just(2)) .subscribe(new FlowableSubscriber<Integer>() { - QueueSubscription<Integer> qd; + QueueSubscription<Integer> qs; @Override - public void onSubscribe(Subscription d) { - qd = (QueueSubscription<Integer>)d; + public void onSubscribe(Subscription s) { + qs = (QueueSubscription<Integer>)s; - assertEquals(QueueFuseable.ASYNC, qd.requestFusion(QueueFuseable.ANY)); + assertEquals(QueueFuseable.ASYNC, qs.requestFusion(QueueFuseable.ANY)); } @Override public void onNext(Integer value) { - assertFalse(qd.isEmpty()); + assertFalse(qs.isEmpty()); - qd.clear(); + qs.clear(); - assertTrue(qd.isEmpty()); + assertTrue(qs.isEmpty()); - qd.cancel(); + qs.cancel(); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java index 497b2894d9..ee4d58adf5 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java @@ -165,7 +165,7 @@ public void testSubscriptionOnlyHappensOnce() throws InterruptedException { final AtomicLong count = new AtomicLong(); Consumer<Disposable> incrementer = new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { count.incrementAndGet(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java index f074441875..a9b6dc6faa 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java @@ -471,7 +471,7 @@ public void testConcatUnsubscribeConcurrent() { static class TestObservable<T> implements ObservableSource<T> { - private final Disposable s = new Disposable() { + private final Disposable upstream = new Disposable() { @Override public void dispose() { subscribed = false; @@ -514,7 +514,7 @@ public boolean isDisposed() { @Override public void subscribe(final Observer<? super T> observer) { - observer.onSubscribe(s); + observer.onSubscribe(upstream); t = new Thread(new Runnable() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java index 5cdb2bed8b..82738bd4de 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java @@ -355,27 +355,27 @@ public void clearIsEmpty() { .subscribe(new Observer<Integer>() { @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { @SuppressWarnings("unchecked") - QueueDisposable<Integer> qs = (QueueDisposable<Integer>)s; + QueueDisposable<Integer> qd = (QueueDisposable<Integer>)d; - qs.requestFusion(QueueFuseable.ANY); + qd.requestFusion(QueueFuseable.ANY); - assertFalse(qs.isEmpty()); + assertFalse(qd.isEmpty()); try { - assertEquals(1, qs.poll().intValue()); + assertEquals(1, qd.poll().intValue()); } catch (Throwable ex) { throw new RuntimeException(ex); } - assertFalse(qs.isEmpty()); + assertFalse(qd.isEmpty()); - qs.clear(); + qd.clear(); - assertTrue(qs.isEmpty()); + assertTrue(qd.isEmpty()); - qs.dispose(); + qd.dispose(); } @Override @@ -402,31 +402,31 @@ public void clearIsEmptyConditional() { .subscribe(new Observer<Integer>() { @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { @SuppressWarnings("unchecked") - QueueDisposable<Integer> qs = (QueueDisposable<Integer>)s; + QueueDisposable<Integer> qd = (QueueDisposable<Integer>)d; - qs.requestFusion(QueueFuseable.ANY); + qd.requestFusion(QueueFuseable.ANY); - assertFalse(qs.isEmpty()); + assertFalse(qd.isEmpty()); - assertFalse(qs.isDisposed()); + assertFalse(qd.isDisposed()); try { - assertEquals(1, qs.poll().intValue()); + assertEquals(1, qd.poll().intValue()); } catch (Throwable ex) { throw new RuntimeException(ex); } - assertFalse(qs.isEmpty()); + assertFalse(qd.isEmpty()); - qs.clear(); + qd.clear(); - assertTrue(qs.isEmpty()); + assertTrue(qd.isEmpty()); - qs.dispose(); + qd.dispose(); - assertTrue(qs.isDisposed()); + assertTrue(qd.isDisposed()); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnSubscribeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnSubscribeTest.java index 93143efe77..76b9737959 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnSubscribeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnSubscribeTest.java @@ -33,7 +33,7 @@ public void testDoOnSubscribe() throws Exception { final AtomicInteger count = new AtomicInteger(); Observable<Integer> o = Observable.just(1).doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { count.incrementAndGet(); } }); @@ -49,12 +49,12 @@ public void testDoOnSubscribe2() throws Exception { final AtomicInteger count = new AtomicInteger(); Observable<Integer> o = Observable.just(1).doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { count.incrementAndGet(); } }).take(1).doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { count.incrementAndGet(); } }); @@ -80,13 +80,13 @@ public void subscribe(Observer<? super Integer> observer) { }).doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { countBefore.incrementAndGet(); } }).publish().refCount() .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { countAfter.incrementAndGet(); } }); @@ -122,7 +122,7 @@ protected void subscribeActual(Observer<? super Integer> observer) { } .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { throw new TestException("First"); } }) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index 9e40bd1925..17382f4dad 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -308,7 +308,7 @@ public void testFlatMapTransformsMergeException() { private static <T> Observable<T> composer(Observable<T> source, final AtomicInteger subscriptionCount, final int m) { return source.doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { int n = subscriptionCount.getAndIncrement(); if (n >= m) { Assert.fail("Too many subscriptions! " + (n + 1)); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java index 95c892da87..42f441bd10 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java @@ -1370,12 +1370,12 @@ public void accept(String s) { @Test public void testGroupByUnsubscribe() { - final Disposable s = mock(Disposable.class); + final Disposable upstream = mock(Disposable.class); Observable<Integer> o = Observable.unsafeCreate( new ObservableSource<Integer>() { @Override public void subscribe(Observer<? super Integer> observer) { - observer.onSubscribe(s); + observer.onSubscribe(upstream); } } ); @@ -1391,7 +1391,7 @@ public Integer apply(Integer integer) { to.dispose(); - verify(s).dispose(); + verify(upstream).dispose(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java index 53f3bff298..3f902cb4a4 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java @@ -202,7 +202,7 @@ public void onComplete() { } @Override - public void onSubscribe(Disposable s) { + public void onSubscribe(Disposable d) { } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java index bd6d291d33..c178b3bddc 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java @@ -133,14 +133,14 @@ public void testUnSubscribeObservableOfObservables() throws InterruptedException @Override public void subscribe(final Observer<? super Observable<Long>> observer) { // verbose on purpose so I can track the inside of it - final Disposable s = Disposables.fromRunnable(new Runnable() { + final Disposable upstream = Disposables.fromRunnable(new Runnable() { @Override public void run() { System.out.println("*** unsubscribed"); unsubscribed.set(true); } }); - observer.onSubscribe(s); + observer.onSubscribe(upstream); new Thread(new Runnable() { @@ -502,12 +502,12 @@ public void subscribe(final Observer<? super Long> child) { .take(5) .subscribe(new Observer<Long>() { @Override - public void onSubscribe(final Disposable s) { + public void onSubscribe(final Disposable d) { child.onSubscribe(Disposables.fromRunnable(new Runnable() { @Override public void run() { unsubscribed.set(true); - s.dispose(); + d.dispose(); } })); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java index 3330d8cd85..1ac99fcb5e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java @@ -635,11 +635,11 @@ public void outputFusedCancelReentrant() throws Exception { us.observeOn(Schedulers.single()) .subscribe(new Observer<Integer>() { - Disposable d; + Disposable upstream; int count; @Override public void onSubscribe(Disposable d) { - this.d = d; + this.upstream = d; ((QueueDisposable<?>)d).requestFusion(QueueFuseable.ANY); } @@ -647,7 +647,7 @@ public void onSubscribe(Disposable d) { public void onNext(Integer value) { if (++count == 1) { us.onNext(2); - d.dispose(); + upstream.dispose(); cdl.countDown(); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java index 9ba3738ce6..b8b3f67f1e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java @@ -191,8 +191,8 @@ public Observer<? super Integer> apply(final Observer<? super String> t1) { return new Observer<Integer>() { @Override - public void onSubscribe(Disposable s) { - t1.onSubscribe(s); + public void onSubscribe(Disposable d) { + t1.onSubscribe(d); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java index 71f9a809fe..3dab17f83f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java @@ -29,9 +29,9 @@ public class ObservableOnErrorResumeNextViaObservableTest { @Test public void testResumeNext() { - Disposable s = mock(Disposable.class); + Disposable upstream = mock(Disposable.class); // Trigger failure on second element - TestObservable f = new TestObservable(s, "one", "fail", "two", "three"); + TestObservable f = new TestObservable(upstream, "one", "fail", "two", "three"); Observable<String> w = Observable.unsafeCreate(f); Observable<String> resume = Observable.just("twoResume", "threeResume"); Observable<String> observable = w.onErrorResumeNext(resume); @@ -146,19 +146,19 @@ public void subscribe(Observer<? super String> t1) { static class TestObservable implements ObservableSource<String> { - final Disposable s; + final Disposable upstream; final String[] values; Thread t; - TestObservable(Disposable s, String... values) { - this.s = s; + TestObservable(Disposable upstream, String... values) { + this.upstream = upstream; this.values = values; } @Override public void subscribe(final Observer<? super String> observer) { System.out.println("TestObservable subscribed to ..."); - observer.onSubscribe(s); + observer.onSubscribe(upstream); t = new Thread(new Runnable() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java index 86194a7bf7..18251f8f78 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java @@ -79,14 +79,14 @@ public void accept(String v) { } }); - Disposable s = o.connect(); + Disposable connection = o.connect(); try { if (!latch.await(1000, TimeUnit.MILLISECONDS)) { fail("subscriptions did not receive values"); } assertEquals(1, counter.get()); } finally { - s.dispose(); + connection.dispose(); } } @@ -273,7 +273,7 @@ public void testSubscribeAfterDisconnectThenConnect() { source.subscribe(to1); - Disposable s = source.connect(); + Disposable connection = source.connect(); to1.assertValue(1); to1.assertNoErrors(); @@ -283,14 +283,14 @@ public void testSubscribeAfterDisconnectThenConnect() { source.subscribe(to2); - Disposable s2 = source.connect(); + Disposable connection2 = source.connect(); to2.assertValue(1); to2.assertNoErrors(); to2.assertTerminated(); - System.out.println(s); - System.out.println(s2); + System.out.println(connection); + System.out.println(connection2); } @Test @@ -326,18 +326,18 @@ public void testNonNullConnection() { public void testNoDisconnectSomeoneElse() { ConnectableObservable<Object> source = Observable.never().publish(); - Disposable s1 = source.connect(); - Disposable s2 = source.connect(); + Disposable connection1 = source.connect(); + Disposable connection2 = source.connect(); - s1.dispose(); + connection1.dispose(); - Disposable s3 = source.connect(); + Disposable connection3 = source.connect(); - s2.dispose(); + connection2.dispose(); - assertTrue(checkPublishDisposed(s1)); - assertTrue(checkPublishDisposed(s2)); - assertFalse(checkPublishDisposed(s3)); + assertTrue(checkPublishDisposed(connection1)); + assertTrue(checkPublishDisposed(connection2)); + assertFalse(checkPublishDisposed(connection3)); } @SuppressWarnings("unchecked") @@ -385,7 +385,7 @@ public void testObserveOn() { obs.subscribe(to); } - Disposable s = co.connect(); + Disposable connection = co.connect(); for (TestObserver<Integer> to : tos) { to.awaitTerminalEvent(2, TimeUnit.SECONDS); @@ -393,7 +393,7 @@ public void testObserveOn() { to.assertNoErrors(); assertEquals(1000, to.valueCount()); } - s.dispose(); + connection.dispose(); } } } @@ -459,7 +459,7 @@ public void connectThrows() { try { co.connect(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { throw new TestException(); } }); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index 381b2b964b..37efa77570 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -50,7 +50,7 @@ public void testRefCountAsync() { Observable<Long> r = Observable.interval(0, 25, TimeUnit.MILLISECONDS) .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { subscribeCount.incrementAndGet(); } }) @@ -63,14 +63,14 @@ public void accept(Long l) { .publish().refCount(); final AtomicInteger receivedCount = new AtomicInteger(); - Disposable s1 = r.subscribe(new Consumer<Long>() { + Disposable d1 = r.subscribe(new Consumer<Long>() { @Override public void accept(Long l) { receivedCount.incrementAndGet(); } }); - Disposable s2 = r.subscribe(); + Disposable d2 = r.subscribe(); // give time to emit try { @@ -79,8 +79,8 @@ public void accept(Long l) { } // now unsubscribe - s2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one Observer getting a value but not the other - s1.dispose(); + d2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one Observer getting a value but not the other + d1.dispose(); System.out.println("onNext: " + nextCount.get()); @@ -97,7 +97,7 @@ public void testRefCountSynchronous() { Observable<Integer> r = Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9) .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { subscribeCount.incrementAndGet(); } }) @@ -110,14 +110,14 @@ public void accept(Integer l) { .publish().refCount(); final AtomicInteger receivedCount = new AtomicInteger(); - Disposable s1 = r.subscribe(new Consumer<Integer>() { + Disposable d1 = r.subscribe(new Consumer<Integer>() { @Override public void accept(Integer l) { receivedCount.incrementAndGet(); } }); - Disposable s2 = r.subscribe(); + Disposable d2 = r.subscribe(); // give time to emit try { @@ -126,8 +126,8 @@ public void accept(Integer l) { } // now unsubscribe - s2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one Observer getting a value but not the other - s1.dispose(); + d2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one Observer getting a value but not the other + d1.dispose(); System.out.println("onNext Count: " + nextCount.get()); @@ -172,7 +172,7 @@ public void testRepeat() { Observable<Long> r = Observable.interval(0, 1, TimeUnit.MILLISECONDS) .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { System.out.println("******************************* Subscribe received"); // when we are subscribed subscribeCount.incrementAndGet(); @@ -217,7 +217,7 @@ public void testConnectUnsubscribe() throws InterruptedException { Observable<Long> o = synchronousInterval() .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { System.out.println("******************************* Subscribe received"); // when we are subscribed subscribeLatch.countDown(); @@ -271,7 +271,7 @@ public void run() { }) .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { System.out.println("******************************* SUBSCRIBE received"); subUnsubCount.incrementAndGet(); } @@ -367,7 +367,7 @@ public void testRefCount() { // subscribe list1 final List<Long> list1 = new ArrayList<Long>(); - Disposable s1 = interval.subscribe(new Consumer<Long>() { + Disposable d1 = interval.subscribe(new Consumer<Long>() { @Override public void accept(Long t1) { list1.add(t1); @@ -382,7 +382,7 @@ public void accept(Long t1) { // subscribe list2 final List<Long> list2 = new ArrayList<Long>(); - Disposable s2 = interval.subscribe(new Consumer<Long>() { + Disposable d2 = interval.subscribe(new Consumer<Long>() { @Override public void accept(Long t1) { list2.add(t1); @@ -404,7 +404,7 @@ public void accept(Long t1) { assertEquals(4L, list2.get(2).longValue()); // unsubscribe list1 - s1.dispose(); + d1.dispose(); // advance further s.advanceTimeBy(300, TimeUnit.MILLISECONDS); @@ -419,7 +419,7 @@ public void accept(Long t1) { assertEquals(7L, list2.get(5).longValue()); // unsubscribe list2 - s2.dispose(); + d2.dispose(); // advance further s.advanceTimeBy(1000, TimeUnit.MILLISECONDS); @@ -519,7 +519,7 @@ public void testUpstreamErrorAllowsRetry() throws InterruptedException { Observable.interval(200,TimeUnit.MILLISECONDS) .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { System.out.println("Subscribing to interval " + intervalSubscribed.incrementAndGet()); } } @@ -671,14 +671,14 @@ public Object call() throws Exception { .replay(1) .refCount(); - Disposable s1 = source.subscribe(); - Disposable s2 = source.subscribe(); + Disposable d1 = source.subscribe(); + Disposable d2 = source.subscribe(); - s1.dispose(); - s2.dispose(); + d1.dispose(); + d2.dispose(); - s1 = null; - s2 = null; + d1 = null; + d2 = null; System.gc(); Thread.sleep(100); @@ -742,14 +742,14 @@ public Object call() throws Exception { .publish() .refCount(); - Disposable s1 = source.test(); - Disposable s2 = source.test(); + Disposable d1 = source.test(); + Disposable d2 = source.test(); - s1.dispose(); - s2.dispose(); + d1.dispose(); + d2.dispose(); - s1 = null; - s2 = null; + d1 = null; + d2 = null; System.gc(); Thread.sleep(100); @@ -767,11 +767,11 @@ public void replayIsUnsubscribed() { assertTrue(((Disposable)co).isDisposed()); - Disposable s = co.connect(); + Disposable connection = co.connect(); assertFalse(((Disposable)co).isDisposed()); - s.dispose(); + connection.dispose(); assertTrue(((Disposable)co).isDisposed()); } @@ -992,7 +992,7 @@ public void byCount() { Observable<Integer> source = Observable.range(1, 5) .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { subscriptions[0]++; } }) @@ -1022,7 +1022,7 @@ public void resubscribeBeforeTimeout() throws Exception { Observable<Integer> source = ps .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { subscriptions[0]++; } }) @@ -1065,7 +1065,7 @@ public void letitTimeout() throws Exception { Observable<Integer> source = ps .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { subscriptions[0]++; } }) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java index 3ad79160a0..01f04653f2 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java @@ -266,17 +266,17 @@ public void sampleWithSamplerThrows() { @Test public void testSampleUnsubscribe() { - final Disposable s = mock(Disposable.class); + final Disposable upstream = mock(Disposable.class); Observable<Integer> o = Observable.unsafeCreate( new ObservableSource<Integer>() { @Override public void subscribe(Observer<? super Integer> observer) { - observer.onSubscribe(s); + observer.onSubscribe(upstream); } } ); o.throttleLast(1, TimeUnit.MILLISECONDS).subscribe().dispose(); - verify(s).dispose(); + verify(upstream).dispose(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmptyTest.java index 482c6f84d6..20c5018d01 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmptyTest.java @@ -35,7 +35,7 @@ public void testSwitchWhenNotEmpty() throws Exception { .switchIfEmpty(Observable.just(2) .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { + public void accept(Disposable d) { subscribed.set(true); } })); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java index 4251fcc108..d78129e2ea 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java @@ -156,10 +156,10 @@ public void testTakeUntilOtherCompleted() { private static class TestObservable implements ObservableSource<String> { Observer<? super String> observer; - Disposable s; + Disposable upstream; - TestObservable(Disposable s) { - this.s = s; + TestObservable(Disposable d) { + this.upstream = d; } /* used to simulate subscription */ @@ -180,7 +180,7 @@ public void sendOnError(Throwable e) { @Override public void subscribe(Observer<? super String> observer) { this.observer = observer; - observer.onSubscribe(s); + observer.onSubscribe(upstream); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeWhileTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeWhileTest.java index 4b615de665..6a92491a87 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeWhileTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeWhileTest.java @@ -145,8 +145,8 @@ public boolean test(String s) { @Test public void testUnsubscribeAfterTake() { - Disposable s = mock(Disposable.class); - TestObservable w = new TestObservable(s, "one", "two", "three"); + Disposable upstream = mock(Disposable.class); + TestObservable w = new TestObservable(upstream, "one", "two", "three"); Observer<String> observer = TestHelper.mockObserver(); Observable<String> take = Observable.unsafeCreate(w) @@ -172,24 +172,24 @@ public boolean test(String s) { verify(observer, times(1)).onNext("one"); verify(observer, never()).onNext("two"); verify(observer, never()).onNext("three"); - verify(s, times(1)).dispose(); + verify(upstream, times(1)).dispose(); } private static class TestObservable implements ObservableSource<String> { - final Disposable s; + final Disposable upstream; final String[] values; Thread t; - TestObservable(Disposable s, String... values) { - this.s = s; + TestObservable(Disposable upstream, String... values) { + this.upstream = upstream; this.values = values; } @Override public void subscribe(final Observer<? super String> observer) { System.out.println("TestObservable subscribed to ..."); - observer.onSubscribe(s); + observer.onSubscribe(upstream); t = new Thread(new Runnable() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java index 07e7c4c39b..21e8caea84 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java @@ -274,12 +274,12 @@ public void subscribe(Observer<? super String> observer) { @Test public void shouldUnsubscribeFromUnderlyingSubscriptionOnTimeout() throws InterruptedException { // From https://github.com/ReactiveX/RxJava/pull/951 - final Disposable s = mock(Disposable.class); + final Disposable upstream = mock(Disposable.class); Observable<String> never = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { - observer.onSubscribe(s); + observer.onSubscribe(upstream); } }); @@ -296,19 +296,19 @@ public void subscribe(Observer<? super String> observer) { inOrder.verify(observer).onError(isA(TimeoutException.class)); inOrder.verifyNoMoreInteractions(); - verify(s, times(1)).dispose(); + verify(upstream, times(1)).dispose(); } @Test @Ignore("s should be considered cancelled upon executing onComplete and not expect downstream to call cancel") public void shouldUnsubscribeFromUnderlyingSubscriptionOnImmediatelyComplete() { // From https://github.com/ReactiveX/RxJava/pull/951 - final Disposable s = mock(Disposable.class); + final Disposable upstream = mock(Disposable.class); Observable<String> immediatelyComplete = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { - observer.onSubscribe(s); + observer.onSubscribe(upstream); observer.onComplete(); } }); @@ -327,19 +327,19 @@ public void subscribe(Observer<? super String> observer) { inOrder.verify(observer).onComplete(); inOrder.verifyNoMoreInteractions(); - verify(s, times(1)).dispose(); + verify(upstream, times(1)).dispose(); } @Test @Ignore("s should be considered cancelled upon executing onError and not expect downstream to call cancel") public void shouldUnsubscribeFromUnderlyingSubscriptionOnImmediatelyErrored() throws InterruptedException { // From https://github.com/ReactiveX/RxJava/pull/951 - final Disposable s = mock(Disposable.class); + final Disposable upstream = mock(Disposable.class); Observable<String> immediatelyError = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { - observer.onSubscribe(s); + observer.onSubscribe(upstream); observer.onError(new IOException("Error")); } }); @@ -358,7 +358,7 @@ public void subscribe(Observer<? super String> observer) { inOrder.verify(observer).onError(isA(IOException.class)); inOrder.verifyNoMoreInteractions(); - verify(s, times(1)).dispose(); + verify(upstream, times(1)).dispose(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java index 4d38f049e7..3dad40f34a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java @@ -824,7 +824,7 @@ public void disposedUpfront() { Observable<Object> timeoutAndFallback = Observable.never().doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { counter.incrementAndGet(); } }); @@ -844,7 +844,7 @@ public void disposedUpfrontFallback() { Observable<Object> timeoutAndFallback = Observable.never().doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { counter.incrementAndGet(); } }); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java index 4276e3bc95..286bb7d4a9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java @@ -52,8 +52,8 @@ public void accept(Resource r) { private final Consumer<Disposable> disposeSubscription = new Consumer<Disposable>() { @Override - public void accept(Disposable s) { - s.dispose(); + public void accept(Disposable d) { + d.dispose(); } }; @@ -185,7 +185,7 @@ public Disposable call() { Function<Disposable, Observable<Integer>> observableFactory = new Function<Disposable, Observable<Integer>>() { @Override - public Observable<Integer> apply(Disposable s) { + public Observable<Integer> apply(Disposable d) { return Observable.empty(); } }; diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTest.java index 8422a44c12..ff524df77a 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTest.java @@ -94,7 +94,7 @@ public void doOnSubscribeNormal() { Single.just(1).doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { count[0]++; } }) @@ -110,7 +110,7 @@ public void doOnSubscribeError() { Single.error(new TestException()).doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { count[0]++; } }) @@ -125,7 +125,7 @@ public void doOnSubscribeJustCrash() { Single.just(1).doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { throw new TestException(); } }) @@ -140,7 +140,7 @@ public void doOnSubscribeErrorCrash() { try { Single.error(new TestException("Outer")).doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { throw new TestException("Inner"); } }) @@ -344,7 +344,7 @@ protected void subscribeActual(SingleObserver<? super Integer> observer) { } .doOnSubscribe(new Consumer<Disposable>() { @Override - public void accept(Disposable s) throws Exception { + public void accept(Disposable d) throws Exception { throw new TestException("First"); } }) diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java index 086f72f838..1839772b67 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowableTest.java @@ -286,24 +286,24 @@ public Iterable<Integer> apply(Object v) throws Exception { return Arrays.asList(1, 2, 3); } }).subscribe(new FlowableSubscriber<Integer>() { - QueueSubscription<Integer> qd; + QueueSubscription<Integer> qs; @SuppressWarnings("unchecked") @Override - public void onSubscribe(Subscription d) { - qd = (QueueSubscription<Integer>)d; + public void onSubscribe(Subscription s) { + qs = (QueueSubscription<Integer>)s; - assertEquals(QueueFuseable.ASYNC, qd.requestFusion(QueueFuseable.ANY)); + assertEquals(QueueFuseable.ASYNC, qs.requestFusion(QueueFuseable.ANY)); } @Override public void onNext(Integer value) { - assertFalse(qd.isEmpty()); + assertFalse(qs.isEmpty()); - qd.clear(); + qs.clear(); - assertTrue(qd.isEmpty()); + assertTrue(qs.isEmpty()); - qd.cancel(); + qs.cancel(); } @Override diff --git a/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java index c6ec1c24ee..8643924bad 100644 --- a/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java @@ -401,8 +401,8 @@ static final class TestingDeferredScalarSubscriber extends DeferredScalarSubscri private static final long serialVersionUID = 6285096158319517837L; - TestingDeferredScalarSubscriber(Subscriber<? super Integer> actual) { - super(actual); + TestingDeferredScalarSubscriber(Subscriber<? super Integer> downstream) { + super(downstream); } @Override diff --git a/src/test/java/io/reactivex/internal/subscribers/StrictSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/StrictSubscriberTest.java index 0850149811..f8a3ccdb21 100644 --- a/src/test/java/io/reactivex/internal/subscribers/StrictSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/StrictSubscriberTest.java @@ -230,10 +230,10 @@ public void cancelAfterOnComplete() { final List<Object> list = new ArrayList<Object>(); Subscriber<Object> sub = new Subscriber<Object>() { - Subscription s; + Subscription upstream; @Override public void onSubscribe(Subscription s) { - this.s = s; + this.upstream = s; } @Override @@ -243,13 +243,13 @@ public void onNext(Object t) { @Override public void onError(Throwable t) { - s.cancel(); + upstream.cancel(); list.add(t); } @Override public void onComplete() { - s.cancel(); + upstream.cancel(); list.add("Done"); } }; @@ -272,10 +272,10 @@ public void cancelAfterOnError() { final List<Object> list = new ArrayList<Object>(); Subscriber<Object> sub = new Subscriber<Object>() { - Subscription s; + Subscription upstream; @Override public void onSubscribe(Subscription s) { - this.s = s; + this.upstream = s; } @Override @@ -285,13 +285,13 @@ public void onNext(Object t) { @Override public void onError(Throwable t) { - s.cancel(); + upstream.cancel(); list.add(t.getMessage()); } @Override public void onComplete() { - s.cancel(); + upstream.cancel(); list.add("Done"); } }; diff --git a/src/test/java/io/reactivex/internal/util/EndConsumerHelperTest.java b/src/test/java/io/reactivex/internal/util/EndConsumerHelperTest.java index fa07598d30..9fbddd4279 100644 --- a/src/test/java/io/reactivex/internal/util/EndConsumerHelperTest.java +++ b/src/test/java/io/reactivex/internal/util/EndConsumerHelperTest.java @@ -482,11 +482,11 @@ public void validateDisposable() { @Test public void validateSubscription() { - BooleanSubscription d1 = new BooleanSubscription(); + BooleanSubscription bs1 = new BooleanSubscription(); - assertFalse(EndConsumerHelper.validate(SubscriptionHelper.CANCELLED, d1, getClass())); + assertFalse(EndConsumerHelper.validate(SubscriptionHelper.CANCELLED, bs1, getClass())); - assertTrue(d1.isCancelled()); + assertTrue(bs1.isCancelled()); assertTrue(errors.toString(), errors.isEmpty()); } diff --git a/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java b/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java index b66f5d5671..dcf4981856 100644 --- a/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java +++ b/src/test/java/io/reactivex/internal/util/HalfSerializerObserverTest.java @@ -34,12 +34,12 @@ public void reentrantOnNextOnNext() { final Observer[] a = { null }; - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observer observer = new Observer() { @Override - public void onSubscribe(Disposable s) { - ts.onSubscribe(s); + public void onSubscribe(Disposable d) { + to.onSubscribe(d); } @Override @@ -47,17 +47,17 @@ public void onNext(Object t) { if (t.equals(1)) { HalfSerializer.onNext(a[0], 2, wip, error); } - ts.onNext(t); + to.onNext(t); } @Override public void onError(Throwable t) { - ts.onError(t); + to.onError(t); } @Override public void onComplete() { - ts.onComplete(); + to.onComplete(); } }; @@ -67,7 +67,7 @@ public void onComplete() { HalfSerializer.onNext(observer, 1, wip, error); - ts.assertValue(1).assertNoErrors().assertNotComplete(); + to.assertValue(1).assertNoErrors().assertNotComplete(); } @Test @@ -78,12 +78,12 @@ public void reentrantOnNextOnError() { final Observer[] a = { null }; - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observer observer = new Observer() { @Override - public void onSubscribe(Disposable s) { - ts.onSubscribe(s); + public void onSubscribe(Disposable d) { + to.onSubscribe(d); } @Override @@ -91,17 +91,17 @@ public void onNext(Object t) { if (t.equals(1)) { HalfSerializer.onError(a[0], new TestException(), wip, error); } - ts.onNext(t); + to.onNext(t); } @Override public void onError(Throwable t) { - ts.onError(t); + to.onError(t); } @Override public void onComplete() { - ts.onComplete(); + to.onComplete(); } }; @@ -111,7 +111,7 @@ public void onComplete() { HalfSerializer.onNext(observer, 1, wip, error); - ts.assertFailure(TestException.class, 1); + to.assertFailure(TestException.class, 1); } @Test @@ -122,12 +122,12 @@ public void reentrantOnNextOnComplete() { final Observer[] a = { null }; - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observer observer = new Observer() { @Override - public void onSubscribe(Disposable s) { - ts.onSubscribe(s); + public void onSubscribe(Disposable d) { + to.onSubscribe(d); } @Override @@ -135,17 +135,17 @@ public void onNext(Object t) { if (t.equals(1)) { HalfSerializer.onComplete(a[0], wip, error); } - ts.onNext(t); + to.onNext(t); } @Override public void onError(Throwable t) { - ts.onError(t); + to.onError(t); } @Override public void onComplete() { - ts.onComplete(); + to.onComplete(); } }; @@ -155,7 +155,7 @@ public void onComplete() { HalfSerializer.onNext(observer, 1, wip, error); - ts.assertResult(1); + to.assertResult(1); } @Test @@ -166,28 +166,28 @@ public void reentrantErrorOnError() { final Observer[] a = { null }; - final TestObserver ts = new TestObserver(); + final TestObserver to = new TestObserver(); Observer observer = new Observer() { @Override - public void onSubscribe(Disposable s) { - ts.onSubscribe(s); + public void onSubscribe(Disposable d) { + to.onSubscribe(d); } @Override public void onNext(Object t) { - ts.onNext(t); + to.onNext(t); } @Override public void onError(Throwable t) { - ts.onError(t); + to.onError(t); HalfSerializer.onError(a[0], new IOException(), wip, error); } @Override public void onComplete() { - ts.onComplete(); + to.onComplete(); } }; @@ -197,7 +197,7 @@ public void onComplete() { HalfSerializer.onError(observer, new TestException(), wip, error); - ts.assertFailure(TestException.class); + to.assertFailure(TestException.class); } @Test diff --git a/src/test/java/io/reactivex/observable/ObservableNullTests.java b/src/test/java/io/reactivex/observable/ObservableNullTests.java index d04c324dfe..7a429c4555 100644 --- a/src/test/java/io/reactivex/observable/ObservableNullTests.java +++ b/src/test/java/io/reactivex/observable/ObservableNullTests.java @@ -1301,7 +1301,7 @@ public void doOnLifecycleOnSubscribeNull() { public void doOnLifecycleOnDisposeNull() { just1.doOnLifecycle(new Consumer<Disposable>() { @Override - public void accept(Disposable s) { } + public void accept(Disposable d) { } }, null); } diff --git a/src/test/java/io/reactivex/observable/ObservableTest.java b/src/test/java/io/reactivex/observable/ObservableTest.java index 64c5059bf8..fbe071714b 100644 --- a/src/test/java/io/reactivex/observable/ObservableTest.java +++ b/src/test/java/io/reactivex/observable/ObservableTest.java @@ -566,7 +566,7 @@ public void run() { }).replay(); // we connect immediately and it will emit the value - Disposable s = o.connect(); + Disposable connection = o.connect(); try { // we then expect the following 2 subscriptions to get that same value @@ -595,7 +595,7 @@ public void accept(String v) { } assertEquals(1, counter.get()); } finally { - s.dispose(); + connection.dispose(); } } diff --git a/src/test/java/io/reactivex/observers/SafeObserverTest.java b/src/test/java/io/reactivex/observers/SafeObserverTest.java index 54d1269138..12c355905f 100644 --- a/src/test/java/io/reactivex/observers/SafeObserverTest.java +++ b/src/test/java/io/reactivex/observers/SafeObserverTest.java @@ -485,7 +485,7 @@ public void onComplete() { }; SafeObserver<Integer> observer = new SafeObserver<Integer>(actual); - assertSame(actual, observer.actual); + assertSame(actual, observer.downstream); } @Test diff --git a/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java b/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java index baa37e3fee..48da2c566f 100644 --- a/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java +++ b/src/test/java/io/reactivex/parallel/ParallelFromPublisherTest.java @@ -80,13 +80,13 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class StripBoundarySubscriber<T> extends BasicFuseableSubscriber<T, T> { - StripBoundarySubscriber(Subscriber<? super T> actual) { - super(actual); + StripBoundarySubscriber(Subscriber<? super T> downstream) { + super(downstream); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override diff --git a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java index 9fa9cc92d0..a8c9668731 100644 --- a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java +++ b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java @@ -712,8 +712,8 @@ public Subscriber apply(Flowable f, final Subscriber t) { return new Subscriber() { @Override - public void onSubscribe(Subscription d) { - t.onSubscribe(d); + public void onSubscribe(Subscription s) { + t.onSubscribe(s); } @SuppressWarnings("unchecked") diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index 75c013d996..fc5635d975 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -354,11 +354,11 @@ public void onNext(String v) { public void testSubscriptionLeak() { ReplayProcessor<Object> replaySubject = ReplayProcessor.create(); - Disposable s = replaySubject.subscribe(); + Disposable connection = replaySubject.subscribe(); assertEquals(1, replaySubject.subscriberCount()); - s.dispose(); + connection.dispose(); assertEquals(0, replaySubject.subscriberCount()); } diff --git a/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java b/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java index 4e53fbcf42..954981a91e 100644 --- a/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java @@ -189,13 +189,13 @@ public void run() { Scheduler custom = Schedulers.from(exec); Worker w = custom.createWorker(); try { - Disposable s1 = w.schedule(task); - Disposable s2 = w.schedule(task); - Disposable s3 = w.schedule(task); + Disposable d1 = w.schedule(task); + Disposable d2 = w.schedule(task); + Disposable d3 = w.schedule(task); - s1.dispose(); - s2.dispose(); - s3.dispose(); + d1.dispose(); + d2.dispose(); + d3.dispose(); exec.executeAll(); @@ -258,11 +258,11 @@ public void run() { // }; // ExecutorWorker w = (ExecutorWorker)Schedulers.from(e).createWorker(); // -// Disposable s = w.schedule(Functions.emptyRunnable(), 1, TimeUnit.DAYS); +// Disposable task = w.schedule(Functions.emptyRunnable(), 1, TimeUnit.DAYS); // // assertTrue(w.tasks.hasSubscriptions()); // -// s.dispose(); +// task.dispose(); // // assertFalse(w.tasks.hasSubscriptions()); // } @@ -285,13 +285,13 @@ public void run() { // } // }; // -// Disposable s = w.schedulePeriodically(action, 0, 1, TimeUnit.DAYS); +// Disposable task = w.schedulePeriodically(action, 0, 1, TimeUnit.DAYS); // // assertTrue(w.tasks.hasSubscriptions()); // // cdl.await(); // -// s.dispose(); +// task.dispose(); // // assertFalse(w.tasks.hasSubscriptions()); // } diff --git a/src/test/java/io/reactivex/schedulers/SchedulerLifecycleTest.java b/src/test/java/io/reactivex/schedulers/SchedulerLifecycleTest.java index 66ed876967..7f3098ef90 100644 --- a/src/test/java/io/reactivex/schedulers/SchedulerLifecycleTest.java +++ b/src/test/java/io/reactivex/schedulers/SchedulerLifecycleTest.java @@ -73,23 +73,23 @@ public void run() { } }; - CompositeDisposable csub = new CompositeDisposable(); + CompositeDisposable cd = new CompositeDisposable(); try { Worker w1 = Schedulers.computation().createWorker(); - csub.add(w1); + cd.add(w1); w1.schedule(countAction); Worker w2 = Schedulers.io().createWorker(); - csub.add(w2); + cd.add(w2); w2.schedule(countAction); Worker w3 = Schedulers.newThread().createWorker(); - csub.add(w3); + cd.add(w3); w3.schedule(countAction); Worker w4 = Schedulers.single().createWorker(); - csub.add(w4); + cd.add(w4); w4.schedule(countAction); @@ -97,7 +97,7 @@ public void run() { fail("countAction was not run by every worker"); } } finally { - csub.dispose(); + cd.dispose(); } } diff --git a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java index 3d93324d94..12f4116814 100644 --- a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java @@ -533,9 +533,9 @@ public void onSubscribeCancelsImmediately() { ps.subscribe(new Observer<Integer>() { @Override - public void onSubscribe(Disposable s) { - s.dispose(); - s.dispose(); + public void onSubscribe(Disposable d) { + d.dispose(); + d.dispose(); } @Override diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java index 870b53e2d9..24d9704b8a 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java @@ -352,11 +352,11 @@ public void onNext(String v) { public void testSubscriptionLeak() { ReplaySubject<Object> subject = ReplaySubject.create(); - Disposable s = subject.subscribe(); + Disposable d = subject.subscribe(); assertEquals(1, subject.observerCount()); - s.dispose(); + d.dispose(); assertEquals(0, subject.observerCount()); } diff --git a/src/test/java/io/reactivex/subscribers/DisposableSubscriberTest.java b/src/test/java/io/reactivex/subscribers/DisposableSubscriberTest.java index 8e49bdea3d..d6ec19dd7c 100644 --- a/src/test/java/io/reactivex/subscribers/DisposableSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/DisposableSubscriberTest.java @@ -86,11 +86,11 @@ public void startOnce() { tc.onSubscribe(new BooleanSubscription()); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - tc.onSubscribe(d); + tc.onSubscribe(bs); - assertTrue(d.isCancelled()); + assertTrue(bs.isCancelled()); assertEquals(1, tc.start); @@ -110,11 +110,11 @@ public void dispose() { assertTrue(tc.isDisposed()); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - tc.onSubscribe(d); + tc.onSubscribe(bs); - assertTrue(d.isCancelled()); + assertTrue(bs.isCancelled()); assertEquals(0, tc.start); } diff --git a/src/test/java/io/reactivex/subscribers/ResourceSubscriberTest.java b/src/test/java/io/reactivex/subscribers/ResourceSubscriberTest.java index 1623765865..bcaf51acf1 100644 --- a/src/test/java/io/reactivex/subscribers/ResourceSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/ResourceSubscriberTest.java @@ -164,11 +164,11 @@ public void startOnce() { tc.onSubscribe(new BooleanSubscription()); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - tc.onSubscribe(d); + tc.onSubscribe(bs); - assertTrue(d.isCancelled()); + assertTrue(bs.isCancelled()); assertEquals(1, tc.start); @@ -183,11 +183,11 @@ public void dispose() { TestResourceSubscriber<Integer> tc = new TestResourceSubscriber<Integer>(); tc.dispose(); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - tc.onSubscribe(d); + tc.onSubscribe(bs); - assertTrue(d.isCancelled()); + assertTrue(bs.isCancelled()); assertEquals(0, tc.start); } diff --git a/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java b/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java index 2e1893d2f8..d66a1ceecf 100644 --- a/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java @@ -612,7 +612,7 @@ public void onComplete() { }; SafeSubscriber<Integer> s = new SafeSubscriber<Integer>(actual); - assertSame(actual, s.actual); + assertSame(actual, s.downstream); } @Test @@ -621,13 +621,13 @@ public void dispose() { SafeSubscriber<Integer> so = new SafeSubscriber<Integer>(ts); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); ts.dispose(); - assertTrue(d.isCancelled()); + assertTrue(bs.isCancelled()); // assertTrue(so.isDisposed()); } @@ -638,9 +638,9 @@ public void onNextAfterComplete() { SafeSubscriber<Integer> so = new SafeSubscriber<Integer>(ts); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); so.onComplete(); @@ -659,9 +659,9 @@ public void onNextNull() { SafeSubscriber<Integer> so = new SafeSubscriber<Integer>(ts); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); so.onNext(null); @@ -710,9 +710,9 @@ public void onNextNormal() { SafeSubscriber<Integer> so = new SafeSubscriber<Integer>(ts); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); so.onNext(1); so.onComplete(); diff --git a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java index 44d2920699..a6d4d4411f 100644 --- a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java @@ -1005,13 +1005,13 @@ public void dispose() { SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); ts.cancel(); - assertTrue(d.isCancelled()); + assertTrue(bs.isCancelled()); } @Test @@ -1021,9 +1021,9 @@ public void onCompleteRace() { final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); Runnable r = new Runnable() { @Override @@ -1047,9 +1047,9 @@ public void onNextOnCompleteRace() { final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); Runnable r1 = new Runnable() { @Override @@ -1083,9 +1083,9 @@ public void onNextOnErrorRace() { final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); final Throwable ex = new TestException(); @@ -1121,9 +1121,9 @@ public void onNextOnErrorRaceDelayError() { final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts, true); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); final Throwable ex = new TestException(); @@ -1164,11 +1164,11 @@ public void startOnce() { so.onSubscribe(new BooleanSubscription()); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); - assertTrue(d.isCancelled()); + assertTrue(bs.isCancelled()); TestHelper.assertError(error, 0, IllegalStateException.class, "Subscription already set!"); } finally { @@ -1183,9 +1183,9 @@ public void onCompleteOnErrorRace() { final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts); - BooleanSubscription d = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(d); + so.onSubscribe(bs); final Throwable ex = new TestException(); diff --git a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java index a720be050c..85cd58baad 100644 --- a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java @@ -1369,22 +1369,22 @@ public void onSubscribe() { ts.onSubscribe(new BooleanSubscription()); - BooleanSubscription d1 = new BooleanSubscription(); + BooleanSubscription bs1 = new BooleanSubscription(); - ts.onSubscribe(d1); + ts.onSubscribe(bs1); - assertTrue(d1.isCancelled()); + assertTrue(bs1.isCancelled()); ts.assertError(IllegalStateException.class); ts = TestSubscriber.create(); ts.dispose(); - d1 = new BooleanSubscription(); + bs1 = new BooleanSubscription(); - ts.onSubscribe(d1); + ts.onSubscribe(bs1); - assertTrue(d1.isCancelled()); + assertTrue(bs1.isCancelled()); } @@ -1544,7 +1544,7 @@ public void completeDelegateThrows() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(new FlowableSubscriber<Integer>() { @Override - public void onSubscribe(Subscription d) { + public void onSubscribe(Subscription s) { } @@ -1580,7 +1580,7 @@ public void errorDelegateThrows() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(new FlowableSubscriber<Integer>() { @Override - public void onSubscribe(Subscription d) { + public void onSubscribe(Subscription s) { } diff --git a/src/test/java/io/reactivex/tck/RefCountProcessor.java b/src/test/java/io/reactivex/tck/RefCountProcessor.java index 43fc5d4064..de0538064b 100644 --- a/src/test/java/io/reactivex/tck/RefCountProcessor.java +++ b/src/test/java/io/reactivex/tck/RefCountProcessor.java @@ -172,14 +172,14 @@ static final class RefCountSubscriber<T> extends AtomicBoolean implements Flowab private static final long serialVersionUID = -4317488092687530631L; - final Subscriber<? super T> actual; + final Subscriber<? super T> downstream; final RefCountProcessor<T> parent; Subscription upstream; RefCountSubscriber(Subscriber<? super T> actual, RefCountProcessor<T> parent) { - this.actual = actual; + this.downstream = actual; this.parent = parent; } @@ -198,22 +198,22 @@ public void cancel() { @Override public void onSubscribe(Subscription s) { this.upstream = s; - actual.onSubscribe(this); + downstream.onSubscribe(this); } @Override public void onNext(T t) { - actual.onNext(t); + downstream.onNext(t); } @Override public void onError(Throwable t) { - actual.onError(t); + downstream.onError(t); } @Override public void onComplete() { - actual.onComplete(); + downstream.onComplete(); } } } diff --git a/src/test/java/io/reactivex/BaseTypeAnnotations.java b/src/test/java/io/reactivex/validators/BaseTypeAnnotations.java similarity index 99% rename from src/test/java/io/reactivex/BaseTypeAnnotations.java rename to src/test/java/io/reactivex/validators/BaseTypeAnnotations.java index 609da2b15a..5445115b44 100644 --- a/src/test/java/io/reactivex/BaseTypeAnnotations.java +++ b/src/test/java/io/reactivex/validators/BaseTypeAnnotations.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import static org.junit.Assert.fail; @@ -20,6 +20,7 @@ import org.junit.Test; import org.reactivestreams.Publisher; +import io.reactivex.*; import io.reactivex.annotations.*; /** diff --git a/src/test/java/io/reactivex/BaseTypeParser.java b/src/test/java/io/reactivex/validators/BaseTypeParser.java similarity index 99% rename from src/test/java/io/reactivex/BaseTypeParser.java rename to src/test/java/io/reactivex/validators/BaseTypeParser.java index 55067f74ce..42903ee386 100644 --- a/src/test/java/io/reactivex/BaseTypeParser.java +++ b/src/test/java/io/reactivex/validators/BaseTypeParser.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import java.io.File; import java.util.*; diff --git a/src/test/java/io/reactivex/CheckLocalVariablesInTests.java b/src/test/java/io/reactivex/validators/CheckLocalVariablesInTests.java similarity index 65% rename from src/test/java/io/reactivex/CheckLocalVariablesInTests.java rename to src/test/java/io/reactivex/validators/CheckLocalVariablesInTests.java index 864dfe4362..9877a66cc1 100644 --- a/src/test/java/io/reactivex/CheckLocalVariablesInTests.java +++ b/src/test/java/io/reactivex/validators/CheckLocalVariablesInTests.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import java.io.*; import java.util.*; @@ -26,11 +26,21 @@ * <li>{@code TestObserver} named as {@code ts*}</li> * <li>{@code PublishProcessor} named as {@code ps*}</li> * <li>{@code PublishSubject} named as {@code pp*}</li> + * <li>{@code Subscription} with single letter name such as "s" or "d"</li> + * <li>{@code Disposable} with single letter name such as "s" or "d"</li> + * <li>{@code Flowable} named as {@code o|observable} + number</li> + * <li>{@code Observable} named as {@code f|flowable} + number</li> + * <li>{@code Subscriber} named as "o" or "observer"</li> + * <li>{@code Observer} named as "s" or "subscriber"</li> * </ul> */ public class CheckLocalVariablesInTests { static void findPattern(String pattern) throws Exception { + findPattern(pattern, false); + } + + static void findPattern(String pattern, boolean checkMain) throws Exception { File f = MaybeNo2Dot0Since.findSource("Flowable"); if (f == null) { System.out.println("Unable to find sources of RxJava"); @@ -44,6 +54,9 @@ static void findPattern(String pattern) throws Exception { File parent = f.getParentFile(); + if (checkMain) { + dirs.offer(new File(parent.getAbsolutePath().replace('\\', '/'))); + } dirs.offer(new File(parent.getAbsolutePath().replace('\\', '/').replace("src/main/java", "src/test/java"))); Pattern p = Pattern.compile(pattern); @@ -114,6 +127,16 @@ public void testObserverAsTs() throws Exception { findPattern("TestObserver<.*>\\s+ts"); } + @Test + public void testSubscriberNoArgAsTo() throws Exception { + findPattern("TestSubscriber\\s+to"); + } + + @Test + public void testObserverNoArgAsTs() throws Exception { + findPattern("TestObserver\\s+ts"); + } + @Test public void publishSubjectAsPp() throws Exception { findPattern("PublishSubject<.*>\\s+pp"); @@ -273,4 +296,126 @@ public void completableAsObservable() throws Exception { public void completableAsFlowable() throws Exception { findPattern("Completable\\s+flowable\\b"); } + + @Test + public void subscriptionAsFieldS() throws Exception { + findPattern("Subscription\\s+s[0-9]?;", true); + } + + @Test + public void subscriptionAsD() throws Exception { + findPattern("Subscription\\s+d[0-9]?", true); + } + + @Test + public void subscriptionAsSubscription() throws Exception { + findPattern("Subscription\\s+subscription[0-9]?;", true); + } + + @Test + public void subscriptionAsDParenthesis() throws Exception { + findPattern("Subscription\\s+d[0-9]?\\)", true); + } + + @Test + public void queueSubscriptionAsD() throws Exception { + findPattern("Subscription<.*>\\s+q?d[0-9]?\\b", true); + } + + @Test + public void booleanSubscriptionAsbd() throws Exception { + findPattern("BooleanSubscription\\s+bd[0-9]?;", true); + } + + @Test + public void atomicSubscriptionAsS() throws Exception { + findPattern("AtomicReference<Subscription>\\s+s[0-9]?;", true); + } + + @Test + public void atomicSubscriptionAsSubscription() throws Exception { + findPattern("AtomicReference<Subscription>\\s+subscription[0-9]?", true); + } + + @Test + public void atomicSubscriptionAsD() throws Exception { + findPattern("AtomicReference<Subscription>\\s+d[0-9]?", true); + } + + @Test + public void disposableAsS() throws Exception { + // the space before makes sure it doesn't match onSubscribe(Subscription) unnecessarily + findPattern("Disposable\\s+s[0-9]?\\b", true); + } + + @Test + public void disposableAsFieldD() throws Exception { + findPattern("Disposable\\s+d[0-9]?;", true); + } + + @Test + public void atomicDisposableAsS() throws Exception { + findPattern("AtomicReference<Disposable>\\s+s[0-9]?", true); + } + + @Test + public void atomicDisposableAsD() throws Exception { + findPattern("AtomicReference<Disposable>\\s+d[0-9]?;", true); + } + + @Test + public void subscriberAsFieldActual() throws Exception { + findPattern("Subscriber<.*>\\s+actual[;\\)]", true); + } + + @Test + public void subscriberNoArgAsFieldActual() throws Exception { + findPattern("Subscriber\\s+actual[;\\)]", true); + } + + @Test + public void subscriberAsFieldS() throws Exception { + findPattern("Subscriber<.*>\\s+s[0-9]?;", true); + } + + @Test + public void observerAsFieldActual() throws Exception { + findPattern("Observer<.*>\\s+actual[;\\)]", true); + } + + @Test + public void observerAsFieldSO() throws Exception { + findPattern("Observer<.*>\\s+[so][0-9]?;", true); + } + + @Test + public void observerNoArgAsFieldActual() throws Exception { + findPattern("Observer\\s+actual[;\\)]", true); + } + + @Test + public void observerNoArgAsFieldCs() throws Exception { + findPattern("Observer\\s+cs[;\\)]", true); + } + + @Test + public void observerNoArgAsFieldSO() throws Exception { + findPattern("Observer\\s+[so][0-9]?;", true); + } + + @Test + public void queueDisposableAsD() throws Exception { + findPattern("Disposable<.*>\\s+q?s[0-9]?\\b", true); + } + + @Test + public void disposableAsDParenthesis() throws Exception { + findPattern("Disposable\\s+s[0-9]?\\)", true); + } + + @Test + public void compositeDisposableAsCs() throws Exception { + findPattern("CompositeDisposable\\s+cs[0-9]?", true); + } + } diff --git a/src/test/java/io/reactivex/FixLicenseHeaders.java b/src/test/java/io/reactivex/validators/FixLicenseHeaders.java similarity index 99% rename from src/test/java/io/reactivex/FixLicenseHeaders.java rename to src/test/java/io/reactivex/validators/FixLicenseHeaders.java index 6cd016a593..3c96e5615e 100644 --- a/src/test/java/io/reactivex/FixLicenseHeaders.java +++ b/src/test/java/io/reactivex/validators/FixLicenseHeaders.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import java.io.*; import java.util.*; diff --git a/src/test/java/io/reactivex/InternalWrongNaming.java b/src/test/java/io/reactivex/validators/InternalWrongNaming.java similarity index 99% rename from src/test/java/io/reactivex/InternalWrongNaming.java rename to src/test/java/io/reactivex/validators/InternalWrongNaming.java index aed20c265d..cbe1cbe104 100644 --- a/src/test/java/io/reactivex/InternalWrongNaming.java +++ b/src/test/java/io/reactivex/validators/InternalWrongNaming.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import java.io.*; import java.util.*; diff --git a/src/test/java/io/reactivex/JavadocFindUnescapedAngleBrackets.java b/src/test/java/io/reactivex/validators/JavadocFindUnescapedAngleBrackets.java similarity index 99% rename from src/test/java/io/reactivex/JavadocFindUnescapedAngleBrackets.java rename to src/test/java/io/reactivex/validators/JavadocFindUnescapedAngleBrackets.java index bf4d2cbff5..1d8354186d 100644 --- a/src/test/java/io/reactivex/JavadocFindUnescapedAngleBrackets.java +++ b/src/test/java/io/reactivex/validators/JavadocFindUnescapedAngleBrackets.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import java.io.*; import java.util.*; diff --git a/src/test/java/io/reactivex/JavadocForAnnotations.java b/src/test/java/io/reactivex/validators/JavadocForAnnotations.java similarity index 99% rename from src/test/java/io/reactivex/JavadocForAnnotations.java rename to src/test/java/io/reactivex/validators/JavadocForAnnotations.java index 45aae9b97e..230a622de7 100644 --- a/src/test/java/io/reactivex/JavadocForAnnotations.java +++ b/src/test/java/io/reactivex/validators/JavadocForAnnotations.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import static org.junit.Assert.fail; @@ -19,6 +19,8 @@ import org.junit.*; +import io.reactivex.*; + /** * Checks the source code of the base reactive types and locates missing * mention of {@code Backpressure:} and {@code Scheduler:} of methods. diff --git a/src/test/java/io/reactivex/JavadocWording.java b/src/test/java/io/reactivex/validators/JavadocWording.java similarity index 99% rename from src/test/java/io/reactivex/JavadocWording.java rename to src/test/java/io/reactivex/validators/JavadocWording.java index 41d50e8d25..c8d01d7b61 100644 --- a/src/test/java/io/reactivex/JavadocWording.java +++ b/src/test/java/io/reactivex/validators/JavadocWording.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import java.util.List; import java.util.regex.Pattern; @@ -19,7 +19,7 @@ import static org.junit.Assert.*; import org.junit.Test; -import io.reactivex.BaseTypeParser.RxMethod; +import io.reactivex.validators.BaseTypeParser.RxMethod; /** * Check if the method wording is consistent with the target base type. diff --git a/src/test/java/io/reactivex/MaybeNo2Dot0Since.java b/src/test/java/io/reactivex/validators/MaybeNo2Dot0Since.java similarity index 98% rename from src/test/java/io/reactivex/MaybeNo2Dot0Since.java rename to src/test/java/io/reactivex/validators/MaybeNo2Dot0Since.java index 774f4ee920..3ee13fbb18 100644 --- a/src/test/java/io/reactivex/MaybeNo2Dot0Since.java +++ b/src/test/java/io/reactivex/validators/MaybeNo2Dot0Since.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import static org.junit.Assert.fail; @@ -20,6 +20,8 @@ import org.junit.Test; +import io.reactivex.Maybe; + /** * Checks the source code of Maybe and finds unnecessary since 2.0 annotations in the * method's javadocs. diff --git a/src/test/java/io/reactivex/NoAnonymousInnerClassesTest.java b/src/test/java/io/reactivex/validators/NoAnonymousInnerClassesTest.java similarity index 98% rename from src/test/java/io/reactivex/NoAnonymousInnerClassesTest.java rename to src/test/java/io/reactivex/validators/NoAnonymousInnerClassesTest.java index c611000c57..e26e3fb91d 100644 --- a/src/test/java/io/reactivex/NoAnonymousInnerClassesTest.java +++ b/src/test/java/io/reactivex/validators/NoAnonymousInnerClassesTest.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import java.io.File; import java.net.URL; diff --git a/src/test/java/io/reactivex/OperatorsAreFinal.java b/src/test/java/io/reactivex/validators/OperatorsAreFinal.java similarity index 98% rename from src/test/java/io/reactivex/OperatorsAreFinal.java rename to src/test/java/io/reactivex/validators/OperatorsAreFinal.java index ae1df8a499..5a149a94c5 100644 --- a/src/test/java/io/reactivex/OperatorsAreFinal.java +++ b/src/test/java/io/reactivex/validators/OperatorsAreFinal.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import java.io.File; import java.lang.reflect.Modifier; diff --git a/src/test/java/io/reactivex/ParamValidationCheckerTest.java b/src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java similarity index 99% rename from src/test/java/io/reactivex/ParamValidationCheckerTest.java rename to src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java index 45c6dcafbf..136ba29581 100644 --- a/src/test/java/io/reactivex/ParamValidationCheckerTest.java +++ b/src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import java.lang.reflect.*; import java.util.*; @@ -20,6 +20,9 @@ import org.junit.Test; import org.reactivestreams.*; +import io.reactivex.*; +import io.reactivex.Observable; +import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; diff --git a/src/test/java/io/reactivex/PublicFinalMethods.java b/src/test/java/io/reactivex/validators/PublicFinalMethods.java similarity index 96% rename from src/test/java/io/reactivex/PublicFinalMethods.java rename to src/test/java/io/reactivex/validators/PublicFinalMethods.java index b71ce574e5..d3d1c47188 100644 --- a/src/test/java/io/reactivex/PublicFinalMethods.java +++ b/src/test/java/io/reactivex/validators/PublicFinalMethods.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import static org.junit.Assert.fail; @@ -19,6 +19,8 @@ import org.junit.Test; +import io.reactivex.*; + /** * Verifies that instance methods of the base reactive classes are all declared final. */ diff --git a/src/test/java/io/reactivex/TextualAorAn.java b/src/test/java/io/reactivex/validators/TextualAorAn.java similarity index 99% rename from src/test/java/io/reactivex/TextualAorAn.java rename to src/test/java/io/reactivex/validators/TextualAorAn.java index 81aba8ccce..b31f40cfa8 100644 --- a/src/test/java/io/reactivex/TextualAorAn.java +++ b/src/test/java/io/reactivex/validators/TextualAorAn.java @@ -11,7 +11,7 @@ * the License for the specific language governing permissions and limitations under the License. */ -package io.reactivex; +package io.reactivex.validators; import java.io.*; import java.util.*; From 3562dfc5d2529efa5de41a7b8689f6847b3fb616 Mon Sep 17 00:00:00 2001 From: Aleksandar Simic <simic.aleksandar87@gmail.com> Date: Sun, 5 Aug 2018 22:40:16 +0200 Subject: [PATCH 258/417] Add marble diagrams for various Single operators (#6141) --- src/main/java/io/reactivex/Single.java | 43 ++++++++++++++++++++------ 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 0a461709df..f75b275a90 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -414,6 +414,8 @@ public static <T> Flowable<T> concatArrayEager(SingleSource<? extends T>... sour /** * Concatenates a Publisher sequence of SingleSources eagerly into a single stream of values. * <p> + * <img width="640" height="307" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatEager.p.png" alt=""> + * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source Publishers as they are observed. The operator buffers the values emitted by these * Publishers and then drains them in order, each one after the previous one completes. @@ -439,6 +441,8 @@ public static <T> Flowable<T> concatEager(Publisher<? extends SingleSource<? ext /** * Concatenates a sequence of SingleSources eagerly into a single stream of values. * <p> + * <img width="640" height="319" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatEager.i.png" alt=""> + * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source SingleSources. The operator buffers the values emitted by these SingleSources and then drains them * in order, each one after the previous one completes. @@ -462,6 +466,8 @@ public static <T> Flowable<T> concatEager(Iterable<? extends SingleSource<? exte /** * Provides an API (via a cold Completable) that bridges the reactive world with the callback-style world. * <p> + * <img width="640" height="454" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.create.png" alt=""> + * <p> * Example: * <pre><code> * Single.<Event>create(emitter -> { @@ -808,6 +814,8 @@ public static <T> Single<T> just(final T item) { /** * Merges an Iterable sequence of SingleSource instances into a single Flowable sequence, * running all SingleSources at once. + * <p> + * <img width="640" height="319" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.i.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -843,6 +851,8 @@ public static <T> Flowable<T> merge(Iterable<? extends SingleSource<? extends T> /** * Merges a Flowable sequence of SingleSource instances into a single Flowable sequence, * running all SingleSources at once. + * <p> + * <img width="640" height="307" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -881,7 +891,7 @@ public static <T> Flowable<T> merge(Publisher<? extends SingleSource<? extends T * Flattens a {@code Single} that emits a {@code Single} into a single {@code Single} that emits the item * emitted by the nested {@code Single}, without any transformation. * <p> - * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.oo.png" alt=""> + * <img width="640" height="412" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.oo.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> @@ -910,7 +920,7 @@ public static <T> Single<T> merge(SingleSource<? extends SingleSource<? extends /** * Flattens two Singles into a single Flowable, without any transformation. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt=""> + * <img width="640" height="414" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt=""> * <p> * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by * using the {@code merge} method. @@ -958,7 +968,7 @@ public static <T> Flowable<T> merge( /** * Flattens three Singles into a single Flowable, without any transformation. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt=""> + * <img width="640" height="366" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.o3.png" alt=""> * <p> * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by using * the {@code merge} method. @@ -1010,7 +1020,7 @@ public static <T> Flowable<T> merge( /** * Flattens four Singles into a single Flowable, without any transformation. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt=""> + * <img width="640" height="362" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.o4.png" alt=""> * <p> * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by using * the {@code merge} method. @@ -1299,6 +1309,8 @@ public static Single<Long> timer(final long delay, final TimeUnit unit, final Sc /** * Compares two SingleSources and emits true if they emit the same value (compared via Object.equals). + * <p> + * <img width="640" height="465" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.equals.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code equals} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1913,6 +1925,8 @@ public static <T, R> Single<R> zipArray(Function<? super Object[], ? extends R> /** * Signals the event of this or the other SingleSource whichever signals first. + * <p> + * <img width="640" height="463" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.ambWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ambWith} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1933,6 +1947,8 @@ public final Single<T> ambWith(SingleSource<? extends T> other) { /** * Calls the specified converter function during assembly time and returns its resulting value. * <p> + * <img width="640" height="553" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.as.png" alt=""> + * <p> * This allows fluent conversion to any other type. * <dl> * <dt><b>Scheduler:</b></dt> @@ -1972,6 +1988,8 @@ public final Single<T> hide() { /** * Transform a Single by applying a particular Transformer function to it. * <p> + * <img width="640" height="612" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.compose.png" alt=""> + * <p> * This method operates on the Single itself whereas {@link #lift} operates on the Single's SingleObservers. * <p> * If the operator you are creating is designed to act on the individual item emitted by a Single, use @@ -2281,7 +2299,10 @@ public final Single<T> delaySubscription(long time, TimeUnit unit, Scheduler sch /** * Calls the specified consumer with the success item after this item has been emitted to the downstream. - * <p>Note that the {@code doAfterSuccess} action is shared between subscriptions and as such + * <p> + * <img width="640" height="460" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doAfterSuccess.png" alt=""> + * <p> + * Note that the {@code doAfterSuccess} action is shared between subscriptions and as such * should be thread-safe. * <dl> * <dt><b>Scheduler:</b></dt> @@ -2301,10 +2322,12 @@ public final Single<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) { /** * Registers an {@link Action} to be called after this Single invokes either onSuccess or onError. - * * <p>Note that the {@code doAfterTerminate} action is shared between subscriptions and as such - * should be thread-safe.</p> * <p> - * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doAfterTerminate.png" alt=""> + * <img width="640" height="460" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doAfterTerminate.png" alt=""> + * <p> + * Note that the {@code doAfterTerminate} action is shared between subscriptions and as such + * should be thread-safe.</p> + * * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doAfterTerminate} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2884,7 +2907,7 @@ public final Single<Boolean> contains(final Object value, final BiPredicate<Obje /** * Flattens this and another Single into a single Flowable, without any transformation. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt=""> + * <img width="640" height="415" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeWith.png" alt=""> * <p> * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by using * the {@code mergeWith} method. @@ -3654,6 +3677,8 @@ private Single<T> timeout0(final long timeout, final TimeUnit unit, final Schedu /** * Calls the specified converter function with the current Single instance * during assembly time and returns its result. + * <p> + * <img width="640" height="553" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.to.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code to} does not operate by default on a particular {@link Scheduler}.</dd> From 1ad606b71f3ebb45282cabe0c7377b0908f3b582 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 7 Aug 2018 08:57:12 +0200 Subject: [PATCH 259/417] 2.x: Add concatArrayEagerDelayError operator (expose feature) (#6143) * 2.x: Add concatArrayEagerDelayError operator (expose feature) * Change text to "Concatenates an array of" --- src/main/java/io/reactivex/Flowable.java | 77 ++++++++++++- src/main/java/io/reactivex/Observable.java | 66 ++++++++++- .../flowable/FlowableConcatMapEagerTest.java | 106 ++++++++++++++++++ .../ObservableConcatMapEagerTest.java | 106 ++++++++++++++++++ .../validators/JavadocForAnnotations.java | 4 +- 5 files changed, 348 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 1afe7b594f..6af68db61d 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -17,6 +17,7 @@ import org.reactivestreams.*; +import io.reactivex.Observable; import io.reactivex.annotations.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; @@ -1415,7 +1416,9 @@ public static <T> Flowable<T> concatArrayDelayError(Publisher<? extends T>... so } /** - * Concatenates a sequence of Publishers eagerly into a single stream of values. + * Concatenates an array of Publishers eagerly into a single stream of values. + * <p> + * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.concatArrayEager.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Publishers. The operator buffers the values emitted by these Publishers and then drains them @@ -1430,7 +1433,7 @@ public static <T> Flowable<T> concatArrayDelayError(Publisher<? extends T>... so * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type - * @param sources a sequence of Publishers that need to be eagerly concatenated + * @param sources an array of Publishers that need to be eagerly concatenated * @return the new Publisher instance with the specified concatenation behavior * @since 2.0 */ @@ -1442,7 +1445,9 @@ public static <T> Flowable<T> concatArrayEager(Publisher<? extends T>... sources } /** - * Concatenates a sequence of Publishers eagerly into a single stream of values. + * Concatenates an array of Publishers eagerly into a single stream of values. + * <p> + * <img width="640" height="406" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.concatArrayEager.nn.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Publishers. The operator buffers the values emitted by these Publishers and then drains them @@ -1457,7 +1462,7 @@ public static <T> Flowable<T> concatArrayEager(Publisher<? extends T>... sources * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type - * @param sources a sequence of Publishers that need to be eagerly concatenated + * @param sources an array of Publishers that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrent subscriptions at a time, Integer.MAX_VALUE * is interpreted as an indication to subscribe to all sources at once * @param prefetch the number of elements to prefetch from each Publisher source @@ -1475,6 +1480,70 @@ public static <T> Flowable<T> concatArrayEager(int maxConcurrency, int prefetch, return RxJavaPlugins.onAssembly(new FlowableConcatMapEager(new FlowableFromArray(sources), Functions.identity(), maxConcurrency, prefetch, ErrorMode.IMMEDIATE)); } + /** + * Concatenates an array of {@link Publisher}s eagerly into a single stream of values + * and delaying any errors until all sources terminate. + * <p> + * <img width="640" height="358" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.concatArrayEagerDelayError.png" alt=""> + * <p> + * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the + * source {@code Publisher}s. The operator buffers the values emitted by these {@code Publisher}s + * and then drains them in order, each one after the previous one completes. + * <dl> + * <dt><b>Backpressure:</b></dt> + * <dd>The operator honors backpressure from downstream. The {@code Publisher} + * sources are expected to honor backpressure as well. + * If any of the source {@code Publisher}s violate this, the operator will signal a + * {@code MissingBackpressureException}.</dd> + * <dt><b>Scheduler:</b></dt> + * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * @param <T> the value type + * @param sources an array of {@code Publisher}s that need to be eagerly concatenated + * @return the new Flowable instance with the specified concatenation behavior + * @since 2.2.1 - experimental + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.FULL) + public static <T> Flowable<T> concatArrayEagerDelayError(Publisher<? extends T>... sources) { + return concatArrayEagerDelayError(bufferSize(), bufferSize(), sources); + } + + /** + * Concatenates an array of {@link Publisher}s eagerly into a single stream of values + * and delaying any errors until all sources terminate. + * <p> + * <img width="640" height="359" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.concatArrayEagerDelayError.nn.png" alt=""> + * <p> + * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the + * source {@code Publisher}s. The operator buffers the values emitted by these {@code Publisher}s + * and then drains them in order, each one after the previous one completes. + * <dl> + * <dt><b>Backpressure:</b></dt> + * <dd>The operator honors backpressure from downstream. The {@code Publisher} + * sources are expected to honor backpressure as well. + * If any of the source {@code Publisher}s violate this, the operator will signal a + * {@code MissingBackpressureException}.</dd> + * <dt><b>Scheduler:</b></dt> + * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * @param <T> the value type + * @param sources an array of {@code Publisher}s that need to be eagerly concatenated + * @param maxConcurrency the maximum number of concurrent subscriptions at a time, Integer.MAX_VALUE + * is interpreted as indication to subscribe to all sources at once + * @param prefetch the number of elements to prefetch from each {@code Publisher} source + * @return the new Flowable instance with the specified concatenation behavior + * @since 2.2.1 - experimental + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.FULL) + public static <T> Flowable<T> concatArrayEagerDelayError(int maxConcurrency, int prefetch, Publisher<? extends T>... sources) { + return fromArray(sources).concatMapEagerDelayError((Function)Functions.identity(), maxConcurrency, prefetch, true); + } + /** * Concatenates the Iterable sequence of Publishers into a single sequence by subscribing to each Publisher, * one after the other, one at a time and delays any errors till the all inner Publishers terminate. diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index ab38ab2374..2c43e0abf0 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -1294,19 +1294,19 @@ public static <T> Observable<T> concatArrayDelayError(ObservableSource<? extends } /** - * Concatenates a sequence of ObservableSources eagerly into a single stream of values. + * Concatenates an array of ObservableSources eagerly into a single stream of values. + * <p> + * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArrayEager.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source ObservableSources. The operator buffers the values emitted by these ObservableSources and then drains them * in order, each one after the previous one completes. - * <p> - * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArrayEager.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type - * @param sources a sequence of ObservableSources that need to be eagerly concatenated + * @param sources an array of ObservableSources that need to be eagerly concatenated * @return the new ObservableSource instance with the specified concatenation behavior * @since 2.0 */ @@ -1317,7 +1317,9 @@ public static <T> Observable<T> concatArrayEager(ObservableSource<? extends T>.. } /** - * Concatenates a sequence of ObservableSources eagerly into a single stream of values. + * Concatenates an array of ObservableSources eagerly into a single stream of values. + * <p> + * <img width="640" height="495" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArrayEager.nn.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source ObservableSources. The operator buffers the values emitted by these ObservableSources and then drains them @@ -1327,7 +1329,7 @@ public static <T> Observable<T> concatArrayEager(ObservableSource<? extends T>.. * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type - * @param sources a sequence of ObservableSources that need to be eagerly concatenated + * @param sources an array of ObservableSources that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrent subscriptions at a time, Integer.MAX_VALUE * is interpreted as indication to subscribe to all sources at once * @param prefetch the number of elements to prefetch from each ObservableSource source @@ -1341,6 +1343,58 @@ public static <T> Observable<T> concatArrayEager(int maxConcurrency, int prefetc return fromArray(sources).concatMapEagerDelayError((Function)Functions.identity(), maxConcurrency, prefetch, false); } + /** + * Concatenates an array of {@link ObservableSource}s eagerly into a single stream of values + * and delaying any errors until all sources terminate. + * <p> + * <img width="640" height="354" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArrayEagerDelayError.png" alt=""> + * <p> + * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the + * source {@code ObservableSource}s. The operator buffers the values emitted by these {@code ObservableSource}s + * and then drains them in order, each one after the previous one completes. + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * @param <T> the value type + * @param sources an array of {@code ObservableSource}s that need to be eagerly concatenated + * @return the new Observable instance with the specified concatenation behavior + * @since 2.2.1 - experimental + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public static <T> Observable<T> concatArrayEagerDelayError(ObservableSource<? extends T>... sources) { + return concatArrayEagerDelayError(bufferSize(), bufferSize(), sources); + } + + /** + * Concatenates an array of {@link ObservableSource}s eagerly into a single stream of values + * and delaying any errors until all sources terminate. + * <p> + * <img width="640" height="460" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArrayEagerDelayError.nn.png" alt=""> + * <p> + * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the + * source {@code ObservableSource}s. The operator buffers the values emitted by these {@code ObservableSource}s + * and then drains them in order, each one after the previous one completes. + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * @param <T> the value type + * @param sources an array of {@code ObservableSource}s that need to be eagerly concatenated + * @param maxConcurrency the maximum number of concurrent subscriptions at a time, Integer.MAX_VALUE + * is interpreted as indication to subscribe to all sources at once + * @param prefetch the number of elements to prefetch from each {@code ObservableSource} source + * @return the new Observable instance with the specified concatenation behavior + * @since 2.2.1 - experimental + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public static <T> Observable<T> concatArrayEagerDelayError(int maxConcurrency, int prefetch, ObservableSource<? extends T>... sources) { + return fromArray(sources).concatMapEagerDelayError((Function)Functions.identity(), maxConcurrency, prefetch, true); + } + /** * Concatenates the Iterable sequence of ObservableSources into a single sequence by subscribing to each ObservableSource, * one after the other, one at a time and delays any errors till the all inner ObservableSources terminate. diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java index 39a9427181..3c77acb502 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java @@ -1228,4 +1228,110 @@ public void accept(List<Integer> v) .awaitDone(5, TimeUnit.SECONDS) .assertResult(list); } + + @Test + public void arrayDelayErrorDefault() { + PublishProcessor<Integer> pp1 = PublishProcessor.create(); + PublishProcessor<Integer> pp2 = PublishProcessor.create(); + PublishProcessor<Integer> pp3 = PublishProcessor.create(); + + @SuppressWarnings("unchecked") + TestSubscriber<Integer> ts = Flowable.concatArrayEagerDelayError(pp1, pp2, pp3) + .test(); + + ts.assertEmpty(); + + assertTrue(pp1.hasSubscribers()); + assertTrue(pp2.hasSubscribers()); + assertTrue(pp3.hasSubscribers()); + + pp2.onNext(2); + pp2.onComplete(); + + ts.assertEmpty(); + + pp1.onNext(1); + + ts.assertValuesOnly(1); + + pp1.onComplete(); + + ts.assertValuesOnly(1, 2); + + pp3.onComplete(); + + ts.assertResult(1, 2); + } + + @Test + public void arrayDelayErrorMaxConcurrency() { + PublishProcessor<Integer> pp1 = PublishProcessor.create(); + PublishProcessor<Integer> pp2 = PublishProcessor.create(); + PublishProcessor<Integer> pp3 = PublishProcessor.create(); + + @SuppressWarnings("unchecked") + TestSubscriber<Integer> ts = Flowable.concatArrayEagerDelayError(2, 2, pp1, pp2, pp3) + .test(); + + ts.assertEmpty(); + + assertTrue(pp1.hasSubscribers()); + assertTrue(pp2.hasSubscribers()); + assertFalse(pp3.hasSubscribers()); + + pp2.onNext(2); + pp2.onComplete(); + + ts.assertEmpty(); + + pp1.onNext(1); + + ts.assertValuesOnly(1); + + pp1.onComplete(); + + assertTrue(pp3.hasSubscribers()); + + ts.assertValuesOnly(1, 2); + + pp3.onComplete(); + + ts.assertResult(1, 2); + } + + @Test + public void arrayDelayErrorMaxConcurrencyErrorDelayed() { + PublishProcessor<Integer> pp1 = PublishProcessor.create(); + PublishProcessor<Integer> pp2 = PublishProcessor.create(); + PublishProcessor<Integer> pp3 = PublishProcessor.create(); + + @SuppressWarnings("unchecked") + TestSubscriber<Integer> ts = Flowable.concatArrayEagerDelayError(2, 2, pp1, pp2, pp3) + .test(); + + ts.assertEmpty(); + + assertTrue(pp1.hasSubscribers()); + assertTrue(pp2.hasSubscribers()); + assertFalse(pp3.hasSubscribers()); + + pp2.onNext(2); + pp2.onError(new TestException()); + + ts.assertEmpty(); + + pp1.onNext(1); + + ts.assertValuesOnly(1); + + pp1.onComplete(); + + assertTrue(pp3.hasSubscribers()); + + ts.assertValuesOnly(1, 2); + + pp3.onComplete(); + + ts.assertFailure(TestException.class, 1, 2); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java index 8874eec137..0f6920ecb3 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java @@ -1036,4 +1036,110 @@ public void accept(List<Integer> v) .awaitDone(5, TimeUnit.SECONDS) .assertResult(list); } + + @Test + public void arrayDelayErrorDefault() { + PublishSubject<Integer> ps1 = PublishSubject.create(); + PublishSubject<Integer> ps2 = PublishSubject.create(); + PublishSubject<Integer> ps3 = PublishSubject.create(); + + @SuppressWarnings("unchecked") + TestObserver<Integer> to = Observable.concatArrayEagerDelayError(ps1, ps2, ps3) + .test(); + + to.assertEmpty(); + + assertTrue(ps1.hasObservers()); + assertTrue(ps2.hasObservers()); + assertTrue(ps3.hasObservers()); + + ps2.onNext(2); + ps2.onComplete(); + + to.assertEmpty(); + + ps1.onNext(1); + + to.assertValuesOnly(1); + + ps1.onComplete(); + + to.assertValuesOnly(1, 2); + + ps3.onComplete(); + + to.assertResult(1, 2); + } + + @Test + public void arrayDelayErrorMaxConcurrency() { + PublishSubject<Integer> ps1 = PublishSubject.create(); + PublishSubject<Integer> ps2 = PublishSubject.create(); + PublishSubject<Integer> ps3 = PublishSubject.create(); + + @SuppressWarnings("unchecked") + TestObserver<Integer> to = Observable.concatArrayEagerDelayError(2, 2, ps1, ps2, ps3) + .test(); + + to.assertEmpty(); + + assertTrue(ps1.hasObservers()); + assertTrue(ps2.hasObservers()); + assertFalse(ps3.hasObservers()); + + ps2.onNext(2); + ps2.onComplete(); + + to.assertEmpty(); + + ps1.onNext(1); + + to.assertValuesOnly(1); + + ps1.onComplete(); + + assertTrue(ps3.hasObservers()); + + to.assertValuesOnly(1, 2); + + ps3.onComplete(); + + to.assertResult(1, 2); + } + + @Test + public void arrayDelayErrorMaxConcurrencyErrorDelayed() { + PublishSubject<Integer> ps1 = PublishSubject.create(); + PublishSubject<Integer> ps2 = PublishSubject.create(); + PublishSubject<Integer> ps3 = PublishSubject.create(); + + @SuppressWarnings("unchecked") + TestObserver<Integer> to = Observable.concatArrayEagerDelayError(2, 2, ps1, ps2, ps3) + .test(); + + to.assertEmpty(); + + assertTrue(ps1.hasObservers()); + assertTrue(ps2.hasObservers()); + assertFalse(ps3.hasObservers()); + + ps2.onNext(2); + ps2.onError(new TestException()); + + to.assertEmpty(); + + ps1.onNext(1); + + to.assertValuesOnly(1); + + ps1.onComplete(); + + assertTrue(ps3.hasObservers()); + + to.assertValuesOnly(1, 2); + + ps3.onComplete(); + + to.assertFailure(TestException.class, 1, 2); + } } diff --git a/src/test/java/io/reactivex/validators/JavadocForAnnotations.java b/src/test/java/io/reactivex/validators/JavadocForAnnotations.java index 230a622de7..9dae922016 100644 --- a/src/test/java/io/reactivex/validators/JavadocForAnnotations.java +++ b/src/test/java/io/reactivex/validators/JavadocForAnnotations.java @@ -129,8 +129,10 @@ static final void scanForBadMethod(StringBuilder sourceCode, String annotation, if ((ll < 0 || ll > idx) && (lm < 0 || lm > idx)) { int n = sourceCode.indexOf("{@code ", k); + int endDD = sourceCode.indexOf("</dd>", k); + // make sure the {@code is within the dt/dd section - if (n < idx) { + if (n < idx && n < endDD) { int m = sourceCode.indexOf("}", n); if (m < idx) { From fd63c492c576a2784a5665925457b75355ecffaa Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 8 Aug 2018 09:42:25 +0200 Subject: [PATCH 260/417] 2.x: Fix boundary fusion of concatMap and publish operator (#6145) --- .../operators/flowable/FlowableConcatMap.java | 2 +- .../operators/flowable/FlowablePublish.java | 16 +-- .../flowable/FlowableConcatMapTest.java | 104 ++++++++++++++++++ .../flowable/FlowablePublishTest.java | 51 +++++++++ 4 files changed, 164 insertions(+), 9 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java index 27016a1dd8..4dc60faa5a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java @@ -113,7 +113,7 @@ public final void onSubscribe(Subscription s) { if (s instanceof QueueSubscription) { @SuppressWarnings("unchecked") QueueSubscription<T> f = (QueueSubscription<T>)s; - int m = f.requestFusion(QueueSubscription.ANY); + int m = f.requestFusion(QueueSubscription.ANY | QueueSubscription.BOUNDARY); if (m == QueueSubscription.SYNC) { sourceMode = m; queue = f; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java index 9bc0d63b65..6122974695 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java @@ -155,7 +155,7 @@ static final class PublishSubscriber<T> */ final AtomicBoolean shouldConnect; - final AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + final AtomicReference<Subscription> upstream = new AtomicReference<Subscription>(); /** Contains either an onComplete or an onError token from upstream. */ volatile Object terminalEvent; @@ -180,7 +180,7 @@ public void dispose() { InnerSubscriber[] ps = subscribers.getAndSet(TERMINATED); if (ps != TERMINATED) { current.compareAndSet(PublishSubscriber.this, null); - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); } } } @@ -192,12 +192,12 @@ public boolean isDisposed() { @Override public void onSubscribe(Subscription s) { - if (SubscriptionHelper.setOnce(this.s, s)) { + if (SubscriptionHelper.setOnce(this.upstream, s)) { if (s instanceof QueueSubscription) { @SuppressWarnings("unchecked") QueueSubscription<T> qs = (QueueSubscription<T>) s; - int m = qs.requestFusion(QueueSubscription.ANY); + int m = qs.requestFusion(QueueSubscription.ANY | QueueSubscription.BOUNDARY); if (m == QueueSubscription.SYNC) { sourceMode = m; queue = qs; @@ -482,7 +482,7 @@ void dispatch() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.get().cancel(); + upstream.get().cancel(); term = NotificationLite.error(ex); terminalEvent = term; v = null; @@ -493,7 +493,7 @@ void dispatch() { } // otherwise, just ask for a new value if (sourceMode != QueueSubscription.SYNC) { - s.get().request(1); + upstream.get().request(1); } // and retry emitting to potential new child subscribers continue; @@ -510,7 +510,7 @@ void dispatch() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.get().cancel(); + upstream.get().cancel(); term = NotificationLite.error(ex); terminalEvent = term; v = null; @@ -562,7 +562,7 @@ void dispatch() { // if we did emit at least one element, request more to replenish the queue if (d > 0) { if (sourceMode != QueueSubscription.SYNC) { - s.get().request(d); + upstream.get().request(d); } } // if we have requests but not an empty queue after emission diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java index c1ad560478..ac5c573910 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java @@ -13,9 +13,16 @@ package io.reactivex.internal.operators.flowable; +import java.util.concurrent.TimeUnit; + import org.junit.Test; +import org.reactivestreams.Publisher; +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; import io.reactivex.internal.operators.flowable.FlowableConcatMap.WeakScalarSubscription; +import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; public class FlowableConcatMapTest { @@ -39,4 +46,101 @@ public void weakSubscriptionRequest() { ts.assertResult(1); } + @Test + public void boundaryFusion() { + Flowable.range(1, 10000) + .observeOn(Schedulers.single()) + .map(new Function<Integer, String>() { + @Override + public String apply(Integer t) throws Exception { + String name = Thread.currentThread().getName(); + if (name.contains("RxSingleScheduler")) { + return "RxSingleScheduler"; + } + return name; + } + }) + .concatMap(new Function<String, Publisher<? extends Object>>() { + @Override + public Publisher<? extends Object> apply(String v) + throws Exception { + return Flowable.just(v); + } + }) + .observeOn(Schedulers.computation()) + .distinct() + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult("RxSingleScheduler"); + } + + @Test + public void boundaryFusionDelayError() { + Flowable.range(1, 10000) + .observeOn(Schedulers.single()) + .map(new Function<Integer, String>() { + @Override + public String apply(Integer t) throws Exception { + String name = Thread.currentThread().getName(); + if (name.contains("RxSingleScheduler")) { + return "RxSingleScheduler"; + } + return name; + } + }) + .concatMapDelayError(new Function<String, Publisher<? extends Object>>() { + @Override + public Publisher<? extends Object> apply(String v) + throws Exception { + return Flowable.just(v); + } + }) + .observeOn(Schedulers.computation()) + .distinct() + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult("RxSingleScheduler"); + } + + @Test + public void pollThrows() { + Flowable.just(1) + .map(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .compose(TestHelper.<Integer>flowableStripBoundary()) + .concatMap(new Function<Integer, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(Integer v) + throws Exception { + return Flowable.just(v); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void pollThrowsDelayError() { + Flowable.just(1) + .map(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .compose(TestHelper.<Integer>flowableStripBoundary()) + .concatMapDelayError(new Function<Integer, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(Integer v) + throws Exception { + return Flowable.just(v); + } + }) + .test() + .assertFailure(TestException.class); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java index bf8b269196..c18cbc928b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java @@ -824,12 +824,36 @@ public Object apply(Integer v) throws Exception { throw new TestException(); } }) + .compose(TestHelper.flowableStripBoundary()) .publish() .autoConnect() .test() .assertFailure(TestException.class); } + @Test + public void pollThrowsNoSubscribers() { + ConnectableFlowable<Integer> cf = Flowable.just(1, 2) + .map(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer v) throws Exception { + if (v == 2) { + throw new TestException(); + } + return v; + } + }) + .compose(TestHelper.<Integer>flowableStripBoundary()) + .publish(); + + TestSubscriber<Integer> ts = cf.take(1) + .test(); + + cf.connect(); + + ts.assertResult(1); + } + @Test public void dryRunCrash() { List<Throwable> errors = TestHelper.trackPluginErrors(); @@ -1316,4 +1340,31 @@ public void onComplete() { ts1.assertEmpty(); ts2.assertValuesOnly(1); } + + @Test + public void boundaryFusion() { + Flowable.range(1, 10000) + .observeOn(Schedulers.single()) + .map(new Function<Integer, String>() { + @Override + public String apply(Integer t) throws Exception { + String name = Thread.currentThread().getName(); + if (name.contains("RxSingleScheduler")) { + return "RxSingleScheduler"; + } + return name; + } + }) + .share() + .observeOn(Schedulers.computation()) + .distinct() + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult("RxSingleScheduler"); + } + + @Test + public void badRequest() { + TestHelper.assertBadRequestReported(Flowable.range(1, 5).publish()); + } } From 10f8c6767b036b8b70bc93a74aa7c62a47431d27 Mon Sep 17 00:00:00 2001 From: spreddy2714 <spreddy2714@gmail.com> Date: Thu, 9 Aug 2018 13:24:35 +0530 Subject: [PATCH 261/417] Grammar fix (#6149) Scheduler description is grammatically error. Replaced "an unifrom" with "a uniform" --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 957d1a05e6..92bdf2946f 100644 --- a/README.md +++ b/README.md @@ -193,7 +193,7 @@ Typically, you can move computations or blocking IO to some other thread via `su ### Schedulers -RxJava operators don't work with `Thread`s or `ExecutorService`s directly but with so called `Scheduler`s that abstract away sources of concurrency behind an uniform API. RxJava 2 features several standard schedulers accessible via `Schedulers` utility class. +RxJava operators don't work with `Thread`s or `ExecutorService`s directly but with so called `Scheduler`s that abstract away sources of concurrency behind a uniform API. RxJava 2 features several standard schedulers accessible via `Schedulers` utility class. - `Schedulers.computation()`: Run computation intensive work on a fixed number of dedicated threads in the background. Most asynchronous operator use this as their default `Scheduler`. - `Schedulers.io()`: Run I/O-like or blocking operations on a dynamically changing set of threads. From 0e7b8eaa61f9cac0538ef6a59bfbd0b119b87732 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 9 Aug 2018 16:35:12 +0200 Subject: [PATCH 262/417] 2.x: cleanup newline separation, some field namings (#6150) * 2.x: cleanup newline separation, some field namings * Fix missed two-empty-line cases --- .../io/reactivex/EachTypeFlatMapPerf.java | 5 + .../io/reactivex/LatchedSingleObserver.java | 3 + src/jmh/java/io/reactivex/PerfObserver.java | 4 + .../io/reactivex/PublishProcessorPerf.java | 3 - src/jmh/java/io/reactivex/ToFlowablePerf.java | 1 + .../internal/disposables/EmptyDisposable.java | 1 - .../observers/DisposableLambdaObserver.java | 1 - .../completable/CompletableFromPublisher.java | 1 - .../completable/CompletablePeek.java | 1 - .../completable/CompletableResumeNext.java | 3 - .../completable/CompletableUsing.java | 1 - .../operators/flowable/FlowableAll.java | 1 + .../operators/flowable/FlowableAllSingle.java | 1 + .../operators/flowable/FlowableAny.java | 1 + .../operators/flowable/FlowableAnySingle.java | 1 + .../flowable/FlowableBufferTimed.java | 1 - .../operators/flowable/FlowableCache.java | 4 + .../operators/flowable/FlowableConcatMap.java | 1 - .../flowable/FlowableDebounceTimed.java | 1 + .../operators/flowable/FlowableDefer.java | 1 + .../flowable/FlowableDematerialize.java | 1 + .../operators/flowable/FlowableError.java | 1 + .../operators/flowable/FlowableFlatMap.java | 5 + .../operators/flowable/FlowableFromArray.java | 2 +- .../flowable/FlowableFromCallable.java | 1 + .../flowable/FlowableFromIterable.java | 2 - .../flowable/FlowableOnBackpressureError.java | 1 - .../operators/flowable/FlowablePublish.java | 2 + .../operators/flowable/FlowableRange.java | 2 +- .../operators/flowable/FlowableRepeat.java | 1 + .../flowable/FlowableRepeatUntil.java | 1 + .../operators/flowable/FlowableReplay.java | 3 + .../flowable/FlowableRetryBiPredicate.java | 1 + .../flowable/FlowableRetryPredicate.java | 1 + .../operators/flowable/FlowableTake.java | 6 + .../flowable/FlowableTimeInterval.java | 1 - .../flowable/FlowableWithLatestFrom.java | 13 +- .../flowable/FlowableWithLatestFromMany.java | 4 +- .../operators/maybe/MaybeSwitchIfEmpty.java | 4 + .../maybe/MaybeSwitchIfEmptySingle.java | 3 + .../mixed/CompletableAndThenObservable.java | 1 - .../operators/observable/ObservableAll.java | 1 + .../observable/ObservableAllSingle.java | 1 + .../operators/observable/ObservableAny.java | 1 + .../observable/ObservableAnySingle.java | 1 + .../observable/ObservableBuffer.java | 1 - .../observable/ObservableBufferTimed.java | 1 - .../operators/observable/ObservableCache.java | 4 + .../observable/ObservableCollect.java | 2 - .../observable/ObservableCollectSingle.java | 2 - .../observable/ObservableCombineLatest.java | 1 - .../observable/ObservableConcatMap.java | 7 + .../operators/observable/ObservableCount.java | 1 - .../observable/ObservableCountSingle.java | 1 - .../observable/ObservableDebounceTimed.java | 1 + .../operators/observable/ObservableDefer.java | 1 + .../observable/ObservableDematerialize.java | 3 +- .../observable/ObservableDoOnEach.java | 2 - .../observable/ObservableElementAt.java | 3 +- .../observable/ObservableElementAtMaybe.java | 3 +- .../observable/ObservableElementAtSingle.java | 2 - .../operators/observable/ObservableError.java | 1 + .../observable/ObservableFlatMap.java | 5 + .../observable/ObservableFromArray.java | 1 + .../observable/ObservableFromCallable.java | 1 + .../observable/ObservableGenerate.java | 1 - .../observable/ObservableMapNotification.java | 2 - .../observable/ObservableMaterialize.java | 1 - .../observable/ObservableOnErrorReturn.java | 1 - .../observable/ObservablePublish.java | 2 + .../observable/ObservableRepeat.java | 1 + .../observable/ObservableRepeatUntil.java | 1 + .../observable/ObservableReplay.java | 4 + .../ObservableRetryBiPredicate.java | 1 + .../observable/ObservableRetryPredicate.java | 1 + .../observable/ObservableSampleTimed.java | 1 - .../operators/observable/ObservableScan.java | 2 - .../observable/ObservableScanSeed.java | 1 - .../observable/ObservableSingleMaybe.java | 3 +- .../observable/ObservableSingleSingle.java | 2 - .../observable/ObservableSkipLast.java | 1 - .../observable/ObservableSkipWhile.java | 2 - .../operators/observable/ObservableTake.java | 4 + .../observable/ObservableTakeUntil.java | 1 + .../observable/ObservableTakeWhile.java | 2 - .../observable/ObservableTimeInterval.java | 1 - .../observable/ObservableToList.java | 2 - .../observable/ObservableToListSingle.java | 2 - .../observable/ObservableWithLatestFrom.java | 1 + .../operators/observable/ObservableZip.java | 1 + .../observable/ObservableZipIterable.java | 2 - .../operators/single/SingleEquals.java | 1 + .../single/SingleInternalHelper.java | 1 + .../operators/single/SingleOnErrorReturn.java | 2 - .../internal/queue/SpscLinkedArrayQueue.java | 2 + .../schedulers/ComputationScheduler.java | 1 + .../internal/schedulers/IoScheduler.java | 1 + .../subscriptions/EmptySubscription.java | 7 + .../internal/util/LinkedArrayList.java | 1 + .../io/reactivex/observers/SafeObserver.java | 1 - .../observers/SerializedObserver.java | 2 - .../processors/PublishProcessor.java | 1 - .../reactivex/processors/ReplayProcessor.java | 2 +- .../io/reactivex/subjects/PublishSubject.java | 1 - .../reactivex/subjects/SerializedSubject.java | 1 - .../subscribers/DisposableSubscriber.java | 12 +- .../subscribers/ResourceSubscriber.java | 10 +- .../completable/CompletableTest.java | 2 +- .../disposables/CompositeDisposableTest.java | 1 + .../exceptions/CompositeExceptionTest.java | 1 + .../OnErrorNotImplementedExceptionTest.java | 1 - .../flowable/FlowableCollectTest.java | 5 - .../reactivex/flowable/FlowableNullTests.java | 1 - .../flowable/FlowableReduceTests.java | 1 - .../flowable/FlowableSubscriberTest.java | 1 - .../io/reactivex/flowable/FlowableTests.java | 2 - .../reactivex/internal/SubscribeWithTest.java | 1 - .../observers/BasicFuseableObserverTest.java | 5 + .../observers/DeferredScalarObserverTest.java | 1 - .../observers/LambdaObserverTest.java | 1 + .../completable/CompletableAmbTest.java | 1 - .../CompletableResumeNextTest.java | 1 - .../completable/CompletableSubscribeTest.java | 1 - .../completable/CompletableUsingTest.java | 1 - .../BlockingFlowableMostRecentTest.java | 1 - .../operators/flowable/FlowableAllTest.java | 2 + .../operators/flowable/FlowableAmbTest.java | 1 - .../operators/flowable/FlowableAnyTest.java | 2 + .../flowable/FlowableAsObservableTest.java | 1 + .../flowable/FlowableBufferTest.java | 11 +- .../operators/flowable/FlowableCacheTest.java | 2 + .../flowable/FlowableCombineLatestTest.java | 1 + .../FlowableConcatDelayErrorTest.java | 1 - .../flowable/FlowableConcatMapEagerTest.java | 1 - .../flowable/FlowableConcatTest.java | 2 + .../flowable/FlowableConcatWithMaybeTest.java | 1 - .../operators/flowable/FlowableCountTest.java | 1 - .../flowable/FlowableCreateTest.java | 1 - .../flowable/FlowableDebounceTest.java | 2 + .../flowable/FlowableDetachTest.java | 1 - .../flowable/FlowableDoFinallyTest.java | 1 - .../flowable/FlowableElementAtTest.java | 2 - .../FlowableFlatMapCompletableTest.java | 2 - .../flowable/FlowableFlatMapTest.java | 4 +- .../flowable/FlowableFromArrayTest.java | 1 + .../flowable/FlowableFromSourceTest.java | 3 - .../flowable/FlowableGroupByTest.java | 1 - .../flowable/FlowableIgnoreElementsTest.java | 1 - .../flowable/FlowableMergeDelayErrorTest.java | 3 +- .../FlowableMergeMaxConcurrentTest.java | 8 + .../operators/flowable/FlowableMergeTest.java | 5 +- .../flowable/FlowableObserveOnTest.java | 1 - .../FlowableOnBackpressureLatestTest.java | 3 + .../flowable/FlowableOnErrorReturnTest.java | 1 - ...eOnExceptionResumeNextViaFlowableTest.java | 1 - .../FlowablePublishMulticastTest.java | 1 - .../flowable/FlowablePublishTest.java | 1 + .../flowable/FlowableRangeLongTest.java | 3 + .../operators/flowable/FlowableRangeTest.java | 5 +- .../flowable/FlowableReduceTest.java | 1 - .../flowable/FlowableReplayTest.java | 2 + .../operators/flowable/FlowableRetryTest.java | 4 +- .../FlowableRetryWithPredicateTest.java | 5 + .../flowable/FlowableSequenceEqualTest.java | 1 - .../flowable/FlowableSingleTest.java | 1 - .../flowable/FlowableSwitchIfEmptyTest.java | 1 + .../flowable/FlowableSwitchTest.java | 1 - .../flowable/FlowableTakeLastTest.java | 1 - .../operators/flowable/FlowableTakeTest.java | 2 - .../FlowableTakeUntilPredicateTest.java | 6 + .../flowable/FlowableTakeUntilTest.java | 2 + .../flowable/FlowableThrottleFirstTest.java | 1 - .../flowable/FlowableThrottleLatestTest.java | 1 - .../flowable/FlowableTimeoutTests.java | 1 - .../operators/flowable/FlowableTimerTest.java | 3 + .../flowable/FlowableToListTest.java | 4 + .../operators/flowable/FlowableToMapTest.java | 1 - .../flowable/FlowableToMultimapTest.java | 1 - .../flowable/FlowableToSortedListTest.java | 2 + .../operators/flowable/FlowableUsingTest.java | 2 - .../FlowableWindowWithFlowableTest.java | 3 +- .../flowable/FlowableWindowWithSizeTest.java | 5 + .../flowable/FlowableWindowWithTimeTest.java | 3 +- .../flowable/FlowableWithLatestFromTest.java | 2 +- .../operators/flowable/FlowableZipTest.java | 4 +- .../operators/maybe/MaybeCacheTest.java | 1 - .../operators/maybe/MaybeContainsTest.java | 1 - .../operators/maybe/MaybeDelayOtherTest.java | 2 - .../operators/maybe/MaybeIsEmptyTest.java | 1 - .../maybe/MaybeSwitchIfEmptySingleTest.java | 1 - .../maybe/MaybeSwitchIfEmptyTest.java | 1 - .../operators/maybe/MaybeUsingTest.java | 1 - .../operators/maybe/MaybeZipArrayTest.java | 1 + .../CompletableAndThenObservableTest.java | 1 - .../mixed/FlowableSwitchMapMaybeTest.java | 1 - .../mixed/FlowableSwitchMapSingleTest.java | 1 - .../mixed/ObservableSwitchMapMaybeTest.java | 1 - .../mixed/ObservableSwitchMapSingleTest.java | 1 - .../observable/ObservableAllTest.java | 5 +- .../observable/ObservableAnyTest.java | 2 + .../observable/ObservableBufferTest.java | 10 ++ .../observable/ObservableCacheTest.java | 1 + .../ObservableConcatMapCompletableTest.java | 1 - .../ObservableConcatMapEagerTest.java | 1 - .../observable/ObservableConcatTest.java | 1 + .../ObservableConcatWithMaybeTest.java | 1 - .../observable/ObservableDebounceTest.java | 2 + .../ObservableDelaySubscriptionOtherTest.java | 1 - .../observable/ObservableDetachTest.java | 1 - .../observable/ObservableDoFinallyTest.java | 2 - .../ObservableFlatMapCompletableTest.java | 2 - .../observable/ObservableFlatMapTest.java | 4 +- .../ObservableMergeDelayErrorTest.java | 1 + .../ObservableMergeMaxConcurrentTest.java | 6 + .../observable/ObservableMergeTest.java | 3 + ...nExceptionResumeNextViaObservableTest.java | 1 - .../observable/ObservablePublishTest.java | 1 + .../observable/ObservableReduceTest.java | 1 - .../observable/ObservableReplayTest.java | 1 + .../observable/ObservableRetryTest.java | 2 + .../ObservableRetryWithPredicateTest.java | 5 + .../observable/ObservableSwitchTest.java | 2 - .../ObservableTakeUntilPredicateTest.java | 5 + .../observable/ObservableTakeUntilTest.java | 3 +- .../ObservableThrottleLatestTest.java | 1 - .../observable/ObservableTimerTest.java | 3 + .../observable/ObservableToMapTest.java | 1 - .../observable/ObservableToMultimapTest.java | 2 - .../ObservableToSortedListTest.java | 1 - .../observable/ObservableUsingTest.java | 2 - .../ObservableWindowWithObservableTest.java | 1 + .../ObservableWindowWithTimeTest.java | 1 + .../ObservableWithLatestFromTest.java | 2 +- .../observable/ObservableZipTest.java | 1 + .../operators/single/SingleConcatTest.java | 1 - .../operators/single/SingleFlatMapTest.java | 1 - .../single/SingleFromCallableTest.java | 1 - .../operators/single/SingleMergeTest.java | 1 - .../operators/single/SingleTakeUntilTest.java | 1 - .../operators/single/SingleZipArrayTest.java | 1 + .../schedulers/AbstractDirectTaskTest.java | 1 + .../ImmediateThinSchedulerTest.java | 1 + .../schedulers/ScheduledRunnableTest.java | 1 - .../subscribers/BlockingSubscriberTest.java | 2 + .../DeferredScalarSubscriberTest.java | 1 + .../InnerQueuedSubscriberTest.java | 4 + .../subscribers/LambdaSubscriberTest.java | 1 + .../subscriptions/SubscriptionHelperTest.java | 52 +++--- .../internal/util/EndConsumerHelperTest.java | 22 +++ .../internal/util/QueueDrainHelperTest.java | 1 + .../io/reactivex/maybe/MaybeCreateTest.java | 1 - .../java/io/reactivex/maybe/MaybeTest.java | 12 +- .../observable/ObservableNullTests.java | 1 - .../observable/ObservableReduceTests.java | 1 - .../observable/ObservableSubscriberTest.java | 1 - .../reactivex/observable/ObservableTest.java | 1 - .../reactivex/observers/SafeObserverTest.java | 4 + .../observers/SerializedObserverTest.java | 1 + .../reactivex/observers/TestObserverTest.java | 1 + .../parallel/ParallelDoOnNextTryTest.java | 1 + .../parallel/ParallelFilterTryTest.java | 1 + .../parallel/ParallelFlowableTest.java | 2 - .../parallel/ParallelMapTryTest.java | 2 + .../reactivex/plugins/RxJavaPluginsTest.java | 1 - .../processors/AsyncProcessorTest.java | 1 + .../processors/BehaviorProcessorTest.java | 5 + .../processors/MulticastProcessorTest.java | 3 - .../processors/PublishProcessorTest.java | 2 + ...ReplayProcessorBoundedConcurrencyTest.java | 4 + .../ReplayProcessorConcurrencyTest.java | 2 + .../processors/ReplayProcessorTest.java | 12 ++ .../processors/SerializedProcessorTest.java | 8 + .../schedulers/ComputationSchedulerTests.java | 1 - .../schedulers/ExecutorSchedulerTest.java | 1 + .../reactivex/schedulers/SchedulerTest.java | 1 - .../schedulers/TestSchedulerTest.java | 4 +- .../io/reactivex/single/SingleNullTests.java | 1 + .../reactivex/subjects/AsyncSubjectTest.java | 2 +- .../subjects/BehaviorSubjectTest.java | 6 +- .../subjects/PublishSubjectTest.java | 2 + .../ReplaySubjectBoundedConcurrencyTest.java | 4 + .../ReplaySubjectConcurrencyTest.java | 2 + .../reactivex/subjects/ReplaySubjectTest.java | 13 +- .../subjects/SerializedSubjectTest.java | 7 + .../subscribers/SafeSubscriberTest.java | 5 +- .../SafeSubscriberWithPluginTest.java | 2 + .../subscribers/SerializedSubscriberTest.java | 1 + .../subscribers/TestSubscriberTest.java | 3 - src/test/java/io/reactivex/tck/BaseTck.java | 1 - .../CheckLocalVariablesInTests.java | 5 + .../validators/NewLinesBeforeAnnotation.java | 162 ++++++++++++++++++ 291 files changed, 607 insertions(+), 262 deletions(-) create mode 100644 src/test/java/io/reactivex/validators/NewLinesBeforeAnnotation.java diff --git a/src/jmh/java/io/reactivex/EachTypeFlatMapPerf.java b/src/jmh/java/io/reactivex/EachTypeFlatMapPerf.java index d8793829f1..7d150960c0 100644 --- a/src/jmh/java/io/reactivex/EachTypeFlatMapPerf.java +++ b/src/jmh/java/io/reactivex/EachTypeFlatMapPerf.java @@ -86,10 +86,12 @@ public Single<Integer> apply(Integer v) { public void bpRange(Blackhole bh) { bpRange.subscribe(new PerfSubscriber(bh)); } + @Benchmark public void bpRangeMapJust(Blackhole bh) { bpRangeMapJust.subscribe(new PerfSubscriber(bh)); } + @Benchmark public void bpRangeMapRange(Blackhole bh) { bpRangeMapRange.subscribe(new PerfSubscriber(bh)); @@ -99,10 +101,12 @@ public void bpRangeMapRange(Blackhole bh) { public void nbpRange(Blackhole bh) { nbpRange.subscribe(new PerfObserver(bh)); } + @Benchmark public void nbpRangeMapJust(Blackhole bh) { nbpRangeMapJust.subscribe(new PerfObserver(bh)); } + @Benchmark public void nbpRangeMapRange(Blackhole bh) { nbpRangeMapRange.subscribe(new PerfObserver(bh)); @@ -112,6 +116,7 @@ public void nbpRangeMapRange(Blackhole bh) { public void singleJust(Blackhole bh) { singleJust.subscribe(new LatchedSingleObserver<Integer>(bh)); } + @Benchmark public void singleJustMapJust(Blackhole bh) { singleJustMapJust.subscribe(new LatchedSingleObserver<Integer>(bh)); diff --git a/src/jmh/java/io/reactivex/LatchedSingleObserver.java b/src/jmh/java/io/reactivex/LatchedSingleObserver.java index 02e74c463e..59b980a0eb 100644 --- a/src/jmh/java/io/reactivex/LatchedSingleObserver.java +++ b/src/jmh/java/io/reactivex/LatchedSingleObserver.java @@ -26,15 +26,18 @@ public LatchedSingleObserver(Blackhole bh) { this.bh = bh; this.cdl = new CountDownLatch(1); } + @Override public void onSubscribe(Disposable d) { } + @Override public void onSuccess(T value) { bh.consume(value); cdl.countDown(); } + @Override public void onError(Throwable e) { e.printStackTrace(); diff --git a/src/jmh/java/io/reactivex/PerfObserver.java b/src/jmh/java/io/reactivex/PerfObserver.java index 33548155ba..8de241e6a0 100644 --- a/src/jmh/java/io/reactivex/PerfObserver.java +++ b/src/jmh/java/io/reactivex/PerfObserver.java @@ -26,19 +26,23 @@ public PerfObserver(Blackhole bh) { this.bh = bh; this.cdl = new CountDownLatch(1); } + @Override public void onSubscribe(Disposable d) { } + @Override public void onNext(Object value) { bh.consume(value); } + @Override public void onError(Throwable e) { e.printStackTrace(); cdl.countDown(); } + @Override public void onComplete() { cdl.countDown(); diff --git a/src/jmh/java/io/reactivex/PublishProcessorPerf.java b/src/jmh/java/io/reactivex/PublishProcessorPerf.java index 37afebfa4f..d9531ab267 100644 --- a/src/jmh/java/io/reactivex/PublishProcessorPerf.java +++ b/src/jmh/java/io/reactivex/PublishProcessorPerf.java @@ -71,7 +71,6 @@ public void bounded1() { bounded.onNext(1); } - @Benchmark public void bounded1k() { for (int i = 0; i < 1000; i++) { @@ -86,13 +85,11 @@ public void bounded1m() { } } - @Benchmark public void subject1() { subject.onNext(1); } - @Benchmark public void subject1k() { for (int i = 0; i < 1000; i++) { diff --git a/src/jmh/java/io/reactivex/ToFlowablePerf.java b/src/jmh/java/io/reactivex/ToFlowablePerf.java index 9bc41083f4..deb97a7e51 100644 --- a/src/jmh/java/io/reactivex/ToFlowablePerf.java +++ b/src/jmh/java/io/reactivex/ToFlowablePerf.java @@ -78,6 +78,7 @@ public Observable<Integer> apply(Integer v) throws Exception { public Object flowable() { return flowable.blockingGet(); } + @Benchmark public Object flowableInner() { return flowableInner.blockingLast(); diff --git a/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java b/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java index 1a00840549..f87df26a17 100644 --- a/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java +++ b/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java @@ -83,7 +83,6 @@ public static void error(Throwable e, MaybeObserver<?> observer) { observer.onError(e); } - @Override public boolean offer(Object value) { throw new UnsupportedOperationException("Should not be called!"); diff --git a/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java b/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java index 47d9990d4f..7e3941e260 100644 --- a/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java +++ b/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java @@ -74,7 +74,6 @@ public void onComplete() { } } - @Override public void dispose() { try { diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromPublisher.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromPublisher.java index 3791931e92..ca33d582c9 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromPublisher.java @@ -53,7 +53,6 @@ public void onSubscribe(Subscription s) { } } - @Override public void onNext(T t) { // ignored diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java b/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java index 327cee0116..02180e4e91 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java @@ -61,7 +61,6 @@ final class CompletableObserverImplementation implements CompletableObserver, Di this.downstream = downstream; } - @Override public void onSubscribe(final Disposable d) { try { diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java index 940942c943..5111d46f32 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableResumeNext.java @@ -34,8 +34,6 @@ public CompletableResumeNext(CompletableSource source, this.errorMapper = errorMapper; } - - @Override protected void subscribeActual(final CompletableObserver observer) { ResumeNextObserver parent = new ResumeNextObserver(observer, errorMapper); @@ -60,7 +58,6 @@ static final class ResumeNextObserver this.errorMapper = errorMapper; } - @Override public void onSubscribe(Disposable d) { DisposableHelper.replace(this, d); diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java index a114199a91..0dc127ec82 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java @@ -40,7 +40,6 @@ public CompletableUsing(Callable<R> resourceSupplier, this.eager = eager; } - @Override protected void subscribeActual(CompletableObserver observer) { R resource; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAll.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAll.java index b3f6076f43..608089ace4 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAll.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAll.java @@ -47,6 +47,7 @@ static final class AllSubscriber<T> extends DeferredScalarSubscription<Boolean> super(actual); this.predicate = predicate; } + @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java index b26087b840..1ec3e9460d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAllSingle.java @@ -57,6 +57,7 @@ static final class AllSubscriber<T> implements FlowableSubscriber<T>, Disposable this.downstream = actual; this.predicate = predicate; } + @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAny.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAny.java index 5a3d7c966f..aed50107e4 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAny.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAny.java @@ -46,6 +46,7 @@ static final class AnySubscriber<T> extends DeferredScalarSubscription<Boolean> super(actual); this.predicate = predicate; } + @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java index 7c665f2ab9..0c30c11107 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableAnySingle.java @@ -56,6 +56,7 @@ static final class AnySubscriber<T> implements FlowableSubscriber<T>, Disposable this.downstream = actual; this.predicate = predicate; } + @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java index 0fb2b19e6a..48212822ff 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java @@ -518,7 +518,6 @@ public boolean accept(Subscriber<? super U> a, U v) { return true; } - @Override public void request(long n) { requested(n); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java index ad4de6050f..db4ccecfa1 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java @@ -200,6 +200,7 @@ public void connect() { source.subscribe(this); isConnected = true; } + @Override public void onNext(T t) { if (!sourceDone) { @@ -210,6 +211,7 @@ public void onNext(T t) { } } } + @SuppressWarnings("unchecked") @Override public void onError(Throwable e) { @@ -225,6 +227,7 @@ public void onError(Throwable e) { RxJavaPlugins.onError(e); } } + @SuppressWarnings("unchecked") @Override public void onComplete() { @@ -284,6 +287,7 @@ static final class ReplaySubscription<T> this.state = state; this.requested = new AtomicLong(); } + @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java index 4dc60faa5a..bb408ef6c8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java @@ -417,7 +417,6 @@ public void innerNext(R value) { downstream.onNext(value); } - @Override public void innerError(Throwable e) { if (errors.addThrowable(e)) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java index 36ece502bd..b30a68c62d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java @@ -125,6 +125,7 @@ public void onComplete() { if (d != null) { d.dispose(); } + @SuppressWarnings("unchecked") DebounceEmitter<T> de = (DebounceEmitter<T>)d; if (de != null) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDefer.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDefer.java index 8a44a0019e..7ac266001f 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDefer.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDefer.java @@ -27,6 +27,7 @@ public final class FlowableDefer<T> extends Flowable<T> { public FlowableDefer(Callable<? extends Publisher<? extends T>> supplier) { this.supplier = supplier; } + @Override public void subscribeActual(Subscriber<? super T> s) { Publisher<? extends T> pub; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java index 6257f48803..930f5aaee6 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java @@ -79,6 +79,7 @@ public void onError(Throwable t) { downstream.onError(t); } + @Override public void onComplete() { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableError.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableError.java index b74ad1d871..dc88f01d7e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableError.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableError.java @@ -27,6 +27,7 @@ public final class FlowableError<T> extends Flowable<T> { public FlowableError(Callable<? extends Throwable> errorSupplier) { this.errorSupplier = errorSupplier; } + @Override public void subscribeActual(Subscriber<? super T> s) { Throwable error; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java index 07e2b20db3..c68e82bb93 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java @@ -461,6 +461,7 @@ void drainLoop() { if (checkTerminate()) { return; } + @SuppressWarnings("unchecked") InnerSubscriber<T, U> is = (InnerSubscriber<T, U>)inner[j]; @@ -629,6 +630,7 @@ static final class InnerSubscriber<T, U> extends AtomicReference<Subscription> this.bufferSize = parent.bufferSize; this.limit = bufferSize >> 2; } + @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.setOnce(this, s)) { @@ -654,6 +656,7 @@ public void onSubscribe(Subscription s) { s.request(bufferSize); } } + @Override public void onNext(U t) { if (fusionMode != QueueSubscription.ASYNC) { @@ -662,11 +665,13 @@ public void onNext(U t) { parent.drain(); } } + @Override public void onError(Throwable t) { lazySet(SubscriptionHelper.CANCELLED); parent.innerError(this, t); } + @Override public void onComplete() { done = true; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java index 462a72481f..25b7610eaa 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java @@ -28,6 +28,7 @@ public final class FlowableFromArray<T> extends Flowable<T> { public FlowableFromArray(T[] array) { this.array = array; } + @Override public void subscribeActual(Subscriber<? super T> s) { if (s instanceof ConditionalSubscriber) { @@ -92,7 +93,6 @@ public final void request(long n) { } } - @Override public final void cancel() { cancelled = true; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromCallable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromCallable.java index 4920c9f206..5a773dffc4 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromCallable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromCallable.java @@ -27,6 +27,7 @@ public final class FlowableFromCallable<T> extends Flowable<T> implements Callab public FlowableFromCallable(Callable<? extends T> callable) { this.callable = callable; } + @Override public void subscribeActual(Subscriber<? super T> s) { DeferredScalarSubscription<T> deferred = new DeferredScalarSubscription<T>(s); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java index 9cf14837b6..3c3017bcfb 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java @@ -104,7 +104,6 @@ public final T poll() { return ObjectHelper.requireNonNull(it.next(), "Iterator.next() returned a null value"); } - @Override public final boolean isEmpty() { return it == null || !it.hasNext(); @@ -128,7 +127,6 @@ public final void request(long n) { } } - @Override public final void cancel() { cancelled = true; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java index 139e61d410..5d758096c3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java @@ -30,7 +30,6 @@ public FlowableOnBackpressureError(Flowable<T> source) { super(source); } - @Override protected void subscribeActual(Subscriber<? super T> s) { this.source.subscribe(new BackpressureErrorSubscriber<T>(s)); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java index 6122974695..0e08551495 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java @@ -230,6 +230,7 @@ public void onNext(T t) { // loop to act on the current state serially dispatch(); } + @Override public void onError(Throwable e) { // The observer front is accessed serially as required by spec so @@ -243,6 +244,7 @@ public void onError(Throwable e) { RxJavaPlugins.onError(e); } } + @Override public void onComplete() { // The observer front is accessed serially as required by spec so diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java index 198721943b..185218480e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java @@ -31,6 +31,7 @@ public FlowableRange(int start, int count) { this.start = start; this.end = start + count; } + @Override public void subscribeActual(Subscriber<? super Integer> s) { if (s instanceof ConditionalSubscriber) { @@ -94,7 +95,6 @@ public final void request(long n) { } } - @Override public final void cancel() { cancelled = true; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java index fe48ac17ea..f99bc48a20 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java @@ -64,6 +64,7 @@ public void onNext(T t) { produced++; downstream.onNext(t); } + @Override public void onError(Throwable t) { downstream.onError(t); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java index e2dbd532e8..d373a3865d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java @@ -66,6 +66,7 @@ public void onNext(T t) { produced++; downstream.onNext(t); } + @Override public void onError(Throwable t) { downstream.onError(t); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java index 7a837f5809..51943b9c48 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java @@ -409,6 +409,7 @@ public void onError(Throwable e) { RxJavaPlugins.onError(e); } } + @SuppressWarnings("unchecked") @Override public void onComplete() { @@ -624,6 +625,7 @@ static final class UnboundedReplayBuffer<T> extends ArrayList<Object> implements UnboundedReplayBuffer(int capacityHint) { super(capacityHint); } + @Override public void next(T value) { add(NotificationLite.next(value)); @@ -1037,6 +1039,7 @@ void truncate() { setFirst(prev); } } + @Override void truncateFinal() { long timeLimit = scheduler.now(unit) - maxAge; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java index a049d76d51..662ddb694c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java @@ -70,6 +70,7 @@ public void onNext(T t) { produced++; downstream.onNext(t); } + @Override public void onError(Throwable t) { boolean b; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java index b29b97b70a..47a8e3d878 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java @@ -73,6 +73,7 @@ public void onNext(T t) { produced++; downstream.onNext(t); } + @Override public void onError(Throwable t) { long r = remaining; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java index badf1d8146..5d33c14523 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTake.java @@ -52,6 +52,7 @@ static final class TakeSubscriber<T> extends AtomicBoolean implements FlowableSu this.limit = limit; this.remaining = limit; } + @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { @@ -65,6 +66,7 @@ public void onSubscribe(Subscription s) { } } } + @Override public void onNext(T t) { if (!done && remaining-- > 0) { @@ -76,6 +78,7 @@ public void onNext(T t) { } } } + @Override public void onError(Throwable t) { if (!done) { @@ -86,6 +89,7 @@ public void onError(Throwable t) { RxJavaPlugins.onError(t); } } + @Override public void onComplete() { if (!done) { @@ -93,6 +97,7 @@ public void onComplete() { downstream.onComplete(); } } + @Override public void request(long n) { if (!SubscriptionHelper.validate(n)) { @@ -106,6 +111,7 @@ public void request(long n) { } upstream.request(n); } + @Override public void cancel() { upstream.cancel(); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeInterval.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeInterval.java index 4e673da5e6..cf8b7087a7 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeInterval.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeInterval.java @@ -31,7 +31,6 @@ public FlowableTimeInterval(Flowable<T> source, TimeUnit unit, Scheduler schedul this.unit = unit; } - @Override protected void subscribeActual(Subscriber<? super Timed<T>> s) { source.subscribe(new TimeIntervalSubscriber<T>(s, unit, scheduler)); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFrom.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFrom.java index 5f403fb150..00017d431d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFrom.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFrom.java @@ -55,7 +55,7 @@ static final class WithLatestFromSubscriber<T, U, R> extends AtomicReference<U> final BiFunction<? super T, ? super U, ? extends R> combiner; - final AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + final AtomicReference<Subscription> upstream = new AtomicReference<Subscription>(); final AtomicLong requested = new AtomicLong(); @@ -65,15 +65,16 @@ static final class WithLatestFromSubscriber<T, U, R> extends AtomicReference<U> this.downstream = actual; this.combiner = combiner; } + @Override public void onSubscribe(Subscription s) { - SubscriptionHelper.deferredSetOnce(this.s, requested, s); + SubscriptionHelper.deferredSetOnce(this.upstream, requested, s); } @Override public void onNext(T t) { if (!tryOnNext(t)) { - s.get().request(1); + upstream.get().request(1); } } @@ -111,12 +112,12 @@ public void onComplete() { @Override public void request(long n) { - SubscriptionHelper.deferredRequest(s, requested, n); + SubscriptionHelper.deferredRequest(upstream, requested, n); } @Override public void cancel() { - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); SubscriptionHelper.cancel(other); } @@ -125,7 +126,7 @@ public boolean setOther(Subscription o) { } public void otherError(Throwable e) { - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); downstream.onError(e); } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java index f0a2231f02..d3014113ed 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java @@ -131,9 +131,9 @@ static final class WithLatestFromSubscriber<T, R> void subscribe(Publisher<?>[] others, int n) { WithLatestInnerSubscriber[] subscribers = this.subscribers; - AtomicReference<Subscription> s = this.upstream; + AtomicReference<Subscription> upstream = this.upstream; for (int i = 0; i < n; i++) { - if (SubscriptionHelper.isCancelled(s.get())) { + if (SubscriptionHelper.isCancelled(upstream.get())) { return; } others[i].subscribe(subscribers[i]); diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmpty.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmpty.java index 77d2d8f333..68d3db37d7 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmpty.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmpty.java @@ -99,18 +99,22 @@ static final class OtherMaybeObserver<T> implements MaybeObserver<T> { this.downstream = actual; this.parent = parent; } + @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(parent, d); } + @Override public void onSuccess(T value) { downstream.onSuccess(value); } + @Override public void onError(Throwable e) { downstream.onError(e); } + @Override public void onComplete() { downstream.onComplete(); diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingle.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingle.java index 798b3ef24f..bd94beb3ea 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingle.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingle.java @@ -106,14 +106,17 @@ static final class OtherSingleObserver<T> implements SingleObserver<T> { this.downstream = actual; this.parent = parent; } + @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(parent, d); } + @Override public void onSuccess(T value) { downstream.onSuccess(value); } + @Override public void onError(Throwable e) { downstream.onError(e); diff --git a/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java b/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java index 39f1a79a19..454c45b4c1 100644 --- a/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java +++ b/src/main/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservable.java @@ -81,7 +81,6 @@ public void onComplete() { } } - @Override public void dispose() { DisposableHelper.dispose(this); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAll.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAll.java index 71d0c32ebf..2349ce4893 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAll.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAll.java @@ -43,6 +43,7 @@ static final class AllObserver<T> implements Observer<T>, Disposable { this.downstream = actual; this.predicate = predicate; } + @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAllSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAllSingle.java index 3089007d6d..1fb756233d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAllSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAllSingle.java @@ -51,6 +51,7 @@ static final class AllObserver<T> implements Observer<T>, Disposable { this.downstream = actual; this.predicate = predicate; } + @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAny.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAny.java index 92f3aa02cf..c1500c3fb6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAny.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAny.java @@ -44,6 +44,7 @@ static final class AnyObserver<T> implements Observer<T>, Disposable { this.downstream = actual; this.predicate = predicate; } + @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAnySingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAnySingle.java index 87f0d7c64c..b8c7001ed5 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAnySingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAnySingle.java @@ -53,6 +53,7 @@ static final class AnyObserver<T> implements Observer<T>, Disposable { this.downstream = actual; this.predicate = predicate; } + @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java index 9cb6ba3de3..369eb4260d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java @@ -168,7 +168,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java index bbfef8ffae..59358c79a9 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java @@ -517,7 +517,6 @@ public void accept(Observer<? super U> a, U v) { a.onNext(v); } - @Override public void dispose() { if (!cancelled) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java index 4d7563608f..3bfe796efc 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java @@ -216,6 +216,7 @@ public void connect() { source.subscribe(this); isConnected = true; } + @Override public void onNext(T t) { if (!sourceDone) { @@ -226,6 +227,7 @@ public void onNext(T t) { } } } + @SuppressWarnings("unchecked") @Override public void onError(Throwable e) { @@ -239,6 +241,7 @@ public void onError(Throwable e) { } } } + @SuppressWarnings("unchecked") @Override public void onComplete() { @@ -296,6 +299,7 @@ static final class ReplayDisposable<T> public boolean isDisposed() { return cancelled; } + @Override public void dispose() { if (!cancelled) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCollect.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCollect.java index 8deff52c47..761fabd49e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCollect.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCollect.java @@ -69,7 +69,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -80,7 +79,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCollectSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCollectSingle.java index 04753eae0a..59c34a0048 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCollectSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCollectSingle.java @@ -77,7 +77,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -88,7 +87,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java index 27b869439a..ccbfc8e6d3 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java @@ -43,7 +43,6 @@ public ObservableCombineLatest(ObservableSource<? extends T>[] sources, this.delayError = delayError; } - @Override @SuppressWarnings("unchecked") public void subscribeActual(Observer<? super R> observer) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java index 742661690a..642f0e01f1 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java @@ -40,6 +40,7 @@ public ObservableConcatMap(ObservableSource<T> source, Function<? super T, ? ext this.delayErrors = delayErrors; this.bufferSize = Math.max(8, bufferSize); } + @Override public void subscribeActual(Observer<? super U> observer) { @@ -82,6 +83,7 @@ static final class SourceObserver<T, U> extends AtomicInteger implements Observe this.bufferSize = bufferSize; this.inner = new InnerObserver<U>(actual, this); } + @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { @@ -117,6 +119,7 @@ public void onSubscribe(Disposable d) { downstream.onSubscribe(this); } } + @Override public void onNext(T t) { if (done) { @@ -127,6 +130,7 @@ public void onNext(T t) { } drain(); } + @Override public void onError(Throwable t) { if (done) { @@ -137,6 +141,7 @@ public void onError(Throwable t) { dispose(); downstream.onError(t); } + @Override public void onComplete() { if (done) { @@ -246,11 +251,13 @@ public void onSubscribe(Disposable d) { public void onNext(U t) { downstream.onNext(t); } + @Override public void onError(Throwable t) { parent.dispose(); downstream.onError(t); } + @Override public void onComplete() { parent.innerComplete(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCount.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCount.java index bf961d47c0..bae08e040b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCount.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCount.java @@ -46,7 +46,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCountSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCountSingle.java index 1568e00f97..6e534b0dcc 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCountSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCountSingle.java @@ -54,7 +54,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java index d37b99ecfd..49f490924a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java @@ -117,6 +117,7 @@ public void onComplete() { if (d != null) { d.dispose(); } + @SuppressWarnings("unchecked") DebounceEmitter<T> de = (DebounceEmitter<T>)d; if (de != null) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDefer.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDefer.java index 411530c81f..adc2c29008 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDefer.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDefer.java @@ -25,6 +25,7 @@ public final class ObservableDefer<T> extends Observable<T> { public ObservableDefer(Callable<? extends ObservableSource<? extends T>> supplier) { this.supplier = supplier; } + @Override public void subscribeActual(Observer<? super T> observer) { ObservableSource<? extends T> pub; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java index 70dd6502b5..9e79e8eba4 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java @@ -49,7 +49,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -60,7 +59,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(Notification<T> t) { if (done) { @@ -91,6 +89,7 @@ public void onError(Throwable t) { downstream.onError(t); } + @Override public void onComplete() { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoOnEach.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoOnEach.java index dc3b4561b2..a88218cbd5 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDoOnEach.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDoOnEach.java @@ -74,7 +74,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -85,7 +84,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAt.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAt.java index 7abc421572..5897fddfed 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAt.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAt.java @@ -31,6 +31,7 @@ public ObservableElementAt(ObservableSource<T> source, long index, T defaultValu this.defaultValue = defaultValue; this.errorOnFewer = errorOnFewer; } + @Override public void subscribeActual(Observer<? super T> t) { source.subscribe(new ElementAtObserver<T>(t, index, defaultValue, errorOnFewer)); @@ -63,7 +64,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -74,7 +74,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtMaybe.java index 84f8d5baf7..921edd6ab3 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtMaybe.java @@ -26,6 +26,7 @@ public ObservableElementAtMaybe(ObservableSource<T> source, long index) { this.source = source; this.index = index; } + @Override public void subscribeActual(MaybeObserver<? super T> t) { source.subscribe(new ElementAtObserver<T>(t, index)); @@ -59,7 +60,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -70,7 +70,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtSingle.java index 6c73a4e91a..7de1fa7bef 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableElementAtSingle.java @@ -67,7 +67,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -78,7 +77,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableError.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableError.java index bc375ddf38..b0eeb95c56 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableError.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableError.java @@ -25,6 +25,7 @@ public final class ObservableError<T> extends Observable<T> { public ObservableError(Callable<? extends Throwable> errorSupplier) { this.errorSupplier = errorSupplier; } + @Override public void subscribeActual(Observer<? super T> observer) { Throwable error; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java index 76247e8e08..0bc25cebaf 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java @@ -413,6 +413,7 @@ void drainLoop() { if (checkTerminate()) { return; } + @SuppressWarnings("unchecked") InnerObserver<T, U> is = (InnerObserver<T, U>)inner[j]; @@ -542,6 +543,7 @@ static final class InnerObserver<T, U> extends AtomicReference<Disposable> this.id = id; this.parent = parent; } + @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { @@ -564,6 +566,7 @@ public void onSubscribe(Disposable d) { } } } + @Override public void onNext(U t) { if (fusionMode == QueueDisposable.NONE) { @@ -572,6 +575,7 @@ public void onNext(U t) { parent.drain(); } } + @Override public void onError(Throwable t) { if (parent.errors.addThrowable(t)) { @@ -584,6 +588,7 @@ public void onError(Throwable t) { RxJavaPlugins.onError(t); } } + @Override public void onComplete() { done = true; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java index 0633d59726..11b871ee46 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java @@ -23,6 +23,7 @@ public final class ObservableFromArray<T> extends Observable<T> { public ObservableFromArray(T[] array) { this.array = array; } + @Override public void subscribeActual(Observer<? super T> observer) { FromArrayDisposable<T> d = new FromArrayDisposable<T>(observer, array); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromCallable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromCallable.java index 214af8f4d7..fe3c364793 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromCallable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromCallable.java @@ -30,6 +30,7 @@ public final class ObservableFromCallable<T> extends Observable<T> implements Ca public ObservableFromCallable(Callable<? extends T> callable) { this.callable = callable; } + @Override public void subscribeActual(Observer<? super T> observer) { DeferredScalarDisposable<T> d = new DeferredScalarDisposable<T>(observer); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java index c74f697b7d..61f4891d1e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableGenerate.java @@ -136,7 +136,6 @@ public boolean isDisposed() { return cancelled; } - @Override public void onNext(T t) { if (!terminate) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMapNotification.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMapNotification.java index d6b6e39f47..f4418e9927 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMapNotification.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMapNotification.java @@ -71,7 +71,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -82,7 +81,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { ObservableSource<? extends R> p; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java index 3a89194e97..a82668cfc3 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java @@ -46,7 +46,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturn.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturn.java index 2ed68d48e9..b91e364856 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturn.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturn.java @@ -50,7 +50,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java index 39975af10b..debc37875b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java @@ -172,6 +172,7 @@ public void onNext(T t) { inner.child.onNext(t); } } + @SuppressWarnings("unchecked") @Override public void onError(Throwable e) { @@ -185,6 +186,7 @@ public void onError(Throwable e) { RxJavaPlugins.onError(e); } } + @SuppressWarnings("unchecked") @Override public void onComplete() { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java index 426bed7dd9..a42a8e85f6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeat.java @@ -59,6 +59,7 @@ public void onSubscribe(Disposable d) { public void onNext(T t) { downstream.onNext(t); } + @Override public void onError(Throwable t) { downstream.onError(t); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java index 8d8b9e29ac..485eb1f51f 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatUntil.java @@ -61,6 +61,7 @@ public void onSubscribe(Disposable d) { public void onNext(T t) { downstream.onNext(t); } + @Override public void onError(Throwable t) { downstream.onError(t); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java index 26efd9be5a..a1c75b67c0 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java @@ -371,6 +371,7 @@ public void onNext(T t) { replay(); } } + @Override public void onError(Throwable e) { // The observer front is accessed serially as required by spec so @@ -383,6 +384,7 @@ public void onError(Throwable e) { RxJavaPlugins.onError(e); } } + @Override public void onComplete() { // The observer front is accessed serially as required by spec so @@ -511,6 +513,7 @@ static final class UnboundedReplayBuffer<T> extends ArrayList<Object> implements UnboundedReplayBuffer(int capacityHint) { super(capacityHint); } + @Override public void next(T value) { add(NotificationLite.next(value)); @@ -862,6 +865,7 @@ void truncate() { setFirst(prev); } } + @Override void truncateFinal() { long timeLimit = scheduler.now(unit) - maxAge; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java index a743ae55c6..c9be2c75ca 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java @@ -65,6 +65,7 @@ public void onSubscribe(Disposable d) { public void onNext(T t) { downstream.onNext(t); } + @Override public void onError(Throwable t) { boolean b; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java index 3f98549c1d..6fb5d7b665 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java @@ -68,6 +68,7 @@ public void onSubscribe(Disposable d) { public void onNext(T t) { downstream.onNext(t); } + @Override public void onError(Throwable t) { long r = remaining; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleTimed.java index 9397438e09..a553a8dbb0 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleTimed.java @@ -36,7 +36,6 @@ public ObservableSampleTimed(ObservableSource<T> source, long period, TimeUnit u this.emitLast = emitLast; } - @Override public void subscribeActual(Observer<? super T> t) { SerializedObserver<T> serial = new SerializedObserver<T>(t); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableScan.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableScan.java index 13fd31fa1a..6b830e8d8f 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableScan.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableScan.java @@ -56,7 +56,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -67,7 +66,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableScanSeed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableScanSeed.java index 6f9222fbee..a9b4a63716 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableScanSeed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableScanSeed.java @@ -74,7 +74,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleMaybe.java index ab45f7b29f..d4e1b9a375 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleMaybe.java @@ -25,6 +25,7 @@ public final class ObservableSingleMaybe<T> extends Maybe<T> { public ObservableSingleMaybe(ObservableSource<T> source) { this.source = source; } + @Override public void subscribeActual(MaybeObserver<? super T> t) { source.subscribe(new SingleElementObserver<T>(t)); @@ -51,7 +52,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -62,7 +62,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleSingle.java index 79f7aaa4b2..e1232f849f 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSingleSingle.java @@ -59,7 +59,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -70,7 +69,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java index 3c6de3847a..2ea5953c39 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipLast.java @@ -54,7 +54,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java index a39b553563..d452fdaf0a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSkipWhile.java @@ -49,7 +49,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -60,7 +59,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (notSkipping) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTake.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTake.java index 7bda3017d5..2796357c80 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTake.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTake.java @@ -42,6 +42,7 @@ static final class TakeObserver<T> implements Observer<T>, Disposable { this.downstream = actual; this.remaining = limit; } + @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { @@ -55,6 +56,7 @@ public void onSubscribe(Disposable d) { } } } + @Override public void onNext(T t) { if (!done && remaining-- > 0) { @@ -65,6 +67,7 @@ public void onNext(T t) { } } } + @Override public void onError(Throwable t) { if (done) { @@ -76,6 +79,7 @@ public void onError(Throwable t) { upstream.dispose(); downstream.onError(t); } + @Override public void onComplete() { if (!done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntil.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntil.java index 35e04300e0..3b831b21d4 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntil.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeUntil.java @@ -28,6 +28,7 @@ public ObservableTakeUntil(ObservableSource<T> source, ObservableSource<? extend super(source); this.other = other; } + @Override public void subscribeActual(Observer<? super T> child) { TakeUntilMainObserver<T, U> parent = new TakeUntilMainObserver<T, U>(child); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeWhile.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeWhile.java index 1b41c6e86b..c57e6dfd12 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeWhile.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeWhile.java @@ -53,7 +53,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -64,7 +63,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeInterval.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeInterval.java index 0cc1a2c018..7d06b18f5e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeInterval.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeInterval.java @@ -69,7 +69,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { long now = scheduler.now(unit); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableToList.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableToList.java index 53dd99fd2b..afeee5399d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableToList.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableToList.java @@ -71,7 +71,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -82,7 +81,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { collection.add(t); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableToListSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableToListSingle.java index 4358229f53..410af1e161 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableToListSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableToListSingle.java @@ -83,7 +83,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -94,7 +93,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { collection.add(t); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFrom.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFrom.java index 9bc7984dd6..83369a73a7 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFrom.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWithLatestFrom.java @@ -61,6 +61,7 @@ static final class WithLatestFromObserver<T, U, R> extends AtomicReference<U> im this.downstream = actual; this.combiner = combiner; } + @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(this.upstream, d); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java index 5ac0027aeb..a259cd6d56 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java @@ -265,6 +265,7 @@ static final class ZipObserver<T, R> implements Observer<T> { this.parent = parent; this.queue = new SpscLinkedArrayQueue<T>(bufferSize); } + @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(this.upstream, d); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableZipIterable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableZipIterable.java index 8db76ed428..22b7b95196 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableZipIterable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableZipIterable.java @@ -90,7 +90,6 @@ public void onSubscribe(Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -101,7 +100,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(T t) { if (done) { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleEquals.java b/src/main/java/io/reactivex/internal/operators/single/SingleEquals.java index 83c40b1416..07d3f36602 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleEquals.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleEquals.java @@ -57,6 +57,7 @@ static class InnerObserver<T> implements SingleObserver<T> { this.downstream = observer; this.count = count; } + @Override public void onSubscribe(Disposable d) { set.add(d); diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleInternalHelper.java b/src/main/java/io/reactivex/internal/operators/single/SingleInternalHelper.java index f4ed04d151..7770fd38b4 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleInternalHelper.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleInternalHelper.java @@ -110,6 +110,7 @@ public Observable apply(SingleSource v) { return new SingleToObservable(v); } } + @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> Function<SingleSource<? extends T>, Observable<? extends T>> toObservable() { return (Function)ToObservable.INSTANCE; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleOnErrorReturn.java b/src/main/java/io/reactivex/internal/operators/single/SingleOnErrorReturn.java index 3f1b0588cf..0ae695a3e8 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleOnErrorReturn.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleOnErrorReturn.java @@ -32,8 +32,6 @@ public SingleOnErrorReturn(SingleSource<? extends T> source, this.value = value; } - - @Override protected void subscribeActual(final SingleObserver<? super T> observer) { diff --git a/src/main/java/io/reactivex/internal/queue/SpscLinkedArrayQueue.java b/src/main/java/io/reactivex/internal/queue/SpscLinkedArrayQueue.java index 35c86222cd..ec874209d0 100644 --- a/src/main/java/io/reactivex/internal/queue/SpscLinkedArrayQueue.java +++ b/src/main/java/io/reactivex/internal/queue/SpscLinkedArrayQueue.java @@ -113,6 +113,7 @@ private void resize(final AtomicReferenceArray<Object> oldBuffer, final long cur private void soNext(AtomicReferenceArray<Object> curr, AtomicReferenceArray<Object> next) { soElement(curr, calcDirectOffset(curr.length() - 1), next); } + @SuppressWarnings("unchecked") private AtomicReferenceArray<Object> lvNextBufferAndUnlink(AtomicReferenceArray<Object> curr, int nextIndex) { int nextOffset = calcDirectOffset(nextIndex); @@ -179,6 +180,7 @@ private T newBufferPeek(AtomicReferenceArray<Object> nextBuffer, final long inde final int offsetInNew = calcWrappedOffset(index, mask); return (T) lvElement(nextBuffer, offsetInNew);// LoadLoad } + @Override public void clear() { while (poll() != null || !isEmpty()) { } // NOPMD diff --git a/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java b/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java index dda22b9255..b7200dee34 100644 --- a/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java @@ -227,6 +227,7 @@ public Disposable schedule(@NonNull Runnable action) { return poolWorker.scheduleActual(action, 0, TimeUnit.MILLISECONDS, serial); } + @NonNull @Override public Disposable schedule(@NonNull Runnable action, long delayTime, @NonNull TimeUnit unit) { diff --git a/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java b/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java index f6913020a5..662335ef43 100644 --- a/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java @@ -167,6 +167,7 @@ public void start() { update.shutdown(); } } + @Override public void shutdown() { for (;;) { diff --git a/src/main/java/io/reactivex/internal/subscriptions/EmptySubscription.java b/src/main/java/io/reactivex/internal/subscriptions/EmptySubscription.java index 08fd1faae8..d4d78f3279 100644 --- a/src/main/java/io/reactivex/internal/subscriptions/EmptySubscription.java +++ b/src/main/java/io/reactivex/internal/subscriptions/EmptySubscription.java @@ -29,6 +29,7 @@ public enum EmptySubscription implements QueueSubscription<Object> { public void request(long n) { SubscriptionHelper.validate(n); } + @Override public void cancel() { // no-op @@ -67,27 +68,33 @@ public static void complete(Subscriber<?> s) { s.onSubscribe(INSTANCE); s.onComplete(); } + @Nullable @Override public Object poll() { return null; // always empty } + @Override public boolean isEmpty() { return true; } + @Override public void clear() { // nothing to do } + @Override public int requestFusion(int mode) { return mode & ASYNC; // accept async mode: an onComplete or onError will be signalled after anyway } + @Override public boolean offer(Object value) { throw new UnsupportedOperationException("Should not be called!"); } + @Override public boolean offer(Object v1, Object v2) { throw new UnsupportedOperationException("Should not be called!"); diff --git a/src/main/java/io/reactivex/internal/util/LinkedArrayList.java b/src/main/java/io/reactivex/internal/util/LinkedArrayList.java index a54527bdfa..6dbf3fb6e4 100644 --- a/src/main/java/io/reactivex/internal/util/LinkedArrayList.java +++ b/src/main/java/io/reactivex/internal/util/LinkedArrayList.java @@ -87,6 +87,7 @@ public Object[] head() { public int size() { return size; } + @Override public String toString() { final int cap = capacityHint; diff --git a/src/main/java/io/reactivex/observers/SafeObserver.java b/src/main/java/io/reactivex/observers/SafeObserver.java index 8dddcf1d9e..77dbfb20da 100644 --- a/src/main/java/io/reactivex/observers/SafeObserver.java +++ b/src/main/java/io/reactivex/observers/SafeObserver.java @@ -63,7 +63,6 @@ public void onSubscribe(@NonNull Disposable d) { } } - @Override public void dispose() { upstream.dispose(); diff --git a/src/main/java/io/reactivex/observers/SerializedObserver.java b/src/main/java/io/reactivex/observers/SerializedObserver.java index d0cdd4eeab..31badf77f8 100644 --- a/src/main/java/io/reactivex/observers/SerializedObserver.java +++ b/src/main/java/io/reactivex/observers/SerializedObserver.java @@ -72,7 +72,6 @@ public void onSubscribe(@NonNull Disposable d) { } } - @Override public void dispose() { upstream.dispose(); @@ -83,7 +82,6 @@ public boolean isDisposed() { return upstream.isDisposed(); } - @Override public void onNext(@NonNull T t) { if (done) { diff --git a/src/main/java/io/reactivex/processors/PublishProcessor.java b/src/main/java/io/reactivex/processors/PublishProcessor.java index 713fc4190f..878ae92cbe 100644 --- a/src/main/java/io/reactivex/processors/PublishProcessor.java +++ b/src/main/java/io/reactivex/processors/PublishProcessor.java @@ -141,7 +141,6 @@ public static <T> PublishProcessor<T> create() { subscribers = new AtomicReference<PublishSubscription<T>[]>(EMPTY); } - @Override protected void subscribeActual(Subscriber<? super T> t) { PublishSubscription<T> ps = new PublishSubscription<T>(t, this); diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index 868d465748..a8c9c700b4 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -605,6 +605,7 @@ static final class ReplaySubscription<T> extends AtomicInteger implements Subscr this.state = state; this.requested = new AtomicLong(); } + @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { @@ -1117,7 +1118,6 @@ void trimFinal() { } } - @Override public void trimHead() { if (head.value != null) { diff --git a/src/main/java/io/reactivex/subjects/PublishSubject.java b/src/main/java/io/reactivex/subjects/PublishSubject.java index b97af134ca..f59ab36754 100644 --- a/src/main/java/io/reactivex/subjects/PublishSubject.java +++ b/src/main/java/io/reactivex/subjects/PublishSubject.java @@ -129,7 +129,6 @@ public static <T> PublishSubject<T> create() { subscribers = new AtomicReference<PublishDisposable<T>[]>(EMPTY); } - @Override protected void subscribeActual(Observer<? super T> t) { PublishDisposable<T> ps = new PublishDisposable<T>(t, this); diff --git a/src/main/java/io/reactivex/subjects/SerializedSubject.java b/src/main/java/io/reactivex/subjects/SerializedSubject.java index 5b8bc16204..ec4263b85e 100644 --- a/src/main/java/io/reactivex/subjects/SerializedSubject.java +++ b/src/main/java/io/reactivex/subjects/SerializedSubject.java @@ -49,7 +49,6 @@ protected void subscribeActual(Observer<? super T> observer) { actual.subscribe(observer); } - @Override public void onSubscribe(Disposable d) { boolean cancel; diff --git a/src/main/java/io/reactivex/subscribers/DisposableSubscriber.java b/src/main/java/io/reactivex/subscribers/DisposableSubscriber.java index 5c460de70b..076dc9427f 100644 --- a/src/main/java/io/reactivex/subscribers/DisposableSubscriber.java +++ b/src/main/java/io/reactivex/subscribers/DisposableSubscriber.java @@ -74,11 +74,11 @@ * @param <T> the received value type. */ public abstract class DisposableSubscriber<T> implements FlowableSubscriber<T>, Disposable { - final AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + final AtomicReference<Subscription> upstream = new AtomicReference<Subscription>(); @Override public final void onSubscribe(Subscription s) { - if (EndConsumerHelper.setOnce(this.s, s, getClass())) { + if (EndConsumerHelper.setOnce(this.upstream, s, getClass())) { onStart(); } } @@ -87,7 +87,7 @@ public final void onSubscribe(Subscription s) { * Called once the single upstream Subscription is set via onSubscribe. */ protected void onStart() { - s.get().request(Long.MAX_VALUE); + upstream.get().request(Long.MAX_VALUE); } /** @@ -99,7 +99,7 @@ protected void onStart() { * @param n the request amount, positive */ protected final void request(long n) { - s.get().request(n); + upstream.get().request(n); } /** @@ -113,11 +113,11 @@ protected final void cancel() { @Override public final boolean isDisposed() { - return s.get() == SubscriptionHelper.CANCELLED; + return upstream.get() == SubscriptionHelper.CANCELLED; } @Override public final void dispose() { - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(upstream); } } diff --git a/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java b/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java index 66c282842c..daa37a024b 100644 --- a/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java +++ b/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java @@ -94,7 +94,7 @@ */ public abstract class ResourceSubscriber<T> implements FlowableSubscriber<T>, Disposable { /** The active subscription. */ - private final AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + private final AtomicReference<Subscription> upstream = new AtomicReference<Subscription>(); /** The resource composite, can never be null. */ private final ListCompositeDisposable resources = new ListCompositeDisposable(); @@ -116,7 +116,7 @@ public final void add(Disposable resource) { @Override public final void onSubscribe(Subscription s) { - if (EndConsumerHelper.setOnce(this.s, s, getClass())) { + if (EndConsumerHelper.setOnce(this.upstream, s, getClass())) { long r = missedRequested.getAndSet(0L); if (r != 0L) { s.request(r); @@ -144,7 +144,7 @@ protected void onStart() { * @param n the request amount, must be positive */ protected final void request(long n) { - SubscriptionHelper.deferredRequest(s, missedRequested, n); + SubscriptionHelper.deferredRequest(upstream, missedRequested, n); } /** @@ -156,7 +156,7 @@ protected final void request(long n) { */ @Override public final void dispose() { - if (SubscriptionHelper.cancel(s)) { + if (SubscriptionHelper.cancel(upstream)) { resources.dispose(); } } @@ -167,6 +167,6 @@ public final void dispose() { */ @Override public final boolean isDisposed() { - return SubscriptionHelper.isCancelled(s.get()); + return SubscriptionHelper.isCancelled(upstream.get()); } } diff --git a/src/test/java/io/reactivex/completable/CompletableTest.java b/src/test/java/io/reactivex/completable/CompletableTest.java index 32461d5d41..4798973835 100644 --- a/src/test/java/io/reactivex/completable/CompletableTest.java +++ b/src/test/java/io/reactivex/completable/CompletableTest.java @@ -2029,6 +2029,7 @@ public void onSubscribe(Disposable d) { }; } } + @Test(timeout = 5000, expected = TestException.class) public void liftOnCompleteError() { Completable c = normal.completable.lift(new CompletableOperatorSwap()); @@ -4660,7 +4661,6 @@ public void accept(final Throwable throwable) throws Exception { } } - @Test(timeout = 5000) public void subscribeTwoCallbacksDispose() { PublishProcessor<Integer> pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java b/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java index ce8cd412b2..aec399a3e7 100644 --- a/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java +++ b/src/test/java/io/reactivex/disposables/CompositeDisposableTest.java @@ -277,6 +277,7 @@ public void run() { // we should have only disposed once assertEquals(1, counter.get()); } + @Test public void testTryRemoveIfNotIn() { CompositeDisposable cd = new CompositeDisposable(); diff --git a/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java b/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java index 4b9f96ba8a..3625aa099a 100644 --- a/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java +++ b/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java @@ -182,6 +182,7 @@ public void testNullCollection() { composite.getCause(); composite.printStackTrace(); } + @Test public void testNullElement() { CompositeException composite = new CompositeException(Collections.singletonList((Throwable) null)); diff --git a/src/test/java/io/reactivex/exceptions/OnErrorNotImplementedExceptionTest.java b/src/test/java/io/reactivex/exceptions/OnErrorNotImplementedExceptionTest.java index d7b69ca107..4097f9a52e 100644 --- a/src/test/java/io/reactivex/exceptions/OnErrorNotImplementedExceptionTest.java +++ b/src/test/java/io/reactivex/exceptions/OnErrorNotImplementedExceptionTest.java @@ -108,7 +108,6 @@ public void singleSubscribe1() { .subscribe(Functions.emptyConsumer()); } - @Test public void maybeSubscribe0() { Maybe.error(new TestException()) diff --git a/src/test/java/io/reactivex/flowable/FlowableCollectTest.java b/src/test/java/io/reactivex/flowable/FlowableCollectTest.java index 09bb562d2b..f187d5b240 100644 --- a/src/test/java/io/reactivex/flowable/FlowableCollectTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableCollectTest.java @@ -83,7 +83,6 @@ public void accept(StringBuilder sb, Integer v) { assertEquals("1-2-3", value); } - @Test public void testFactoryFailureResultsInErrorEmissionFlowable() { final RuntimeException e = new RuntimeException(); @@ -167,7 +166,6 @@ public void accept(Object o, Integer t) { assertFalse(added.get()); } - @SuppressWarnings("unchecked") @Test public void collectIntoFlowable() { @@ -183,7 +181,6 @@ public void accept(HashSet<Integer> s, Integer v) throws Exception { .assertResult(new HashSet<Integer>(Arrays.asList(1, 2))); } - @Test public void testCollectToList() { Single<List<Integer>> o = Flowable.just(1, 2, 3) @@ -238,7 +235,6 @@ public void accept(StringBuilder sb, Integer v) { assertEquals("1-2-3", value); } - @Test public void testFactoryFailureResultsInErrorEmission() { final RuntimeException e = new RuntimeException(); @@ -319,7 +315,6 @@ public void accept(Object o, Integer t) { assertFalse(added.get()); } - @SuppressWarnings("unchecked") @Test public void collectInto() { diff --git a/src/test/java/io/reactivex/flowable/FlowableNullTests.java b/src/test/java/io/reactivex/flowable/FlowableNullTests.java index 80f70a75ad..3e9582363b 100644 --- a/src/test/java/io/reactivex/flowable/FlowableNullTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableNullTests.java @@ -2724,7 +2724,6 @@ public Object apply(Integer a, Integer b) { }); } - @Test(expected = NullPointerException.class) public void zipWithCombinerNull() { just1.zipWith(just1, null); diff --git a/src/test/java/io/reactivex/flowable/FlowableReduceTests.java b/src/test/java/io/reactivex/flowable/FlowableReduceTests.java index e98c56f0f5..8381a510a4 100644 --- a/src/test/java/io/reactivex/flowable/FlowableReduceTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableReduceTests.java @@ -77,7 +77,6 @@ public Movie apply(Movie t1, Movie t2) { assertNotNull(reduceResult2); } - @Test public void reduceInts() { Flowable<Integer> f = Flowable.just(1, 2, 3); diff --git a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java index b72df7a98c..f7789656a3 100644 --- a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java @@ -771,7 +771,6 @@ public void safeSubscriberAlreadySafe() { ts.assertResult(1); } - @Test public void methodTestNoCancel() { PublishProcessor<Integer> pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/flowable/FlowableTests.java b/src/test/java/io/reactivex/flowable/FlowableTests.java index f3b7d2b371..377254f95e 100644 --- a/src/test/java/io/reactivex/flowable/FlowableTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableTests.java @@ -148,7 +148,6 @@ public Throwable call() { verify(w, times(1)).onError(any(RuntimeException.class)); } - @Test public void testCountAFewItems() { Flowable<String> flowable = Flowable.just("a", "b", "c", "d"); @@ -862,7 +861,6 @@ public void testContainsWithEmptyObservableFlowable() { verify(subscriber, times(1)).onComplete(); } - @Test public void testContains() { Single<Boolean> single = Flowable.just("a", "b", "c").contains("b"); // FIXME nulls not allowed, changed to "c" diff --git a/src/test/java/io/reactivex/internal/SubscribeWithTest.java b/src/test/java/io/reactivex/internal/SubscribeWithTest.java index e2c23b51d5..ee6cdf5c0b 100644 --- a/src/test/java/io/reactivex/internal/SubscribeWithTest.java +++ b/src/test/java/io/reactivex/internal/SubscribeWithTest.java @@ -30,7 +30,6 @@ public void withFlowable() { .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } - @Test public void withObservable() { Observable.range(1, 10) diff --git a/src/test/java/io/reactivex/internal/observers/BasicFuseableObserverTest.java b/src/test/java/io/reactivex/internal/observers/BasicFuseableObserverTest.java index 93aef221b2..797ae8e07a 100644 --- a/src/test/java/io/reactivex/internal/observers/BasicFuseableObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/BasicFuseableObserverTest.java @@ -30,13 +30,16 @@ public void offer() { public Integer poll() throws Exception { return null; } + @Override public int requestFusion(int mode) { return 0; } + @Override public void onNext(Integer value) { } + @Override protected boolean beforeDownstream() { return false; @@ -58,10 +61,12 @@ public void offer2() { public Integer poll() throws Exception { return null; } + @Override public int requestFusion(int mode) { return 0; } + @Override public void onNext(Integer value) { } diff --git a/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java b/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java index 8defb098ef..7d2640b71c 100644 --- a/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/DeferredScalarObserverTest.java @@ -181,7 +181,6 @@ static final class TakeLast extends DeferredScalarObserver<Integer, Integer> { super(downstream); } - @Override public void onNext(Integer value) { this.value = value; diff --git a/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java b/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java index 8e520fd402..81221cfc21 100644 --- a/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/LambdaObserverTest.java @@ -247,6 +247,7 @@ public void accept(Disposable d) throws Exception { RxJavaPlugins.reset(); } } + @Test public void badSourceEmitAfterDone() { List<Throwable> errors = TestHelper.trackPluginErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java index f6f3dc0337..0e45cd1c1b 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java @@ -187,7 +187,6 @@ public void ambRace() { } } - @Test public void untilCompletableMainComplete() { CompletableSubject main = CompletableSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableResumeNextTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableResumeNextTest.java index c2a3af2769..1633954fbf 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableResumeNextTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableResumeNextTest.java @@ -40,7 +40,6 @@ public CompletableSource apply(Completable c) throws Exception { }); } - @Test public void disposeInResume() { TestHelper.checkDisposedCompletable(new Function<Completable, CompletableSource>() { diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableSubscribeTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableSubscribeTest.java index 543d7015c4..4f546e548f 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableSubscribeTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableSubscribeTest.java @@ -30,7 +30,6 @@ public void subscribeAlreadyCancelled() { assertFalse(pp.hasSubscribers()); } - @Test public void methodTestNoCancel() { PublishSubject<Integer> ps = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java index 598abdd29c..5d1a4cfc42 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableUsingTest.java @@ -347,7 +347,6 @@ public void accept(Object d) throws Exception { .assertFailure(TestException.class); } - @Test public void emptyDisposerCrashes() { Completable.using(new Callable<Object>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecentTest.java b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecentTest.java index 71c075c2c4..26e6eb5716 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecentTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecentTest.java @@ -103,7 +103,6 @@ public void constructorshouldbeprivate() { TestHelper.checkUtilityClass(BlockingFlowableMostRecent.class); } - @Test public void empty() { Iterator<Integer> it = Flowable.<Integer>empty() diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java index 7ab08915d2..e859766ca8 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java @@ -124,6 +124,7 @@ public boolean test(Integer i) { assertFalse(allOdd.blockingGet()); } + @Test(timeout = 5000) public void testIssue1935NoUnsubscribeDownstream() { Flowable<Integer> source = Flowable.just(1) @@ -297,6 +298,7 @@ public boolean test(Integer i) { assertFalse(allOdd.blockingFirst()); } + @Test(timeout = 5000) public void testIssue1935NoUnsubscribeDownstreamFlowable() { Flowable<Integer> source = Flowable.just(1) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java index 9e68ec3948..a4b03c633c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java @@ -236,7 +236,6 @@ public void testBackpressure() { assertEquals(Flowable.bufferSize() * 2, ts.values().size()); } - @SuppressWarnings("unchecked") @Test public void testSubscriptionOnlyHappensOnce() throws InterruptedException { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java index 76bd59591a..76d4b034b7 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java @@ -223,6 +223,7 @@ public boolean test(Integer i) { assertTrue(anyEven.blockingGet()); } + @Test(timeout = 5000) public void testIssue1935NoUnsubscribeDownstream() { Flowable<Integer> source = Flowable.just(1).isEmpty() @@ -489,6 +490,7 @@ public boolean test(Integer i) { assertTrue(anyEven.blockingFirst()); } + @Test(timeout = 5000) public void testIssue1935NoUnsubscribeDownstreamFlowable() { Flowable<Integer> source = Flowable.just(1).isEmpty() diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java index 23cf4ecf02..a297911040 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java @@ -45,6 +45,7 @@ public void testHiding() { verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } + @Test public void testHidingError() { PublishProcessor<Integer> src = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index aa8c3ef23c..00568da3ec 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -496,6 +496,7 @@ public void bufferWithBOBoundaryThrows() { verify(subscriber, never()).onComplete(); verify(subscriber, never()).onNext(any()); } + @Test(timeout = 2000) public void bufferWithSizeTake1() { Flowable<Integer> source = Flowable.just(1).repeat(); @@ -525,6 +526,7 @@ public void bufferWithSizeSkipTake1() { verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } + @Test(timeout = 2000) public void bufferWithTimeTake1() { Flowable<Long> source = Flowable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); @@ -541,6 +543,7 @@ public void bufferWithTimeTake1() { verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } + @Test(timeout = 2000) public void bufferWithTimeSkipTake2() { Flowable<Long> source = Flowable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); @@ -614,6 +617,7 @@ public void accept(List<Long> pv) { inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } + @Test public void bufferWithSizeThrows() { PublishProcessor<Integer> source = PublishProcessor.create(); @@ -683,6 +687,7 @@ public void bufferWithTimeAndSize() { inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } + @Test public void bufferWithStartEndStartThrows() { PublishProcessor<Integer> start = PublishProcessor.create(); @@ -711,6 +716,7 @@ public Flowable<Integer> apply(Integer t1) { verify(subscriber, never()).onComplete(); verify(subscriber).onError(any(TestException.class)); } + @Test public void bufferWithStartEndEndFunctionThrows() { PublishProcessor<Integer> start = PublishProcessor.create(); @@ -738,6 +744,7 @@ public Flowable<Integer> apply(Integer t1) { verify(subscriber, never()).onComplete(); verify(subscriber).onError(any(TestException.class)); } + @Test public void bufferWithStartEndEndThrows() { PublishProcessor<Integer> start = PublishProcessor.create(); @@ -881,7 +888,6 @@ public void cancel() { assertEquals(Long.MAX_VALUE, requested.get()); } - @Test public void testProducerRequestOverflowThroughBufferWithSize1() { TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>(Long.MAX_VALUE >> 1); @@ -991,6 +997,7 @@ public void onNext(List<Integer> t) { // FIXME I'm not sure why this is MAX_VALUE in 1.x because MAX_VALUE/2 is even and thus can't overflow when multiplied by 2 assertEquals(Long.MAX_VALUE - 1, requested.get()); } + @Test(timeout = 3000) public void testBufferWithTimeDoesntUnsubscribeDownstream() throws InterruptedException { final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); @@ -1001,11 +1008,13 @@ public void testBufferWithTimeDoesntUnsubscribeDownstream() throws InterruptedEx public void onNext(Object t) { subscriber.onNext(t); } + @Override public void onError(Throwable e) { subscriber.onError(e); cdl.countDown(); } + @Override public void onComplete() { subscriber.onComplete(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java index c26e612e09..f3d241bfd6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java @@ -54,6 +54,7 @@ public void testColdReplayNoBackpressure() { assertEquals((Integer)i, onNextEvents.get(i)); } } + @Test public void testColdReplayBackpressure() { FlowableCache<Integer> source = new FlowableCache<Integer>(Flowable.range(0, 1000), 16); @@ -178,6 +179,7 @@ public void testAsync() { assertEquals(10000, ts2.values().size()); } } + @Test public void testAsyncComeAndGo() { Flowable<Long> source = Flowable.interval(1, 1, TimeUnit.MILLISECONDS) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java index 2934084b0d..1d759a6e44 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java @@ -1206,6 +1206,7 @@ public Object apply(Object[] a) throws Exception { .test() .assertFailure(TestException.class, "[1, 2]"); } + @SuppressWarnings("unchecked") @Test public void combineLatestEmpty() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatDelayErrorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatDelayErrorTest.java index ab307df66f..7d343c1f3d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatDelayErrorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatDelayErrorTest.java @@ -216,7 +216,6 @@ static <T> Flowable<T> withError(Flowable<T> source) { return source.concatWith(Flowable.<T>error(new TestException())); } - @Test public void concatDelayErrorFlowable() { TestSubscriber<Integer> ts = TestSubscriber.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java index 3c77acb502..1e34d2937b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java @@ -655,7 +655,6 @@ public Flowable<Integer> apply(Integer t) { ts.assertValue(null); } - @Test public void testMaxConcurrent5() { final List<Long> requests = new ArrayList<Long>(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java index 7c53083548..4b199482e9 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java @@ -169,6 +169,7 @@ public void subscribe(final Subscriber<? super Flowable<String>> subscriber) { public void request(long n) { } + @Override public void cancel() { d.dispose(); @@ -636,6 +637,7 @@ public Flowable<Integer> apply(Integer v) { inOrder.verify(o).onSuccess(list); verify(o, never()).onError(any(Throwable.class)); } + @Test public void concatVeryLongObservableOfObservablesTakeHalf() { final int n = 10000; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybeTest.java index eb1fd62fe2..64a7c62149 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatWithMaybeTest.java @@ -41,7 +41,6 @@ public void run() throws Exception { ts.assertResult(1, 2, 3, 4, 5, 100); } - @Test public void normalNonEmpty() { final TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCountTest.java index e11fb643eb..998569148d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCountTest.java @@ -39,7 +39,6 @@ public void simple() { } - @Test public void dispose() { TestHelper.checkDisposed(Flowable.just(1).count()); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java index 8aeef598c8..899f145ca2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java @@ -1001,7 +1001,6 @@ public void cancel() throws Exception { } } - @Test public void tryOnError() { for (BackpressureStrategy strategy : BackpressureStrategy.values()) { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java index 40348b0ee6..8df7c9c193 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java @@ -239,6 +239,7 @@ public Flowable<Integer> apply(Integer t1) { verify(subscriber, never()).onComplete(); verify(subscriber).onError(any(TestException.class)); } + @Test public void debounceTimedLastIsNotLost() { PublishProcessor<Integer> source = PublishProcessor.create(); @@ -256,6 +257,7 @@ public void debounceTimedLastIsNotLost() { verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } + @Test public void debounceSelectorLastIsNotLost() { PublishProcessor<Integer> source = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java index a42c0d889f..1114f17a1d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java @@ -87,7 +87,6 @@ public void range() { ts.assertComplete(); } - @Test public void backpressured() throws Exception { o = new Object(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoFinallyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoFinallyTest.java index 943d92ff03..93dd960cf3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoFinallyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoFinallyTest.java @@ -157,7 +157,6 @@ public void asyncFusedBoundary() { assertEquals(1, calls); } - @Test public void normalJustConditional() { Flowable.just(1) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableElementAtTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableElementAtTest.java index e8a395fc3b..d5665d6bf3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableElementAtTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableElementAtTest.java @@ -186,7 +186,6 @@ public void elementAtOrErrorIndex1OnEmptySource() { .assertFailure(NoSuchElementException.class); } - @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<Object>>() { @@ -229,7 +228,6 @@ public void errorFlowable() { .assertFailure(TestException.class); } - @Test public void error() { Flowable.error(new TestException()) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java index 01309ff55c..62cee79161 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletableTest.java @@ -183,7 +183,6 @@ public CompletableSource apply(Integer v) throws Exception { .assertFailure(TestException.class); } - @Test public void fusedFlowable() { TestSubscriber<Integer> ts = SubscriberFusion.newTest(QueueFuseable.ANY); @@ -338,7 +337,6 @@ public CompletableSource apply(Integer v) throws Exception { .assertFailure(TestException.class); } - @Test public void fused() { TestSubscriber<Integer> ts = SubscriberFusion.newTest(QueueFuseable.ANY); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index 9cdbfc26af..c9c24e7ef5 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -355,6 +355,7 @@ public Flowable<Integer> apply(Integer t1) { Assert.assertEquals(expected.size(), ts.valueCount()); Assert.assertTrue(expected.containsAll(ts.values())); } + @Test public void testFlatMapSelectorMaxConcurrent() { final int m = 4; @@ -478,6 +479,7 @@ public Flowable<Integer> apply(Integer t) { } } } + @Test(timeout = 30000) public void flatMapRangeMixedAsyncLoop() { for (int i = 0; i < 2000; i++) { @@ -537,6 +539,7 @@ public Flowable<Integer> apply(Integer t) { ts.assertValueCount(1000); } } + @Test public void flatMapTwoNestedSync() { for (final int n : new int[] { 1, 1000, 1000000 }) { @@ -856,7 +859,6 @@ public void run() { } } - @Test public void fusedInnerThrows() { Flowable.just(1).hide() diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromArrayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromArrayTest.java index b07fe3bf2d..2112541c29 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromArrayTest.java @@ -33,6 +33,7 @@ Flowable<Integer> create(int n) { } return Flowable.fromArray(array); } + @Test public void simple() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromSourceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromSourceTest.java index e1f15bb261..b2452a65fb 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromSourceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromSourceTest.java @@ -40,7 +40,6 @@ public void before() { ts = new TestSubscriber<Integer>(0L); } - @Test public void normalBuffered() { Flowable.create(source, BackpressureStrategy.BUFFER).subscribe(ts); @@ -125,7 +124,6 @@ public void normalMissingRequested() { ts.assertComplete(); } - @Test public void normalError() { Flowable.create(source, BackpressureStrategy.ERROR).subscribe(ts); @@ -489,7 +487,6 @@ public void unsubscribeNoCancel() { ts.assertNotComplete(); } - @Test public void unsubscribeInline() { TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index 022ab3788f..9b2ae32416 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -1638,7 +1638,6 @@ public void accept(GroupedFlowable<Integer, Integer> g) { .assertComplete(); } - @Test public void keySelectorAndDelayError() { Flowable.just(1).concatWith(Flowable.<Integer>error(new TestException())) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java index 8656afde8d..1f6c9e23a5 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java @@ -144,7 +144,6 @@ public void onNext(Integer t) { assertEquals(0, count.get()); } - @Test public void testWithEmpty() { assertNull(Flowable.empty().ignoreElements().blockingGet()); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java index 03300d4dda..67129c956b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java @@ -436,6 +436,7 @@ public void onNext(String args) { } } + @Test @Ignore("Subscribers should not throw") public void testMergeSourceWhichDoesntPropagateExceptionBack() { @@ -559,6 +560,7 @@ public void run() { t.start(); } } + @Test public void testDelayErrorMaxConcurrent() { final List<Long> requests = new ArrayList<Long>(); @@ -737,7 +739,6 @@ public void array() { } } - @SuppressWarnings("unchecked") @Test public void mergeArrayDelayError() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeMaxConcurrentTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeMaxConcurrentTest.java index 0973027f3b..ef5dd519ff 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeMaxConcurrentTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeMaxConcurrentTest.java @@ -129,6 +129,7 @@ public void testMergeALotOfSourcesOneByOneSynchronously() { } assertEquals(j, n); } + @Test public void testMergeALotOfSourcesOneByOneSynchronouslyTakeHalf() { int n = 10000; @@ -163,6 +164,7 @@ public void testSimple() { ts.assertValueSequence(result); } } + @Test public void testSimpleOneLess() { for (int i = 2; i < 100; i++) { @@ -181,6 +183,7 @@ public void testSimpleOneLess() { ts.assertValueSequence(result); } } + @Test//(timeout = 20000) public void testSimpleAsyncLoop() { IoScheduler ios = (IoScheduler)Schedulers.io(); @@ -193,6 +196,7 @@ public void testSimpleAsyncLoop() { } } } + @Test(timeout = 10000) public void testSimpleAsync() { for (int i = 1; i < 50; i++) { @@ -213,12 +217,14 @@ public void testSimpleAsync() { assertEquals(expected, actual); } } + @Test(timeout = 10000) public void testSimpleOneLessAsyncLoop() { for (int i = 0; i < 200; i++) { testSimpleOneLessAsync(); } } + @Test(timeout = 10000) public void testSimpleOneLessAsync() { long t = System.currentTimeMillis(); @@ -243,6 +249,7 @@ public void testSimpleOneLessAsync() { assertEquals(expected, actual); } } + @Test(timeout = 5000) public void testBackpressureHonored() throws Exception { List<Flowable<Integer>> sourceList = new ArrayList<Flowable<Integer>>(3); @@ -273,6 +280,7 @@ public void onNext(Integer t) { ts.dispose(); } + @Test(timeout = 5000) public void testTake() throws Exception { List<Flowable<Integer>> sourceList = new ArrayList<Flowable<Integer>>(3); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java index e66206c865..fc09bd1dc5 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java @@ -1360,10 +1360,12 @@ void runMerge(Function<Integer, Flowable<Integer>> func, TestSubscriber<Integer> public void testFastMergeFullScalar() { runMerge(toScalar, new TestSubscriber<Integer>()); } + @Test public void testFastMergeHiddenScalar() { runMerge(toHiddenScalar, new TestSubscriber<Integer>()); } + @Test public void testSlowMergeFullScalar() { for (final int req : new int[] { 16, 32, 64, 128, 256 }) { @@ -1382,6 +1384,7 @@ public void onNext(Integer t) { runMerge(toScalar, ts); } } + @Test public void testSlowMergeHiddenScalar() { for (final int req : new int[] { 16, 32, 64, 128, 256 }) { @@ -1462,7 +1465,6 @@ public void mergeConcurrentJustRange() { ts.assertComplete(); } - @SuppressWarnings("unchecked") @Test @Ignore("No 2-9 argument merge()") @@ -1622,7 +1624,6 @@ public void array() { } } - @SuppressWarnings("unchecked") @Test public void mergeArray() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java index 10c1facc16..2beacebd84 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java @@ -794,7 +794,6 @@ public void onNext(Integer t) { assertEquals(Arrays.asList(128L), requests); } - @Test public void testErrorDelayed() { TestScheduler s = new TestScheduler(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureLatestTest.java index 6fb70da88b..db6b3d9580 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureLatestTest.java @@ -37,6 +37,7 @@ public void testSimple() { ts.assertTerminated(); ts.assertValues(1, 2, 3, 4, 5); } + @Test public void testSimpleError() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); @@ -48,6 +49,7 @@ public void testSimpleError() { ts.assertError(TestException.class); ts.assertValues(1, 2, 3, 4, 5); } + @Test public void testSimpleBackpressure() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(2L); @@ -100,6 +102,7 @@ public void testSynchronousDrop() { ts.assertNoErrors(); ts.assertTerminated(); } + @Test public void testAsynchronousDrop() throws InterruptedException { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(1L) { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java index 9bcc27d5f3..eb2f120e43 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java @@ -242,7 +242,6 @@ public Integer apply(Throwable e) { ts.assertComplete(); } - @Test public void returnItem() { Flowable.error(new TestException()) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java index 3da05ffedf..e9f19585bf 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java @@ -186,7 +186,6 @@ public String apply(String s) { verify(subscriber, times(1)).onComplete(); } - @Test public void testBackpressure() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticastTest.java index 8e004d7af7..4078b5b0b0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticastTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticastTest.java @@ -152,7 +152,6 @@ public void errorAllCancelled() { mp.errorAll(null); } - @Test public void completeAllCancelled() { MulticastProcessor<Integer> mp = new MulticastProcessor<Integer>(128, true); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java index c18cbc928b..c7c9865f24 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java @@ -371,6 +371,7 @@ public void testZeroRequested() { ts.assertNoErrors(); ts.assertTerminated(); } + @Test public void testConnectIsIdempotent() { final AtomicInteger calls = new AtomicInteger(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java index f97febd9e2..470e0e8cc0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java @@ -164,18 +164,21 @@ void testWithBackpressureAllAtOnce(long start) { ts.assertValueSequence(list); ts.assertTerminated(); } + @Test public void testWithBackpressure1() { for (long i = 0; i < 100; i++) { testWithBackpressureOneByOne(i); } } + @Test public void testWithBackpressureAllAtOnce() { for (long i = 0; i < 100; i++) { testWithBackpressureAllAtOnce(i); } } + @Test public void testWithBackpressureRequestWayMore() { Flowable<Long> source = Flowable.rangeLong(50, 100); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java index 36a345c617..b0af47585b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java @@ -164,18 +164,21 @@ void testWithBackpressureAllAtOnce(int start) { ts.assertValueSequence(list); ts.assertTerminated(); } + @Test public void testWithBackpressure1() { for (int i = 0; i < 100; i++) { testWithBackpressureOneByOne(i); } } + @Test public void testWithBackpressureAllAtOnce() { for (int i = 0; i < 100; i++) { testWithBackpressureAllAtOnce(i); } } + @Test public void testWithBackpressureRequestWayMore() { Flowable<Integer> source = Flowable.range(50, 100); @@ -260,6 +263,7 @@ public void testNearMaxValueWithoutBackpressure() { ts.assertNoErrors(); ts.assertValues(Integer.MAX_VALUE - 1, Integer.MAX_VALUE); } + @Test(timeout = 1000) public void testNearMaxValueWithBackpressure() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(3L); @@ -270,7 +274,6 @@ public void testNearMaxValueWithBackpressure() { ts.assertValues(Integer.MAX_VALUE - 1, Integer.MAX_VALUE); } - @Test public void negativeCount() { try { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java index 12425aed42..e6103b5a7b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java @@ -141,7 +141,6 @@ public void testBackpressureWithInitialValueFlowable() throws InterruptedExcepti assertEquals(21, r.intValue()); } - @Test public void testAggregateAsIntSum() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index 137565dae4..cb6db6ef11 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -876,6 +876,7 @@ public void testColdReplayNoBackpressure() { assertEquals((Integer)i, onNextEvents.get(i)); } } + @Test public void testColdReplayBackpressure() { Flowable<Integer> source = Flowable.range(0, 1000).replay().autoConnect(); @@ -995,6 +996,7 @@ public void testAsync() { assertEquals(10000, ts2.values().size()); } } + @Test public void testAsyncComeAndGo() { Flowable<Long> source = Flowable.interval(1, 1, TimeUnit.MILLISECONDS) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java index e7a2bb8eaa..8b35cb37f9 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java @@ -433,6 +433,7 @@ public void request(long n) { } } } + @Override public void cancel() { // TODO Auto-generated method stub @@ -829,6 +830,7 @@ static <T> StringBuilder sequenceFrequency(Iterable<T> it) { return sb; } + @Test//(timeout = 3000) public void testIssue1900() throws InterruptedException { Subscriber<String> subscriber = TestHelper.mockSubscriber(); @@ -869,6 +871,7 @@ public Flowable<String> apply(GroupedFlowable<String, String> t1) { inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } + @Test//(timeout = 3000) public void testIssue1900SourceNotSupportingBackpressure() { Subscriber<String> subscriber = TestHelper.mockSubscriber(); @@ -997,7 +1000,6 @@ public boolean getAsBoolean() throws Exception { .assertResult(1, 1, 1, 1, 1); } - @Test public void shouldDisposeInnerObservable() { final PublishProcessor<Object> processor = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java index 1f9f8c0736..f25c276ece 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java @@ -70,6 +70,7 @@ public void testWithNothingToRetry() { inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } + @Test public void testRetryTwice() { Flowable<Integer> source = Flowable.unsafeCreate(new Publisher<Integer>() { @@ -105,6 +106,7 @@ public void subscribe(Subscriber<? super Integer> t1) { verify(subscriber, never()).onError(any(Throwable.class)); } + @Test public void testRetryTwiceAndGiveUp() { Flowable<Integer> source = Flowable.unsafeCreate(new Publisher<Integer>() { @@ -132,6 +134,7 @@ public void subscribe(Subscriber<? super Integer> t1) { verify(subscriber, never()).onComplete(); } + @Test public void testRetryOnSpecificException() { Flowable<Integer> source = Flowable.unsafeCreate(new Publisher<Integer>() { @@ -166,6 +169,7 @@ public void subscribe(Subscriber<? super Integer> t1) { inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } + @Test public void testRetryOnSpecificExceptionAndNotOther() { final IOException ioe = new IOException(); @@ -289,6 +293,7 @@ public Integer apply(Integer t1) { assertEquals(6, c.get()); assertEquals(Collections.singletonList(e), ts.errors()); } + @Test public void testJustAndRetry() throws Exception { final AtomicBoolean throwException = new AtomicBoolean(true); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java index 4ee2fad368..fb65114e42 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java @@ -483,7 +483,6 @@ protected void subscribeActual(Subscriber<? super Object> s) { } } - @Test public void longSequenceEquals() { Flowable<Integer> source = Flowable.range(1, Flowable.bufferSize() * 4).subscribeOn(Schedulers.computation()); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java index 88cb84d40d..62f662804f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java @@ -192,7 +192,6 @@ public void onNext(Integer t) { assertEquals(Arrays.asList(Long.MAX_VALUE), requests); } - @Test public void testSingleWithPredicateFlowable() { Flowable<Integer> flowable = Flowable.just(1, 2) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java index 6c7cc67603..e301c29aec 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java @@ -156,6 +156,7 @@ public void testSwitchRequestAlternativeObservableWithBackpressure() { ts.request(1); ts.assertValueCount(3); } + @Test public void testBackpressureNoRequest() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java index 1878d133a4..d2caa4ada8 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java @@ -583,7 +583,6 @@ public Flowable<Long> apply(Long t) { assertTrue(ts.valueCount() > 0); } - @Test(timeout = 10000) public void testSecondaryRequestsDontOverflow() throws InterruptedException { TestSubscriber<Long> ts = new TestSubscriber<Long>(0L); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java index 3277d5f831..37f5ee0d1f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java @@ -241,7 +241,6 @@ public void onNext(Integer integer) { }); } - @Test public void testIgnoreRequest4() { // If `takeLast` does not ignore `request` properly, StackOverflowError will be thrown. diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java index 5510b534ea..91d4d4ea8b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java @@ -451,7 +451,6 @@ public void accept(Integer v) { ts.assertComplete(); } - @Test public void takeNegative() { try { @@ -485,7 +484,6 @@ public Flowable<Object> apply(Flowable<Object> f) throws Exception { }); } - @Test public void badRequest() { TestHelper.assertBadRequestReported(Flowable.never().take(1)); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java index 22e96421f0..acba2b1294 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java @@ -47,6 +47,7 @@ public boolean test(Object v) { verify(subscriber, never()).onError(any(Throwable.class)); verify(subscriber).onComplete(); } + @Test public void takeAll() { Subscriber<Object> subscriber = TestHelper.mockSubscriber(); @@ -63,6 +64,7 @@ public boolean test(Integer v) { verify(subscriber, never()).onError(any(Throwable.class)); verify(subscriber).onComplete(); } + @Test public void takeFirst() { Subscriber<Object> subscriber = TestHelper.mockSubscriber(); @@ -79,6 +81,7 @@ public boolean test(Integer v) { verify(subscriber, never()).onError(any(Throwable.class)); verify(subscriber).onComplete(); } + @Test public void takeSome() { Subscriber<Object> subscriber = TestHelper.mockSubscriber(); @@ -97,6 +100,7 @@ public boolean test(Integer t1) { verify(subscriber, never()).onError(any(Throwable.class)); verify(subscriber).onComplete(); } + @Test public void functionThrows() { Subscriber<Object> subscriber = TestHelper.mockSubscriber(); @@ -115,6 +119,7 @@ public boolean test(Integer t1) { verify(subscriber).onError(any(TestException.class)); verify(subscriber, never()).onComplete(); } + @Test public void sourceThrows() { Subscriber<Object> subscriber = TestHelper.mockSubscriber(); @@ -134,6 +139,7 @@ public boolean test(Integer v) { verify(subscriber).onError(any(TestException.class)); verify(subscriber, never()).onComplete(); } + @Test public void backpressure() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(5L); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java index 702f4660e1..b254ecdf8d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java @@ -209,6 +209,7 @@ public void testUntilFires() { assertFalse("Until still has observers", until.hasSubscribers()); assertFalse("TestSubscriber is unsubscribed", ts.isCancelled()); } + @Test public void testMainCompletes() { PublishProcessor<Integer> source = PublishProcessor.create(); @@ -232,6 +233,7 @@ public void testMainCompletes() { assertFalse("Until still has observers", until.hasSubscribers()); assertFalse("TestSubscriber is unsubscribed", ts.isCancelled()); } + @Test public void testDownstreamUnsubscribes() { PublishProcessor<Integer> source = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java index f9dc9c01f1..2e5fd020e7 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java @@ -153,7 +153,6 @@ public void testThrottle() { inOrder.verifyNoMoreInteractions(); } - @Test public void throttleFirstDefaultScheduler() { Flowable.just(1).throttleFirst(100, TimeUnit.MILLISECONDS) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatestTest.java index 2b07d178d9..5612307c28 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleLatestTest.java @@ -130,7 +130,6 @@ public void normal() { ts.assertResult(1, 3, 5, 6); } - @Test public void normalEmitLast() { TestScheduler sch = new TestScheduler(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java index ded3661e95..8ba33edca7 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java @@ -477,7 +477,6 @@ protected void subscribeActual(Subscriber<? super Integer> subscriber) { } } - @Test public void timedTake() { PublishProcessor<Integer> pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java index 21009d0da7..e5b9c61de4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java @@ -86,6 +86,7 @@ public void testTimerPeriodically() { ts.assertNotComplete(); ts.assertNoErrors(); } + @Test public void testInterval() { Flowable<Long> w = Flowable.interval(1, TimeUnit.SECONDS, scheduler); @@ -226,6 +227,7 @@ public void testWithMultipleStaggeredSubscribersAndPublish() { ts2.assertNoErrors(); ts2.assertNotComplete(); } + @Test public void testOnceObserverThrows() { Flowable<Long> source = Flowable.timer(100, TimeUnit.MILLISECONDS, scheduler); @@ -254,6 +256,7 @@ public void onComplete() { verify(subscriber, never()).onNext(anyLong()); verify(subscriber, never()).onComplete(); } + @Test public void testPeriodicObserverThrows() { Flowable<Long> source = Flowable.interval(100, 100, TimeUnit.MILLISECONDS, scheduler); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java index 20a0534285..ffa4d0eba3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java @@ -101,6 +101,7 @@ public void testListWithBlockingFirstFlowable() { List<String> actual = f.toList().toFlowable().blockingFirst(); Assert.assertEquals(Arrays.asList("one", "two", "three"), actual); } + @Test public void testBackpressureHonoredFlowable() { Flowable<List<Integer>> w = Flowable.just(1, 2, 3, 4, 5).toList().toFlowable(); @@ -124,6 +125,7 @@ public void testBackpressureHonoredFlowable() { ts.assertNoErrors(); ts.assertComplete(); } + @Test(timeout = 2000) @Ignore("PublishProcessor no longer emits without requests so this test fails due to the race of onComplete and request") public void testAsyncRequestedFlowable() { @@ -230,6 +232,7 @@ public void testListWithBlockingFirst() { List<String> actual = f.toList().blockingGet(); Assert.assertEquals(Arrays.asList("one", "two", "three"), actual); } + @Test @Ignore("Single doesn't do backpressure") public void testBackpressureHonored() { @@ -254,6 +257,7 @@ public void testBackpressureHonored() { to.assertNoErrors(); to.assertComplete(); } + @Test(timeout = 2000) @Ignore("PublishProcessor no longer emits without requests so this test fails due to the race of onComplete and request") public void testAsyncRequested() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMapTest.java index f8914e7182..296f68eef6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMapTest.java @@ -224,7 +224,6 @@ public String apply(String v) { verify(objectSubscriber, times(1)).onError(any(Throwable.class)); } - @Test public void testToMap() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMultimapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMultimapTest.java index 1546815355..bb77dab822 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMultimapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToMultimapTest.java @@ -296,7 +296,6 @@ public Map<Integer, Collection<String>> call() { verify(objectSubscriber, never()).onComplete(); } - @Test public void testToMultimap() { Flowable<String> source = Flowable.just("a", "b", "cc", "dd"); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java index bea7ef749a..173da4830d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java @@ -69,6 +69,7 @@ public void testWithFollowingFirstFlowable() { Flowable<Integer> f = Flowable.just(1, 3, 2, 5, 4); assertEquals(Arrays.asList(1, 2, 3, 4, 5), f.toSortedList().toFlowable().blockingFirst()); } + @Test public void testBackpressureHonoredFlowable() { Flowable<List<Integer>> w = Flowable.just(1, 3, 2, 5, 4).toSortedList().toFlowable(); @@ -202,6 +203,7 @@ public void testWithFollowingFirst() { Flowable<Integer> f = Flowable.just(1, 3, 2, 5, 4); assertEquals(Arrays.asList(1, 2, 3, 4, 5), f.toSortedList().blockingGet()); } + @Test @Ignore("Single doesn't do backpressure") public void testBackpressureHonored() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java index b67437e7a9..cfc8ab20b1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java @@ -331,8 +331,6 @@ public Flowable<String> apply(Resource resource) { } - - @Test public void testUsingDisposesEagerlyBeforeError() { final List<String> events = new ArrayList<String>(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java index a6469281c4..014ebbf756 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java @@ -326,6 +326,7 @@ public Flowable<Integer> call() { ts.assertNoErrors(); ts.assertValueCount(1); } + @Test public void testMainUnsubscribedOnBoundaryCompletion() { PublishProcessor<Integer> source = PublishProcessor.create(); @@ -386,6 +387,7 @@ public Flowable<Integer> call() { ts.assertNoErrors(); ts.assertValueCount(1); } + @Test public void testInnerBackpressure() { Flowable<Integer> source = Flowable.range(1, 10); @@ -771,7 +773,6 @@ public Flowable<Integer> apply( ts.assertResult(1); } - @Test public void mainAndBoundaryBothError() { List<Throwable> errors = TestHelper.trackPluginErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java index aeb5381da7..b6fb51f6d2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java @@ -211,6 +211,7 @@ public void testBackpressureOuter() { public void onStart() { request(1); } + @Override public void onNext(Flowable<Integer> t) { t.subscribe(new DefaultSubscriber<Integer>() { @@ -218,20 +219,24 @@ public void onNext(Flowable<Integer> t) { public void onNext(Integer t) { list.add(t); } + @Override public void onError(Throwable e) { subscriber.onError(e); } + @Override public void onComplete() { subscriber.onComplete(); } }); } + @Override public void onError(Throwable e) { subscriber.onError(e); } + @Override public void onComplete() { subscriber.onComplete(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java index 296c973963..d2eef83d88 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java @@ -158,6 +158,7 @@ public void onNext(T args) { } }; } + @Test public void testExactWindowSize() { Flowable<Flowable<Integer>> source = Flowable.range(1, 10) @@ -222,7 +223,6 @@ public void accept(Integer pv) { Assert.assertTrue(ts.valueCount() != 0); } - @Test public void timespanTimeskipCustomSchedulerBufferSize() { Flowable.range(1, 10) @@ -811,6 +811,7 @@ public void periodicWindowCompletionRestartTimerBoundedSomeData() { .assertNoErrors() .assertNotComplete(); } + @Test public void countRestartsOnTimeTick() { TestScheduler scheduler = new TestScheduler(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java index e87ff9fe50..070176bdb0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java @@ -134,7 +134,6 @@ public void testEmptyOther() { assertFalse(other.hasSubscribers()); } - @Test public void testUnsubscription() { PublishProcessor<Integer> source = PublishProcessor.create(); @@ -189,6 +188,7 @@ public void testSourceThrows() { assertFalse(source.hasSubscribers()); assertFalse(other.hasSubscribers()); } + @Test public void testOtherThrows() { PublishProcessor<Integer> source = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java index b02fa664fe..ef1223d66a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java @@ -1224,6 +1224,7 @@ public Integer apply(Integer i1, Integer i2) { } assertEquals(expected, zip2.toList().blockingGet()); } + @Test public void testUnboundedDownstreamOverrequesting() { Flowable<Integer> source = Flowable.range(1, 2).zipWith(Flowable.range(1, 2), new BiFunction<Integer, Integer, Integer>() { @@ -1247,6 +1248,7 @@ public void onNext(Integer t) { ts.assertTerminated(); ts.assertValues(11, 22); } + @Test(timeout = 10000) public void testZipRace() { long startTime = System.currentTimeMillis(); @@ -1570,6 +1572,7 @@ public Object apply(Integer a, Integer b, Integer c, Integer d, Integer e, Integ .test() .assertResult("12345678"); } + @Test public void zip9() { Flowable.zip(Flowable.just(1), @@ -1589,7 +1592,6 @@ public Object apply(Integer a, Integer b, Integer c, Integer d, Integer e, Integ .assertResult("123456789"); } - @Test public void zipArrayMany() { @SuppressWarnings("unchecked") diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java index 57c856b472..bae05a46b4 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java @@ -52,7 +52,6 @@ public void offlineError() { .assertFailure(TestException.class); } - @Test public void offlineComplete() { Maybe<Integer> source = Maybe.<Integer>empty().cache(); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeContainsTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeContainsTest.java index 588de845a8..60f319f873 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeContainsTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeContainsTest.java @@ -59,7 +59,6 @@ public void dispose() { assertFalse(pp.hasSubscribers()); } - @Test public void isDisposed() { PublishProcessor<Integer> pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java index 40cb873836..4719ac8977 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java @@ -65,7 +65,6 @@ public void justWithOnComplete() { to.assertResult(1); } - @Test public void justWithOnError() { PublishProcessor<Object> pp = PublishProcessor.create(); @@ -102,7 +101,6 @@ public void emptyWithOnNext() { to.assertResult(); } - @Test public void emptyWithOnComplete() { PublishProcessor<Object> pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeIsEmptyTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeIsEmptyTest.java index 3efe9dbec3..3602d44aa0 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeIsEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeIsEmptyTest.java @@ -54,7 +54,6 @@ public void fusedBackToMaybe() { .toMaybe() instanceof MaybeIsEmpty); } - @Test public void normalToMaybe() { Maybe.just(1) diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java index bacd1c1870..2c242fc1a5 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingleTest.java @@ -61,7 +61,6 @@ public void dispose() { assertFalse(pp.hasSubscribers()); } - @Test public void isDisposed() { PublishProcessor<Integer> pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java index d2e53a7225..142943ba67 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java @@ -76,7 +76,6 @@ public void dispose() { assertFalse(pp.hasSubscribers()); } - @Test public void isDisposed() { PublishProcessor<Integer> pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java index c78a7cf5d7..d007667097 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeUsingTest.java @@ -346,7 +346,6 @@ public void accept(Object d) throws Exception { .assertFailure(TestException.class); } - @Test public void emptyDisposerCrashes() { Maybe.using(new Callable<Object>() { diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java index 7fb24e1e27..cd97bea762 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java @@ -150,6 +150,7 @@ public void run() { } } } + @SuppressWarnings("unchecked") @Test(expected = NullPointerException.class) public void zipArrayOneIsNull() { diff --git a/src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservableTest.java b/src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservableTest.java index e75c8538ca..8493f9a15e 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/CompletableAndThenObservableTest.java @@ -63,7 +63,6 @@ public void cancelOther() { assertFalse(ps.hasObservers()); } - @Test public void errorMain() { CompletableSubject cs = CompletableSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybeTest.java index d080928047..58188a34eb 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapMaybeTest.java @@ -399,7 +399,6 @@ public MaybeSource<Integer> apply(Integer v) } } - @Test public void innerErrorAfterTermination() { List<Throwable> errors = TestHelper.trackPluginErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingleTest.java index 3c6c832b76..803e9bf013 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingleTest.java @@ -347,7 +347,6 @@ public SingleSource<Integer> apply(Integer v) } } - @Test public void innerErrorAfterTermination() { List<Throwable> errors = TestHelper.trackPluginErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java index 3faa98caa5..7830b885da 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java @@ -375,7 +375,6 @@ public MaybeSource<Integer> apply(Integer v) } } - @Test public void innerErrorAfterTermination() { List<Throwable> errors = TestHelper.trackPluginErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java index 03c38e54de..da35b10df1 100644 --- a/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java @@ -344,7 +344,6 @@ public SingleSource<Integer> apply(Integer v) } } - @Test public void innerErrorAfterTermination() { List<Throwable> errors = TestHelper.trackPluginErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java index d37fc5fb74..dc8445068c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java @@ -124,6 +124,7 @@ public boolean test(Integer i) { assertFalse(allOdd.blockingFirst()); } + @Test(timeout = 5000) public void testIssue1935NoUnsubscribeDownstreamObservable() { Observable<Integer> source = Observable.just(1) @@ -143,7 +144,6 @@ public Observable<Integer> apply(Boolean t1) { assertEquals((Object)2, source.blockingFirst()); } - @Test public void testPredicateThrowsExceptionAndValueInCauseMessageObservable() { TestObserver<Boolean> to = new TestObserver<Boolean>(); @@ -166,7 +166,6 @@ public boolean test(String v) { // assertTrue(ex.getCause().getMessage().contains("Boo!")); } - @Test public void testAll() { Observable<String> obs = Observable.just("one", "two", "six"); @@ -256,6 +255,7 @@ public boolean test(Integer i) { assertFalse(allOdd.blockingGet()); } + @Test(timeout = 5000) public void testIssue1935NoUnsubscribeDownstream() { Observable<Integer> source = Observable.just(1) @@ -275,7 +275,6 @@ public Observable<Integer> apply(Boolean t1) { assertEquals((Object)2, source.blockingFirst()); } - @Test public void testPredicateThrowsExceptionAndValueInCauseMessage() { TestObserver<Boolean> to = new TestObserver<Boolean>(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java index 150a13580f..7c66cba3f6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java @@ -231,6 +231,7 @@ public boolean test(Integer i) { assertTrue(anyEven.blockingFirst()); } + @Test(timeout = 5000) public void testIssue1935NoUnsubscribeDownstreamObservable() { Observable<Integer> source = Observable.just(1).isEmpty().toObservable() @@ -452,6 +453,7 @@ public boolean test(Integer i) { assertTrue(anyEven.blockingGet()); } + @Test(timeout = 5000) public void testIssue1935NoUnsubscribeDownstream() { Observable<Integer> source = Observable.just(1).isEmpty() diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 9ce8103e77..961bb7bfed 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -497,6 +497,7 @@ public void bufferWithBOBoundaryThrows() { verify(o, never()).onComplete(); verify(o, never()).onNext(any()); } + @Test(timeout = 2000) public void bufferWithSizeTake1() { Observable<Integer> source = Observable.just(1).repeat(); @@ -526,6 +527,7 @@ public void bufferWithSizeSkipTake1() { verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } + @Test(timeout = 2000) public void bufferWithTimeTake1() { Observable<Long> source = Observable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); @@ -542,6 +544,7 @@ public void bufferWithTimeTake1() { verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } + @Test(timeout = 2000) public void bufferWithTimeSkipTake2() { Observable<Long> source = Observable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); @@ -560,6 +563,7 @@ public void bufferWithTimeSkipTake2() { inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } + @Test(timeout = 2000) public void bufferWithBoundaryTake2() { Observable<Long> boundary = Observable.interval(60, 60, TimeUnit.MILLISECONDS, scheduler); @@ -614,6 +618,7 @@ public void accept(List<Long> pv) { inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } + @Test public void bufferWithSizeThrows() { PublishSubject<Integer> source = PublishSubject.create(); @@ -683,6 +688,7 @@ public void bufferWithTimeAndSize() { inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } + @Test public void bufferWithStartEndStartThrows() { PublishSubject<Integer> start = PublishSubject.create(); @@ -711,6 +717,7 @@ public Observable<Integer> apply(Integer t1) { verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } + @Test public void bufferWithStartEndEndFunctionThrows() { PublishSubject<Integer> start = PublishSubject.create(); @@ -738,6 +745,7 @@ public Observable<Integer> apply(Integer t1) { verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } + @Test public void bufferWithStartEndEndThrows() { PublishSubject<Integer> start = PublishSubject.create(); @@ -776,11 +784,13 @@ public void testBufferWithTimeDoesntUnsubscribeDownstream() throws InterruptedEx public void onNext(Object t) { o.onNext(t); } + @Override public void onError(Throwable e) { o.onError(e); cdl.countDown(); } + @Override public void onComplete() { o.onComplete(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java index c664c2591c..614fb29bf5 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java @@ -154,6 +154,7 @@ public void testAsync() { assertEquals(10000, to2.values().size()); } } + @Test public void testAsyncComeAndGo() { Observable<Long> source = Observable.interval(1, 1, TimeUnit.MILLISECONDS) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java index 63789a756d..ab34d4e03e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletableTest.java @@ -155,7 +155,6 @@ public void mapperThrows() { .assertFailure(TestException.class); } - @Test public void fusedPollThrows() { Observable.just(1) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java index 0f6920ecb3..3959fab45e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java @@ -623,7 +623,6 @@ public Observable<Integer> apply(Integer t) { to.assertValue(null); } - @Test @Ignore("Observable doesn't do backpressure") public void testMaxConcurrent5() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java index a9b6dc6faa..effef90136 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java @@ -623,6 +623,7 @@ public Observable<Integer> apply(Integer v) { inOrder.verify(o).onSuccess(list); verify(o, never()).onError(any(Throwable.class)); } + @Test public void concatVeryLongObservableOfObservablesTakeHalf() { final int n = 10000; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java index cbbed97785..3d03c3d8a1 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatWithMaybeTest.java @@ -42,7 +42,6 @@ public void run() throws Exception { to.assertResult(1, 2, 3, 4, 5, 100); } - @Test public void normalNonEmpty() { final TestObserver<Integer> to = new TestObserver<Integer>(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java index 9edae7bdc9..0aaacb1432 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java @@ -239,6 +239,7 @@ public Observable<Integer> apply(Integer t1) { verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } + @Test public void debounceTimedLastIsNotLost() { PublishSubject<Integer> source = PublishSubject.create(); @@ -256,6 +257,7 @@ public void debounceTimedLastIsNotLost() { verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } + @Test public void debounceSelectorLastIsNotLost() { PublishSubject<Integer> source = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDelaySubscriptionOtherTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDelaySubscriptionOtherTest.java index 6c416421a7..a37a2b00a7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDelaySubscriptionOtherTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDelaySubscriptionOtherTest.java @@ -203,7 +203,6 @@ public Object apply(Observable<Integer> o) throws Exception { }, false, 1, 1, 1); } - @Test public void afterDelayNoInterrupt() { ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java index 8a9c9f6daa..f8d274bc86 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java @@ -85,7 +85,6 @@ public void range() { to.assertComplete(); } - @Test @Ignore("Observable doesn't do backpressure") public void backpressured() throws Exception { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java index 82738bd4de..d6f08fff27 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoFinallyTest.java @@ -159,7 +159,6 @@ public void asyncFusedBoundary() { assertEquals(1, calls); } - @Test public void normalJustConditional() { Observable.just(1) @@ -445,7 +444,6 @@ public void onComplete() { assertEquals(1, calls); } - @Test public void eventOrdering() { final List<String> list = new ArrayList<String>(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java index 84ff5fa5ec..bd7dc12cf6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletableTest.java @@ -166,7 +166,6 @@ public CompletableSource apply(Integer v) throws Exception { .assertFailure(TestException.class); } - @Test public void fusedObservable() { TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.ANY); @@ -332,7 +331,6 @@ public CompletableSource apply(Integer v) throws Exception { .assertFailure(TestException.class); } - @Test public void fused() { TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.ANY); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index 17382f4dad..4ace4eacb2 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -350,6 +350,7 @@ public Observable<Integer> apply(Integer t1) { Assert.assertEquals(expected.size(), to.valueCount()); Assert.assertTrue(expected.containsAll(to.values())); } + @Test public void testFlatMapSelectorMaxConcurrent() { final int m = 4; @@ -471,6 +472,7 @@ public Observable<Integer> apply(Integer t) { } } } + @Test(timeout = 30000) public void flatMapRangeMixedAsyncLoop() { for (int i = 0; i < 2000; i++) { @@ -530,6 +532,7 @@ public Observable<Integer> apply(Integer t) { to.assertValueCount(1000); } } + @Test public void flatMapTwoNestedSync() { for (final int n : new int[] { 1, 1000, 1000000 }) { @@ -895,7 +898,6 @@ public Object apply(Integer v, Object w) throws Exception { .assertFailureAndMessage(NullPointerException.class, "The mapper returned a null ObservableSource"); } - @Test public void failingFusedInnerCancelsSource() { final AtomicInteger counter = new AtomicInteger(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeDelayErrorTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeDelayErrorTest.java index 472a25300b..833f9105c5 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeDelayErrorTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeDelayErrorTest.java @@ -429,6 +429,7 @@ public void onNext(String args) { } } + @Test @Ignore("Subscribers should not throw") public void testMergeSourceWhichDoesntPropagateExceptionBack() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeMaxConcurrentTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeMaxConcurrentTest.java index 582421d42b..ef52095f25 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeMaxConcurrentTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeMaxConcurrentTest.java @@ -137,6 +137,7 @@ public void testMergeALotOfSourcesOneByOneSynchronously() { } assertEquals(j, n); } + @Test public void testMergeALotOfSourcesOneByOneSynchronouslyTakeHalf() { int n = 10000; @@ -171,6 +172,7 @@ public void testSimple() { to.assertValueSequence(result); } } + @Test public void testSimpleOneLess() { for (int i = 2; i < 100; i++) { @@ -189,6 +191,7 @@ public void testSimpleOneLess() { to.assertValueSequence(result); } } + @Test//(timeout = 20000) public void testSimpleAsyncLoop() { IoScheduler ios = (IoScheduler)Schedulers.io(); @@ -201,6 +204,7 @@ public void testSimpleAsyncLoop() { } } } + @Test(timeout = 30000) public void testSimpleAsync() { for (int i = 1; i < 50; i++) { @@ -221,12 +225,14 @@ public void testSimpleAsync() { assertEquals(expected, actual); } } + @Test(timeout = 30000) public void testSimpleOneLessAsyncLoop() { for (int i = 0; i < 200; i++) { testSimpleOneLessAsync(); } } + @Test(timeout = 30000) public void testSimpleOneLessAsync() { long t = System.currentTimeMillis(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java index c178b3bddc..fb50ae0f0a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java @@ -1082,10 +1082,12 @@ void runMerge(Function<Integer, Observable<Integer>> func, TestObserver<Integer> public void testFastMergeFullScalar() { runMerge(toScalar, new TestObserver<Integer>()); } + @Test public void testFastMergeHiddenScalar() { runMerge(toHiddenScalar, new TestObserver<Integer>()); } + @Test public void testSlowMergeFullScalar() { for (final int req : new int[] { 16, 32, 64, 128, 256 }) { @@ -1103,6 +1105,7 @@ public void onNext(Integer t) { runMerge(toScalar, to); } } + @Test public void testSlowMergeHiddenScalar() { for (final int req : new int[] { 16, 32, 64, 128, 256 }) { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java index 173f506bce..181564df1c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java @@ -183,7 +183,6 @@ public String apply(String s) { verify(observer, times(1)).onComplete(); } - @Test public void testBackpressure() { TestObserver<Integer> to = new TestObserver<Integer>(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java index 18251f8f78..2f2a0e677e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java @@ -372,6 +372,7 @@ public void subscribe(Observer<? super Integer> t) { assertEquals(2, calls.get()); } + @Test public void testObserveOn() { ConnectableObservable<Integer> co = Observable.range(0, 1000).publish(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java index 5dce27dcaa..cb6e61e8f6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java @@ -145,7 +145,6 @@ public void testBackpressureWithInitialValueObservable() throws InterruptedExcep assertEquals(21, r.intValue()); } - @Test public void testAggregateAsIntSum() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java index 0c62893a77..b79e8c6c20 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java @@ -986,6 +986,7 @@ public void testAsync() { assertEquals(10000, to2.values().size()); } } + @Test public void testAsyncComeAndGo() { Observable<Long> source = Observable.interval(1, 1, TimeUnit.MILLISECONDS) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java index 9ebb3fd450..010b618c34 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java @@ -779,6 +779,7 @@ static <T> StringBuilder sequenceFrequency(Iterable<T> it) { return sb; } + @Test//(timeout = 3000) public void testIssue1900() throws InterruptedException { Observer<String> observer = TestHelper.mockObserver(); @@ -819,6 +820,7 @@ public Observable<String> apply(GroupedObservable<String, String> t1) { inOrder.verify(observer, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } + @Test//(timeout = 3000) public void testIssue1900SourceNotSupportingBackpressure() { Observer<String> observer = TestHelper.mockObserver(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java index 79ca287629..bd03c8874b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java @@ -69,6 +69,7 @@ public void testWithNothingToRetry() { inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } + @Test public void testRetryTwice() { Observable<Integer> source = Observable.unsafeCreate(new ObservableSource<Integer>() { @@ -104,6 +105,7 @@ public void subscribe(Observer<? super Integer> t1) { verify(o, never()).onError(any(Throwable.class)); } + @Test public void testRetryTwiceAndGiveUp() { Observable<Integer> source = Observable.unsafeCreate(new ObservableSource<Integer>() { @@ -131,6 +133,7 @@ public void subscribe(Observer<? super Integer> t1) { verify(o, never()).onComplete(); } + @Test public void testRetryOnSpecificException() { Observable<Integer> source = Observable.unsafeCreate(new ObservableSource<Integer>() { @@ -165,6 +168,7 @@ public void subscribe(Observer<? super Integer> t1) { inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } + @Test public void testRetryOnSpecificExceptionAndNotOther() { final IOException ioe = new IOException(); @@ -288,6 +292,7 @@ public Integer apply(Integer t1) { assertEquals(6, c.get()); assertEquals(Collections.singletonList(e), to.errors()); } + @Test public void testJustAndRetry() throws Exception { final AtomicBoolean throwException = new AtomicBoolean(true); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java index ab68bd6790..610f49eac4 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java @@ -484,7 +484,6 @@ public void onNext(String t) { Assert.assertEquals(250, to.valueCount()); } - @Test public void delayErrors() { PublishSubject<ObservableSource<Integer>> source = PublishSubject.create(); @@ -608,7 +607,6 @@ public ObservableSource<Integer> apply(Object v) throws Exception { } - @Test public void switchMapInnerCancelled() { PublishSubject<Integer> ps = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java index 722da7890a..0e6f040972 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java @@ -46,6 +46,7 @@ public boolean test(Object v) { verify(o, never()).onError(any(Throwable.class)); verify(o).onComplete(); } + @Test public void takeAll() { Observer<Object> o = TestHelper.mockObserver(); @@ -62,6 +63,7 @@ public boolean test(Integer v) { verify(o, never()).onError(any(Throwable.class)); verify(o).onComplete(); } + @Test public void takeFirst() { Observer<Object> o = TestHelper.mockObserver(); @@ -78,6 +80,7 @@ public boolean test(Integer v) { verify(o, never()).onError(any(Throwable.class)); verify(o).onComplete(); } + @Test public void takeSome() { Observer<Object> o = TestHelper.mockObserver(); @@ -96,6 +99,7 @@ public boolean test(Integer t1) { verify(o, never()).onError(any(Throwable.class)); verify(o).onComplete(); } + @Test public void functionThrows() { Observer<Object> o = TestHelper.mockObserver(); @@ -114,6 +118,7 @@ public boolean test(Integer t1) { verify(o).onError(any(TestException.class)); verify(o, never()).onComplete(); } + @Test public void sourceThrows() { Observer<Object> o = TestHelper.mockObserver(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java index d78129e2ea..7ea5698be3 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java @@ -210,6 +210,7 @@ public void testUntilFires() { // 2.0.2 - not anymore // assertTrue("Not cancelled!", ts.isCancelled()); } + @Test public void testMainCompletes() { PublishSubject<Integer> source = PublishSubject.create(); @@ -234,6 +235,7 @@ public void testMainCompletes() { // 2.0.2 - not anymore // assertTrue("Not cancelled!", ts.isCancelled()); } + @Test public void testDownstreamUnsubscribes() { PublishSubject<Integer> source = PublishSubject.create(); @@ -273,7 +275,6 @@ public Observable<Integer> apply(Observable<Integer> o) throws Exception { }); } - @Test public void untilPublisherMainSuccess() { PublishSubject<Integer> main = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableThrottleLatestTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableThrottleLatestTest.java index 9d60e5d232..059d516da1 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableThrottleLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableThrottleLatestTest.java @@ -129,7 +129,6 @@ public void normal() { to.assertResult(1, 3, 5, 6); } - @Test public void normalEmitLast() { TestScheduler sch = new TestScheduler(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java index 416a5e10e0..c8af9d88b8 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java @@ -87,6 +87,7 @@ public void testTimerPeriodically() { to.assertNotComplete(); to.assertNoErrors(); } + @Test public void testInterval() { Observable<Long> w = Observable.interval(1, TimeUnit.SECONDS, scheduler); @@ -227,6 +228,7 @@ public void testWithMultipleStaggeredSubscribersAndPublish() { to2.assertNoErrors(); to2.assertNotComplete(); } + @Test public void testOnceObserverThrows() { Observable<Long> source = Observable.timer(100, TimeUnit.MILLISECONDS, scheduler); @@ -255,6 +257,7 @@ public void onComplete() { verify(observer, never()).onNext(anyLong()); verify(observer, never()).onComplete(); } + @Test public void testPeriodicObserverThrows() { Observable<Long> source = Observable.interval(100, 100, TimeUnit.MILLISECONDS, scheduler); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableToMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableToMapTest.java index 1f477a0a38..f9eb6e1634 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableToMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableToMapTest.java @@ -225,7 +225,6 @@ public String apply(String v) { verify(objectObserver, times(1)).onError(any(Throwable.class)); } - @Test public void testToMap() { Observable<String> source = Observable.just("a", "bb", "ccc", "dddd"); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableToMultimapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableToMultimapTest.java index 9a1ebc44d8..f762930fc1 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableToMultimapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableToMultimapTest.java @@ -296,8 +296,6 @@ public Map<Integer, Collection<String>> call() { verify(objectObserver, never()).onComplete(); } - - @Test public void testToMultimap() { Observable<String> source = Observable.just("a", "b", "cc", "dd"); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableToSortedListTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableToSortedListTest.java index f715b6b08c..20ffdd236a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableToSortedListTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableToSortedListTest.java @@ -115,7 +115,6 @@ public int compare(Integer a, Integer b) { .assertResult(Arrays.asList(5, 4, 3, 2, 1)); } - @Test public void testSortedList() { Observable<Integer> w = Observable.just(1, 3, 2, 5, 4); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java index 286bb7d4a9..02fd41ef54 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java @@ -330,8 +330,6 @@ public Observable<String> apply(Resource resource) { } - - @Test public void testUsingDisposesEagerlyBeforeError() { final List<String> events = new ArrayList<String>(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java index 000b116615..b015bfb737 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java @@ -329,6 +329,7 @@ public Observable<Integer> call() { to.assertNoErrors(); to.assertValueCount(1); } + @Test public void testMainUnsubscribedOnBoundaryCompletion() { PublishSubject<Integer> source = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java index bfccb343da..8c81f6a70a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java @@ -158,6 +158,7 @@ public void onNext(T args) { } }; } + @Test public void testExactWindowSize() { Observable<Observable<Integer>> source = Observable.range(1, 10) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java index 9b1ea3e54e..4f3c62b992 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java @@ -134,7 +134,6 @@ public void testEmptyOther() { assertFalse(other.hasObservers()); } - @Test public void testUnsubscription() { PublishSubject<Integer> source = PublishSubject.create(); @@ -189,6 +188,7 @@ public void testSourceThrows() { assertFalse(source.hasObservers()); assertFalse(other.hasObservers()); } + @Test public void testOtherThrows() { PublishSubject<Integer> source = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java index ac68979af9..2fc7d7cb52 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java @@ -1261,6 +1261,7 @@ public Object apply(Integer a, Integer b, Integer c, Integer d, Integer e, Integ .test() .assertResult("12345678"); } + @Test public void zip9() { Observable.zip(Observable.just(1), diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java index 52d67e742a..09a29e55ff 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleConcatTest.java @@ -163,7 +163,6 @@ public void subscribe(SingleEmitter<Integer> s) throws Exception { assertEquals(1, calls[0]); } - @SuppressWarnings("unchecked") @Test public void noSubsequentSubscriptionIterable() { diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java index ee1de82fb7..ca586a0907 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java @@ -105,7 +105,6 @@ public Completable apply(Integer t) throws Exception { assertFalse(b[0]); } - @Test public void flatMapObservable() { Single.just(1).flatMapObservable(new Function<Integer, Observable<Integer>>() { diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java index ebd0445358..2c4ebcc321 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java @@ -111,7 +111,6 @@ public void shouldNotInvokeFuncUntilSubscription() throws Exception { verify(func).call(); } - @Test public void noErrorLoss() throws Exception { List<Throwable> errors = TestHelper.trackPluginErrors(); diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleMergeTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleMergeTest.java index bf1a100ac9..ef5f6de826 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleMergeTest.java @@ -125,7 +125,6 @@ public void mergeDelayError3() { .assertFailure(TestException.class, 1, 2); } - @Test public void mergeDelayError4() { Single.mergeDelayError( diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java index d646542a93..c7a1180a30 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java @@ -59,7 +59,6 @@ public void mainSuccessSingle() { to.assertResult(1); } - @Test public void mainSuccessCompletable() { PublishProcessor<Integer> pp = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java index 2f7e398c03..f188547bc9 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java @@ -150,6 +150,7 @@ public void run() { } } } + @SuppressWarnings("unchecked") @Test(expected = NullPointerException.class) public void zipArrayOneIsNull() { diff --git a/src/test/java/io/reactivex/internal/schedulers/AbstractDirectTaskTest.java b/src/test/java/io/reactivex/internal/schedulers/AbstractDirectTaskTest.java index 1357f27b5c..17a69ab93d 100644 --- a/src/test/java/io/reactivex/internal/schedulers/AbstractDirectTaskTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/AbstractDirectTaskTest.java @@ -115,6 +115,7 @@ public boolean cancel(boolean mayInterruptIfRunning) { assertTrue(interrupted[0]); } + @Test public void setFutureCancelSameThread() { AbstractDirectTask task = new AbstractDirectTask(Functions.EMPTY_RUNNABLE) { diff --git a/src/test/java/io/reactivex/internal/schedulers/ImmediateThinSchedulerTest.java b/src/test/java/io/reactivex/internal/schedulers/ImmediateThinSchedulerTest.java index 747aa49bfe..507ebd32d0 100644 --- a/src/test/java/io/reactivex/internal/schedulers/ImmediateThinSchedulerTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/ImmediateThinSchedulerTest.java @@ -47,6 +47,7 @@ public void scheduleDirectTimed() { public void scheduleDirectPeriodic() { ImmediateThinScheduler.INSTANCE.schedulePeriodicallyDirect(Functions.EMPTY_RUNNABLE, 1, 1, TimeUnit.SECONDS); } + @Test public void schedule() { final int[] count = { 0 }; diff --git a/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java b/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java index add5de3ed0..9d1718f7d0 100644 --- a/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/ScheduledRunnableTest.java @@ -372,7 +372,6 @@ public void asyncDisposeIdempotent() { assertEquals(ScheduledRunnable.ASYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); } - @Test public void noParentIsDisposed() { ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); diff --git a/src/test/java/io/reactivex/internal/subscribers/BlockingSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/BlockingSubscriberTest.java index 3c35e2315d..3d6017bad4 100644 --- a/src/test/java/io/reactivex/internal/subscribers/BlockingSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/BlockingSubscriberTest.java @@ -93,6 +93,7 @@ public void cancelOnRequest() { public void request(long n) { bf.cancelled = true; } + @Override public void cancel() { b.set(true); @@ -118,6 +119,7 @@ public void cancelUpfront() { public void request(long n) { b.set(true); } + @Override public void cancel() { } diff --git a/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java index 8643924bad..7b47129559 100644 --- a/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java @@ -303,6 +303,7 @@ public void callsAfterUnsubscribe() { ts.assertNoErrors(); ts.assertNotComplete(); } + @Test public void emissionRequestRace() { Worker w = Schedulers.computation().createWorker(); diff --git a/src/test/java/io/reactivex/internal/subscribers/InnerQueuedSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/InnerQueuedSubscriberTest.java index 28058606c4..f71ad289d0 100644 --- a/src/test/java/io/reactivex/internal/subscribers/InnerQueuedSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/InnerQueuedSubscriberTest.java @@ -27,12 +27,15 @@ public void requestInBatches() { @Override public void innerNext(InnerQueuedSubscriber<Integer> inner, Integer value) { } + @Override public void innerError(InnerQueuedSubscriber<Integer> inner, Throwable e) { } + @Override public void innerComplete(InnerQueuedSubscriber<Integer> inner) { } + @Override public void drain() { } @@ -47,6 +50,7 @@ public void drain() { public void request(long n) { requests.add(n); } + @Override public void cancel() { // ignore diff --git a/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java index 7f16d6e0ee..d61d1a4dfe 100644 --- a/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/LambdaSubscriberTest.java @@ -242,6 +242,7 @@ public void accept(Subscription s) throws Exception { assertEquals(Arrays.asList(1, 100), received); } + @Test public void badSourceEmitAfterDone() { Flowable<Integer> source = Flowable.fromPublisher(new Publisher<Integer>() { diff --git a/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java b/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java index f7314b1d68..dd010ca100 100644 --- a/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java +++ b/src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java @@ -51,15 +51,15 @@ public void cancelNoOp() { @Test public void set() { - AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + AtomicReference<Subscription> atomicSubscription = new AtomicReference<Subscription>(); BooleanSubscription bs1 = new BooleanSubscription(); - assertTrue(SubscriptionHelper.set(s, bs1)); + assertTrue(SubscriptionHelper.set(atomicSubscription, bs1)); BooleanSubscription bs2 = new BooleanSubscription(); - assertTrue(SubscriptionHelper.set(s, bs2)); + assertTrue(SubscriptionHelper.set(atomicSubscription, bs2)); assertTrue(bs1.isCancelled()); @@ -68,15 +68,15 @@ public void set() { @Test public void replace() { - AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + AtomicReference<Subscription> atomicSubscription = new AtomicReference<Subscription>(); BooleanSubscription bs1 = new BooleanSubscription(); - assertTrue(SubscriptionHelper.replace(s, bs1)); + assertTrue(SubscriptionHelper.replace(atomicSubscription, bs1)); BooleanSubscription bs2 = new BooleanSubscription(); - assertTrue(SubscriptionHelper.replace(s, bs2)); + assertTrue(SubscriptionHelper.replace(atomicSubscription, bs2)); assertFalse(bs1.isCancelled()); @@ -86,12 +86,12 @@ public void replace() { @Test public void cancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + final AtomicReference<Subscription> atomicSubscription = new AtomicReference<Subscription>(); Runnable r = new Runnable() { @Override public void run() { - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(atomicSubscription); } }; @@ -102,7 +102,7 @@ public void run() { @Test public void setRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + final AtomicReference<Subscription> atomicSubscription = new AtomicReference<Subscription>(); final BooleanSubscription bs1 = new BooleanSubscription(); final BooleanSubscription bs2 = new BooleanSubscription(); @@ -110,14 +110,14 @@ public void setRace() { Runnable r1 = new Runnable() { @Override public void run() { - SubscriptionHelper.set(s, bs1); + SubscriptionHelper.set(atomicSubscription, bs1); } }; Runnable r2 = new Runnable() { @Override public void run() { - SubscriptionHelper.set(s, bs2); + SubscriptionHelper.set(atomicSubscription, bs2); } }; @@ -130,7 +130,7 @@ public void run() { @Test public void replaceRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + final AtomicReference<Subscription> atomicSubscription = new AtomicReference<Subscription>(); final BooleanSubscription bs1 = new BooleanSubscription(); final BooleanSubscription bs2 = new BooleanSubscription(); @@ -138,14 +138,14 @@ public void replaceRace() { Runnable r1 = new Runnable() { @Override public void run() { - SubscriptionHelper.replace(s, bs1); + SubscriptionHelper.replace(atomicSubscription, bs1); } }; Runnable r2 = new Runnable() { @Override public void run() { - SubscriptionHelper.replace(s, bs2); + SubscriptionHelper.replace(atomicSubscription, bs2); } }; @@ -158,31 +158,31 @@ public void run() { @Test public void cancelAndChange() { - AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + AtomicReference<Subscription> atomicSubscription = new AtomicReference<Subscription>(); - SubscriptionHelper.cancel(s); + SubscriptionHelper.cancel(atomicSubscription); BooleanSubscription bs1 = new BooleanSubscription(); - assertFalse(SubscriptionHelper.set(s, bs1)); + assertFalse(SubscriptionHelper.set(atomicSubscription, bs1)); assertTrue(bs1.isCancelled()); - assertFalse(SubscriptionHelper.set(s, null)); + assertFalse(SubscriptionHelper.set(atomicSubscription, null)); BooleanSubscription bs2 = new BooleanSubscription(); - assertFalse(SubscriptionHelper.replace(s, bs2)); + assertFalse(SubscriptionHelper.replace(atomicSubscription, bs2)); assertTrue(bs2.isCancelled()); - assertFalse(SubscriptionHelper.replace(s, null)); + assertFalse(SubscriptionHelper.replace(atomicSubscription, null)); } @Test public void invalidDeferredRequest() { - AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + AtomicReference<Subscription> atomicSubscription = new AtomicReference<Subscription>(); AtomicLong r = new AtomicLong(); List<Throwable> errors = TestHelper.trackPluginErrors(); try { - SubscriptionHelper.deferredRequest(s, r, -99); + SubscriptionHelper.deferredRequest(atomicSubscription, r, -99); TestHelper.assertError(errors, 0, IllegalArgumentException.class, "n > 0 required but it was -99"); } finally { @@ -193,7 +193,7 @@ public void invalidDeferredRequest() { @Test public void deferredRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - final AtomicReference<Subscription> s = new AtomicReference<Subscription>(); + final AtomicReference<Subscription> atomicSubscription = new AtomicReference<Subscription>(); final AtomicLong r = new AtomicLong(); final AtomicLong q = new AtomicLong(); @@ -213,20 +213,20 @@ public void cancel() { Runnable r1 = new Runnable() { @Override public void run() { - SubscriptionHelper.deferredSetOnce(s, r, a); + SubscriptionHelper.deferredSetOnce(atomicSubscription, r, a); } }; Runnable r2 = new Runnable() { @Override public void run() { - SubscriptionHelper.deferredRequest(s, r, 1); + SubscriptionHelper.deferredRequest(atomicSubscription, r, 1); } }; TestHelper.race(r1, r2); - assertSame(a, s.get()); + assertSame(a, atomicSubscription.get()); assertEquals(1, q.get()); assertEquals(0, r.get()); } diff --git a/src/test/java/io/reactivex/internal/util/EndConsumerHelperTest.java b/src/test/java/io/reactivex/internal/util/EndConsumerHelperTest.java index 9fbddd4279..13a672f566 100644 --- a/src/test/java/io/reactivex/internal/util/EndConsumerHelperTest.java +++ b/src/test/java/io/reactivex/internal/util/EndConsumerHelperTest.java @@ -54,9 +54,11 @@ public void checkDoubleDefaultSubscriber() { @Override public void onNext(Integer t) { } + @Override public void onError(Throwable t) { } + @Override public void onComplete() { } @@ -85,9 +87,11 @@ static final class EndDefaultSubscriber extends DefaultSubscriber<Integer> { @Override public void onNext(Integer t) { } + @Override public void onError(Throwable t) { } + @Override public void onComplete() { } @@ -124,9 +128,11 @@ public void checkDoubleDisposableSubscriber() { @Override public void onNext(Integer t) { } + @Override public void onError(Throwable t) { } + @Override public void onComplete() { } @@ -157,9 +163,11 @@ public void checkDoubleResourceSubscriber() { @Override public void onNext(Integer t) { } + @Override public void onError(Throwable t) { } + @Override public void onComplete() { } @@ -190,9 +198,11 @@ public void checkDoubleDefaultObserver() { @Override public void onNext(Integer t) { } + @Override public void onError(Throwable t) { } + @Override public void onComplete() { } @@ -223,9 +233,11 @@ public void checkDoubleDisposableObserver() { @Override public void onNext(Integer t) { } + @Override public void onError(Throwable t) { } + @Override public void onComplete() { } @@ -256,9 +268,11 @@ public void checkDoubleResourceObserver() { @Override public void onNext(Integer t) { } + @Override public void onError(Throwable t) { } + @Override public void onComplete() { } @@ -289,6 +303,7 @@ public void checkDoubleDisposableSingleObserver() { @Override public void onSuccess(Integer t) { } + @Override public void onError(Throwable t) { } @@ -319,6 +334,7 @@ public void checkDoubleResourceSingleObserver() { @Override public void onSuccess(Integer t) { } + @Override public void onError(Throwable t) { } @@ -349,9 +365,11 @@ public void checkDoubleDisposableMaybeObserver() { @Override public void onSuccess(Integer t) { } + @Override public void onError(Throwable t) { } + @Override public void onComplete() { } @@ -382,9 +400,11 @@ public void checkDoubleResourceMaybeObserver() { @Override public void onSuccess(Integer t) { } + @Override public void onError(Throwable t) { } + @Override public void onComplete() { } @@ -415,6 +435,7 @@ public void checkDoubleDisposableCompletableObserver() { @Override public void onError(Throwable t) { } + @Override public void onComplete() { } @@ -445,6 +466,7 @@ public void checkDoubleResourceCompletableObserver() { @Override public void onError(Throwable t) { } + @Override public void onComplete() { } diff --git a/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java b/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java index 14375b506a..6be3075191 100644 --- a/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java +++ b/src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java @@ -814,6 +814,7 @@ public void accept(Observer<? super Integer> a, Integer v) { to.assertFailure(TestException.class); } + @Test public void observerCheckTerminatedNonDelayErrorErrorResource() { TestObserver<Integer> to = new TestObserver<Integer>(); diff --git a/src/test/java/io/reactivex/maybe/MaybeCreateTest.java b/src/test/java/io/reactivex/maybe/MaybeCreateTest.java index e13b5f09cb..f6d24bd980 100644 --- a/src/test/java/io/reactivex/maybe/MaybeCreateTest.java +++ b/src/test/java/io/reactivex/maybe/MaybeCreateTest.java @@ -92,7 +92,6 @@ public void subscribe(MaybeEmitter<Integer> e) throws Exception { assertTrue(d.isDisposed()); } - @Test public void basicWithCompletion() { final Disposable d = Disposables.empty(); diff --git a/src/test/java/io/reactivex/maybe/MaybeTest.java b/src/test/java/io/reactivex/maybe/MaybeTest.java index 94c7c9eb8a..b726b77611 100644 --- a/src/test/java/io/reactivex/maybe/MaybeTest.java +++ b/src/test/java/io/reactivex/maybe/MaybeTest.java @@ -350,7 +350,6 @@ public void completableMaybeCompletable() { Completable.complete().toMaybe().ignoreElement().test().assertResult(); } - @Test public void unsafeCreate() { Maybe.unsafeCreate(new MaybeSource<Integer>() { @@ -646,7 +645,6 @@ public void accept(Throwable e) throws Exception { assertNotEquals(main, name[0]); } - @Test public void observeOnCompleteThread() { String main = Thread.currentThread().getName(); @@ -688,7 +686,6 @@ public void subscribeOnComplete() { ; } - @Test public void fromAction() { final int[] call = { 0 }; @@ -801,7 +798,6 @@ public void accept(Integer v) throws Exception { .assertFailure(TestException.class); } - @Test public void doOnSubscribe() { final Disposable[] value = { null }; @@ -830,7 +826,6 @@ public void accept(Disposable v) throws Exception { .assertFailure(TestException.class); } - @Test public void doOnCompleteThrows() { Maybe.empty().doOnComplete(new Action() { @@ -862,7 +857,6 @@ public void run() throws Exception { assertEquals(1, call[0]); } - @Test public void doOnDisposeThrows() { List<Throwable> list = TestHelper.trackPluginErrors(); @@ -971,7 +965,6 @@ public void run() throws Exception { assertEquals(-1, call[0]); } - @Test public void doAfterTerminateComplete() { final int[] call = { 0 }; @@ -1013,7 +1006,6 @@ public void subscribe(MaybeObserver<? super Object> observer) { } } - @Test public void sourceThrowsIAE() { try { @@ -1180,6 +1172,7 @@ public void ignoreElementComplete() { .test() .assertResult(); } + @Test public void ignoreElementSuccessMaybe() { Maybe.just(1) @@ -2436,7 +2429,6 @@ public void accept(Integer v, Throwable e) throws Exception { assertEquals(2, list.size()); } - @Test public void doOnEventCompleteThrows() { Maybe.<Integer>empty() @@ -2880,7 +2872,6 @@ public void zipArray() { .assertResult("[1]"); } - @SuppressWarnings("unchecked") @Test public void zipIterable() { @@ -2983,7 +2974,6 @@ public void zip9() { .assertResult("123456789"); } - @Test public void ambWith1SignalsSuccess() { PublishProcessor<Integer> pp1 = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/observable/ObservableNullTests.java b/src/test/java/io/reactivex/observable/ObservableNullTests.java index 7a429c4555..847b7c0422 100644 --- a/src/test/java/io/reactivex/observable/ObservableNullTests.java +++ b/src/test/java/io/reactivex/observable/ObservableNullTests.java @@ -2768,7 +2768,6 @@ public Object apply(Integer a, Integer b) { }); } - @Test(expected = NullPointerException.class) public void zipWithCombinerNull() { just1.zipWith(just1, null); diff --git a/src/test/java/io/reactivex/observable/ObservableReduceTests.java b/src/test/java/io/reactivex/observable/ObservableReduceTests.java index 5a08fd2d65..a5bdacf48b 100644 --- a/src/test/java/io/reactivex/observable/ObservableReduceTests.java +++ b/src/test/java/io/reactivex/observable/ObservableReduceTests.java @@ -77,7 +77,6 @@ public Movie apply(Movie t1, Movie t2) { assertNotNull(reduceResult2); } - @Test public void reduceInts() { Observable<Integer> o = Observable.just(1, 2, 3); diff --git a/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java b/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java index 14af3cf2d0..9544bb5030 100644 --- a/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java +++ b/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java @@ -180,7 +180,6 @@ public void safeSubscriberAlreadySafe() { to.assertResult(1); } - @Test public void methodTestNoCancel() { PublishSubject<Integer> ps = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/observable/ObservableTest.java b/src/test/java/io/reactivex/observable/ObservableTest.java index fbe071714b..1d754c5e68 100644 --- a/src/test/java/io/reactivex/observable/ObservableTest.java +++ b/src/test/java/io/reactivex/observable/ObservableTest.java @@ -145,7 +145,6 @@ public Throwable call() { verify(w, times(1)).onError(any(RuntimeException.class)); } - @Test public void testCountAFewItems() { Observable<String> o = Observable.just("a", "b", "c", "d"); diff --git a/src/test/java/io/reactivex/observers/SafeObserverTest.java b/src/test/java/io/reactivex/observers/SafeObserverTest.java index 12c355905f..edd725b7ed 100644 --- a/src/test/java/io/reactivex/observers/SafeObserverTest.java +++ b/src/test/java/io/reactivex/observers/SafeObserverTest.java @@ -452,10 +452,12 @@ public void testOnCompletedThrows() { public void onNext(Integer t) { } + @Override public void onError(Throwable e) { error.set(e); } + @Override public void onComplete() { throw new TestException(); @@ -476,9 +478,11 @@ public void testActual() { @Override public void onNext(Integer t) { } + @Override public void onError(Throwable e) { } + @Override public void onComplete() { } diff --git a/src/test/java/io/reactivex/observers/SerializedObserverTest.java b/src/test/java/io/reactivex/observers/SerializedObserverTest.java index 726ca7aee4..a2f0e63ece 100644 --- a/src/test/java/io/reactivex/observers/SerializedObserverTest.java +++ b/src/test/java/io/reactivex/observers/SerializedObserverTest.java @@ -974,6 +974,7 @@ public void onNext(Integer v) { to.assertValue(1); to.assertError(TestException.class); } + @Test public void testCompleteReentry() { final AtomicReference<Observer<Integer>> serial = new AtomicReference<Observer<Integer>>(); diff --git a/src/test/java/io/reactivex/observers/TestObserverTest.java b/src/test/java/io/reactivex/observers/TestObserverTest.java index 1b638ace38..efe9798bae 100644 --- a/src/test/java/io/reactivex/observers/TestObserverTest.java +++ b/src/test/java/io/reactivex/observers/TestObserverTest.java @@ -272,6 +272,7 @@ public void testTerminalErrorOnce() { } fail("Failed to report multiple onError terminal events!"); } + @Test public void testTerminalCompletedOnce() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); diff --git a/src/test/java/io/reactivex/parallel/ParallelDoOnNextTryTest.java b/src/test/java/io/reactivex/parallel/ParallelDoOnNextTryTest.java index 3a40edc229..41f82363d6 100644 --- a/src/test/java/io/reactivex/parallel/ParallelDoOnNextTryTest.java +++ b/src/test/java/io/reactivex/parallel/ParallelDoOnNextTryTest.java @@ -49,6 +49,7 @@ public void doOnNextNoError() { calls = 0; } } + @Test public void doOnNextErrorNoError() { for (ParallelFailureHandling e : ParallelFailureHandling.values()) { diff --git a/src/test/java/io/reactivex/parallel/ParallelFilterTryTest.java b/src/test/java/io/reactivex/parallel/ParallelFilterTryTest.java index bb7d919ce0..e49090acf8 100644 --- a/src/test/java/io/reactivex/parallel/ParallelFilterTryTest.java +++ b/src/test/java/io/reactivex/parallel/ParallelFilterTryTest.java @@ -94,6 +94,7 @@ public void filterConditionalNoError() { .assertResult(1); } } + @Test public void filterErrorConditionalNoError() { for (ParallelFailureHandling e : ParallelFailureHandling.values()) { diff --git a/src/test/java/io/reactivex/parallel/ParallelFlowableTest.java b/src/test/java/io/reactivex/parallel/ParallelFlowableTest.java index 577d4be1cd..ab98b5a9f4 100644 --- a/src/test/java/io/reactivex/parallel/ParallelFlowableTest.java +++ b/src/test/java/io/reactivex/parallel/ParallelFlowableTest.java @@ -454,7 +454,6 @@ public void accept(List<Integer> v) throws Exception { } } - @Test public void collectAsync2() { ExecutorService exec = Executors.newFixedThreadPool(3); @@ -551,7 +550,6 @@ public void accept(List<Integer> v) throws Exception { } } - @Test public void collectAsync3Fused() { ExecutorService exec = Executors.newFixedThreadPool(3); diff --git a/src/test/java/io/reactivex/parallel/ParallelMapTryTest.java b/src/test/java/io/reactivex/parallel/ParallelMapTryTest.java index bed3f5eae8..09b3dbcf6d 100644 --- a/src/test/java/io/reactivex/parallel/ParallelMapTryTest.java +++ b/src/test/java/io/reactivex/parallel/ParallelMapTryTest.java @@ -44,6 +44,7 @@ public void mapNoError() { .assertResult(1); } } + @Test public void mapErrorNoError() { for (ParallelFailureHandling e : ParallelFailureHandling.values()) { @@ -68,6 +69,7 @@ public void mapConditionalNoError() { .assertResult(1); } } + @Test public void mapErrorConditionalNoError() { for (ParallelFailureHandling e : ParallelFailureHandling.values()) { diff --git a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java index a8c9668731..f522b84fd3 100644 --- a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java +++ b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java @@ -1954,7 +1954,6 @@ public Subscriber apply(Flowable f, Subscriber s) throws Exception { } } - @SuppressWarnings("rawtypes") @Test public void maybeCreate() { diff --git a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java index c97f3398e1..d90fe6705f 100644 --- a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java +++ b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java @@ -368,6 +368,7 @@ public void testCurrentStateMethodsEmpty() { assertNull(as.getValue()); assertNull(as.getThrowable()); } + @Test public void testCurrentStateMethodsError() { AsyncProcessor<Object> as = AsyncProcessor.create(); diff --git a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java index 59d8cbff02..d7f3dca92b 100644 --- a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java +++ b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java @@ -282,6 +282,7 @@ public void onComplete() { verify(subscriber, never()).onError(any(Throwable.class)); } } + @Test public void testStartEmpty() { BehaviorProcessor<Integer> source = BehaviorProcessor.create(); @@ -307,6 +308,7 @@ public void testStartEmpty() { } + @Test public void testStartEmptyThenAddOne() { BehaviorProcessor<Integer> source = BehaviorProcessor.create(); @@ -329,6 +331,7 @@ public void testStartEmptyThenAddOne() { verify(subscriber, never()).onError(any(Throwable.class)); } + @Test public void testStartEmptyCompleteWithOne() { BehaviorProcessor<Integer> source = BehaviorProcessor.create(); @@ -406,6 +409,7 @@ public void testTakeOneSubscriber() { // // even though the onError above throws we should still receive it on the other subscriber // assertEquals(1, ts.getOnErrorEvents().size()); // } + @Test public void testEmissionSubscriptionRace() throws Exception { Scheduler s = Schedulers.io(); @@ -550,6 +554,7 @@ public void testCurrentStateMethodsEmpty() { assertNull(as.getValue()); assertNull(as.getThrowable()); } + @Test public void testCurrentStateMethodsError() { BehaviorProcessor<Object> as = BehaviorProcessor.create(); diff --git a/src/test/java/io/reactivex/processors/MulticastProcessorTest.java b/src/test/java/io/reactivex/processors/MulticastProcessorTest.java index c85665eacd..63a7b1a60b 100644 --- a/src/test/java/io/reactivex/processors/MulticastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/MulticastProcessorTest.java @@ -185,7 +185,6 @@ public void longRunning() { mp.test().assertValueCount(1000).assertNoErrors().assertComplete(); } - @Test public void oneByOne() { MulticastProcessor<Integer> mp = MulticastProcessor.create(16); @@ -419,7 +418,6 @@ public void onNextNull() { mp.onNext(null); } - @Test(expected = NullPointerException.class) public void onOfferNull() { MulticastProcessor<Integer> mp = MulticastProcessor.create(4, false); @@ -623,7 +621,6 @@ public void cancelUpfront() { assertFalse(mp.hasSubscribers()); } - @Test public void cancelUpfrontOtherConsumersPresent() { MulticastProcessor<Integer> mp = MulticastProcessor.create(); diff --git a/src/test/java/io/reactivex/processors/PublishProcessorTest.java b/src/test/java/io/reactivex/processors/PublishProcessorTest.java index 8d9d4b7a88..4160ed27ea 100644 --- a/src/test/java/io/reactivex/processors/PublishProcessorTest.java +++ b/src/test/java/io/reactivex/processors/PublishProcessorTest.java @@ -384,6 +384,7 @@ public void onComplete() { // // even though the onError above throws we should still receive it on the other subscriber // assertEquals(1, ts.getOnErrorEvents().size()); // } + @Test public void testCurrentStateMethodsNormal() { PublishProcessor<Object> as = PublishProcessor.create(); @@ -419,6 +420,7 @@ public void testCurrentStateMethodsEmpty() { assertTrue(as.hasComplete()); assertNull(as.getThrowable()); } + @Test public void testCurrentStateMethodsError() { PublishProcessor<Object> as = PublishProcessor.create(); diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java index dd0f32821f..8a26d4d80d 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java @@ -318,6 +318,7 @@ public void run() { } } } + @Test public void testReplaySubjectEmissionSubscriptionRace() throws Exception { Scheduler s = Schedulers.io(); @@ -403,6 +404,7 @@ public void run() { worker.dispose(); } } + @Test(timeout = 5000) public void testConcurrentSizeAndHasAnyValue() throws InterruptedException { final ReplayProcessor<Object> rs = ReplayProcessor.createUnbounded(); @@ -457,6 +459,7 @@ public void run() { t.join(); } + @Test(timeout = 5000) public void testConcurrentSizeAndHasAnyValueBounded() throws InterruptedException { final ReplayProcessor<Object> rs = ReplayProcessor.createWithSize(3); @@ -500,6 +503,7 @@ public void run() { t.join(); } + @Test(timeout = 10000) public void testConcurrentSizeAndHasAnyValueTimeBounded() throws InterruptedException { final ReplayProcessor<Object> rs = ReplayProcessor.createWithTime(1, TimeUnit.MILLISECONDS, Schedulers.computation()); diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java index e63f8f361f..6161c484fa 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java @@ -318,6 +318,7 @@ public void run() { } } } + @Test public void testReplaySubjectEmissionSubscriptionRace() throws Exception { Scheduler s = Schedulers.io(); @@ -391,6 +392,7 @@ public void run() { worker.dispose(); } } + @Test(timeout = 10000) public void testConcurrentSizeAndHasAnyValue() throws InterruptedException { final ReplayProcessor<Object> rs = ReplayProcessor.create(); diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index fc5635d975..3038840266 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -350,6 +350,7 @@ public void onNext(String v) { assertEquals("three", lastValueForSubscriber2.get()); } + @Test public void testSubscriptionLeak() { ReplayProcessor<Object> replaySubject = ReplayProcessor.create(); @@ -403,6 +404,7 @@ public void onComplete() { verify(subscriber, never()).onError(any(Throwable.class)); } } + @Test public void testTerminateOnce() { ReplayProcessor<Integer> source = ReplayProcessor.create(); @@ -455,6 +457,7 @@ public void testReplay1AfterTermination() { verify(subscriber, never()).onError(any(Throwable.class)); } } + @Test public void testReplay1Directly() { ReplayProcessor<Integer> source = ReplayProcessor.createWithSize(1); @@ -618,6 +621,7 @@ public void testCurrentStateMethodsEmpty() { assertTrue(as.hasComplete()); assertNull(as.getThrowable()); } + @Test public void testCurrentStateMethodsError() { ReplayProcessor<Object> as = ReplayProcessor.create(); @@ -632,6 +636,7 @@ public void testCurrentStateMethodsError() { assertFalse(as.hasComplete()); assertTrue(as.getThrowable() instanceof TestException); } + @Test public void testSizeAndHasAnyValueUnbounded() { ReplayProcessor<Object> rs = ReplayProcessor.create(); @@ -654,6 +659,7 @@ public void testSizeAndHasAnyValueUnbounded() { assertEquals(2, rs.size()); assertTrue(rs.hasValue()); } + @Test public void testSizeAndHasAnyValueEffectivelyUnbounded() { ReplayProcessor<Object> rs = ReplayProcessor.createUnbounded(); @@ -699,6 +705,7 @@ public void testSizeAndHasAnyValueUnboundedError() { assertEquals(2, rs.size()); assertTrue(rs.hasValue()); } + @Test public void testSizeAndHasAnyValueEffectivelyUnboundedError() { ReplayProcessor<Object> rs = ReplayProcessor.createUnbounded(); @@ -731,6 +738,7 @@ public void testSizeAndHasAnyValueUnboundedEmptyError() { assertEquals(0, rs.size()); assertFalse(rs.hasValue()); } + @Test public void testSizeAndHasAnyValueEffectivelyUnboundedEmptyError() { ReplayProcessor<Object> rs = ReplayProcessor.createUnbounded(); @@ -750,6 +758,7 @@ public void testSizeAndHasAnyValueUnboundedEmptyCompleted() { assertEquals(0, rs.size()); assertFalse(rs.hasValue()); } + @Test public void testSizeAndHasAnyValueEffectivelyUnboundedEmptyCompleted() { ReplayProcessor<Object> rs = ReplayProcessor.createUnbounded(); @@ -802,6 +811,7 @@ public void testSizeAndHasAnyValueTimeBounded() { assertEquals(0, rs.size()); assertFalse(rs.hasValue()); } + @Test public void testGetValues() { ReplayProcessor<Object> rs = ReplayProcessor.create(); @@ -816,6 +826,7 @@ public void testGetValues() { assertArrayEquals(expected, rs.getValues()); } + @Test public void testGetValuesUnbounded() { ReplayProcessor<Object> rs = ReplayProcessor.createUnbounded(); @@ -1533,6 +1544,7 @@ public void timeBoundCancelAfterOne() { source.subscribeWith(take1AndCancel()) .assertResult(1); } + @Test public void timeAndSizeBoundCancelAfterOne() { ReplayProcessor<Integer> source = ReplayProcessor.createWithTimeAndSize(1, TimeUnit.MINUTES, Schedulers.single(), 16); diff --git a/src/test/java/io/reactivex/processors/SerializedProcessorTest.java b/src/test/java/io/reactivex/processors/SerializedProcessorTest.java index efbfe02a69..9d5b51c152 100644 --- a/src/test/java/io/reactivex/processors/SerializedProcessorTest.java +++ b/src/test/java/io/reactivex/processors/SerializedProcessorTest.java @@ -121,6 +121,7 @@ public void testPublishSubjectValueEmpty() { assertFalse(serial.hasThrowable()); assertNull(serial.getThrowable()); } + @Test public void testPublishSubjectValueError() { PublishProcessor<Integer> async = PublishProcessor.create(); @@ -248,6 +249,7 @@ public void testReplaySubjectValueRelay() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectValueRelayIncomplete() { ReplayProcessor<Integer> async = ReplayProcessor.create(); @@ -265,6 +267,7 @@ public void testReplaySubjectValueRelayIncomplete() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectValueRelayBounded() { ReplayProcessor<Integer> async = ReplayProcessor.createWithSize(1); @@ -284,6 +287,7 @@ public void testReplaySubjectValueRelayBounded() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectValueRelayBoundedIncomplete() { ReplayProcessor<Integer> async = ReplayProcessor.createWithSize(1); @@ -302,6 +306,7 @@ public void testReplaySubjectValueRelayBoundedIncomplete() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectValueRelayBoundedEmptyIncomplete() { ReplayProcessor<Integer> async = ReplayProcessor.createWithSize(1); @@ -318,6 +323,7 @@ public void testReplaySubjectValueRelayBoundedEmptyIncomplete() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectValueRelayEmptyIncomplete() { ReplayProcessor<Integer> async = ReplayProcessor.create(); @@ -352,6 +358,7 @@ public void testReplaySubjectEmpty() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectError() { ReplayProcessor<Integer> async = ReplayProcessor.create(); @@ -388,6 +395,7 @@ public void testReplaySubjectBoundedEmpty() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectBoundedError() { ReplayProcessor<Integer> async = ReplayProcessor.createWithSize(1); diff --git a/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java b/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java index 9caa79e7b3..b33efed40b 100644 --- a/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java +++ b/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java @@ -111,7 +111,6 @@ public void accept(String t) { }); } - @Test public final void testMergeWithExecutorScheduler() { diff --git a/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java b/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java index 954981a91e..312ccf92df 100644 --- a/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java @@ -204,6 +204,7 @@ public void run() { w.dispose(); } } + @Test public void testCancelledWorkerDoesntRunTasks() { final AtomicInteger calls = new AtomicInteger(); diff --git a/src/test/java/io/reactivex/schedulers/SchedulerTest.java b/src/test/java/io/reactivex/schedulers/SchedulerTest.java index bee0b3935b..99ffca6afb 100644 --- a/src/test/java/io/reactivex/schedulers/SchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/SchedulerTest.java @@ -204,7 +204,6 @@ public void run() { } - @Test public void periodicDirectTaskRaceIO() throws Exception { final Scheduler scheduler = Schedulers.io(); diff --git a/src/test/java/io/reactivex/schedulers/TestSchedulerTest.java b/src/test/java/io/reactivex/schedulers/TestSchedulerTest.java index 2d5484cbb3..4139365384 100644 --- a/src/test/java/io/reactivex/schedulers/TestSchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/TestSchedulerTest.java @@ -232,9 +232,9 @@ public void timedRunnableToString() { TimedRunnable r = new TimedRunnable((TestWorker) new TestScheduler().createWorker(), 5, new Runnable() { @Override public void run() { - // TODO Auto-generated method stub - + // deliberately no-op } + @Override public String toString() { return "Runnable"; diff --git a/src/test/java/io/reactivex/single/SingleNullTests.java b/src/test/java/io/reactivex/single/SingleNullTests.java index 3efcbbcc6e..96ffe78eeb 100644 --- a/src/test/java/io/reactivex/single/SingleNullTests.java +++ b/src/test/java/io/reactivex/single/SingleNullTests.java @@ -809,6 +809,7 @@ public void subscribeOnErrorNull() { public void accept(Integer v) { } }, null); } + @Test(expected = NullPointerException.class) public void subscribeSubscriberNull() { just1.toFlowable().subscribe((Subscriber<Integer>)null); diff --git a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java index 9376962b95..5e628f3ec6 100644 --- a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java @@ -367,6 +367,7 @@ public void testCurrentStateMethodsEmpty() { assertNull(as.getValue()); assertNull(as.getThrowable()); } + @Test public void testCurrentStateMethodsError() { AsyncSubject<Object> as = AsyncSubject.create(); @@ -386,7 +387,6 @@ public void testCurrentStateMethodsError() { assertTrue(as.getThrowable() instanceof TestException); } - @Test public void fusionLive() { AsyncSubject<Integer> ap = new AsyncSubject<Integer>(); diff --git a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java index f8044d5a11..06b7079fdf 100644 --- a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java @@ -282,6 +282,7 @@ public void onComplete() { verify(o, never()).onError(any(Throwable.class)); } } + @Test public void testStartEmpty() { BehaviorSubject<Integer> source = BehaviorSubject.create(); @@ -307,6 +308,7 @@ public void testStartEmpty() { } + @Test public void testStartEmptyThenAddOne() { BehaviorSubject<Integer> source = BehaviorSubject.create(); @@ -329,6 +331,7 @@ public void testStartEmptyThenAddOne() { verify(o, never()).onError(any(Throwable.class)); } + @Test public void testStartEmptyCompleteWithOne() { BehaviorSubject<Integer> source = BehaviorSubject.create(); @@ -406,6 +409,7 @@ public void testTakeOneSubscriber() { // // even though the onError above throws we should still receive it on the other subscriber // assertEquals(1, to.getOnErrorEvents().size()); // } + @Test public void testEmissionSubscriptionRace() throws Exception { Scheduler s = Schedulers.io(); @@ -550,6 +554,7 @@ public void testCurrentStateMethodsEmpty() { assertNull(as.getValue()); assertNull(as.getThrowable()); } + @Test public void testCurrentStateMethodsError() { BehaviorSubject<Object> as = BehaviorSubject.create(); @@ -716,7 +721,6 @@ public void onComplete() { }); } - @Test public void completeSubscribeRace() throws Exception { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { diff --git a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java index 12f4116814..dd9f964100 100644 --- a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java @@ -384,6 +384,7 @@ public void onComplete() { // // even though the onError above throws we should still receive it on the other subscriber // assertEquals(1, to.getOnErrorEvents().size()); // } + @Test public void testCurrentStateMethodsNormal() { PublishSubject<Object> as = PublishSubject.create(); @@ -419,6 +420,7 @@ public void testCurrentStateMethodsEmpty() { assertTrue(as.hasComplete()); assertNull(as.getThrowable()); } + @Test public void testCurrentStateMethodsError() { PublishSubject<Object> as = PublishSubject.create(); diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java index 4a03449597..9379e0059f 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java @@ -322,6 +322,7 @@ public void run() { } } } + @Test public void testReplaySubjectEmissionSubscriptionRace() throws Exception { Scheduler s = Schedulers.io(); @@ -407,6 +408,7 @@ public void run() { worker.dispose(); } } + @Test(timeout = 5000) public void testConcurrentSizeAndHasAnyValue() throws InterruptedException { final ReplaySubject<Object> rs = ReplaySubject.createUnbounded(); @@ -461,6 +463,7 @@ public void run() { t.join(); } + @Test(timeout = 5000) public void testConcurrentSizeAndHasAnyValueBounded() throws InterruptedException { final ReplaySubject<Object> rs = ReplaySubject.createWithSize(3); @@ -504,6 +507,7 @@ public void run() { t.join(); } + @Test(timeout = 10000) public void testConcurrentSizeAndHasAnyValueTimeBounded() throws InterruptedException { final ReplaySubject<Object> rs = ReplaySubject.createWithTime(1, TimeUnit.MILLISECONDS, Schedulers.computation()); diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java index adf238118f..bec6a10b2d 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java @@ -322,6 +322,7 @@ public void run() { } } } + @Test public void testReplaySubjectEmissionSubscriptionRace() throws Exception { Scheduler s = Schedulers.io(); @@ -395,6 +396,7 @@ public void run() { worker.dispose(); } } + @Test(timeout = 10000) public void testConcurrentSizeAndHasAnyValue() throws InterruptedException { final ReplaySubject<Object> rs = ReplaySubject.create(); diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java index 24d9704b8a..2326241cfd 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java @@ -348,6 +348,7 @@ public void onNext(String v) { assertEquals("three", lastValueForSubscriber2.get()); } + @Test public void testSubscriptionLeak() { ReplaySubject<Object> subject = ReplaySubject.create(); @@ -360,6 +361,7 @@ public void testSubscriptionLeak() { assertEquals(0, subject.observerCount()); } + @Test(timeout = 1000) public void testUnsubscriptionCase() { ReplaySubject<String> src = ReplaySubject.create(); @@ -401,6 +403,7 @@ public void onComplete() { verify(o, never()).onError(any(Throwable.class)); } } + @Test public void testTerminateOnce() { ReplaySubject<Integer> source = ReplaySubject.create(); @@ -453,6 +456,7 @@ public void testReplay1AfterTermination() { verify(o, never()).onError(any(Throwable.class)); } } + @Test public void testReplay1Directly() { ReplaySubject<Integer> source = ReplaySubject.createWithSize(1); @@ -616,6 +620,7 @@ public void testCurrentStateMethodsEmpty() { assertTrue(as.hasComplete()); assertNull(as.getThrowable()); } + @Test public void testCurrentStateMethodsError() { ReplaySubject<Object> as = ReplaySubject.create(); @@ -630,6 +635,7 @@ public void testCurrentStateMethodsError() { assertFalse(as.hasComplete()); assertTrue(as.getThrowable() instanceof TestException); } + @Test public void testSizeAndHasAnyValueUnbounded() { ReplaySubject<Object> rs = ReplaySubject.create(); @@ -652,6 +658,7 @@ public void testSizeAndHasAnyValueUnbounded() { assertEquals(2, rs.size()); assertTrue(rs.hasValue()); } + @Test public void testSizeAndHasAnyValueEffectivelyUnbounded() { ReplaySubject<Object> rs = ReplaySubject.createUnbounded(); @@ -697,6 +704,7 @@ public void testSizeAndHasAnyValueUnboundedError() { assertEquals(2, rs.size()); assertTrue(rs.hasValue()); } + @Test public void testSizeAndHasAnyValueEffectivelyUnboundedError() { ReplaySubject<Object> rs = ReplaySubject.createUnbounded(); @@ -729,6 +737,7 @@ public void testSizeAndHasAnyValueUnboundedEmptyError() { assertEquals(0, rs.size()); assertFalse(rs.hasValue()); } + @Test public void testSizeAndHasAnyValueEffectivelyUnboundedEmptyError() { ReplaySubject<Object> rs = ReplaySubject.createUnbounded(); @@ -748,6 +757,7 @@ public void testSizeAndHasAnyValueUnboundedEmptyCompleted() { assertEquals(0, rs.size()); assertFalse(rs.hasValue()); } + @Test public void testSizeAndHasAnyValueEffectivelyUnboundedEmptyCompleted() { ReplaySubject<Object> rs = ReplaySubject.createUnbounded(); @@ -800,6 +810,7 @@ public void testSizeAndHasAnyValueTimeBounded() { assertEquals(0, rs.size()); assertFalse(rs.hasValue()); } + @Test public void testGetValues() { ReplaySubject<Object> rs = ReplaySubject.create(); @@ -814,6 +825,7 @@ public void testGetValues() { assertArrayEquals(expected, rs.getValues()); } + @Test public void testGetValuesUnbounded() { ReplaySubject<Object> rs = ReplaySubject.createUnbounded(); @@ -1205,7 +1217,6 @@ public void noHeadRetentionCompleteSize() { assertSame(o, buf.head); } - @Test public void noHeadRetentionSize() { ReplaySubject<Integer> source = ReplaySubject.createWithSize(1); diff --git a/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java b/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java index 31498d7a04..8d679b7024 100644 --- a/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/SerializedSubjectTest.java @@ -122,6 +122,7 @@ public void testPublishSubjectValueEmpty() { assertFalse(serial.hasThrowable()); assertNull(serial.getThrowable()); } + @Test public void testPublishSubjectValueError() { PublishSubject<Integer> async = PublishSubject.create(); @@ -267,6 +268,7 @@ public void testReplaySubjectValueRelayIncomplete() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectValueRelayBounded() { ReplaySubject<Integer> async = ReplaySubject.createWithSize(1); @@ -286,6 +288,7 @@ public void testReplaySubjectValueRelayBounded() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectValueRelayBoundedIncomplete() { ReplaySubject<Integer> async = ReplaySubject.createWithSize(1); @@ -304,6 +307,7 @@ public void testReplaySubjectValueRelayBoundedIncomplete() { assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectValueRelayBoundedEmptyIncomplete() { ReplaySubject<Integer> async = ReplaySubject.createWithSize(1); @@ -320,6 +324,7 @@ public void testReplaySubjectValueRelayBoundedEmptyIncomplete() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectValueRelayEmptyIncomplete() { ReplaySubject<Integer> async = ReplaySubject.create(); @@ -354,6 +359,7 @@ public void testReplaySubjectEmpty() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectError() { ReplaySubject<Integer> async = ReplaySubject.create(); @@ -390,6 +396,7 @@ public void testReplaySubjectBoundedEmpty() { assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 })); assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 })); } + @Test public void testReplaySubjectBoundedError() { ReplaySubject<Integer> async = ReplaySubject.createWithSize(1); diff --git a/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java b/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java index d66a1ceecf..3ac4a19d7c 100644 --- a/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java @@ -579,10 +579,12 @@ public void testOnCompletedThrows() { public void onNext(Integer t) { } + @Override public void onError(Throwable e) { error.set(e); } + @Override public void onComplete() { throw new TestException(); @@ -603,9 +605,11 @@ public void testActual() { @Override public void onNext(Integer t) { } + @Override public void onError(Throwable e) { } + @Override public void onComplete() { } @@ -1085,7 +1089,6 @@ public void cancelCrash() { } } - @Test public void requestCancelCrash() { List<Throwable> list = TestHelper.trackPluginErrors(); diff --git a/src/test/java/io/reactivex/subscribers/SafeSubscriberWithPluginTest.java b/src/test/java/io/reactivex/subscribers/SafeSubscriberWithPluginTest.java index 2f3df019ce..b95f00b3fd 100644 --- a/src/test/java/io/reactivex/subscribers/SafeSubscriberWithPluginTest.java +++ b/src/test/java/io/reactivex/subscribers/SafeSubscriberWithPluginTest.java @@ -171,6 +171,7 @@ public void onError(Throwable e) { safe.onError(new TestException()); } + @Test(expected = RuntimeException.class) @Ignore("Subscribers can't throw") public void testPluginExceptionWhileOnErrorThrowsAndUnsubscribeThrows() { @@ -195,6 +196,7 @@ public void onError(Throwable e) { safe.onError(new TestException()); } + @Test(expected = RuntimeException.class) @Ignore("Subscribers can't throw") public void testPluginExceptionWhenUnsubscribing2() { diff --git a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java index a6d4d4411f..0ecec64e8e 100644 --- a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java @@ -976,6 +976,7 @@ public void onNext(Integer v) { ts.assertValue(1); ts.assertError(TestException.class); } + @Test public void testCompleteReentry() { final AtomicReference<Subscriber<Integer>> serial = new AtomicReference<Subscriber<Integer>>(); diff --git a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java index 85cd58baad..bd2748371f 100644 --- a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java @@ -746,7 +746,6 @@ public void onError(Throwable e) { ts.awaitTerminalEvent(); } - @Test public void createDelegate() { TestSubscriber<Integer> ts1 = TestSubscriber.create(); @@ -1611,7 +1610,6 @@ public void onComplete() { } } - @Test public void syncQueueThrows() { TestSubscriber<Object> ts = new TestSubscriber<Object>(); @@ -1826,7 +1824,6 @@ public void timeoutIndicated2() throws InterruptedException { } } - @Test public void timeoutIndicated3() throws InterruptedException { TestSubscriber<Object> ts = Flowable.never() diff --git a/src/test/java/io/reactivex/tck/BaseTck.java b/src/test/java/io/reactivex/tck/BaseTck.java index 42df479448..a06522a399 100644 --- a/src/test/java/io/reactivex/tck/BaseTck.java +++ b/src/test/java/io/reactivex/tck/BaseTck.java @@ -44,7 +44,6 @@ public Publisher<T> createFailedPublisher() { return Flowable.error(new TestException()); } - @Override public long maxElementsFromPublisher() { return 1024; diff --git a/src/test/java/io/reactivex/validators/CheckLocalVariablesInTests.java b/src/test/java/io/reactivex/validators/CheckLocalVariablesInTests.java index 9877a66cc1..8f8acaf3d4 100644 --- a/src/test/java/io/reactivex/validators/CheckLocalVariablesInTests.java +++ b/src/test/java/io/reactivex/validators/CheckLocalVariablesInTests.java @@ -332,6 +332,11 @@ public void atomicSubscriptionAsS() throws Exception { findPattern("AtomicReference<Subscription>\\s+s[0-9]?;", true); } + @Test + public void atomicSubscriptionAsSInit() throws Exception { + findPattern("AtomicReference<Subscription>\\s+s[0-9]?\\s", true); + } + @Test public void atomicSubscriptionAsSubscription() throws Exception { findPattern("AtomicReference<Subscription>\\s+subscription[0-9]?", true); diff --git a/src/test/java/io/reactivex/validators/NewLinesBeforeAnnotation.java b/src/test/java/io/reactivex/validators/NewLinesBeforeAnnotation.java new file mode 100644 index 0000000000..49f19daec0 --- /dev/null +++ b/src/test/java/io/reactivex/validators/NewLinesBeforeAnnotation.java @@ -0,0 +1,162 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.validators; + +import java.io.*; +import java.util.*; + +import org.junit.Test; + +/** + * These tests verify the code style that a typical closing curly brace + * and the next annotation @ indicator + * are not separated by less than or more than one empty line. + * <p>Thus this is detected: + * <pre><code> + * } + * @Override + * </code></pre> + * <p> + * as well as + * <pre><code> + * } + * + * + * @Override + * </code></pre> + */ +public class NewLinesBeforeAnnotation { + + @Test + public void missingEmptyNewLine() throws Exception { + findPattern(0); + } + + @Test + public void tooManyEmptyNewLines2() throws Exception { + findPattern(2); + } + + @Test + public void tooManyEmptyNewLines3() throws Exception { + findPattern(3); + } + + @Test + public void tooManyEmptyNewLines4() throws Exception { + findPattern(5); + } + + @Test + public void tooManyEmptyNewLines5() throws Exception { + findPattern(5); + } + + static void findPattern(int newLines) throws Exception { + File f = MaybeNo2Dot0Since.findSource("Flowable"); + if (f == null) { + System.out.println("Unable to find sources of RxJava"); + return; + } + + Queue<File> dirs = new ArrayDeque<File>(); + + StringBuilder fail = new StringBuilder(); + fail.append("The following code pattern was found: "); + fail.append("\\}\\R"); + for (int i = 0; i < newLines; i++) { + fail.append("\\R"); + } + fail.append("[ ]+@\n"); + + File parent = f.getParentFile(); + + dirs.offer(new File(parent.getAbsolutePath().replace('\\', '/'))); + dirs.offer(new File(parent.getAbsolutePath().replace('\\', '/').replace("src/main/java", "src/test/java"))); + + int total = 0; + + while (!dirs.isEmpty()) { + f = dirs.poll(); + + File[] list = f.listFiles(); + if (list != null && list.length != 0) { + + for (File u : list) { + if (u.isDirectory()) { + dirs.offer(u); + } else { + String fname = u.getName(); + if (fname.endsWith(".java")) { + + List<String> lines = new ArrayList<String>(); + BufferedReader in = new BufferedReader(new FileReader(u)); + try { + for (;;) { + String line = in.readLine(); + if (line == null) { + break; + } + lines.add(line); + } + } finally { + in.close(); + } + + for (int i = 0; i < lines.size() - 1; i++) { + String line = lines.get(i); + if (line.endsWith("}") && !line.trim().startsWith("*") && !line.trim().startsWith("//")) { + int emptyLines = 0; + boolean found = false; + for (int j = i + 1; j < lines.size(); j++) { + String line2 = lines.get(j); + if (line2.trim().startsWith("@")) { + found = true; + break; + } + if (!line2.trim().isEmpty()) { + break; + } + emptyLines++; + } + + if (emptyLines == newLines && found) { + fail + .append(fname) + .append("#L").append(i + 1) + .append(" "); + for (int k = 0; k < emptyLines + 2; k++) { + fail + .append(lines.get(k + i)) + .append("\\R"); + } + fail.append("\n"); + total++; + } + } + } + } + } + } + } + } + if (total != 0) { + fail.append("Found ") + .append(total) + .append(" instances"); + System.out.println(fail); + throw new AssertionError(fail.toString()); + } + } +} From a16f63fa9030dc7ed4a5b9e2b8c948e02d92e557 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 10 Aug 2018 10:15:21 +0200 Subject: [PATCH 263/417] 2.x: Clarify TestObserver.assertValueSet in docs and via tests (#6152) * 2.x: Clarify TestObserver.assertValueSet in docs and via tests * Grammar. --- .../reactivex/observers/BaseTestConsumer.java | 9 +++-- .../reactivex/observers/TestObserverTest.java | 34 +++++++++++++++++++ .../subscribers/TestSubscriberTest.java | 34 +++++++++++++++++++ 3 files changed, 75 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/observers/BaseTestConsumer.java b/src/main/java/io/reactivex/observers/BaseTestConsumer.java index 373339f020..69d227d91d 100644 --- a/src/main/java/io/reactivex/observers/BaseTestConsumer.java +++ b/src/main/java/io/reactivex/observers/BaseTestConsumer.java @@ -565,9 +565,14 @@ public final U assertValuesOnly(T... values) { } /** - * Assert that the TestObserver/TestSubscriber received only the specified values in any order. - * <p>This helps asserting when the order of the values is not guaranteed, i.e., when merging + * Assert that the TestObserver/TestSubscriber received only items that are in the specified + * collection as well, irrespective of the order they were received. + * <p> + * This helps asserting when the order of the values is not guaranteed, i.e., when merging * asynchronous streams. + * <p> + * To ensure that only the expected items have been received, no more and no less, in any order, + * apply {@link #assertValueCount(int)} with {@code expected.size()}. * * @param expected the collection of values expected in any order * @return this diff --git a/src/test/java/io/reactivex/observers/TestObserverTest.java b/src/test/java/io/reactivex/observers/TestObserverTest.java index efe9798bae..27f4f7442c 100644 --- a/src/test/java/io/reactivex/observers/TestObserverTest.java +++ b/src/test/java/io/reactivex/observers/TestObserverTest.java @@ -1626,4 +1626,38 @@ public void assertValueSequenceOnlyThrowsWhenErrored() { // expected } } + + @Test + public void assertValueSetWiderSet() { + Set<Integer> set = new HashSet<Integer>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7)); + + Observable.just(4, 5, 1, 3, 2) + .test() + .assertValueSet(set); + } + + @Test + public void assertValueSetExact() { + Set<Integer> set = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4, 5)); + + Observable.just(4, 5, 1, 3, 2) + .test() + .assertValueSet(set) + .assertValueCount(set.size()); + } + + @Test + public void assertValueSetMissing() { + Set<Integer> set = new HashSet<Integer>(Arrays.asList(0, 1, 2, 4, 5, 6, 7)); + + try { + Observable.range(1, 5) + .test() + .assertValueSet(set); + + throw new RuntimeException("Should have failed"); + } catch (AssertionError ex) { + assertTrue(ex.getMessage(), ex.getMessage().contains("Value not in the expected collection: " + 3)); + } + } } diff --git a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java index bd2748371f..d4358f4bb8 100644 --- a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java @@ -2186,4 +2186,38 @@ public void awaitCount0() { TestSubscriber<Integer> ts = TestSubscriber.create(); ts.awaitCount(0, TestWaitStrategy.SLEEP_1MS, 0); } + + @Test + public void assertValueSetWiderSet() { + Set<Integer> set = new HashSet<Integer>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7)); + + Flowable.just(4, 5, 1, 3, 2) + .test() + .assertValueSet(set); + } + + @Test + public void assertValueSetExact() { + Set<Integer> set = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4, 5)); + + Flowable.just(4, 5, 1, 3, 2) + .test() + .assertValueSet(set) + .assertValueCount(set.size()); + } + + @Test + public void assertValueSetMissing() { + Set<Integer> set = new HashSet<Integer>(Arrays.asList(0, 1, 2, 4, 5, 6, 7)); + + try { + Flowable.range(1, 5) + .test() + .assertValueSet(set); + + throw new RuntimeException("Should have failed"); + } catch (AssertionError ex) { + assertTrue(ex.getMessage(), ex.getMessage().contains("Value not in the expected collection: " + 3)); + } + } } From 835ab00699d39c092ef6e90cf1868722b9180fe1 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 10 Aug 2018 12:08:24 +0200 Subject: [PATCH 264/417] 2.x: Fix marble of Maybe.flatMap events to MaybeSource (#6155) --- src/main/java/io/reactivex/Maybe.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 519a64f6b9..4bc994e3d3 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -2909,7 +2909,7 @@ public final <R> Maybe<R> flatMap(Function<? super T, ? extends MaybeSource<? ex * Maps the onSuccess, onError or onComplete signals of this Maybe into MaybeSource and emits that * MaybeSource's signals. * <p> - * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.nce.png" alt=""> + * <img width="640" height="354" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMap.mmm.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd> From 7d652913772abcdbb429d5b132b830462661ee23 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 14 Aug 2018 14:53:54 +0200 Subject: [PATCH 265/417] 2.x: Make Flowable.fromCallable consitent with the other fromCallables (#6158) 2.x: Make Flowable.fromCallable consistent with the other fromCallables --- .../flowable/FlowableFromCallable.java | 7 ++++- .../flowable/FlowableFromCallableTest.java | 29 ++++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromCallable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromCallable.java index 5a773dffc4..6dcb226daa 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromCallable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromCallable.java @@ -21,6 +21,7 @@ import io.reactivex.exceptions.Exceptions; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.subscriptions.DeferredScalarSubscription; +import io.reactivex.plugins.RxJavaPlugins; public final class FlowableFromCallable<T> extends Flowable<T> implements Callable<T> { final Callable<? extends T> callable; @@ -38,7 +39,11 @@ public void subscribeActual(Subscriber<? super T> s) { t = ObjectHelper.requireNonNull(callable.call(), "The callable returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); - s.onError(ex); + if (deferred.isCancelled()) { + RxJavaPlugins.onError(ex); + } else { + s.onError(ex); + } return; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java index f3f5e00fa5..f3239001ee 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java @@ -16,9 +16,11 @@ package io.reactivex.internal.operators.flowable; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; -import static org.junit.Assert.*; +import java.util.List; import java.util.concurrent.*; import org.junit.Test; @@ -27,7 +29,9 @@ import org.reactivestreams.*; import io.reactivex.*; +import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; @@ -238,4 +242,27 @@ public Object call() throws Exception { .test() .assertFailure(NullPointerException.class); } + + @Test(timeout = 5000) + public void undeliverableUponCancellation() throws Exception { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + + Flowable.fromCallable(new Callable<Integer>() { + @Override + public Integer call() throws Exception { + ts.cancel(); + throw new TestException(); + } + }) + .subscribe(ts); + + ts.assertEmpty(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } } From 592b991dd8d148351fe4d52de6e8512f274285de Mon Sep 17 00:00:00 2001 From: Muh Isfhani Ghiath <isfaaghyth@gmail.com> Date: Wed, 22 Aug 2018 00:56:58 +0700 Subject: [PATCH 266/417] Error handle on Completable.fromCallable with RxJavaPlugins (#6165) --- .../operators/completable/CompletableFromCallable.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromCallable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromCallable.java index 3dbd3701b5..6b7e68defb 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromCallable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromCallable.java @@ -18,6 +18,7 @@ import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.Exceptions; +import io.reactivex.plugins.RxJavaPlugins; public final class CompletableFromCallable extends Completable { @@ -37,6 +38,8 @@ protected void subscribeActual(CompletableObserver observer) { Exceptions.throwIfFatal(e); if (!d.isDisposed()) { observer.onError(e); + } else { + RxJavaPlugins.onError(e); } return; } From 5c67fe4ec72f41256874fc1ecd4faf2b92d1899f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Karnok?= <akarnokd@gmail.com> Date: Wed, 22 Aug 2018 13:51:04 +0200 Subject: [PATCH 267/417] Update `unsubscribeOn` tests to avoid the termination-cancel race --- .../operators/flowable/FlowableUnsubscribeOnTest.java | 10 ++++++++-- .../observable/ObservableUnsubscribeOnTest.java | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java index 3ed444424f..cd6f22ea56 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java @@ -47,7 +47,10 @@ public void subscribe(Subscriber<? super Integer> t1) { t1.onSubscribe(subscription); t1.onNext(1); t1.onNext(2); - t1.onComplete(); + // observeOn will prevent canceling the upstream upon its termination now + // this call is racing for that state in this test + // not doing it will make sure the unsubscribeOn always gets through + // t1.onComplete(); } }); @@ -93,7 +96,10 @@ public void subscribe(Subscriber<? super Integer> t1) { t1.onSubscribe(subscription); t1.onNext(1); t1.onNext(2); - t1.onComplete(); + // observeOn will prevent canceling the upstream upon its termination now + // this call is racing for that state in this test + // not doing it will make sure the unsubscribeOn always gets through + // t1.onComplete(); } }); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java index cdb21dafa5..2b7d7f4141 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java @@ -46,7 +46,10 @@ public void subscribe(Observer<? super Integer> t1) { t1.onSubscribe(subscription); t1.onNext(1); t1.onNext(2); - t1.onComplete(); + // observeOn will prevent canceling the upstream upon its termination now + // this call is racing for that state in this test + // not doing it will make sure the unsubscribeOn always gets through + // t1.onComplete(); } }); @@ -92,7 +95,10 @@ public void subscribe(Observer<? super Integer> t1) { t1.onSubscribe(subscription); t1.onNext(1); t1.onNext(2); - t1.onComplete(); + // observeOn will prevent canceling the upstream upon its termination now + // this call is racing for that state in this test + // not doing it will make sure the unsubscribeOn always gets through + // t1.onComplete(); } }); From ab649824e6d55505cc7b3e6d9fb033143146b110 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 22 Aug 2018 16:58:17 +0200 Subject: [PATCH 268/417] 2.x: Make observeOn not let worker.dispose() called prematurely (#6167) * 2.x: Make observeOn not let worker.dispose() called prematurely * Merge in master. --- .../operators/flowable/FlowableObserveOn.java | 13 ++ .../observable/ObservableObserveOn.java | 18 +- .../flowable/FlowableObserveOnTest.java | 162 +++++++++++++++++- .../observable/ObservableObserveOnTest.java | 76 ++++++++ 4 files changed, 262 insertions(+), 7 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java index d1c97b6801..2a7d499d1a 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java @@ -191,6 +191,7 @@ final boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a) { if (d) { if (delayError) { if (empty) { + cancelled = true; Throwable e = error; if (e != null) { a.onError(e); @@ -203,12 +204,14 @@ final boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a) { } else { Throwable e = error; if (e != null) { + cancelled = true; clear(); a.onError(e); worker.dispose(); return true; } else if (empty) { + cancelled = true; a.onComplete(); worker.dispose(); return true; @@ -314,6 +317,7 @@ void runSync() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); + cancelled = true; upstream.cancel(); a.onError(ex); worker.dispose(); @@ -324,6 +328,7 @@ void runSync() { return; } if (v == null) { + cancelled = true; a.onComplete(); worker.dispose(); return; @@ -339,6 +344,7 @@ void runSync() { } if (q.isEmpty()) { + cancelled = true; a.onComplete(); worker.dispose(); return; @@ -379,6 +385,7 @@ void runAsync() { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); + cancelled = true; upstream.cancel(); q.clear(); @@ -441,6 +448,7 @@ void runBackfused() { downstream.onNext(null); if (d) { + cancelled = true; Throwable e = error; if (e != null) { downstream.onError(e); @@ -552,6 +560,7 @@ void runSync() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); + cancelled = true; upstream.cancel(); a.onError(ex); worker.dispose(); @@ -562,6 +571,7 @@ void runSync() { return; } if (v == null) { + cancelled = true; a.onComplete(); worker.dispose(); return; @@ -577,6 +587,7 @@ void runSync() { } if (q.isEmpty()) { + cancelled = true; a.onComplete(); worker.dispose(); return; @@ -617,6 +628,7 @@ void runAsync() { } catch (Throwable ex) { Exceptions.throwIfFatal(ex); + cancelled = true; upstream.cancel(); q.clear(); @@ -680,6 +692,7 @@ void runBackfused() { downstream.onNext(null); if (d) { + cancelled = true; Throwable e = error; if (e != null) { downstream.onError(e); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java index f415e7016f..abf1f0bb85 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java @@ -62,7 +62,7 @@ static final class ObserveOnObserver<T> extends BasicIntQueueDisposable<T> Throwable error; volatile boolean done; - volatile boolean cancelled; + volatile boolean disposed; int sourceMode; @@ -141,8 +141,8 @@ public void onComplete() { @Override public void dispose() { - if (!cancelled) { - cancelled = true; + if (!disposed) { + disposed = true; upstream.dispose(); worker.dispose(); if (getAndIncrement() == 0) { @@ -153,7 +153,7 @@ public void dispose() { @Override public boolean isDisposed() { - return cancelled; + return disposed; } void schedule() { @@ -181,6 +181,7 @@ void drainNormal() { v = q.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); + disposed = true; upstream.dispose(); q.clear(); a.onError(ex); @@ -211,7 +212,7 @@ void drainFused() { int missed = 1; for (;;) { - if (cancelled) { + if (disposed) { return; } @@ -219,6 +220,7 @@ void drainFused() { Throwable ex = error; if (!delayError && d && ex != null) { + disposed = true; downstream.onError(error); worker.dispose(); return; @@ -227,6 +229,7 @@ void drainFused() { downstream.onNext(null); if (d) { + disposed = true; ex = error; if (ex != null) { downstream.onError(ex); @@ -254,7 +257,7 @@ public void run() { } boolean checkTerminated(boolean d, boolean empty, Observer<? super T> a) { - if (cancelled) { + if (disposed) { queue.clear(); return true; } @@ -262,6 +265,7 @@ boolean checkTerminated(boolean d, boolean empty, Observer<? super T> a) { Throwable e = error; if (delayError) { if (empty) { + disposed = true; if (e != null) { a.onError(e); } else { @@ -272,12 +276,14 @@ boolean checkTerminated(boolean d, boolean empty, Observer<? super T> a) { } } else { if (e != null) { + disposed = true; queue.clear(); a.onError(e); worker.dispose(); return true; } else if (empty) { + disposed = true; a.onComplete(); worker.dispose(); return true; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java index 2beacebd84..d4fdbe15db 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java @@ -21,12 +21,13 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; -import io.reactivex.annotations.Nullable; import org.junit.Test; import org.mockito.InOrder; import org.reactivestreams.*; import io.reactivex.*; +import io.reactivex.annotations.Nullable; +import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; @@ -1781,4 +1782,163 @@ public void syncFusedRequestOneByOneConditional() { .test() .assertResult(1, 2, 3, 4, 5); } + + public static final class DisposeTrackingScheduler extends Scheduler { + + public final AtomicInteger disposedCount = new AtomicInteger(); + + @Override + public Worker createWorker() { + return new TrackingWorker(); + } + + final class TrackingWorker extends Scheduler.Worker { + + @Override + public void dispose() { + disposedCount.getAndIncrement(); + } + + @Override + public boolean isDisposed() { + return false; + } + + @Override + public Disposable schedule(Runnable run, long delay, + TimeUnit unit) { + run.run(); + return Disposables.empty(); + } + } + } + + @Test + public void workerNotDisposedPrematurelyNormalInNormalOut() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + Flowable.concat( + Flowable.just(1).hide().observeOn(s), + Flowable.just(2) + ) + .test() + .assertResult(1, 2); + + assertEquals(1, s.disposedCount.get()); + } + + @Test + public void workerNotDisposedPrematurelySyncInNormalOut() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + Flowable.concat( + Flowable.just(1).observeOn(s), + Flowable.just(2) + ) + .test() + .assertResult(1, 2); + + assertEquals(1, s.disposedCount.get()); + } + + @Test + public void workerNotDisposedPrematurelyAsyncInNormalOut() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + UnicastProcessor<Integer> up = UnicastProcessor.create(); + up.onNext(1); + up.onComplete(); + + Flowable.concat( + up.observeOn(s), + Flowable.just(2) + ) + .test() + .assertResult(1, 2); + + assertEquals(1, s.disposedCount.get()); + } + + static final class TestSubscriberFusedCanceling + extends TestSubscriber<Integer> { + + public TestSubscriberFusedCanceling() { + super(); + initialFusionMode = QueueFuseable.ANY; + } + + @Override + public void onComplete() { + cancel(); + super.onComplete(); + } + } + + @Test + public void workerNotDisposedPrematurelyNormalInAsyncOut() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + TestSubscriber<Integer> ts = new TestSubscriberFusedCanceling(); + + Flowable.just(1).hide().observeOn(s).subscribe(ts); + + assertEquals(1, s.disposedCount.get()); + } + + @Test + public void workerNotDisposedPrematurelyNormalInNormalOutConditional() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + Flowable.concat( + Flowable.just(1).hide().observeOn(s).filter(Functions.alwaysTrue()), + Flowable.just(2) + ) + .test() + .assertResult(1, 2); + + assertEquals(1, s.disposedCount.get()); + } + + @Test + public void workerNotDisposedPrematurelySyncInNormalOutConditional() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + Flowable.concat( + Flowable.just(1).observeOn(s).filter(Functions.alwaysTrue()), + Flowable.just(2) + ) + .test() + .assertResult(1, 2); + + assertEquals(1, s.disposedCount.get()); + } + + @Test + public void workerNotDisposedPrematurelyAsyncInNormalOutConditional() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + UnicastProcessor<Integer> up = UnicastProcessor.create(); + up.onNext(1); + up.onComplete(); + + Flowable.concat( + up.observeOn(s).filter(Functions.alwaysTrue()), + Flowable.just(2) + ) + .test() + .assertResult(1, 2); + + assertEquals(1, s.disposedCount.get()); + } + + @Test + public void workerNotDisposedPrematurelyNormalInAsyncOutConditional() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + TestSubscriber<Integer> ts = new TestSubscriberFusedCanceling(); + + Flowable.just(1).hide().observeOn(s).filter(Functions.alwaysTrue()).subscribe(ts); + + assertEquals(1, s.disposedCount.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java index 1ac99fcb5e..227b734b3a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java @@ -32,12 +32,15 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.internal.fuseable.*; +import io.reactivex.internal.operators.flowable.FlowableObserveOnTest.DisposeTrackingScheduler; import io.reactivex.internal.operators.observable.ObservableObserveOn.ObserveOnObserver; import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.UnicastProcessor; import io.reactivex.schedulers.*; import io.reactivex.subjects.*; +import io.reactivex.subscribers.TestSubscriber; public class ObservableObserveOnTest { @@ -740,4 +743,77 @@ public void onNext(Integer t) { }) .assertValuesOnly(2, 3); } + + @Test + public void workerNotDisposedPrematurelyNormalInNormalOut() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + Observable.concat( + Observable.just(1).hide().observeOn(s), + Observable.just(2) + ) + .test() + .assertResult(1, 2); + + assertEquals(1, s.disposedCount.get()); + } + + @Test + public void workerNotDisposedPrematurelySyncInNormalOut() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + Observable.concat( + Observable.just(1).observeOn(s), + Observable.just(2) + ) + .test() + .assertResult(1, 2); + + assertEquals(1, s.disposedCount.get()); + } + + @Test + public void workerNotDisposedPrematurelyAsyncInNormalOut() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + UnicastSubject<Integer> up = UnicastSubject.create(); + up.onNext(1); + up.onComplete(); + + Observable.concat( + up.observeOn(s), + Observable.just(2) + ) + .test() + .assertResult(1, 2); + + assertEquals(1, s.disposedCount.get()); + } + + static final class TestObserverFusedCanceling + extends TestObserver<Integer> { + + public TestObserverFusedCanceling() { + super(); + initialFusionMode = QueueFuseable.ANY; + } + + @Override + public void onComplete() { + cancel(); + super.onComplete(); + } + } + + @Test + public void workerNotDisposedPrematurelyNormalInAsyncOut() { + DisposeTrackingScheduler s = new DisposeTrackingScheduler(); + + TestObserver<Integer> to = new TestObserverFusedCanceling(); + + Observable.just(1).hide().observeOn(s).subscribe(to); + + assertEquals(1, s.disposedCount.get()); + } + } From eceae80aedfb942c82f66890c4c7c7e2bcf80d8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Karnok?= <akarnokd@gmail.com> Date: Wed, 22 Aug 2018 22:10:47 +0200 Subject: [PATCH 269/417] Remove unused imports --- .../internal/operators/observable/ObservableObserveOnTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java index 227b734b3a..70f047a005 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java @@ -37,10 +37,8 @@ import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.processors.UnicastProcessor; import io.reactivex.schedulers.*; import io.reactivex.subjects.*; -import io.reactivex.subscribers.TestSubscriber; public class ObservableObserveOnTest { From 5445b4a18088a14185eb4bd7f2f7556a48698755 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 23 Aug 2018 10:22:23 +0200 Subject: [PATCH 270/417] Release 2.2.1 --- CHANGES.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 86d4eda074..a4dfea7e35 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,43 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.1 - August 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.1%7C)) + +#### API changes + + - [Pull 6143](https://github.com/ReactiveX/RxJava/pull/6143): Add `concatArrayEagerDelayError` operator (expose feature). + +#### Bugfixes + + - [Pull 6145](https://github.com/ReactiveX/RxJava/pull/6145): Fix boundary fusion of `concatMap` and `publish` operator. + - [Pull 6158](https://github.com/ReactiveX/RxJava/pull/6158): Make `Flowable.fromCallable` consistent with the other `fromCallable`s. + - [Pull 6165](https://github.com/ReactiveX/RxJava/pull/6165): Handle undeliverable error in `Completable.fromCallable` via `RxJavaPlugins`. + - [Pull 6167](https://github.com/ReactiveX/RxJava/pull/6167): Make `observeOn` not let `worker.dispose()` get called prematurely. + +#### Performance improvements + + - [Pull 6123](https://github.com/ReactiveX/RxJava/pull/6123): Improve `Completable.onErrorResumeNext` internals. + - [Pull 6121](https://github.com/ReactiveX/RxJava/pull/6121): `Flowable.onErrorResumeNext` improvements. + +#### Documentation changes + +##### JavaDocs + + - [Pull 6095](https://github.com/ReactiveX/RxJava/pull/6095): Add marbles for `Single.timer`, `Single.defer` and `Single.toXXX` operators. + - [Pull 6137](https://github.com/ReactiveX/RxJava/pull/6137): Add marbles for `Single.concat` operator. + - [Pull 6141](https://github.com/ReactiveX/RxJava/pull/6141): Add marble diagrams for various `Single` operators. + - [Pull 6152](https://github.com/ReactiveX/RxJava/pull/6152): Clarify `TestObserver.assertValueSet` in docs and via tests. + - [Pull 6155](https://github.com/ReactiveX/RxJava/pull/6155): Fix marble of `Maybe.flatMap` events to `MaybeSource`. + +##### Wiki changes + + - [Pull 6128](https://github.com/ReactiveX/RxJava/pull/6128): Remove `fromEmitter()` in wiki. + - [Pull 6133](https://github.com/ReactiveX/RxJava/pull/6133): Update `_Sidebar.md` with new order of topics. + - [Pull 6135](https://github.com/ReactiveX/RxJava/pull/6135): Initial clean up for Combining Observables docs. + - [Pull 6131](https://github.com/ReactiveX/RxJava/pull/6131): Expand `Creating-Observables.md` wiki. + - [Pull 6134](https://github.com/ReactiveX/RxJava/pull/6134): Update RxJava Android Module documentation. + - [Pull 6140](https://github.com/ReactiveX/RxJava/pull/6140): Update Mathematical and Aggregate Operators docs. + ### Version 2.2.0 - July 31, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.0%7C)) #### Summary From 3e2b1b3fa19aa394c846e32735f6589bc5aa551a Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sat, 25 Aug 2018 09:53:04 +0200 Subject: [PATCH 271/417] 2.x: Add explanation text to Undeliverable & OnErrorNotImplemented exs (#6171) * 2.x: Add explanation text to Undeliverable & OnErrorNotImplemented exs * Link to the wiki instead of the docs directory due to broken [[]] links * Reword OnErrorNotImplemented --- .../reactivex/exceptions/OnErrorNotImplementedException.java | 2 +- .../java/io/reactivex/exceptions/UndeliverableException.java | 2 +- src/test/java/io/reactivex/exceptions/ExceptionsTest.java | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java b/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java index 994a5c25a5..6fdc42aeec 100644 --- a/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java +++ b/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java @@ -48,6 +48,6 @@ public OnErrorNotImplementedException(String message, @NonNull Throwable e) { * the {@code Throwable} to signal; if null, a NullPointerException is constructed */ public OnErrorNotImplementedException(@NonNull Throwable e) { - super(e != null ? e.getMessage() : null, e != null ? e : new NullPointerException()); + this("The exception was not handled due to missing onError handler in the subscribe() method call. Further reading: https://github.com/ReactiveX/RxJava/wiki/Error-Handling | " + (e != null ? e.getMessage() : ""), e); } } \ No newline at end of file diff --git a/src/main/java/io/reactivex/exceptions/UndeliverableException.java b/src/main/java/io/reactivex/exceptions/UndeliverableException.java index 6f6aec0938..d8bb99ce5c 100644 --- a/src/main/java/io/reactivex/exceptions/UndeliverableException.java +++ b/src/main/java/io/reactivex/exceptions/UndeliverableException.java @@ -28,6 +28,6 @@ public final class UndeliverableException extends IllegalStateException { * @param cause the cause, not null */ public UndeliverableException(Throwable cause) { - super(cause); + super("The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | " + cause.getMessage(), cause); } } diff --git a/src/test/java/io/reactivex/exceptions/ExceptionsTest.java b/src/test/java/io/reactivex/exceptions/ExceptionsTest.java index 43b316a7f7..4928f14bf1 100644 --- a/src/test/java/io/reactivex/exceptions/ExceptionsTest.java +++ b/src/test/java/io/reactivex/exceptions/ExceptionsTest.java @@ -53,7 +53,8 @@ public void accept(Integer t1) { }); - TestHelper.assertError(errors, 0, RuntimeException.class, "hello"); + TestHelper.assertError(errors, 0, RuntimeException.class); + assertTrue(errors.get(0).toString(), errors.get(0).getMessage().contains("hello")); RxJavaPlugins.reset(); } From ba7bbb497d43a1353a3e5f81b0887b26bf4cadfb Mon Sep 17 00:00:00 2001 From: Aaron Friedman <aaron.js.friedman@gmail.com> Date: Sat, 25 Aug 2018 22:42:56 -1000 Subject: [PATCH 272/417] Auto-clean up RxJavaPlugins JavaDocs HTML (#6173) (#6174) --- gradle/javadoc_cleanup.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/gradle/javadoc_cleanup.gradle b/gradle/javadoc_cleanup.gradle index 32db33b963..79f4d5411a 100644 --- a/gradle/javadoc_cleanup.gradle +++ b/gradle/javadoc_cleanup.gradle @@ -11,6 +11,7 @@ task javadocCleanup(dependsOn: "javadoc") doLast { fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/subjects/ReplaySubject.html')); fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/processors/ReplayProcessor.html')); + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/plugins/RxJavaPlugins.html')); } def fixJavadocFile(file) { From e2a21599fa451ff26f00ec52133604e8daf7d78c Mon Sep 17 00:00:00 2001 From: punitd <punitdama@gmail.com> Date: Sun, 26 Aug 2018 16:44:52 +0530 Subject: [PATCH 273/417] 2.x: explain null observer/subscriber return errors from RxJavaPlugins in detail (#6175) --- src/main/java/io/reactivex/Completable.java | 2 ++ src/main/java/io/reactivex/Flowable.java | 2 +- src/main/java/io/reactivex/Maybe.java | 2 +- src/main/java/io/reactivex/Observable.java | 2 +- src/main/java/io/reactivex/Single.java | 2 +- src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java | 2 +- .../java/io/reactivex/observable/ObservableSubscriberTest.java | 2 +- 7 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index b4f18a56c2..cb08465a2a 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -2168,6 +2168,8 @@ public final void subscribe(CompletableObserver observer) { observer = RxJavaPlugins.onSubscribe(this, observer); + ObjectHelper.requireNonNull(observer, "The RxJavaPlugins.onSubscribe hook returned a null CompletableObserver. Please check the handler provided to RxJavaPlugins.setOnCompletableSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins"); + subscribeActual(observer); } catch (NullPointerException ex) { // NOPMD throw ex; diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 6af68db61d..15abe6bd95 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -14473,7 +14473,7 @@ public final void subscribe(FlowableSubscriber<? super T> s) { try { Subscriber<? super T> z = RxJavaPlugins.onSubscribe(this, s); - ObjectHelper.requireNonNull(z, "Plugin returned null Subscriber"); + ObjectHelper.requireNonNull(z, "The RxJavaPlugins.onSubscribe hook returned a null FlowableSubscriber. Please check the handler provided to RxJavaPlugins.setOnFlowableSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins"); subscribeActual(z); } catch (NullPointerException e) { // NOPMD diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 4bc994e3d3..1338323569 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -4150,7 +4150,7 @@ public final void subscribe(MaybeObserver<? super T> observer) { observer = RxJavaPlugins.onSubscribe(this, observer); - ObjectHelper.requireNonNull(observer, "observer returned by the RxJavaPlugins hook is null"); + ObjectHelper.requireNonNull(observer, "The RxJavaPlugins.onSubscribe hook returned a null MaybeObserver. Please check the handler provided to RxJavaPlugins.setOnMaybeSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins"); try { subscribeActual(observer); diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 2c43e0abf0..9781a3dad4 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -12079,7 +12079,7 @@ public final void subscribe(Observer<? super T> observer) { try { observer = RxJavaPlugins.onSubscribe(this, observer); - ObjectHelper.requireNonNull(observer, "Plugin returned null Observer"); + ObjectHelper.requireNonNull(observer, "The RxJavaPlugins.onSubscribe hook returned a null Observer. Please change the handler provided to RxJavaPlugins.setOnObservableSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins"); subscribeActual(observer); } catch (NullPointerException e) { // NOPMD diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index f75b275a90..b6896e7cec 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -3427,7 +3427,7 @@ public final void subscribe(SingleObserver<? super T> observer) { observer = RxJavaPlugins.onSubscribe(this, observer); - ObjectHelper.requireNonNull(observer, "subscriber returned by the RxJavaPlugins hook is null"); + ObjectHelper.requireNonNull(observer, "The RxJavaPlugins.onSubscribe hook returned a null SingleObserver. Please check the handler provided to RxJavaPlugins.setOnSingleSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins"); try { subscribeActual(observer); diff --git a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java index f7789656a3..189747dfa4 100644 --- a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java @@ -815,7 +815,7 @@ public Subscriber apply(Flowable a, Subscriber b) throws Exception { Flowable.just(1).test(); fail("Should have thrown"); } catch (NullPointerException ex) { - assertEquals("Plugin returned null Subscriber", ex.getMessage()); + assertEquals("The RxJavaPlugins.onSubscribe hook returned a null FlowableSubscriber. Please check the handler provided to RxJavaPlugins.setOnFlowableSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins", ex.getMessage()); } } finally { RxJavaPlugins.reset(); diff --git a/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java b/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java index 9544bb5030..848d6128e1 100644 --- a/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java +++ b/src/test/java/io/reactivex/observable/ObservableSubscriberTest.java @@ -205,7 +205,7 @@ public Observer apply(Observable a, Observer b) throws Exception { Observable.just(1).test(); fail("Should have thrown"); } catch (NullPointerException ex) { - assertEquals("Plugin returned null Observer", ex.getMessage()); + assertEquals("The RxJavaPlugins.onSubscribe hook returned a null Observer. Please change the handler provided to RxJavaPlugins.setOnObservableSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins", ex.getMessage()); } } finally { RxJavaPlugins.reset(); From 13f7b01f4e681a6aa7494cdae5f2cf4474b2baab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20Bia=C5=82orucki?= <maciej.bialorucki@gmail.com> Date: Tue, 28 Aug 2018 10:54:19 +0200 Subject: [PATCH 274/417] Update Additional-Reading.md (#6180) * Update Additional-Reading.md Check existing links, add new links about RxAndroid * Update Additional-Reading.md Add code version marks where possible --- docs/Additional-Reading.md | 42 ++++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/docs/Additional-Reading.md b/docs/Additional-Reading.md index 6f65b4f677..b5a4a2604a 100644 --- a/docs/Additional-Reading.md +++ b/docs/Additional-Reading.md @@ -1,11 +1,11 @@ (A more complete and up-to-date list of resources can be found at the reactivex.io site: [[http://reactivex.io/tutorials.html]]) # Introducing Reactive Programming -* [Introduction to Rx](http://www.introtorx.com/): a free, on-line book by Lee Campbell +* [Introduction to Rx](http://www.introtorx.com/): a free, on-line book by Lee Campbell **(1.x)** * [The introduction to Reactive Programming you've been missing](https://gist.github.com/staltz/868e7e9bc2a7b8c1f754) by Andre Staltz -* [Mastering Observables](http://docs.couchbase.com/developer/java-2.0/observables.html) from the Couchbase documentation -* [Reactive Programming in Java 8 With RxJava](http://pluralsight.com/training/Courses/TableOfContents/reactive-programming-java-8-rxjava), a course designed by Russell Elledge -* [33rd Degree Reactive Java](http://www.slideshare.net/tkowalcz/33rd-degree-reactive-java) by Tomasz Kowalczewski +* [Mastering Observables](http://docs.couchbase.com/developer/java-2.0/observables.html) from the Couchbase documentation **(1.x)** +* [Reactive Programming in Java 8 With RxJava](http://pluralsight.com/training/Courses/TableOfContents/reactive-programming-java-8-rxjava), a course designed by Russell Elledge **(1.x)** +* [33rd Degree Reactive Java](http://www.slideshare.net/tkowalcz/33rd-degree-reactive-java) by Tomasz Kowalczewski **(1.x)** * [What Every Hipster Should Know About Functional Reactive Programming](http://www.infoq.com/presentations/game-functional-reactive-programming) - Bodil Stokke demos the creation of interactive game mechanics in RxJS * [Your Mouse is a Database](http://queue.acm.org/detail.cfm?id=2169076) by Erik Meijer * [A Playful Introduction to Rx](https://www.youtube.com/watch?v=WKore-AkisY) a video lecture by Erik Meijer @@ -14,18 +14,17 @@ * [2 minute introduction to Rx](https://medium.com/@andrestaltz/2-minute-introduction-to-rx-24c8ca793877) by André Staltz * StackOverflow: [What is (functional) reactive programming?](http://stackoverflow.com/a/1030631/1946802) * [The Reactive Manifesto](http://www.reactivemanifesto.org/) -* Grokking RxJava, [Part 1: The Basics](http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/), [Part 2: Operator, Operator](http://blog.danlew.net/2014/09/22/grokking-rxjava-part-2/), [Part 3: Reactive with Benefits](http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3/), [Part 4: Reactive Android](http://blog.danlew.net/2014/10/08/grokking-rxjava-part-4/) - published in Sep/Oct 2014 by Daniel Lew -* [FRP on Android](http://slides.com/yaroslavheriatovych/frponandroid#/) - publish in Jan 2014 by Yaroslav Heriatovych +* Grokking RxJava, [Part 1: The Basics](http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/), [Part 2: Operator, Operator](http://blog.danlew.net/2014/09/22/grokking-rxjava-part-2/), [Part 3: Reactive with Benefits](http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3/), [Part 4: Reactive Android](http://blog.danlew.net/2014/10/08/grokking-rxjava-part-4/) - published in Sep/Oct 2014 by Daniel Lew **(1.x)** # How Netflix Is Using RxJava -* LambdaJam Chicago 2013: [Functional Reactive Programming in the Netflix API](https://speakerdeck.com/benjchristensen/functional-reactive-programming-in-the-netflix-api-lambdajam-2013) by Ben Christensen -* QCon London 2013 presentation: [Functional Reactive Programming in the Netflix API](http://www.infoq.com/presentations/netflix-functional-rx) and a related [interview](http://www.infoq.com/interviews/christensen-hystrix-rxjava) with Ben Christensen -* [Functional Reactive in the Netflix API with RxJava](http://techblog.netflix.com/2013/02/rxjava-netflix-api.html) by Ben Christensen and Jafar Husain -* [Optimizing the Netflix API](http://techblog.netflix.com/2013/01/optimizing-netflix-api.html) by Ben Christensen -* [Reactive Programming at Netflix](http://techblog.netflix.com/2013/01/reactive-programming-at-netflix.html) by Jafar Husain +* LambdaJam Chicago 2013: [Functional Reactive Programming in the Netflix API](https://speakerdeck.com/benjchristensen/functional-reactive-programming-in-the-netflix-api-lambdajam-2013) by Ben Christensen **(1.x)** +* QCon London 2013 presentation: [Functional Reactive Programming in the Netflix API](http://www.infoq.com/presentations/netflix-functional-rx) and a related [interview](http://www.infoq.com/interviews/christensen-hystrix-rxjava) with Ben Christensen **(1.x)** +* [Functional Reactive in the Netflix API with RxJava](http://techblog.netflix.com/2013/02/rxjava-netflix-api.html) by Ben Christensen and Jafar Husain **(1.x)** +* [Optimizing the Netflix API](http://techblog.netflix.com/2013/01/optimizing-netflix-api.html) by Ben Christensen **(1.x)** +* [Reactive Programming at Netflix](http://techblog.netflix.com/2013/01/reactive-programming-at-netflix.html) by Jafar Husain **(1.x)** # RxScala -* [RxJava: Reactive Extensions in Scala](http://www.youtube.com/watch?v=tOMK_FYJREw&feature=youtu.be): video of Ben Christensen and Matt Jacobs presenting at SF Scala +* [RxJava: Reactive Extensions in Scala](http://www.youtube.com/watch?v=tOMK_FYJREw&feature=youtu.be): video of Ben Christensen and Matt Jacobs presenting at SF Scala **(1.x)** # Rx.NET * [rx.codeplex.com](https://rx.codeplex.com) @@ -44,7 +43,20 @@ * [RxJS](https://xgrommx.github.io/rx-book/), an on-line book by @xgrommx * [Journey from procedural to reactive Javascript with stops](https://glebbahmutov.com/blog/journey-from-procedural-to-reactive-javascript-with-stops/) by Gleb Bahmutov +# RxAndroid + +* [FRP on Android](http://slides.com/yaroslavheriatovych/frponandroid#/) - publish in Jan 2014 by Yaroslav Heriatovych **(1.x)** +* [RxAndroid Github page](https://github.com/ReactiveX/RxAndroid) **(2.x)** +* [RxAndroid basics](https://medium.com/@kurtisnusbaum/rxandroid-basics-part-1-c0d5edcf6850) **(1.x & 2.x)** +* [RxJava and RxAndroid on AndroidHive](https://www.androidhive.info/RxJava/) **(1.x & 2.x)** +* [Reactive Programming with RxAndroid in Kotlin: An Introduction](https://www.raywenderlich.com/384-reactive-programming-with-rxandroid-in-kotlin-an-introduction) **(2.x)** +* [Difference between RxJava and RxAndroid](https://stackoverflow.com/questions/49651249/difference-between-rxjava-and-rxandroid) **(2.x)** +* [Reactive programming with RxAndroid](https://www.androidauthority.com/reactive-programming-with-rxandroid-711104/) **(1.x)** +* [RxJava - Vogella.com](http://www.vogella.com/tutorials/RxJava/article.html) **(2.x)** +* [Funcitional reactive Android](https://www.toptal.com/android/functional-reactive-android-rxjava) **(1.x)** +* [Reactive Programming with RxAndroid and Kotlin](https://www.pluralsight.com/courses/rxandroid-kotlin-reactive-programming) + # Miscellany -* [RxJava Observables and Akka Actors](http://onoffswitch.net/rxjava-observables-akka-actors/) by Anton Kropp -* [Vert.x and RxJava](http://slid.es/petermd/eclipsecon2014) by @petermd -* [RxJava in Different Flavours of Java](http://instil.co/2014/08/05/rxjava-in-different-flavours-of-java/): Java 7 and Java 8 implementations of the same code \ No newline at end of file +* [RxJava Observables and Akka Actors](http://onoffswitch.net/rxjava-observables-akka-actors/) by Anton Kropp **(1.x & 2.x)** +* [Vert.x and RxJava](http://slid.es/petermd/eclipsecon2014) by @petermd **(1.x)** +* [RxJava in Different Flavours of Java](http://instil.co/2014/08/05/rxjava-in-different-flavours-of-java/): Java 7 and Java 8 implementations of the same code **(1.x)** From 2e566fbc34e47de59cf76d862e5bfb631e36215c Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 28 Aug 2018 17:33:10 +0200 Subject: [PATCH 275/417] 2.x: Cleanup multiple empty lines in sources (#6182) --- gradle/stylesheet.css | 1 - src/jmh/java/io/reactivex/XMapYPerf.java | 4 - src/main/java/io/reactivex/Completable.java | 2 - src/main/java/io/reactivex/Flowable.java | 6 - src/main/java/io/reactivex/Maybe.java | 9 -- src/main/java/io/reactivex/Observable.java | 1 - src/main/java/io/reactivex/Scheduler.java | 1 - src/main/java/io/reactivex/Single.java | 2 - .../disposables/CancellableDisposable.java | 1 - .../disposables/DisposableHelper.java | 1 - .../internal/disposables/EmptyDisposable.java | 1 - .../disposables/SequentialDisposable.java | 1 - .../internal/fuseable/QueueFuseable.java | 1 - .../observers/BasicIntQueueDisposable.java | 1 - .../observers/BiConsumerSingleObserver.java | 1 - .../CallbackCompletableObserver.java | 1 - .../observers/ConsumerSingleObserver.java | 1 - .../observers/EmptyCompletableObserver.java | 1 - .../observers/ForEachWhileObserver.java | 1 - .../observers/InnerQueuedObserver.java | 1 - .../completable/CompletableObserveOn.java | 1 - .../completable/CompletableUsing.java | 1 - .../operators/flowable/FlowableBuffer.java | 2 - .../flowable/FlowableBufferTimed.java | 2 - .../flowable/FlowableCombineLatest.java | 3 - .../operators/flowable/FlowableConcatMap.java | 6 - .../operators/flowable/FlowableCount.java | 1 - .../operators/flowable/FlowableCreate.java | 6 - .../flowable/FlowableDebounceTimed.java | 1 - .../FlowableDistinctUntilChanged.java | 1 - .../operators/flowable/FlowableFilter.java | 2 - .../flowable/FlowableFlattenIterable.java | 1 - .../operators/flowable/FlowableFromArray.java | 3 - .../flowable/FlowableFromIterable.java | 3 - .../operators/flowable/FlowableGroupJoin.java | 1 - .../operators/flowable/FlowableJoin.java | 1 - .../operators/flowable/FlowableMap.java | 1 - .../flowable/FlowableMapPublisher.java | 1 - .../flowable/FlowableOnBackpressureError.java | 1 - .../operators/flowable/FlowableRange.java | 3 - .../operators/flowable/FlowableRangeLong.java | 2 - .../flowable/FlowableReduceMaybe.java | 2 - .../operators/flowable/FlowableRefCount.java | 1 - .../flowable/FlowableRepeatWhen.java | 1 - .../operators/flowable/FlowableRetryWhen.java | 1 - .../operators/flowable/FlowableSwitchMap.java | 1 - .../flowable/FlowableThrottleFirstTimed.java | 2 - .../flowable/FlowableTimeoutTimed.java | 1 - .../operators/flowable/FlowableToList.java | 2 - .../operators/flowable/FlowableWindow.java | 4 - .../FlowableWindowBoundarySelector.java | 1 - .../operators/flowable/FlowableZip.java | 2 - .../internal/operators/maybe/MaybeAmb.java | 1 - .../maybe/MaybeCallbackObserver.java | 1 - .../internal/operators/maybe/MaybeCreate.java | 1 - .../operators/maybe/MaybeEqualSingle.java | 1 - .../internal/operators/maybe/MaybeFilter.java | 3 - .../maybe/MaybeFlatMapIterableFlowable.java | 1 - .../maybe/MaybeFlatMapIterableObservable.java | 1 - .../maybe/MaybeFlatMapNotification.java | 1 - .../operators/maybe/MaybeFlatten.java | 1 - .../internal/operators/maybe/MaybeMap.java | 3 - .../operators/maybe/MaybeMergeArray.java | 1 - .../operators/maybe/MaybeObserveOn.java | 1 - .../operators/maybe/MaybeOnErrorNext.java | 1 - .../operators/maybe/MaybeTimeoutMaybe.java | 3 - .../maybe/MaybeTimeoutPublisher.java | 5 - .../internal/operators/maybe/MaybeUsing.java | 1 - .../operators/maybe/MaybeZipArray.java | 2 - .../BlockingObservableIterable.java | 1 - .../BlockingObservableMostRecent.java | 1 - .../observable/ObservableBufferTimed.java | 1 - .../observable/ObservableConcatMap.java | 1 - .../observable/ObservableCreate.java | 1 - .../observable/ObservableFlatMap.java | 1 - .../observable/ObservableGroupJoin.java | 1 - .../observable/ObservableInternalHelper.java | 1 - .../observable/ObservableInterval.java | 1 - .../observable/ObservableIntervalRange.java | 1 - .../operators/observable/ObservableJoin.java | 1 - .../operators/observable/ObservableMap.java | 2 - .../observable/ObservableMaterialize.java | 1 - .../ObservableThrottleFirstTimed.java | 2 - .../observable/ObservableTimeoutTimed.java | 1 - .../ObservableWindowBoundarySelector.java | 1 - .../observable/ObservableWindowTimed.java | 1 - .../operators/parallel/ParallelCollect.java | 1 - .../parallel/ParallelFromPublisher.java | 1 - .../operators/parallel/ParallelReduce.java | 1 - .../parallel/ParallelReduceFull.java | 1 - .../parallel/ParallelSortedJoin.java | 1 - .../single/SingleDelayWithCompletable.java | 1 - .../single/SingleDelayWithObservable.java | 1 - .../single/SingleDelayWithPublisher.java | 1 - .../single/SingleDelayWithSingle.java | 1 - .../single/SingleFlatMapIterableFlowable.java | 1 - .../SingleFlatMapIterableObservable.java | 1 - .../operators/single/SingleToFlowable.java | 1 - .../operators/single/SingleZipArray.java | 2 - .../schedulers/ComputationScheduler.java | 1 - .../schedulers/ExecutorScheduler.java | 1 - .../internal/schedulers/NewThreadWorker.java | 1 - .../subscribers/ForEachWhileSubscriber.java | 1 - .../subscribers/InnerQueuedSubscriber.java | 1 - .../BasicIntQueueSubscription.java | 1 - .../subscriptions/BasicQueueSubscription.java | 1 - .../DeferredScalarSubscription.java | 1 - .../util/AppendOnlyLinkedArrayList.java | 1 - .../internal/util/AtomicThrowable.java | 1 - .../internal/util/HalfSerializer.java | 1 - .../reactivex/internal/util/OpenHashSet.java | 1 - .../java/io/reactivex/internal/util/Pow2.java | 1 - .../reactivex/observers/BaseTestConsumer.java | 4 - .../reactivex/parallel/ParallelFlowable.java | 2 - .../processors/BehaviorProcessor.java | 2 - .../reactivex/processors/ReplayProcessor.java | 1 - .../processors/UnicastProcessor.java | 1 - .../reactivex/subjects/BehaviorSubject.java | 1 - .../io/reactivex/subjects/ReplaySubject.java | 2 - .../io/reactivex/subjects/UnicastSubject.java | 2 - .../reactivex/subscribers/SafeSubscriber.java | 1 - .../reactivex/subscribers/TestSubscriber.java | 1 - .../reactivex/exceptions/TestException.java | 2 - .../flowable/FlowableBackpressureTests.java | 1 - .../flowable/FlowableSubscriberTest.java | 3 +- .../reactivex/flowable/FlowableZipTests.java | 1 - .../reactivex/internal/SubscribeWithTest.java | 1 - .../operators/flowable/FlowableCacheTest.java | 1 - .../flowable/FlowableConcatTest.java | 1 - .../flowable/FlowableDetachTest.java | 1 - .../FlowableDistinctUntilChangedTest.java | 1 - .../flowable/FlowableFlatMapTest.java | 1 - ...wableOnBackpressureBufferStrategyTest.java | 1 - ...eOnExceptionResumeNextViaFlowableTest.java | 1 - .../flowable/FlowablePublishFunctionTest.java | 1 - .../flowable/FlowableReplayTest.java | 5 - .../flowable/FlowableSwitchIfEmptyTest.java | 2 - .../flowable/FlowableSwitchTest.java | 1 - .../FlowableWindowWithFlowableTest.java | 3 - .../flowable/FlowableWindowWithTimeTest.java | 1 - .../flowable/NotificationLiteTest.java | 1 - .../operators/maybe/MaybeConcatArrayTest.java | 1 - .../maybe/MaybeFromCompletableTest.java | 1 - .../operators/maybe/MaybeZipArrayTest.java | 1 - .../observable/ObservableCacheTest.java | 1 - .../observable/ObservableConcatTest.java | 1 - .../observable/ObservableDebounceTest.java | 1 - .../observable/ObservableDetachTest.java | 1 - .../observable/ObservableFlatMapTest.java | 1 - .../ObservableFromCallableTest.java | 3 - ...nExceptionResumeNextViaObservableTest.java | 1 - .../observable/ObservableReplayTest.java | 4 - .../ObservableSwitchIfEmptyTest.java | 2 - .../ObservableWindowWithObservableTest.java | 2 - .../ObservableWindowWithSizeTest.java | 1 - .../ObservableWindowWithTimeTest.java | 1 - .../ObservableWithLatestFromTest.java | 1 - .../single/SingleInternalHelperTest.java | 1 - .../operators/single/SingleZipArrayTest.java | 1 - .../ExecutorSchedulerDelayedRunnableTest.java | 1 - .../DeferredScalarSubscriberTest.java | 1 - .../reactivex/observers/ObserverFusion.java | 1 - .../reactivex/observers/TestObserverTest.java | 3 - .../reactivex/plugins/RxJavaPluginsTest.java | 2 - .../processors/AsyncProcessorTest.java | 1 - .../processors/BehaviorProcessorTest.java | 2 - .../processors/PublishProcessorTest.java | 1 - .../processors/ReplayProcessorTest.java | 3 - .../processors/UnicastProcessorTest.java | 2 - .../schedulers/AbstractSchedulerTests.java | 1 - .../schedulers/ExecutorSchedulerTest.java | 1 - .../schedulers/SchedulerLifecycleTest.java | 1 - .../io/reactivex/single/SingleNullTests.java | 1 - .../reactivex/subjects/AsyncSubjectTest.java | 1 - .../subjects/BehaviorSubjectTest.java | 2 - .../subjects/PublishSubjectTest.java | 1 - .../subjects/UnicastSubjectTest.java | 2 - .../subscribers/TestSubscriberTest.java | 4 - .../validators/JavadocForAnnotations.java | 1 - .../validators/NewLinesBeforeAnnotation.java | 2 +- .../ParamValidationCheckerTest.java | 1 - .../validators/TooManyEmptyNewLines.java | 132 ++++++++++++++++++ 182 files changed, 134 insertions(+), 277 deletions(-) create mode 100644 src/test/java/io/reactivex/validators/TooManyEmptyNewLines.java diff --git a/gradle/stylesheet.css b/gradle/stylesheet.css index 5e381dce8b..60f1d665bf 100644 --- a/gradle/stylesheet.css +++ b/gradle/stylesheet.css @@ -534,7 +534,6 @@ td.colLast div { padding-top:0px; } - td.colLast a { padding-bottom:3px; } diff --git a/src/jmh/java/io/reactivex/XMapYPerf.java b/src/jmh/java/io/reactivex/XMapYPerf.java index 389a89000f..d9e198b284 100644 --- a/src/jmh/java/io/reactivex/XMapYPerf.java +++ b/src/jmh/java/io/reactivex/XMapYPerf.java @@ -94,7 +94,6 @@ public class XMapYPerf { Observable<Integer> obsFlatMapIterableAsObs0; - @Setup public void setup() { Integer[] values = new Integer[times]; @@ -158,7 +157,6 @@ public Iterable<Integer> apply(Integer v) throws Exception { } }); - flowFlatMapSingle1 = fsource.flatMapSingle(new Function<Integer, SingleSource<Integer>>() { @Override public SingleSource<Integer> apply(Integer v) throws Exception { @@ -231,7 +229,6 @@ public Publisher<Integer> apply(Integer v) throws Exception { } }); - // ------------------------------------------------------------------- Observable<Integer> osource = Observable.fromArray(values); @@ -271,7 +268,6 @@ public MaybeSource<Integer> apply(Integer v) throws Exception { } }); - obsFlatMapCompletable0 = osource.flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index cb08465a2a..6cf5aa75f4 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -388,7 +388,6 @@ public static Completable error(final Throwable error) { return RxJavaPlugins.onAssembly(new CompletableError(error)); } - /** * Returns a Completable instance that runs the given Action for each subscriber and * emits either an unchecked exception or simply completes. @@ -790,7 +789,6 @@ public static Completable mergeDelayError(Iterable<? extends CompletableSource> return RxJavaPlugins.onAssembly(new CompletableMergeDelayErrorIterable(sources)); } - /** * Returns a Completable that subscribes to all Completables in the source sequence and delays * any error emitted by either the sources observable or any of the inner Completables until all of diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 15abe6bd95..bab8443357 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -3474,7 +3474,6 @@ public static <T> Flowable<T> mergeDelayError(Iterable<? extends Publisher<? ext return fromIterable(sources).flatMap((Function)Functions.identity(), true); } - /** * Flattens an Iterable of Publishers into one Publisher, in a way that allows a Subscriber to receive all * successfully emitted items from each of the source Publishers without being interrupted by an error @@ -3787,7 +3786,6 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends T> source1, Pu return fromArray(source1, source2, source3).flatMap((Function)Functions.identity(), true, 3); } - /** * Flattens four Publishers into one Publisher, in a way that allows a Subscriber to receive all * successfully emitted items from all of the source Publishers without being interrupted by an error @@ -4629,7 +4627,6 @@ public static <T1, T2, R> Flowable<R> zip( return zipArray(Functions.toFunction(zipper), delayError, bufferSize(), source1, source2); } - /** * Returns a Flowable that emits the results of a specified combiner function applied to combinations of * two items emitted, in sequence, by two other Publishers. @@ -7357,7 +7354,6 @@ public final <R> Flowable<R> concatMapDelayError(Function<? super T, ? extends P return RxJavaPlugins.onAssembly(new FlowableConcatMap<T, R>(this, mapper, prefetch, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY)); } - /** * Maps a sequence of values into Publishers and concatenates these Publishers eagerly into a single * Publisher. @@ -10749,7 +10745,6 @@ public final <TRight, TLeftEnd, TRightEnd, R> Flowable<R> join( this, other, leftEnd, rightEnd, resultSelector)); } - /** * Returns a Maybe that emits the last item emitted by this Flowable or completes if * this Flowable is empty. @@ -14703,7 +14698,6 @@ public final <R> Flowable<R> switchMap(Function<? super T, ? extends Publisher<? return switchMap0(mapper, bufferSize, false); } - /** * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 1338323569..8750c83cd2 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -839,7 +839,6 @@ public static <T> Maybe<T> fromRunnable(final Runnable run) { return RxJavaPlugins.onAssembly(new MaybeFromRunnable<T>(run)); } - /** * Returns a {@code Maybe} that emits a specified item. * <p> @@ -1238,7 +1237,6 @@ public static <T> Flowable<T> mergeArrayDelayError(MaybeSource<? extends T>... s return Flowable.fromArray(sources).flatMap((Function)MaybeToPublisher.instance(), true, sources.length); } - /** * Flattens an Iterable of MaybeSources into one Flowable, in a way that allows a Subscriber to receive all * successfully emitted items from each of the source MaybeSources without being interrupted by an error @@ -1274,7 +1272,6 @@ public static <T> Flowable<T> mergeDelayError(Iterable<? extends MaybeSource<? e return Flowable.fromIterable(sources).flatMap((Function)MaybeToPublisher.instance(), true); } - /** * Flattens a Publisher that emits MaybeSources into one Publisher, in a way that allows a Subscriber to * receive all successfully emitted items from all of the source MaybeSources without being interrupted by @@ -1310,7 +1307,6 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends MaybeSource<? return mergeDelayError(sources, Integer.MAX_VALUE); } - /** * Flattens a Publisher that emits MaybeSources into one Publisher, in a way that allows a Subscriber to * receive all successfully emitted items from all of the source MaybeSources without being interrupted by @@ -1432,7 +1428,6 @@ public static <T> Flowable<T> mergeDelayError(MaybeSource<? extends T> source1, return mergeArrayDelayError(source1, source2, source3); } - /** * Flattens four MaybeSources into one Flowable, in a way that allows a Subscriber to receive all * successfully emitted items from all of the source MaybeSources without being interrupted by an error @@ -1503,7 +1498,6 @@ public static <T> Maybe<T> never() { return RxJavaPlugins.onAssembly((Maybe<T>)MaybeNever.INSTANCE); } - /** * Returns a Single that emits a Boolean value that indicates whether two MaybeSource sequences are the * same by comparing the items emitted by each MaybeSource pairwise. @@ -2388,7 +2382,6 @@ public final <R> Maybe<R> concatMap(Function<? super T, ? extends MaybeSource<? return RxJavaPlugins.onAssembly(new MaybeFlatten<T, R>(this, mapper)); } - /** * Returns a Flowable that emits the items emitted from the current MaybeSource, then the next, one after * the other, without interleaving them. @@ -2486,7 +2479,6 @@ public final Maybe<T> defaultIfEmpty(T defaultItem) { return switchIfEmpty(just(defaultItem)); } - /** * Returns a Maybe that signals the events emitted by the source Maybe shifted forward in time by a * specified delay. @@ -3838,7 +3830,6 @@ public final Flowable<T> repeatWhen(final Function<? super Flowable<Object>, ? e return toFlowable().repeatWhen(handler); } - /** * Returns a Maybe that mirrors the source Maybe, resubscribing to it if it calls {@code onError} * (infinite retry count). diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 9781a3dad4..d1adc46efa 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -5429,7 +5429,6 @@ public final void blockingSubscribe(Consumer<? super T> onNext, Consumer<? super ObservableBlockingSubscribe.subscribe(this, onNext, onError, Functions.EMPTY_ACTION); } - /** * Subscribes to the source and calls the given callbacks <strong>on the current thread</strong>. * <p> diff --git a/src/main/java/io/reactivex/Scheduler.java b/src/main/java/io/reactivex/Scheduler.java index 0f4806d4a0..2e99e288f1 100644 --- a/src/main/java/io/reactivex/Scheduler.java +++ b/src/main/java/io/reactivex/Scheduler.java @@ -110,7 +110,6 @@ public static long clockDriftTolerance() { return CLOCK_DRIFT_TOLERANCE_NANOSECONDS; } - /** * Retrieves or creates a new {@link Scheduler.Worker} that represents sequential execution of actions. * <p> diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index b6896e7cec..51a896c887 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -1072,7 +1072,6 @@ public static <T> Flowable<T> merge( return merge(Flowable.fromArray(source1, source2, source3, source4)); } - /** * Merges an Iterable sequence of SingleSource instances into a single Flowable sequence, * running all SingleSources at once and delaying any error(s) until all sources succeed or fail. @@ -1121,7 +1120,6 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends SingleSource<? return RxJavaPlugins.onAssembly(new FlowableFlatMapPublisher(sources, SingleInternalHelper.toFlowable(), true, Integer.MAX_VALUE, Flowable.bufferSize())); } - /** * Flattens two Singles into a single Flowable, without any transformation, delaying * any error(s) until all sources succeed or fail. diff --git a/src/main/java/io/reactivex/internal/disposables/CancellableDisposable.java b/src/main/java/io/reactivex/internal/disposables/CancellableDisposable.java index e5cc4ad656..446dd6cdf6 100644 --- a/src/main/java/io/reactivex/internal/disposables/CancellableDisposable.java +++ b/src/main/java/io/reactivex/internal/disposables/CancellableDisposable.java @@ -28,7 +28,6 @@ public final class CancellableDisposable extends AtomicReference<Cancellable> implements Disposable { - private static final long serialVersionUID = 5718521705281392066L; public CancellableDisposable(Cancellable cancellable) { diff --git a/src/main/java/io/reactivex/internal/disposables/DisposableHelper.java b/src/main/java/io/reactivex/internal/disposables/DisposableHelper.java index f9ad177399..46f13bd743 100644 --- a/src/main/java/io/reactivex/internal/disposables/DisposableHelper.java +++ b/src/main/java/io/reactivex/internal/disposables/DisposableHelper.java @@ -20,7 +20,6 @@ import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.plugins.RxJavaPlugins; - /** * Utility methods for working with Disposables atomically. */ diff --git a/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java b/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java index f87df26a17..4e90491b69 100644 --- a/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java +++ b/src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java @@ -114,5 +114,4 @@ public int requestFusion(int mode) { return mode & ASYNC; } - } diff --git a/src/main/java/io/reactivex/internal/disposables/SequentialDisposable.java b/src/main/java/io/reactivex/internal/disposables/SequentialDisposable.java index e250bf1925..458194ab63 100644 --- a/src/main/java/io/reactivex/internal/disposables/SequentialDisposable.java +++ b/src/main/java/io/reactivex/internal/disposables/SequentialDisposable.java @@ -28,7 +28,6 @@ public final class SequentialDisposable extends AtomicReference<Disposable> implements Disposable { - private static final long serialVersionUID = -754898800686245608L; /** diff --git a/src/main/java/io/reactivex/internal/fuseable/QueueFuseable.java b/src/main/java/io/reactivex/internal/fuseable/QueueFuseable.java index 850e9284af..f5e803807e 100644 --- a/src/main/java/io/reactivex/internal/fuseable/QueueFuseable.java +++ b/src/main/java/io/reactivex/internal/fuseable/QueueFuseable.java @@ -13,7 +13,6 @@ package io.reactivex.internal.fuseable; - /** * Represents a SimpleQueue plus the means and constants for requesting a fusion mode. * @param <T> the value type returned by the SimpleQueue.poll() diff --git a/src/main/java/io/reactivex/internal/observers/BasicIntQueueDisposable.java b/src/main/java/io/reactivex/internal/observers/BasicIntQueueDisposable.java index 39d68c80dc..a5d2adf430 100644 --- a/src/main/java/io/reactivex/internal/observers/BasicIntQueueDisposable.java +++ b/src/main/java/io/reactivex/internal/observers/BasicIntQueueDisposable.java @@ -26,7 +26,6 @@ public abstract class BasicIntQueueDisposable<T> extends AtomicInteger implements QueueDisposable<T> { - private static final long serialVersionUID = -1001730202384742097L; @Override diff --git a/src/main/java/io/reactivex/internal/observers/BiConsumerSingleObserver.java b/src/main/java/io/reactivex/internal/observers/BiConsumerSingleObserver.java index e14425f70e..188c78b1b3 100644 --- a/src/main/java/io/reactivex/internal/observers/BiConsumerSingleObserver.java +++ b/src/main/java/io/reactivex/internal/observers/BiConsumerSingleObserver.java @@ -26,7 +26,6 @@ public final class BiConsumerSingleObserver<T> extends AtomicReference<Disposable> implements SingleObserver<T>, Disposable { - private static final long serialVersionUID = 4943102778943297569L; final BiConsumer<? super T, ? super Throwable> onCallback; diff --git a/src/main/java/io/reactivex/internal/observers/CallbackCompletableObserver.java b/src/main/java/io/reactivex/internal/observers/CallbackCompletableObserver.java index 3555751a8e..ee059c5b37 100644 --- a/src/main/java/io/reactivex/internal/observers/CallbackCompletableObserver.java +++ b/src/main/java/io/reactivex/internal/observers/CallbackCompletableObserver.java @@ -27,7 +27,6 @@ public final class CallbackCompletableObserver extends AtomicReference<Disposable> implements CompletableObserver, Disposable, Consumer<Throwable>, LambdaConsumerIntrospection { - private static final long serialVersionUID = -4361286194466301354L; final Consumer<? super Throwable> onError; diff --git a/src/main/java/io/reactivex/internal/observers/ConsumerSingleObserver.java b/src/main/java/io/reactivex/internal/observers/ConsumerSingleObserver.java index 7c3c4ad3b7..59735e9c11 100644 --- a/src/main/java/io/reactivex/internal/observers/ConsumerSingleObserver.java +++ b/src/main/java/io/reactivex/internal/observers/ConsumerSingleObserver.java @@ -28,7 +28,6 @@ public final class ConsumerSingleObserver<T> extends AtomicReference<Disposable> implements SingleObserver<T>, Disposable, LambdaConsumerIntrospection { - private static final long serialVersionUID = -7012088219455310787L; final Consumer<? super T> onSuccess; diff --git a/src/main/java/io/reactivex/internal/observers/EmptyCompletableObserver.java b/src/main/java/io/reactivex/internal/observers/EmptyCompletableObserver.java index 5b70ddb624..38d0f3746e 100644 --- a/src/main/java/io/reactivex/internal/observers/EmptyCompletableObserver.java +++ b/src/main/java/io/reactivex/internal/observers/EmptyCompletableObserver.java @@ -26,7 +26,6 @@ public final class EmptyCompletableObserver extends AtomicReference<Disposable> implements CompletableObserver, Disposable, LambdaConsumerIntrospection { - private static final long serialVersionUID = -7545121636549663526L; @Override diff --git a/src/main/java/io/reactivex/internal/observers/ForEachWhileObserver.java b/src/main/java/io/reactivex/internal/observers/ForEachWhileObserver.java index 54b8fdbd5c..22ba3f80a8 100644 --- a/src/main/java/io/reactivex/internal/observers/ForEachWhileObserver.java +++ b/src/main/java/io/reactivex/internal/observers/ForEachWhileObserver.java @@ -26,7 +26,6 @@ public final class ForEachWhileObserver<T> extends AtomicReference<Disposable> implements Observer<T>, Disposable { - private static final long serialVersionUID = -4403180040475402120L; final Predicate<? super T> onNext; diff --git a/src/main/java/io/reactivex/internal/observers/InnerQueuedObserver.java b/src/main/java/io/reactivex/internal/observers/InnerQueuedObserver.java index 27d800e183..3a18b38153 100644 --- a/src/main/java/io/reactivex/internal/observers/InnerQueuedObserver.java +++ b/src/main/java/io/reactivex/internal/observers/InnerQueuedObserver.java @@ -31,7 +31,6 @@ public final class InnerQueuedObserver<T> extends AtomicReference<Disposable> implements Observer<T>, Disposable { - private static final long serialVersionUID = -5417183359794346637L; final InnerQueuedObserverSupport<T> parent; diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java index 11dbebe280..b931ed4a5d 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableObserveOn.java @@ -38,7 +38,6 @@ static final class ObserveOnCompletableObserver extends AtomicReference<Disposable> implements CompletableObserver, Disposable, Runnable { - private static final long serialVersionUID = 8571289934935992137L; final CompletableObserver downstream; diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java index 0dc127ec82..1f107f2c00 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java @@ -88,7 +88,6 @@ static final class UsingObserver<R> extends AtomicReference<Object> implements CompletableObserver, Disposable { - private static final long serialVersionUID = -674404550052917487L; final CompletableObserver downstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBuffer.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBuffer.java index bf0cda25b1..f2f940ac2e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBuffer.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBuffer.java @@ -159,7 +159,6 @@ static final class PublisherBufferSkipSubscriber<T, C extends Collection<? super extends AtomicInteger implements FlowableSubscriber<T>, Subscription { - private static final long serialVersionUID = -5616169793639412593L; final Subscriber<? super C> downstream; @@ -286,7 +285,6 @@ public void onComplete() { } } - static final class PublisherBufferOverlappingSubscriber<T, C extends Collection<? super T>> extends AtomicLong implements FlowableSubscriber<T>, Subscription, BooleanSupplier { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java index 48212822ff..4e3be8a9e5 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java @@ -78,7 +78,6 @@ protected void subscribeActual(Subscriber<? super U> s) { bufferSupplier, timespan, timeskip, unit, w)); } - static final class BufferExactUnboundedSubscriber<T, U extends Collection<? super T>> extends QueueDrainSubscriber<T, U, U> implements Subscription, Runnable, Disposable { final Callable<U> bufferSupplier; @@ -236,7 +235,6 @@ static final class BufferSkipBoundedSubscriber<T, U extends Collection<? super T Subscription upstream; - BufferSkipBoundedSubscriber(Subscriber<? super U> actual, Callable<U> bufferSupplier, long timespan, long timeskip, TimeUnit unit, Worker w) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java index a4bc8f6bc4..c690701fcf 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java @@ -136,7 +136,6 @@ public void subscribeActual(Subscriber<? super R> s) { return; } - CombineLatestCoordinator<T, R> coordinator = new CombineLatestCoordinator<T, R>(s, combiner, n, bufferSize, delayErrors); @@ -148,7 +147,6 @@ public void subscribeActual(Subscriber<? super R> s) { static final class CombineLatestCoordinator<T, R> extends BasicIntQueueSubscription<R> { - private static final long serialVersionUID = -5082275438355852221L; final Subscriber<? super R> downstream; @@ -494,7 +492,6 @@ static final class CombineLatestInnerSubscriber<T> extends AtomicReference<Subscription> implements FlowableSubscriber<T> { - private static final long serialVersionUID = -8730235182291002949L; final CombineLatestCoordinator<T, ?> parent; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java index bb408ef6c8..edde82442e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java @@ -173,11 +173,9 @@ public final void innerComplete() { } - static final class ConcatMapImmediate<T, R> extends BaseConcatMapSubscriber<T, R> { - private static final long serialVersionUID = 7898995095634264146L; final Subscriber<? super R> downstream; @@ -303,7 +301,6 @@ void drain() { } } - if (p instanceof Callable) { @SuppressWarnings("unchecked") Callable<R> callable = (Callable<R>) p; @@ -320,7 +317,6 @@ void drain() { return; } - if (vr == null) { continue; } @@ -382,7 +378,6 @@ public void cancel() { static final class ConcatMapDelayed<T, R> extends BaseConcatMapSubscriber<T, R> { - private static final long serialVersionUID = -2945777694260521066L; final Subscriber<? super R> downstream; @@ -569,7 +564,6 @@ static final class ConcatMapInner<R> extends SubscriptionArbiter implements FlowableSubscriber<R> { - private static final long serialVersionUID = 897683679971470653L; final ConcatMapSupport<R> parent; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCount.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCount.java index ebe2b07024..b29e2690a1 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCount.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCount.java @@ -32,7 +32,6 @@ protected void subscribeActual(Subscriber<? super Long> s) { static final class CountSubscriber extends DeferredScalarSubscription<Long> implements FlowableSubscriber<Object> { - private static final long serialVersionUID = 4973004223787171406L; Subscription upstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java index e7d43e466b..caf6d31101 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java @@ -28,7 +28,6 @@ import io.reactivex.internal.util.*; import io.reactivex.plugins.RxJavaPlugins; - public final class FlowableCreate<T> extends Flowable<T> { final FlowableOnSubscribe<T> source; @@ -352,7 +351,6 @@ public String toString() { static final class MissingEmitter<T> extends BaseEmitter<T> { - private static final long serialVersionUID = 3776720187248809713L; MissingEmitter(Subscriber<? super T> downstream) { @@ -414,7 +412,6 @@ public final void onNext(T t) { static final class DropAsyncEmitter<T> extends NoOverflowBaseAsyncEmitter<T> { - private static final long serialVersionUID = 8360058422307496563L; DropAsyncEmitter(Subscriber<? super T> downstream) { @@ -430,7 +427,6 @@ void onOverflow() { static final class ErrorAsyncEmitter<T> extends NoOverflowBaseAsyncEmitter<T> { - private static final long serialVersionUID = 338953216916120960L; ErrorAsyncEmitter(Subscriber<? super T> downstream) { @@ -446,7 +442,6 @@ void onOverflow() { static final class BufferAsyncEmitter<T> extends BaseEmitter<T> { - private static final long serialVersionUID = 2427151001689639875L; final SpscLinkedArrayQueue<T> queue; @@ -589,7 +584,6 @@ void drain() { static final class LatestAsyncEmitter<T> extends BaseEmitter<T> { - private static final long serialVersionUID = 4023437720691792495L; final AtomicReference<T> queue; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java index b30a68c62d..51d365e849 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java @@ -175,7 +175,6 @@ static final class DebounceEmitter<T> extends AtomicReference<Disposable> implem final AtomicBoolean once = new AtomicBoolean(); - DebounceEmitter(T value, long idx, DebounceTimedSubscriber<T> parent) { this.value = value; this.idx = idx; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChanged.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChanged.java index f54be6360b..c1cf54658e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChanged.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChanged.java @@ -46,7 +46,6 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class DistinctUntilChangedSubscriber<T, K> extends BasicFuseableSubscriber<T, T> implements ConditionalSubscriber<T> { - final Function<? super T, K> keySelector; final BiPredicate<? super K, ? super K> comparer; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFilter.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFilter.java index 30487f90d7..dd90b2c1ec 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFilter.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFilter.java @@ -102,8 +102,6 @@ public T poll() throws Exception { } } } - - } static final class FilterConditionalSubscriber<T> extends BasicFuseableConditionalSubscriber<T, T> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java index 29e425f58e..01398b9a29 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java @@ -85,7 +85,6 @@ static final class FlattenIterableSubscriber<T, R> extends BasicIntQueueSubscription<R> implements FlowableSubscriber<T> { - private static final long serialVersionUID = -3096000382929934955L; final Subscriber<? super R> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java index 25b7610eaa..c8c6201daa 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java @@ -98,7 +98,6 @@ public final void cancel() { cancelled = true; } - abstract void fastPath(); abstract void slowPath(long r); @@ -106,7 +105,6 @@ public final void cancel() { static final class ArraySubscription<T> extends BaseArraySubscription<T> { - private static final long serialVersionUID = 2587302975077663557L; final Subscriber<? super T> downstream; @@ -190,7 +188,6 @@ void slowPath(long r) { static final class ArrayConditionalSubscription<T> extends BaseArraySubscription<T> { - private static final long serialVersionUID = 2587302975077663557L; final ConditionalSubscriber<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java index 3c3017bcfb..e893dca7e8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java @@ -139,7 +139,6 @@ public final void cancel() { static final class IteratorSubscription<T> extends BaseRangeSubscription<T> { - private static final long serialVersionUID = -6022804456014692607L; final Subscriber<? super T> downstream; @@ -193,7 +192,6 @@ void fastPath() { return; } - if (!b) { if (!cancelled) { a.onComplete(); @@ -277,7 +275,6 @@ void slowPath(long r) { static final class IteratorConditionalSubscription<T> extends BaseRangeSubscription<T> { - private static final long serialVersionUID = -6022804456014692607L; final ConditionalSubscriber<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java index d42e3e05af..c9a2b69adb 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java @@ -89,7 +89,6 @@ interface JoinSupport { static final class GroupJoinSubscription<TLeft, TRight, TLeftEnd, TRightEnd, R> extends AtomicInteger implements Subscription, JoinSupport { - private static final long serialVersionUID = -6071216598687999801L; final Subscriber<? super R> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableJoin.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableJoin.java index 5ff5c97c3f..2bd33b64a3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableJoin.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableJoin.java @@ -73,7 +73,6 @@ protected void subscribeActual(Subscriber<? super R> s) { static final class JoinSubscription<TLeft, TRight, TLeftEnd, TRightEnd, R> extends AtomicInteger implements Subscription, JoinSupport { - private static final long serialVersionUID = -6071216598687999801L; final Subscriber<? super R> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMap.java index 905f3cb6cb..7b6632dcf9 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMap.java @@ -11,7 +11,6 @@ * the License for the specific language governing permissions and limitations under the License. */ - package io.reactivex.internal.operators.flowable; import org.reactivestreams.Subscriber; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapPublisher.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapPublisher.java index ac9fee861e..3378af4b15 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMapPublisher.java @@ -11,7 +11,6 @@ * the License for the specific language governing permissions and limitations under the License. */ - package io.reactivex.internal.operators.flowable; import org.reactivestreams.*; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java index 5d758096c3..f60c43bc31 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java @@ -25,7 +25,6 @@ public final class FlowableOnBackpressureError<T> extends AbstractFlowableWithUpstream<T, T> { - public FlowableOnBackpressureError(Flowable<T> source) { super(source); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java index 185218480e..d4b6b50a59 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java @@ -100,7 +100,6 @@ public final void cancel() { cancelled = true; } - abstract void fastPath(); abstract void slowPath(long r); @@ -108,7 +107,6 @@ public final void cancel() { static final class RangeSubscription extends BaseRangeSubscription { - private static final long serialVersionUID = 2587302975077663557L; final Subscriber<? super Integer> downstream; @@ -177,7 +175,6 @@ void slowPath(long r) { static final class RangeConditionalSubscription extends BaseRangeSubscription { - private static final long serialVersionUID = 2587302975077663557L; final ConditionalSubscriber<? super Integer> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRangeLong.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRangeLong.java index 96bc5cddb0..d641e6a285 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRangeLong.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRangeLong.java @@ -102,7 +102,6 @@ public final void cancel() { cancelled = true; } - abstract void fastPath(); abstract void slowPath(long r); @@ -178,7 +177,6 @@ void slowPath(long r) { static final class RangeConditionalSubscription extends BaseRangeSubscription { - private static final long serialVersionUID = 2587302975077663557L; final ConditionalSubscriber<? super Long> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceMaybe.java index 7745c047a7..569dcdccf8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReduceMaybe.java @@ -138,7 +138,5 @@ public void onComplete() { downstream.onComplete(); } } - - } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java index deec615b20..82a1373228 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java @@ -114,7 +114,6 @@ void cancel(RefConnection rc) { sd.replace(scheduler.scheduleDirect(rc, timeout, unit)); } - void terminated(RefConnection rc) { synchronized (this) { if (connection != null) { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java index ce137d4f52..c5fac022ad 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java @@ -178,7 +178,6 @@ public final void cancel() { static final class RepeatWhenSubscriber<T> extends WhenSourceSubscriber<T, Object> { - private static final long serialVersionUID = -2680129890138081029L; RepeatWhenSubscriber(Subscriber<? super T> actual, FlowableProcessor<Object> processor, diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryWhen.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryWhen.java index 4cf535cd90..de0f735802 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryWhen.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryWhen.java @@ -64,7 +64,6 @@ public void subscribeActual(Subscriber<? super T> s) { static final class RetryWhenSubscriber<T> extends WhenSourceSubscriber<T, Throwable> { - private static final long serialVersionUID = -2680129890138081029L; RetryWhenSubscriber(Subscriber<? super T> actual, FlowableProcessor<Throwable> processor, diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java index 0b00c03c9a..9730bd38b2 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java @@ -57,7 +57,6 @@ static final class SwitchMapSubscriber<T, R> extends AtomicInteger implements Fl final int bufferSize; final boolean delayErrors; - volatile boolean done; final AtomicThrowable error; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTimed.java index 727bd4d484..ca10e8d47c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTimed.java @@ -107,8 +107,6 @@ public void onNext(T t) { timer.replace(worker.schedule(this, timeout, unit)); } - - } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java index 9be6bc847b..28f00cfe1b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java @@ -152,7 +152,6 @@ public void cancel() { } } - static final class TimeoutTask implements Runnable { final TimeoutSupport parent; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java index a49c3dcc8c..60508e3e7e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java @@ -44,12 +44,10 @@ protected void subscribeActual(Subscriber<? super U> s) { source.subscribe(new ToListSubscriber<T, U>(s, coll)); } - static final class ToListSubscriber<T, U extends Collection<? super T>> extends DeferredScalarSubscription<U> implements FlowableSubscriber<T>, Subscription { - private static final long serialVersionUID = -8134157938864266736L; Subscription upstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindow.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindow.java index bbe2f2b6e0..e9c1259b65 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindow.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindow.java @@ -55,7 +55,6 @@ static final class WindowExactSubscriber<T> extends AtomicInteger implements FlowableSubscriber<T>, Subscription, Runnable { - private static final long serialVersionUID = -2365647875069161133L; final Subscriber<? super Flowable<T>> downstream; @@ -164,7 +163,6 @@ static final class WindowSkipSubscriber<T> extends AtomicInteger implements FlowableSubscriber<T>, Subscription, Runnable { - private static final long serialVersionUID = -8792836352386833856L; final Subscriber<? super Flowable<T>> downstream; @@ -211,7 +209,6 @@ public void onNext(T t) { if (i == 0) { getAndIncrement(); - w = UnicastProcessor.<T>create(bufferSize, this); window = w; @@ -292,7 +289,6 @@ static final class WindowOverlapSubscriber<T> extends AtomicInteger implements FlowableSubscriber<T>, Subscription, Runnable { - private static final long serialVersionUID = 2428527070996323976L; final Subscriber<? super Flowable<T>> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java index 246b1be106..0e3fe58b83 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java @@ -240,7 +240,6 @@ void drainLoop() { continue; } - w = UnicastProcessor.<T>create(bufferSize); long r = requested(); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableZip.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableZip.java index 1d585cc02c..b8516a93e9 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableZip.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableZip.java @@ -83,7 +83,6 @@ static final class ZipCoordinator<T, R> extends AtomicInteger implements Subscription { - private static final long serialVersionUID = -2434867452883857743L; final Subscriber<? super R> downstream; @@ -320,7 +319,6 @@ void drain() { } } - static final class ZipSubscriber<T, R> extends AtomicReference<Subscription> implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = -4627193790118206028L; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java index fb6940c479..d9c1c6963c 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java @@ -91,7 +91,6 @@ static final class AmbMaybeObserver<T> extends AtomicBoolean implements MaybeObserver<T>, Disposable { - private static final long serialVersionUID = -7044685185359438206L; final MaybeObserver<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCallbackObserver.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCallbackObserver.java index 1a3da7d04b..9dc56e137f 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCallbackObserver.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCallbackObserver.java @@ -33,7 +33,6 @@ public final class MaybeCallbackObserver<T> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable, LambdaConsumerIntrospection { - private static final long serialVersionUID = -6076952298809384986L; final Consumer<? super T> onSuccess; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java index 5a3852662a..e328a2b3c7 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeCreate.java @@ -59,7 +59,6 @@ static final class Emitter<T> this.downstream = downstream; } - private static final long serialVersionUID = -2467358622224974244L; @Override diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeEqualSingle.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeEqualSingle.java index 4f843635aa..f5f83fbcfc 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeEqualSingle.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeEqualSingle.java @@ -127,7 +127,6 @@ static final class EqualObserver<T> extends AtomicReference<Disposable> implements MaybeObserver<T> { - private static final long serialVersionUID = -3031974433025990931L; final EqualCoordinator<T> parent; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilter.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilter.java index fd556c3a66..763ad258e0 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilter.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFilter.java @@ -101,8 +101,5 @@ public void onError(Throwable e) { public void onComplete() { downstream.onComplete(); } - - } - } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowable.java index 5ea9adb386..f4d174d924 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowable.java @@ -158,7 +158,6 @@ void fastPath(Subscriber<? super R> a, Iterator<? extends R> iterator) { return; } - boolean b; try { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java index 4e5755fb8f..5513eb5e8f 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java @@ -128,7 +128,6 @@ public void onSuccess(T value) { return; } - boolean b; try { diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapNotification.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapNotification.java index f5bb71e110..81eb167484 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapNotification.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapNotification.java @@ -56,7 +56,6 @@ static final class FlatMapMaybeObserver<T, R> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable { - private static final long serialVersionUID = 4375739915521278546L; final MaybeObserver<? super R> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatten.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatten.java index b05aebd236..6463ef270b 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatten.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatten.java @@ -46,7 +46,6 @@ static final class FlatMapMaybeObserver<T, R> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable { - private static final long serialVersionUID = 4375739915521278546L; final MaybeObserver<? super R> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeMap.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeMap.java index cda167855c..7d7c7a47b5 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeMap.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeMap.java @@ -98,8 +98,5 @@ public void onError(Throwable e) { public void onComplete() { downstream.onComplete(); } - - } - } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeMergeArray.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeMergeArray.java index 762452ba7a..1edfdd69da 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeMergeArray.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeMergeArray.java @@ -318,7 +318,6 @@ static final class MpscFillOnceSimpleQueue<T> extends AtomicReferenceArray<T> implements SimpleQueueWithConsumerIndex<T> { - private static final long serialVersionUID = -7969063454040569579L; final AtomicInteger producerIndex; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeObserveOn.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeObserveOn.java index a3d83612d5..cce201fedb 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeObserveOn.java @@ -42,7 +42,6 @@ static final class ObserveOnMaybeObserver<T> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable, Runnable { - private static final long serialVersionUID = 8571289934935992137L; final MaybeObserver<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorNext.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorNext.java index 5591d41c20..f7fff884ad 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorNext.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeOnErrorNext.java @@ -50,7 +50,6 @@ static final class OnErrorNextMaybeObserver<T> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable { - private static final long serialVersionUID = 2026620218879969836L; final MaybeObserver<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutMaybe.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutMaybe.java index d162573139..83d22cf232 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutMaybe.java @@ -54,7 +54,6 @@ static final class TimeoutMainMaybeObserver<T, U> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable { - private static final long serialVersionUID = -5955289211445418871L; final MaybeObserver<? super T> downstream; @@ -141,7 +140,6 @@ static final class TimeoutOtherMaybeObserver<T, U> extends AtomicReference<Disposable> implements MaybeObserver<Object> { - private static final long serialVersionUID = 8663801314800248617L; final TimeoutMainMaybeObserver<T, U> parent; @@ -174,7 +172,6 @@ static final class TimeoutFallbackMaybeObserver<T> extends AtomicReference<Disposable> implements MaybeObserver<T> { - private static final long serialVersionUID = 8663801314800248617L; final MaybeObserver<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java index 64ab706f5e..f0d690d567 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java @@ -57,7 +57,6 @@ static final class TimeoutMainMaybeObserver<T, U> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable { - private static final long serialVersionUID = -5955289211445418871L; final MaybeObserver<? super T> downstream; @@ -144,7 +143,6 @@ static final class TimeoutOtherMaybeObserver<T, U> extends AtomicReference<Subscription> implements FlowableSubscriber<Object> { - private static final long serialVersionUID = 8663801314800248617L; final TimeoutMainMaybeObserver<T, U> parent; @@ -179,7 +177,6 @@ static final class TimeoutFallbackMaybeObserver<T> extends AtomicReference<Disposable> implements MaybeObserver<T> { - private static final long serialVersionUID = 8663801314800248617L; final MaybeObserver<? super T> downstream; @@ -208,6 +205,4 @@ public void onComplete() { downstream.onComplete(); } } - - } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeUsing.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeUsing.java index 786772eacf..4628d1261c 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeUsing.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeUsing.java @@ -99,7 +99,6 @@ static final class UsingObserver<T, D> extends AtomicReference<Object> implements MaybeObserver<T>, Disposable { - private static final long serialVersionUID = -674404550052917487L; final MaybeObserver<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeZipArray.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeZipArray.java index 430d3ff2b6..d9cc0028af 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeZipArray.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeZipArray.java @@ -39,7 +39,6 @@ protected void subscribeActual(MaybeObserver<? super R> observer) { MaybeSource<? extends T>[] sources = this.sources; int n = sources.length; - if (n == 1) { sources[0].subscribe(new MaybeMap.MapMaybeObserver<T, R>(observer, new SingletonArrayFunc())); return; @@ -66,7 +65,6 @@ protected void subscribeActual(MaybeObserver<? super R> observer) { static final class ZipCoordinator<T, R> extends AtomicInteger implements Disposable { - private static final long serialVersionUID = -5556924161382950569L; final MaybeObserver<? super R> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java b/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java index 776721c84e..3fdd26f9b6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java @@ -44,7 +44,6 @@ static final class BlockingObservableIterator<T> extends AtomicReference<Disposable> implements io.reactivex.Observer<T>, Iterator<T>, Disposable { - private static final long serialVersionUID = 6695226475494099826L; final SpscLinkedArrayQueue<T> queue; diff --git a/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecent.java b/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecent.java index 44156e1171..90a603f65c 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecent.java +++ b/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecent.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; - import java.util.*; import io.reactivex.ObservableSource; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java index 59358c79a9..8a6fafea6e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java @@ -223,7 +223,6 @@ static final class BufferSkipBoundedObserver<T, U extends Collection<? super T>> final Worker w; final List<U> buffers; - Disposable upstream; BufferSkipBoundedObserver(Observer<? super U> actual, diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java index 642f0e01f1..831cfd1c55 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java @@ -273,7 +273,6 @@ static final class ConcatMapDelayErrorObserver<T, R> extends AtomicInteger implements Observer<T>, Disposable { - private static final long serialVersionUID = -6951100001833242599L; final Observer<? super R> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java index 1e48bdabee..03ba3f1186 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCreate.java @@ -48,7 +48,6 @@ static final class CreateEmitter<T> extends AtomicReference<Disposable> implements ObservableEmitter<T>, Disposable { - private static final long serialVersionUID = -3434801548987643227L; final Observer<? super T> observer; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java index 0bc25cebaf..9039aa78a6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java @@ -232,7 +232,6 @@ boolean tryEmitScalar(Callable<? extends U> value) { return true; } - if (get() == 0 && compareAndSet(0, 1)) { downstream.onNext(u); if (decrementAndGet() == 0) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java index 3b4baaa78a..23e39af881 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java @@ -88,7 +88,6 @@ interface JoinSupport { static final class GroupJoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R> extends AtomicInteger implements Disposable, JoinSupport { - private static final long serialVersionUID = -6071216598687999801L; final Observer<? super R> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java index 0af4a15f0a..733b18f0ee 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java @@ -83,7 +83,6 @@ public static <T, U> Function<T, ObservableSource<T>> itemDelay(final Function<? return new ItemDelayFunction<T, U>(itemDelay); } - static final class ObserverOnNext<T> implements Consumer<T> { final Observer<T> observer; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java index f786cffaba..947a3941fa 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableInterval.java @@ -56,7 +56,6 @@ static final class IntervalObserver extends AtomicReference<Disposable> implements Disposable, Runnable { - private static final long serialVersionUID = 346773832286157679L; final Observer<? super Long> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java index 2e69495e66..5d48d1d3d0 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableIntervalRange.java @@ -60,7 +60,6 @@ static final class IntervalRangeObserver extends AtomicReference<Disposable> implements Disposable, Runnable { - private static final long serialVersionUID = 1891866368734007884L; final Observer<? super Long> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java index b8393e3f78..9a293ca7d5 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java @@ -74,7 +74,6 @@ protected void subscribeActual(Observer<? super R> observer) { static final class JoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R> extends AtomicInteger implements Disposable, JoinSupport { - private static final long serialVersionUID = -6071216598687999801L; final Observer<? super R> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMap.java index 5df2a6c341..475963ce85 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMap.java @@ -11,7 +11,6 @@ * the License for the specific language governing permissions and limitations under the License. */ - package io.reactivex.internal.operators.observable; import io.reactivex.*; @@ -33,7 +32,6 @@ public void subscribeActual(Observer<? super U> t) { source.subscribe(new MapObserver<T, U>(t, function)); } - static final class MapObserver<T, U> extends BasicFuseableObserver<T, U> { final Function<? super T, ? extends U> mapper; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java index a82668cfc3..9cfe82b16a 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMaterialize.java @@ -19,7 +19,6 @@ public final class ObservableMaterialize<T> extends AbstractObservableWithUpstream<T, Notification<T>> { - public ObservableMaterialize(ObservableSource<T> source) { super(source); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleFirstTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleFirstTimed.java index 54e94ab0b7..ab1ce459f4 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleFirstTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableThrottleFirstTimed.java @@ -87,8 +87,6 @@ public void onNext(T t) { } DisposableHelper.replace(this, worker.schedule(this, timeout, unit)); } - - } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java index 7c955939c0..7ceda44b73 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java @@ -147,7 +147,6 @@ public boolean isDisposed() { } } - static final class TimeoutTask implements Runnable { final TimeoutSupport parent; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java index b15d4ee140..1e2a2ea052 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java @@ -233,7 +233,6 @@ void drainLoop() { continue; } - w = UnicastSubject.create(bufferSize); ws.add(w); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java index 5b76d067e7..1ffc0f475e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java @@ -264,7 +264,6 @@ static final class WindowExactBoundedObserver<T> UnicastSubject<T> window; - volatile boolean terminated; final AtomicReference<Disposable> timer = new AtomicReference<Disposable>(); diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelCollect.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelCollect.java index 4f7b53ed94..b1052b2fd6 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelCollect.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelCollect.java @@ -87,7 +87,6 @@ public int parallelism() { static final class ParallelCollectSubscriber<T, C> extends DeferredScalarSubscriber<T, C> { - private static final long serialVersionUID = -4767392946044436228L; final BiConsumer<? super C, ? super T> collector; diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java index fc7288a1a1..33d83ca34c 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelFromPublisher.java @@ -62,7 +62,6 @@ static final class ParallelDispatcher<T> extends AtomicInteger implements FlowableSubscriber<T> { - private static final long serialVersionUID = -4470634016609963609L; final Subscriber<? super T>[] subscribers; diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduce.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduce.java index 8e421ef112..0c3bcfbba1 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduce.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduce.java @@ -86,7 +86,6 @@ public int parallelism() { static final class ParallelReduceSubscriber<T, R> extends DeferredScalarSubscriber<T, R> { - private static final long serialVersionUID = 8200530050639449080L; final BiFunction<R, ? super T, R> reducer; diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java index 347ce2ead9..8757752322 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java @@ -52,7 +52,6 @@ protected void subscribeActual(Subscriber<? super T> s) { static final class ParallelReduceFullMainSubscriber<T> extends DeferredScalarSubscription<T> { - private static final long serialVersionUID = -5370107872170712765L; final ParallelReduceFullInnerSubscriber<T>[] subscribers; diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java index 1151716fff..a7c4947709 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java @@ -266,7 +266,6 @@ static final class SortedJoinInnerSubscriber<T> extends AtomicReference<Subscription> implements FlowableSubscriber<List<T>> { - private static final long serialVersionUID = 6751017204873808094L; final SortedJoinSubscription<T> parent; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java index ba5beeec9d..86dbd4d39f 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithCompletable.java @@ -40,7 +40,6 @@ static final class OtherObserver<T> extends AtomicReference<Disposable> implements CompletableObserver, Disposable { - private static final long serialVersionUID = -8565274649390031272L; final SingleObserver<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java index 0614c091c0..c905bba0c6 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithObservable.java @@ -41,7 +41,6 @@ static final class OtherSubscriber<T, U> extends AtomicReference<Disposable> implements Observer<U>, Disposable { - private static final long serialVersionUID = -8565274649390031272L; final SingleObserver<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java index bbc8a9e460..ee93007020 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithPublisher.java @@ -44,7 +44,6 @@ static final class OtherSubscriber<T, U> extends AtomicReference<Disposable> implements FlowableSubscriber<U>, Disposable { - private static final long serialVersionUID = -8565274649390031272L; final SingleObserver<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java index 1c1b4aabe3..83255b95c3 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java @@ -40,7 +40,6 @@ static final class OtherObserver<T, U> extends AtomicReference<Disposable> implements SingleObserver<U>, Disposable { - private static final long serialVersionUID = -8565274649390031272L; final SingleObserver<? super T> downstream; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowable.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowable.java index 1243413dff..f6f4c79cf5 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowable.java @@ -235,7 +235,6 @@ void slowPath(Subscriber<? super R> a, Iterator<? extends R> iterator) { return; } - boolean b; try { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java index 760a052278..b3f822cc91 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java @@ -126,7 +126,6 @@ public void onSuccess(T value) { return; } - boolean b; try { diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleToFlowable.java b/src/main/java/io/reactivex/internal/operators/single/SingleToFlowable.java index f48aa4659b..de2b8a9ed8 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleToFlowable.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleToFlowable.java @@ -40,7 +40,6 @@ public void subscribeActual(final Subscriber<? super T> s) { static final class SingleToFlowableObserver<T> extends DeferredScalarSubscription<T> implements SingleObserver<T> { - private static final long serialVersionUID = 187782011903685568L; Disposable upstream; diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleZipArray.java b/src/main/java/io/reactivex/internal/operators/single/SingleZipArray.java index e9ba27d755..31fd470ecd 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleZipArray.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleZipArray.java @@ -39,7 +39,6 @@ protected void subscribeActual(SingleObserver<? super R> observer) { SingleSource<? extends T>[] sources = this.sources; int n = sources.length; - if (n == 1) { sources[0].subscribe(new SingleMap.MapSingleObserver<T, R>(observer, new SingletonArrayFunc())); return; @@ -67,7 +66,6 @@ protected void subscribeActual(SingleObserver<? super R> observer) { static final class ZipCoordinator<T, R> extends AtomicInteger implements Disposable { - private static final long serialVersionUID = -5556924161382950569L; final SingleObserver<? super R> downstream; diff --git a/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java b/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java index b7200dee34..6f10ab2867 100644 --- a/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/ComputationScheduler.java @@ -187,7 +187,6 @@ public void shutdown() { } } - static final class EventLoopWorker extends Scheduler.Worker { private final ListCompositeDisposable serial; private final CompositeDisposable timed; diff --git a/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java b/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java index b18e18d16d..45e3c1850e 100644 --- a/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java @@ -162,7 +162,6 @@ public Disposable schedule(@NonNull Runnable run, long delay, @NonNull TimeUnit return EmptyDisposable.INSTANCE; } - SequentialDisposable first = new SequentialDisposable(); final SequentialDisposable mar = new SequentialDisposable(first); diff --git a/src/main/java/io/reactivex/internal/schedulers/NewThreadWorker.java b/src/main/java/io/reactivex/internal/schedulers/NewThreadWorker.java index 3499168f71..9ef225aceb 100644 --- a/src/main/java/io/reactivex/internal/schedulers/NewThreadWorker.java +++ b/src/main/java/io/reactivex/internal/schedulers/NewThreadWorker.java @@ -116,7 +116,6 @@ public Disposable schedulePeriodicallyDirect(Runnable run, long initialDelay, lo } } - /** * Wraps the given runnable into a ScheduledRunnable and schedules it * on the underlying ScheduledExecutorService. diff --git a/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java index c296ffe088..ebf47f12a6 100644 --- a/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java @@ -28,7 +28,6 @@ public final class ForEachWhileSubscriber<T> extends AtomicReference<Subscription> implements FlowableSubscriber<T>, Disposable { - private static final long serialVersionUID = -4403180040475402120L; final Predicate<? super T> onNext; diff --git a/src/main/java/io/reactivex/internal/subscribers/InnerQueuedSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/InnerQueuedSubscriber.java index fc6647a83b..70ea26740e 100644 --- a/src/main/java/io/reactivex/internal/subscribers/InnerQueuedSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/InnerQueuedSubscriber.java @@ -32,7 +32,6 @@ public final class InnerQueuedSubscriber<T> extends AtomicReference<Subscription> implements FlowableSubscriber<T>, Subscription { - private static final long serialVersionUID = 22876611072430776L; final InnerQueuedSubscriberSupport<T> parent; diff --git a/src/main/java/io/reactivex/internal/subscriptions/BasicIntQueueSubscription.java b/src/main/java/io/reactivex/internal/subscriptions/BasicIntQueueSubscription.java index eea08d07e7..a3d2259fd9 100644 --- a/src/main/java/io/reactivex/internal/subscriptions/BasicIntQueueSubscription.java +++ b/src/main/java/io/reactivex/internal/subscriptions/BasicIntQueueSubscription.java @@ -24,7 +24,6 @@ */ public abstract class BasicIntQueueSubscription<T> extends AtomicInteger implements QueueSubscription<T> { - private static final long serialVersionUID = -6671519529404341862L; @Override diff --git a/src/main/java/io/reactivex/internal/subscriptions/BasicQueueSubscription.java b/src/main/java/io/reactivex/internal/subscriptions/BasicQueueSubscription.java index 8776e8c5a3..ebb9935ed8 100644 --- a/src/main/java/io/reactivex/internal/subscriptions/BasicQueueSubscription.java +++ b/src/main/java/io/reactivex/internal/subscriptions/BasicQueueSubscription.java @@ -24,7 +24,6 @@ */ public abstract class BasicQueueSubscription<T> extends AtomicLong implements QueueSubscription<T> { - private static final long serialVersionUID = -6671519529404341862L; @Override diff --git a/src/main/java/io/reactivex/internal/subscriptions/DeferredScalarSubscription.java b/src/main/java/io/reactivex/internal/subscriptions/DeferredScalarSubscription.java index 536ddf4c00..131d1d2342 100644 --- a/src/main/java/io/reactivex/internal/subscriptions/DeferredScalarSubscription.java +++ b/src/main/java/io/reactivex/internal/subscriptions/DeferredScalarSubscription.java @@ -34,7 +34,6 @@ */ public class DeferredScalarSubscription<T> extends BasicIntQueueSubscription<T> { - private static final long serialVersionUID = -2151279923272604993L; /** The Subscriber to emit the value to. */ diff --git a/src/main/java/io/reactivex/internal/util/AppendOnlyLinkedArrayList.java b/src/main/java/io/reactivex/internal/util/AppendOnlyLinkedArrayList.java index fce0130657..12c4d062c0 100644 --- a/src/main/java/io/reactivex/internal/util/AppendOnlyLinkedArrayList.java +++ b/src/main/java/io/reactivex/internal/util/AppendOnlyLinkedArrayList.java @@ -125,7 +125,6 @@ public <U> boolean accept(Subscriber<? super U> subscriber) { return false; } - /** * Interprets the contents as NotificationLite objects and calls * the appropriate Observer method. diff --git a/src/main/java/io/reactivex/internal/util/AtomicThrowable.java b/src/main/java/io/reactivex/internal/util/AtomicThrowable.java index 5f4d4940d8..60c19155c5 100644 --- a/src/main/java/io/reactivex/internal/util/AtomicThrowable.java +++ b/src/main/java/io/reactivex/internal/util/AtomicThrowable.java @@ -23,7 +23,6 @@ */ public final class AtomicThrowable extends AtomicReference<Throwable> { - private static final long serialVersionUID = 3949248817947090603L; /** diff --git a/src/main/java/io/reactivex/internal/util/HalfSerializer.java b/src/main/java/io/reactivex/internal/util/HalfSerializer.java index 011528ec2a..8e160ab2ea 100644 --- a/src/main/java/io/reactivex/internal/util/HalfSerializer.java +++ b/src/main/java/io/reactivex/internal/util/HalfSerializer.java @@ -74,7 +74,6 @@ public static void onError(Subscriber<?> subscriber, Throwable ex, } } - /** * Emits an onComplete signal or an onError signal with the given error or indicates * the concurrently running onNext should do that. diff --git a/src/main/java/io/reactivex/internal/util/OpenHashSet.java b/src/main/java/io/reactivex/internal/util/OpenHashSet.java index 8a1b4fe50e..f971002ad0 100644 --- a/src/main/java/io/reactivex/internal/util/OpenHashSet.java +++ b/src/main/java/io/reactivex/internal/util/OpenHashSet.java @@ -140,7 +140,6 @@ void rehash() { T[] b = (T[])new Object[newCap]; - for (int j = size; j-- != 0; ) { while (a[--i] == null) { } // NOPMD int pos = mix(a[i].hashCode()) & m; diff --git a/src/main/java/io/reactivex/internal/util/Pow2.java b/src/main/java/io/reactivex/internal/util/Pow2.java index d9782a53b0..db4317132c 100644 --- a/src/main/java/io/reactivex/internal/util/Pow2.java +++ b/src/main/java/io/reactivex/internal/util/Pow2.java @@ -11,7 +11,6 @@ * the License for the specific language governing permissions and limitations under the License. */ - /* * Original License: https://github.com/JCTools/JCTools/blob/master/LICENSE * Original location: https://github.com/JCTools/JCTools/blob/master/jctools-core/src/main/java/org/jctools/util/Pow2.java diff --git a/src/main/java/io/reactivex/observers/BaseTestConsumer.java b/src/main/java/io/reactivex/observers/BaseTestConsumer.java index 69d227d91d..2bb9285787 100644 --- a/src/main/java/io/reactivex/observers/BaseTestConsumer.java +++ b/src/main/java/io/reactivex/observers/BaseTestConsumer.java @@ -148,7 +148,6 @@ public final int errorCount() { return errors.size(); } - /** * Fail with the given message and add the sequence of errors as suppressed ones. * <p>Note this is deliberately the only fail method. Most of the times an assertion @@ -869,7 +868,6 @@ public final U awaitDone(long time, TimeUnit unit) { return (U)this; } - /** * Assert that the TestObserver/TestSubscriber has received a Disposable but no other events. * @return this @@ -958,7 +956,6 @@ static void sleep(int millis) { } } - /** * Await until the TestObserver/TestSubscriber receives the given * number of items or terminates by sleeping 10 milliseconds at a time @@ -1065,7 +1062,6 @@ public final U assertTimeout() { return (U)this; } - /** * Asserts that some awaitX method has not timed out. * <p>History: 2.0.7 - experimental diff --git a/src/main/java/io/reactivex/parallel/ParallelFlowable.java b/src/main/java/io/reactivex/parallel/ParallelFlowable.java index 519e731776..13ebb021a4 100644 --- a/src/main/java/io/reactivex/parallel/ParallelFlowable.java +++ b/src/main/java/io/reactivex/parallel/ParallelFlowable.java @@ -228,7 +228,6 @@ public final ParallelFlowable<T> filter(@NonNull Predicate<? super T> predicate, return RxJavaPlugins.onAssembly(new ParallelFilterTry<T>(this, predicate, errorHandler)); } - /** * Filters the source values on each 'rail' and * handles errors based on the returned value by the handler function. @@ -536,7 +535,6 @@ public final ParallelFlowable<T> doOnNext(@NonNull Consumer<? super T> onNext) { )); } - /** * Call the specified consumer with the current element passing through any 'rail' and * handles errors based on the given {@link ParallelFailureHandling} enumeration value. diff --git a/src/main/java/io/reactivex/processors/BehaviorProcessor.java b/src/main/java/io/reactivex/processors/BehaviorProcessor.java index ff69ef4273..a81c51085e 100644 --- a/src/main/java/io/reactivex/processors/BehaviorProcessor.java +++ b/src/main/java/io/reactivex/processors/BehaviorProcessor.java @@ -346,7 +346,6 @@ public boolean hasSubscribers() { return subscribers.get().length != 0; } - /* test support*/ int subscriberCount() { return subscribers.get().length; } @@ -447,7 +446,6 @@ public boolean hasValue() { return o != null && !NotificationLite.isComplete(o) && !NotificationLite.isError(o); } - boolean add(BehaviorSubscription<T> rs) { for (;;) { BehaviorSubscription<T>[] a = subscribers.get(); diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index a8c9c700b4..ff98ff25d9 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -1049,7 +1049,6 @@ static final class SizeAndTimeBoundReplayBuffer<T> Throwable error; volatile boolean done; - SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) { this.maxSize = ObjectHelper.verifyPositive(maxSize, "maxSize"); this.maxAge = ObjectHelper.verifyPositive(maxAge, "maxAge"); diff --git a/src/main/java/io/reactivex/processors/UnicastProcessor.java b/src/main/java/io/reactivex/processors/UnicastProcessor.java index c754629374..47f02489b4 100644 --- a/src/main/java/io/reactivex/processors/UnicastProcessor.java +++ b/src/main/java/io/reactivex/processors/UnicastProcessor.java @@ -506,7 +506,6 @@ protected void subscribeActual(Subscriber<? super T> s) { final class UnicastQueueSubscription extends BasicIntQueueSubscription<T> { - private static final long serialVersionUID = -4896760517184205454L; @Nullable diff --git a/src/main/java/io/reactivex/subjects/BehaviorSubject.java b/src/main/java/io/reactivex/subjects/BehaviorSubject.java index 7f13dfb432..c58cb40779 100644 --- a/src/main/java/io/reactivex/subjects/BehaviorSubject.java +++ b/src/main/java/io/reactivex/subjects/BehaviorSubject.java @@ -298,7 +298,6 @@ public boolean hasObservers() { return subscribers.get().length != 0; } - /* test support*/ int subscriberCount() { return subscribers.get().length; } diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java index 344ef99fee..703692bd57 100644 --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java @@ -700,7 +700,6 @@ public T[] getValues(T[] array) { } } - if (array.length < s) { array = (T[])Array.newInstance(array.getClass().getComponentType(), s); } @@ -1051,7 +1050,6 @@ static final class SizeAndTimeBoundReplayBuffer<T> volatile boolean done; - SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) { this.maxSize = ObjectHelper.verifyPositive(maxSize, "maxSize"); this.maxAge = ObjectHelper.verifyPositive(maxAge, "maxAge"); diff --git a/src/main/java/io/reactivex/subjects/UnicastSubject.java b/src/main/java/io/reactivex/subjects/UnicastSubject.java index 72f0563637..8c3eae8af0 100644 --- a/src/main/java/io/reactivex/subjects/UnicastSubject.java +++ b/src/main/java/io/reactivex/subjects/UnicastSubject.java @@ -251,7 +251,6 @@ public static <T> UnicastSubject<T> create(boolean delayError) { return new UnicastSubject<T>(bufferSize(), delayError); } - /** * Creates an UnicastSubject with the given capacity hint and delay error flag. * <p>History: 2.0.8 - experimental @@ -522,7 +521,6 @@ public boolean hasComplete() { final class UnicastQueueDisposable extends BasicIntQueueDisposable<T> { - private static final long serialVersionUID = 7926949470189395511L; @Override diff --git a/src/main/java/io/reactivex/subscribers/SafeSubscriber.java b/src/main/java/io/reactivex/subscribers/SafeSubscriber.java index a7c1fb3ad6..e903a5519c 100644 --- a/src/main/java/io/reactivex/subscribers/SafeSubscriber.java +++ b/src/main/java/io/reactivex/subscribers/SafeSubscriber.java @@ -176,7 +176,6 @@ public void onComplete() { return; } - try { downstream.onComplete(); } catch (Throwable e) { diff --git a/src/main/java/io/reactivex/subscribers/TestSubscriber.java b/src/main/java/io/reactivex/subscribers/TestSubscriber.java index 30c1a22b03..3b02dbdd09 100644 --- a/src/main/java/io/reactivex/subscribers/TestSubscriber.java +++ b/src/main/java/io/reactivex/subscribers/TestSubscriber.java @@ -167,7 +167,6 @@ public void onSubscribe(Subscription s) { } } - downstream.onSubscribe(s); long mr = missedRequested.getAndSet(0L); diff --git a/src/test/java/io/reactivex/exceptions/TestException.java b/src/test/java/io/reactivex/exceptions/TestException.java index 6893fe54b4..eef7a47a85 100644 --- a/src/test/java/io/reactivex/exceptions/TestException.java +++ b/src/test/java/io/reactivex/exceptions/TestException.java @@ -52,6 +52,4 @@ public TestException(String message) { public TestException(Throwable cause) { super(cause); } - - } diff --git a/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java b/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java index 9db71ac805..7898628f70 100644 --- a/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java @@ -181,7 +181,6 @@ public void testMergeAsyncThenObserveOnLoop() { .take(num) .subscribe(ts); - ts.awaitTerminalEvent(5, TimeUnit.SECONDS); ts.assertComplete(); ts.assertNoErrors(); diff --git a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java index 189747dfa4..e95d5a9ab2 100644 --- a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java @@ -231,9 +231,8 @@ public void onError(Throwable e) { public void onNext(String t) { } - - }; + return as; } }; diff --git a/src/test/java/io/reactivex/flowable/FlowableZipTests.java b/src/test/java/io/reactivex/flowable/FlowableZipTests.java index 78ffa8cee5..d901d36bc2 100644 --- a/src/test/java/io/reactivex/flowable/FlowableZipTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableZipTests.java @@ -129,7 +129,6 @@ public void accept(ExtendedResult t1) { } }; - @Test public void zipWithDelayError() { Flowable.just(1) diff --git a/src/test/java/io/reactivex/internal/SubscribeWithTest.java b/src/test/java/io/reactivex/internal/SubscribeWithTest.java index ee6cdf5c0b..942762009c 100644 --- a/src/test/java/io/reactivex/internal/SubscribeWithTest.java +++ b/src/test/java/io/reactivex/internal/SubscribeWithTest.java @@ -37,7 +37,6 @@ public void withObservable() { .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } - class ObserverImpl implements SingleObserver<Object>, CompletableObserver { Object value; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java index f3d241bfd6..6a427124bd 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java @@ -246,7 +246,6 @@ public void testValuesAndThenError() { .concatWith(Flowable.<Integer>error(new TestException())) .cache(); - TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); source.subscribe(ts); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java index 4b199482e9..ed0f556b7f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java @@ -158,7 +158,6 @@ public void testNestedAsyncConcat() throws InterruptedException { final CountDownLatch parentHasStarted = new CountDownLatch(1); final CountDownLatch parentHasFinished = new CountDownLatch(1); - Flowable<Flowable<String>> observableOfObservables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java index 1114f17a1d..2b5bcea1e6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDetachTest.java @@ -26,7 +26,6 @@ import io.reactivex.functions.Function; import io.reactivex.subscribers.TestSubscriber; - public class FlowableDetachTest { Object o; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java index 2e5e97bb67..0502283132 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java @@ -469,7 +469,6 @@ public boolean test(Integer v) throws Exception { }) .subscribe(ts); - TestHelper.emit(up, 1, 2, 1, 3, 3, 4, 3, 5, 5); SubscriberFusion.assertFusion(ts, QueueFuseable.ASYNC) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index c9c24e7ef5..b05b847c90 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -203,7 +203,6 @@ public void testFlatMapTransformsException() { Flowable.<Integer> error(new RuntimeException("Forced failure!")) ); - Subscriber<Object> subscriber = TestHelper.mockSubscriber(); source.flatMap(just(onNext), just(onError), just0(onComplete)).subscribe(subscriber); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferStrategyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferStrategyTest.java index 85468f8753..c52888548d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferStrategyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferStrategyTest.java @@ -116,7 +116,6 @@ public void subscribe(Subscriber<? super Long> s) { } }); - @Test(expected = IllegalArgumentException.class) public void backpressureBufferNegativeCapacity() throws InterruptedException { Flowable.empty().onBackpressureBuffer(-1, EMPTY_ACTION , DROP_OLDEST); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java index e9f19585bf..ee1b4e3051 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java @@ -214,7 +214,6 @@ public Integer apply(Integer t1) { ts.assertNoErrors(); } - private static class TestObservable implements Publisher<String> { final String[] values; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java index 039114d1c7..e744a00aa1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishFunctionTest.java @@ -33,7 +33,6 @@ import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; - public class FlowablePublishFunctionTest { @Test public void concatTakeFirstLastCompletes() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index cb6db6ef11..e20c417da9 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -506,7 +506,6 @@ public void run() { } } - /* * test the basic expectation of OperatorMulticast via replay */ @@ -696,7 +695,6 @@ public static Worker workerSpy(final Disposable mockDisposable) { return spy(new InprocessWorker(mockDisposable)); } - private static class InprocessWorker extends Worker { private final Disposable mockDisposable; public boolean unsubscribed; @@ -1063,7 +1061,6 @@ public void testValuesAndThenError() { .concatWith(Flowable.<Integer>error(new TestException())) .replay().autoConnect(); - TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); source.subscribe(ts); @@ -1169,7 +1166,6 @@ public void testSubscribersComeAndGoAtRequestBoundaries() { ts22.assertNoErrors(); ts22.dispose(); - TestSubscriber<Integer> ts3 = new TestSubscriber<Integer>(); source.subscribe(ts3); @@ -1225,7 +1221,6 @@ public void testSubscribersComeAndGoAtRequestBoundaries2() { ts22.assertNoErrors(); ts22.dispose(); - TestSubscriber<Integer> ts3 = new TestSubscriber<Integer>(); source.subscribe(ts3); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java index e301c29aec..2ab9d75bfd 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java @@ -29,7 +29,6 @@ import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.*; - public class FlowableSwitchIfEmptyTest { @Test @@ -122,7 +121,6 @@ public void onNext(Long aLong) { } }).subscribe(); - assertTrue(bs.isCancelled()); // FIXME no longer assertable // assertTrue(sub.isUnsubscribed()); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java index d2caa4ada8..dc5f2a8313 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java @@ -449,7 +449,6 @@ public void testBackpressure() { publishCompleted(o2, 50); publishCompleted(o3, 55); - final TestSubscriber<String> testSubscriber = new TestSubscriber<String>(); Flowable.switchOnNext(o).subscribe(new DefaultSubscriber<String>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java index 014ebbf756..919ca0e468 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java @@ -75,7 +75,6 @@ public void onComplete() { } source.onComplete(); - verify(subscriber, never()).onError(any(Throwable.class)); assertEquals(n / 3, values.size()); @@ -346,7 +345,6 @@ public Flowable<Integer> call() { boundary.onComplete(); - assertFalse(source.hasSubscribers()); assertFalse(boundary.hasSubscribers()); @@ -374,7 +372,6 @@ public Flowable<Integer> call() { ts.dispose(); - assertTrue(source.hasSubscribers()); assertFalse(boundary.hasSubscribers()); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java index d2eef83d88..157faae1a5 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java @@ -32,7 +32,6 @@ import io.reactivex.schedulers.*; import io.reactivex.subscribers.*; - public class FlowableWindowWithTimeTest { private TestScheduler scheduler; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/NotificationLiteTest.java b/src/test/java/io/reactivex/internal/operators/flowable/NotificationLiteTest.java index a03d91385f..1f29136e00 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/NotificationLiteTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/NotificationLiteTest.java @@ -23,7 +23,6 @@ import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.internal.util.NotificationLite; - public class NotificationLiteTest { @Test diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayTest.java index 29eac9a2a3..fb14e27a19 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeConcatArrayTest.java @@ -151,7 +151,6 @@ protected void subscribeActual(MaybeObserver<? super Integer> observer) { o[0].onError(new TestException()); - TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCompletableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCompletableTest.java index 1b511dd515..3086eb6c57 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCompletableTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.maybe; - import io.reactivex.*; import io.reactivex.functions.Function; import io.reactivex.internal.fuseable.HasUpstreamCompletableSource; diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java index cd97bea762..8d07b6be3a 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeZipArrayTest.java @@ -36,7 +36,6 @@ public Object apply(Object a, Object b) throws Exception { } }; - final Function3<Object, Object, Object, Object> addString3 = new Function3<Object, Object, Object, Object>() { @Override public Object apply(Object a, Object b, Object c) throws Exception { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java index 614fb29bf5..9629946ecb 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java @@ -221,7 +221,6 @@ public void testValuesAndThenError() { .concatWith(Observable.<Integer>error(new TestException())) .cache(); - TestObserver<Integer> to = new TestObserver<Integer>(); source.subscribe(to); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java index effef90136..fc2a01619b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java @@ -155,7 +155,6 @@ public void testNestedAsyncConcat() throws InterruptedException { final CountDownLatch parentHasStarted = new CountDownLatch(1); final CountDownLatch parentHasFinished = new CountDownLatch(1); - Observable<Observable<String>> observableOfObservables = Observable.unsafeCreate(new ObservableSource<Observable<String>>() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java index 0aaacb1432..01bf61ac6e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; - import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java index f8d274bc86..ab20fccc38 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDetachTest.java @@ -24,7 +24,6 @@ import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; - public class ObservableDetachTest { Object o; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index 4ace4eacb2..22a6889abc 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -205,7 +205,6 @@ public void testFlatMapTransformsException() { Observable.<Integer> error(new RuntimeException("Forced failure!")) ); - Observer<Object> o = TestHelper.mockObserver(); source.flatMap(just(onNext), just(onError), just0(onComplete)).subscribe(o); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java index 56d7b7ee47..542165907f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java @@ -310,7 +310,4 @@ public Object call() throws Exception { .test() .assertResult(1); } - - - } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java index 181564df1c..50312e3884 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java @@ -211,7 +211,6 @@ public Integer apply(Integer t1) { to.assertNoErrors(); } - private static class TestObservable implements ObservableSource<String> { final String[] values; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java index b79e8c6c20..c480a3b1df 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java @@ -506,7 +506,6 @@ public void run() { } } - /* * test the basic expectation of OperatorMulticast via replay */ @@ -644,7 +643,6 @@ public void testIssue2191_SchedulerUnsubscribeOnError() throws Exception { verify(mockObserverBeforeConnect).onSubscribe((Disposable)any()); verify(mockObserverAfterConnect).onSubscribe((Disposable)any()); - mockScheduler.advanceTimeBy(1, TimeUnit.SECONDS); // verify interactions verify(sourceNext, times(1)).accept(1); @@ -681,7 +679,6 @@ public static Worker workerSpy(final Disposable mockDisposable) { return spy(new InprocessWorker(mockDisposable)); } - static class InprocessWorker extends Worker { private final Disposable mockDisposable; public boolean unsubscribed; @@ -1053,7 +1050,6 @@ public void testValuesAndThenError() { .concatWith(Observable.<Integer>error(new TestException())) .replay().autoConnect(); - TestObserver<Integer> to = new TestObserver<Integer>(); source.subscribe(to); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmptyTest.java index 20c5018d01..83024d1ea5 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchIfEmptyTest.java @@ -25,7 +25,6 @@ import io.reactivex.functions.Consumer; import io.reactivex.observers.DefaultObserver; - public class ObservableSwitchIfEmptyTest { @Test @@ -90,7 +89,6 @@ public void onNext(Long aLong) { } }).subscribe(); - assertTrue(d.isDisposed()); // FIXME no longer assertable // assertTrue(sub.isUnsubscribed()); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java index b015bfb737..a82e876464 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java @@ -76,7 +76,6 @@ public void onComplete() { } source.onComplete(); - verify(o, never()).onError(any(Throwable.class)); assertEquals(n / 3, values.size()); @@ -349,7 +348,6 @@ public Observable<Integer> call() { boundary.onComplete(); - assertFalse(source.hasObservers()); assertFalse(boundary.hasObservers()); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java index 8ef033d5f1..af1503e8a7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithSizeTest.java @@ -204,7 +204,6 @@ private List<String> list(String... args) { return list; } - public static Observable<Integer> hotStream() { return Observable.unsafeCreate(new ObservableSource<Integer>() { @Override diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java index 8c81f6a70a..4eb90f4e50 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java @@ -32,7 +32,6 @@ import io.reactivex.schedulers.*; import io.reactivex.subjects.*; - public class ObservableWindowWithTimeTest { private TestScheduler scheduler; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java index 4f3c62b992..713772c535 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java @@ -260,7 +260,6 @@ public void testNoDownstreamUnsubscribe() { // assertTrue("Not cancelled!", ts.isCancelled()); } - static final Function<Object[], String> toArray = new Function<Object[], String>() { @Override public String apply(Object[] args) { diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleInternalHelperTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleInternalHelperTest.java index 5d4459259b..0a6d5473f7 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleInternalHelperTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleInternalHelperTest.java @@ -21,7 +21,6 @@ import io.reactivex.*; - public class SingleInternalHelperTest { @Test diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java index f188547bc9..7d1175bfc2 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleZipArrayTest.java @@ -36,7 +36,6 @@ public Object apply(Object a, Object b) throws Exception { } }; - final Function3<Object, Object, Object, Object> addString3 = new Function3<Object, Object, Object, Object>() { @Override public Object apply(Object a, Object b, Object c) throws Exception { diff --git a/src/test/java/io/reactivex/internal/schedulers/ExecutorSchedulerDelayedRunnableTest.java b/src/test/java/io/reactivex/internal/schedulers/ExecutorSchedulerDelayedRunnableTest.java index 0356ed6cbf..a8f61daeab 100644 --- a/src/test/java/io/reactivex/internal/schedulers/ExecutorSchedulerDelayedRunnableTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/ExecutorSchedulerDelayedRunnableTest.java @@ -24,7 +24,6 @@ public class ExecutorSchedulerDelayedRunnableTest { - @Test(expected = TestException.class) public void delayedRunnableCrash() { DelayedRunnable dl = new DelayedRunnable(new Runnable() { diff --git a/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java index 7b47129559..726828bbd7 100644 --- a/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java @@ -230,7 +230,6 @@ public void doubleComplete() { ds.onComplete(); ds.onComplete(); - ts.assertValue(1); ts.assertNoErrors(); ts.assertComplete(); diff --git a/src/test/java/io/reactivex/observers/ObserverFusion.java b/src/test/java/io/reactivex/observers/ObserverFusion.java index 22b3466b19..05b694eba6 100644 --- a/src/test/java/io/reactivex/observers/ObserverFusion.java +++ b/src/test/java/io/reactivex/observers/ObserverFusion.java @@ -150,7 +150,6 @@ public static <T> Consumer<TestObserver<T>> assertFusionMode(final int mode) { return new AssertFusionConsumer<T>(mode); } - /** * Constructs a TestObserver with the given required fusion mode. * @param <T> the value type diff --git a/src/test/java/io/reactivex/observers/TestObserverTest.java b/src/test/java/io/reactivex/observers/TestObserverTest.java index 27f4f7442c..2258d15779 100644 --- a/src/test/java/io/reactivex/observers/TestObserverTest.java +++ b/src/test/java/io/reactivex/observers/TestObserverTest.java @@ -485,8 +485,6 @@ public boolean test(Throwable t) throws Exception { to.assertValueCount(0); to.assertNoValues(); - - } @Test @@ -898,7 +896,6 @@ public void assertTerminated2() { // expected } - to = TestObserver.create(); to.onSubscribe(Disposables.empty()); diff --git a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java index f522b84fd3..cd66ce7b7e 100644 --- a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java +++ b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java @@ -1285,7 +1285,6 @@ public Completable apply(Completable completable) throws Exception { } }; - RxJavaPlugins.setInitComputationSchedulerHandler(callable2scheduler); RxJavaPlugins.setComputationSchedulerHandler(scheduler2scheduler); RxJavaPlugins.setIoSchedulerHandler(scheduler2scheduler); @@ -1378,7 +1377,6 @@ public void subscribeActual(MaybeObserver t) { assertSame(myb, RxJavaPlugins.onAssembly(myb)); - Runnable action = Functions.EMPTY_RUNNABLE; assertSame(action, RxJavaPlugins.onSchedule(action)); diff --git a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java index d90fe6705f..963171d30e 100644 --- a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java +++ b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java @@ -296,7 +296,6 @@ public void run() { // assertEquals(1, ts.getOnErrorEvents().size()); // } - // FIXME subscriber methods are not allowed to throw // /** // * This one has multiple failures so should get a CompositeException diff --git a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java index d7f3dca92b..a0e3996f41 100644 --- a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java +++ b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java @@ -305,8 +305,6 @@ public void testStartEmpty() { inOrder.verify(subscriber).onNext(1); inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); - - } @Test diff --git a/src/test/java/io/reactivex/processors/PublishProcessorTest.java b/src/test/java/io/reactivex/processors/PublishProcessorTest.java index 4160ed27ea..f91e61551f 100644 --- a/src/test/java/io/reactivex/processors/PublishProcessorTest.java +++ b/src/test/java/io/reactivex/processors/PublishProcessorTest.java @@ -338,7 +338,6 @@ public void onComplete() { } } - // FIXME RS subscribers are not allowed to throw // @Test // public void testOnErrorThrowsDoesntPreventDelivery() { diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index 3038840266..810e80d9e5 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -859,7 +859,6 @@ public void testBackpressureHonored() { ts.assertNotComplete(); ts.assertNoErrors(); - ts.request(1); ts.assertValues(1, 2); ts.assertNotComplete(); @@ -888,7 +887,6 @@ public void testBackpressureHonoredSizeBound() { ts.assertNotComplete(); ts.assertNoErrors(); - ts.request(1); ts.assertValues(1, 2); ts.assertNotComplete(); @@ -917,7 +915,6 @@ public void testBackpressureHonoredTimeBound() { ts.assertNotComplete(); ts.assertNoErrors(); - ts.request(1); ts.assertValues(1, 2); ts.assertNotComplete(); diff --git a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java index fdd8d4e2a9..b058d51e16 100644 --- a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java @@ -373,7 +373,6 @@ public void hasObservers() { public void drainFusedFailFast() { UnicastProcessor<Integer> us = UnicastProcessor.create(false); - TestSubscriber<Integer> ts = us.to(SubscriberFusion.<Integer>test(1, QueueFuseable.ANY, false)); us.done = true; @@ -386,7 +385,6 @@ public void drainFusedFailFast() { public void drainFusedFailFastEmpty() { UnicastProcessor<Integer> us = UnicastProcessor.create(false); - TestSubscriber<Integer> ts = us.to(SubscriberFusion.<Integer>test(1, QueueFuseable.ANY, false)); us.drainFused(ts); diff --git a/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java b/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java index ed67bce571..0c9755fd60 100644 --- a/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java +++ b/src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java @@ -707,7 +707,6 @@ public void unwrapDefaultPeriodicTask() throws InterruptedException { return; } - final CountDownLatch cdl = new CountDownLatch(1); Runnable countDownRunnable = new Runnable() { @Override diff --git a/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java b/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java index 312ccf92df..eaa5b692f1 100644 --- a/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java @@ -59,7 +59,6 @@ public static void testCancelledRetention(Scheduler.Worker w, boolean periodic) Thread.sleep(1000); - MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); long initial = memHeap.getUsed(); diff --git a/src/test/java/io/reactivex/schedulers/SchedulerLifecycleTest.java b/src/test/java/io/reactivex/schedulers/SchedulerLifecycleTest.java index 7f3098ef90..aa0af9816b 100644 --- a/src/test/java/io/reactivex/schedulers/SchedulerLifecycleTest.java +++ b/src/test/java/io/reactivex/schedulers/SchedulerLifecycleTest.java @@ -92,7 +92,6 @@ public void run() { cd.add(w4); w4.schedule(countAction); - if (!cdl.await(3, TimeUnit.SECONDS)) { fail("countAction was not run by every worker"); } diff --git a/src/test/java/io/reactivex/single/SingleNullTests.java b/src/test/java/io/reactivex/single/SingleNullTests.java index 96ffe78eeb..ff7ddf19d0 100644 --- a/src/test/java/io/reactivex/single/SingleNullTests.java +++ b/src/test/java/io/reactivex/single/SingleNullTests.java @@ -13,7 +13,6 @@ package io.reactivex.single; - import java.lang.reflect.*; import java.util.*; import java.util.concurrent.*; diff --git a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java index 5e628f3ec6..efd643e8d9 100644 --- a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java @@ -295,7 +295,6 @@ public void run() { // assertEquals(1, to.getOnErrorEvents().size()); // } - // FIXME subscriber methods are not allowed to throw // /** // * This one has multiple failures so should get a CompositeException diff --git a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java index 06b7079fdf..9a2b52f8f7 100644 --- a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java @@ -305,8 +305,6 @@ public void testStartEmpty() { inOrder.verify(o).onNext(1); inOrder.verify(o).onComplete(); inOrder.verifyNoMoreInteractions(); - - } @Test diff --git a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java index dd9f964100..7731d508f8 100644 --- a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java @@ -338,7 +338,6 @@ public void onComplete() { } } - // FIXME RS subscribers are not allowed to throw // @Test // public void testOnErrorThrowsDoesntPreventDelivery() { diff --git a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java index 41a1d3e759..ca13ba0495 100644 --- a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java @@ -438,7 +438,6 @@ public void hasObservers() { public void drainFusedFailFast() { UnicastSubject<Integer> us = UnicastSubject.create(false); - TestObserver<Integer> to = us.to(ObserverFusion.<Integer>test(QueueFuseable.ANY, false)); us.done = true; @@ -451,7 +450,6 @@ public void drainFusedFailFast() { public void drainFusedFailFastEmpty() { UnicastSubject<Integer> us = UnicastSubject.create(false); - TestObserver<Integer> to = us.to(ObserverFusion.<Integer>test(QueueFuseable.ANY, false)); us.drainFused(to); diff --git a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java index d4358f4bb8..6c634d8d91 100644 --- a/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/TestSubscriberTest.java @@ -79,7 +79,6 @@ public void testAssertNotMatchValue() { // FIXME different message pattern // thrown.expectMessage("Value at index: 1 expected to be [3] (Integer) but was: [2] (Integer)"); - ts.assertValues(1, 3); ts.assertValueCount(2); ts.assertTerminated(); @@ -928,8 +927,6 @@ public boolean test(Throwable t) { ts.assertValueCount(0); ts.assertNoValues(); - - } @Test @@ -1340,7 +1337,6 @@ public void assertTerminated2() { // expected } - ts = TestSubscriber.create(); ts.onSubscribe(new BooleanSubscription()); diff --git a/src/test/java/io/reactivex/validators/JavadocForAnnotations.java b/src/test/java/io/reactivex/validators/JavadocForAnnotations.java index 9dae922016..3912ced5ce 100644 --- a/src/test/java/io/reactivex/validators/JavadocForAnnotations.java +++ b/src/test/java/io/reactivex/validators/JavadocForAnnotations.java @@ -104,7 +104,6 @@ static final void scanFor(StringBuilder sourceCode, String annotation, String in } } - static final void scanForBadMethod(StringBuilder sourceCode, String annotation, String inDoc, StringBuilder e, String baseClassName) { int index = 0; diff --git a/src/test/java/io/reactivex/validators/NewLinesBeforeAnnotation.java b/src/test/java/io/reactivex/validators/NewLinesBeforeAnnotation.java index 49f19daec0..e7c1c13bb3 100644 --- a/src/test/java/io/reactivex/validators/NewLinesBeforeAnnotation.java +++ b/src/test/java/io/reactivex/validators/NewLinesBeforeAnnotation.java @@ -55,7 +55,7 @@ public void tooManyEmptyNewLines3() throws Exception { @Test public void tooManyEmptyNewLines4() throws Exception { - findPattern(5); + findPattern(4); } @Test diff --git a/src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java b/src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java index 136ba29581..ac078393e1 100644 --- a/src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java +++ b/src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java @@ -326,7 +326,6 @@ public void checkParallelFlowable() { addOverride(new ParamOverride(Single.class, 0, ParamMode.ANY, "delay", Long.TYPE, TimeUnit.class, Scheduler.class)); addOverride(new ParamOverride(Single.class, 0, ParamMode.ANY, "delay", Long.TYPE, TimeUnit.class, Scheduler.class, Boolean.TYPE)); - // zero repeat is allowed addOverride(new ParamOverride(Single.class, 0, ParamMode.NON_NEGATIVE, "repeat", Long.TYPE)); diff --git a/src/test/java/io/reactivex/validators/TooManyEmptyNewLines.java b/src/test/java/io/reactivex/validators/TooManyEmptyNewLines.java new file mode 100644 index 0000000000..2da65b36c8 --- /dev/null +++ b/src/test/java/io/reactivex/validators/TooManyEmptyNewLines.java @@ -0,0 +1,132 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.validators; + +import java.io.*; +import java.util.*; + +import org.junit.Test; + +/** + * Test verifying there are no 2..5 empty newlines in the code. + */ +public class TooManyEmptyNewLines { + + @Test + public void tooManyEmptyNewLines2() throws Exception { + findPattern(2); + } + + @Test + public void tooManyEmptyNewLines3() throws Exception { + findPattern(3); + } + + @Test + public void tooManyEmptyNewLines4() throws Exception { + findPattern(4); + } + + @Test + public void tooManyEmptyNewLines5() throws Exception { + findPattern(5); + } + + static void findPattern(int newLines) throws Exception { + File f = MaybeNo2Dot0Since.findSource("Flowable"); + if (f == null) { + System.out.println("Unable to find sources of TestHelper.findSourceDir()"); + return; + } + + Queue<File> dirs = new ArrayDeque<File>(); + + StringBuilder fail = new StringBuilder(); + fail.append("The following code pattern was found: "); + fail.append("\\R"); + for (int i = 0; i < newLines; i++) { + fail.append("\\R"); + } + fail.append("\n"); + + File parent = f.getParentFile(); + + dirs.offer(new File(parent.getAbsolutePath().replace('\\', '/'))); + dirs.offer(new File(parent.getAbsolutePath().replace('\\', '/').replace("src/main/java", "src/test/java"))); + + int total = 0; + + while (!dirs.isEmpty()) { + f = dirs.poll(); + + File[] list = f.listFiles(); + if (list != null && list.length != 0) { + + for (File u : list) { + if (u.isDirectory()) { + dirs.offer(u); + } else { + String fname = u.getName(); + if (fname.endsWith(".java")) { + + List<String> lines = new ArrayList<String>(); + BufferedReader in = new BufferedReader(new FileReader(u)); + try { + for (;;) { + String line = in.readLine(); + if (line == null) { + break; + } + lines.add(line); + } + } finally { + in.close(); + } + + for (int i = 0; i < lines.size() - newLines; i++) { + String line1 = lines.get(i); + if (line1.isEmpty()) { + int c = 1; + for (int j = i + 1; j < lines.size(); j++) { + if (lines.get(j).isEmpty()) { + c++; + } else { + break; + } + } + + if (c == newLines) { + fail + .append(fname) + .append("#L").append(i + 1) + .append("\n"); + total++; + i += c; + } + } + } + } + } + } + } + } + if (total != 0) { + fail.append("Found ") + .append(total) + .append(" instances"); + System.out.println(fail); + throw new AssertionError(fail.toString()); + } + } +} From c7d91c68ef8011f9d753111a8c839297850aeb66 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 30 Aug 2018 15:29:58 +0200 Subject: [PATCH 276/417] 2.x: Fix refCount termination-reconnect race (#6187) * 2.x: Fix refCount termination-reconnect race * Add/restore coverage * Update ResettableConnectable interface and definitions --- .../disposables/ResettableConnectable.java | 54 +++++++++++++ .../operators/flowable/FlowableRefCount.java | 11 ++- .../operators/flowable/FlowableReplay.java | 14 ++-- .../observable/ObservableRefCount.java | 11 ++- .../observable/ObservableReplay.java | 13 +-- .../flowable/FlowableRefCountTest.java | 78 ++++++++++++++++-- .../observable/ObservableRefCountTest.java | 80 +++++++++++++++++-- 7 files changed, 229 insertions(+), 32 deletions(-) create mode 100644 src/main/java/io/reactivex/internal/disposables/ResettableConnectable.java diff --git a/src/main/java/io/reactivex/internal/disposables/ResettableConnectable.java b/src/main/java/io/reactivex/internal/disposables/ResettableConnectable.java new file mode 100644 index 0000000000..a111080a77 --- /dev/null +++ b/src/main/java/io/reactivex/internal/disposables/ResettableConnectable.java @@ -0,0 +1,54 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.disposables; + +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.flowables.ConnectableFlowable; +import io.reactivex.observables.ConnectableObservable; + +/** + * Interface allowing conditional resetting of connections in {@link ConnectableObservable}s + * and {@link ConnectableFlowable}s. + * @since 2.2.2 - experimental + */ +@Experimental +public interface ResettableConnectable { + + /** + * Reset the connectable source only if the given {@link Disposable} {@code connection} instance + * is still representing a connection established by a previous {@code connect()} connection. + * <p> + * For example, an immediately previous connection should reset the connectable source: + * <pre><code> + * Disposable d = connectable.connect(); + * + * ((ResettableConnectable)connectable).resetIf(d); + * </code></pre> + * However, if the connection indicator {@code Disposable} is from a much earlier connection, + * it should not affect the current connection: + * <pre><code> + * Disposable d1 = connectable.connect(); + * d.dispose(); + * + * Disposable d2 = connectable.connect(); + * + * ((ResettableConnectable)connectable).resetIf(d); + * + * assertFalse(d2.isDisposed()); + * </code></pre> + * @param connection the disposable received from a previous {@code connect()} call. + */ + void resetIf(Disposable connection); +} diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java index 82a1373228..f966f01365 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java @@ -95,7 +95,7 @@ protected void subscribeActual(Subscriber<? super T> s) { void cancel(RefConnection rc) { SequentialDisposable sd; synchronized (this) { - if (connection == null) { + if (connection == null || connection != rc) { return; } long c = rc.subscriberCount - 1; @@ -116,13 +116,17 @@ void cancel(RefConnection rc) { void terminated(RefConnection rc) { synchronized (this) { - if (connection != null) { + if (connection != null && connection == rc) { connection = null; if (rc.timer != null) { rc.timer.dispose(); } + } + if (--rc.subscriberCount == 0) { if (source instanceof Disposable) { ((Disposable)source).dispose(); + } else if (source instanceof ResettableConnectable) { + ((ResettableConnectable)source).resetIf(rc.get()); } } } @@ -132,9 +136,12 @@ void timeout(RefConnection rc) { synchronized (this) { if (rc.subscriberCount == 0 && rc == connection) { connection = null; + Disposable connectionObject = rc.get(); DisposableHelper.dispose(rc); if (source instanceof Disposable) { ((Disposable)source).dispose(); + } else if (source instanceof ResettableConnectable) { + ((ResettableConnectable)source).resetIf(connectionObject); } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java index 51943b9c48..21b1b1d39c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java @@ -24,6 +24,7 @@ import io.reactivex.exceptions.Exceptions; import io.reactivex.flowables.ConnectableFlowable; import io.reactivex.functions.*; +import io.reactivex.internal.disposables.ResettableConnectable; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.fuseable.HasUpstreamPublisher; import io.reactivex.internal.subscribers.SubscriberResourceWrapper; @@ -32,7 +33,7 @@ import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Timed; -public final class FlowableReplay<T> extends ConnectableFlowable<T> implements HasUpstreamPublisher<T>, Disposable { +public final class FlowableReplay<T> extends ConnectableFlowable<T> implements HasUpstreamPublisher<T>, ResettableConnectable { /** The source observable. */ final Flowable<T> source; /** Holds the current subscriber that is, will be or just was subscribed to the source observable. */ @@ -161,15 +162,10 @@ protected void subscribeActual(Subscriber<? super T> s) { onSubscribe.subscribe(s); } + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public void dispose() { - current.lazySet(null); - } - - @Override - public boolean isDisposed() { - Disposable d = current.get(); - return d == null || d.isDisposed(); + public void resetIf(Disposable connectionObject) { + current.compareAndSet((ReplaySubscriber)connectionObject, null); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java index 59b571640d..3dced24de6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java @@ -92,7 +92,7 @@ protected void subscribeActual(Observer<? super T> observer) { void cancel(RefConnection rc) { SequentialDisposable sd; synchronized (this) { - if (connection == null) { + if (connection == null || connection != rc) { return; } long c = rc.subscriberCount - 1; @@ -113,13 +113,17 @@ void cancel(RefConnection rc) { void terminated(RefConnection rc) { synchronized (this) { - if (connection != null) { + if (connection != null && connection == rc) { connection = null; if (rc.timer != null) { rc.timer.dispose(); } + } + if (--rc.subscriberCount == 0) { if (source instanceof Disposable) { ((Disposable)source).dispose(); + } else if (source instanceof ResettableConnectable) { + ((ResettableConnectable)source).resetIf(rc.get()); } } } @@ -129,9 +133,12 @@ void timeout(RefConnection rc) { synchronized (this) { if (rc.subscriberCount == 0 && rc == connection) { connection = null; + Disposable connectionObject = rc.get(); DisposableHelper.dispose(rc); if (source instanceof Disposable) { ((Disposable)source).dispose(); + } else if (source instanceof ResettableConnectable) { + ((ResettableConnectable)source).resetIf(connectionObject); } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java index a1c75b67c0..89db184d6b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java @@ -31,7 +31,7 @@ import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Timed; -public final class ObservableReplay<T> extends ConnectableObservable<T> implements HasUpstreamObservableSource<T>, Disposable { +public final class ObservableReplay<T> extends ConnectableObservable<T> implements HasUpstreamObservableSource<T>, ResettableConnectable { /** The source observable. */ final ObservableSource<T> source; /** Holds the current subscriber that is, will be or just was subscribed to the source observable. */ @@ -159,15 +159,10 @@ public ObservableSource<T> source() { return source; } + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public void dispose() { - current.lazySet(null); - } - - @Override - public boolean isDisposed() { - Disposable d = current.get(); - return d == null || d.isDisposed(); + public void resetIf(Disposable connectionObject) { + current.compareAndSet((ReplayObserver)connectionObject, null); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index 8eefc701e3..6bd46295e3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -788,15 +788,17 @@ public void replayIsUnsubscribed() { ConnectableFlowable<Integer> cf = Flowable.just(1) .replay(); - assertTrue(((Disposable)cf).isDisposed()); + if (cf instanceof Disposable) { + assertTrue(((Disposable)cf).isDisposed()); - Disposable connection = cf.connect(); + Disposable connection = cf.connect(); - assertFalse(((Disposable)cf).isDisposed()); + assertFalse(((Disposable)cf).isDisposed()); - connection.dispose(); + connection.dispose(); - assertTrue(((Disposable)cf).isDisposed()); + assertTrue(((Disposable)cf).isDisposed()); + } } static final class BadFlowableSubscribe extends ConnectableFlowable<Object> { @@ -1325,5 +1327,71 @@ public void cancelTerminateStateExclusion() { rc.connected = true; o.connection = rc; o.cancel(rc); + + o.connection = rc; + o.cancel(new RefConnection(o)); + } + + @Test + public void replayRefCountShallBeThreadSafe() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + Flowable<Integer> flowable = Flowable.just(1).replay(1).refCount(); + + TestSubscriber<Integer> ts1 = flowable + .subscribeOn(Schedulers.io()) + .test(); + + TestSubscriber<Integer> ts2 = flowable + .subscribeOn(Schedulers.io()) + .test(); + + ts1 + .withTag("" + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + ts2 + .withTag("" + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + } + } + + static final class TestConnectableFlowable<T> extends ConnectableFlowable<T> + implements Disposable { + + volatile boolean disposed; + + @Override + public void dispose() { + disposed = true; + } + + @Override + public boolean isDisposed() { + return disposed; + } + + @Override + public void connect(Consumer<? super Disposable> connection) { + // not relevant + } + + @Override + protected void subscribeActual(Subscriber<? super T> subscriber) { + // not relevant + } + } + + @Test + public void timeoutDisposesSource() { + FlowableRefCount<Object> o = (FlowableRefCount<Object>)new TestConnectableFlowable<Object>().refCount(); + + RefConnection rc = new RefConnection(o); + o.connection = rc; + + o.timeout(rc); + + assertTrue(((Disposable)o.source).isDisposed()); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index 37efa77570..d75498bc69 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -765,15 +765,17 @@ public void replayIsUnsubscribed() { ConnectableObservable<Integer> co = Observable.just(1).concatWith(Observable.<Integer>never()) .replay(); - assertTrue(((Disposable)co).isDisposed()); + if (co instanceof Disposable) { + assertTrue(((Disposable)co).isDisposed()); - Disposable connection = co.connect(); + Disposable connection = co.connect(); - assertFalse(((Disposable)co).isDisposed()); + assertFalse(((Disposable)co).isDisposed()); - connection.dispose(); + connection.dispose(); - assertTrue(((Disposable)co).isDisposed()); + assertTrue(((Disposable)co).isDisposed()); + } } static final class BadObservableSubscribe extends ConnectableObservable<Object> { @@ -1239,6 +1241,8 @@ public void cancelTerminateStateExclusion() { o.cancel(null); + o.cancel(new RefConnection(o)); + RefConnection rc = new RefConnection(o); o.connection = null; rc.subscriberCount = 0; @@ -1274,5 +1278,71 @@ public void cancelTerminateStateExclusion() { rc.connected = true; o.connection = rc; o.cancel(rc); + + o.connection = rc; + o.cancel(new RefConnection(o)); + } + + @Test + public void replayRefCountShallBeThreadSafe() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + Observable<Integer> observable = Observable.just(1).replay(1).refCount(); + + TestObserver<Integer> observer1 = observable + .subscribeOn(Schedulers.io()) + .test(); + + TestObserver<Integer> observer2 = observable + .subscribeOn(Schedulers.io()) + .test(); + + observer1 + .withTag("" + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + observer2 + .withTag("" + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + } + } + + static final class TestConnectableObservable<T> extends ConnectableObservable<T> + implements Disposable { + + volatile boolean disposed; + + @Override + public void dispose() { + disposed = true; + } + + @Override + public boolean isDisposed() { + return disposed; + } + + @Override + public void connect(Consumer<? super Disposable> connection) { + // not relevant + } + + @Override + protected void subscribeActual(Observer<? super T> observer) { + // not relevant + } + } + + @Test + public void timeoutDisposesSource() { + ObservableRefCount<Object> o = (ObservableRefCount<Object>)new TestConnectableObservable<Object>().refCount(); + + RefConnection rc = new RefConnection(o); + o.connection = rc; + + o.timeout(rc); + + assertTrue(((Disposable)o.source).isDisposed()); } } From 205fea69982f5f0f2eb7f1b767e864c0d3901a71 Mon Sep 17 00:00:00 2001 From: Yannick Lecaillez <ylecaillez@gmail.com> Date: Mon, 3 Sep 2018 14:05:58 +0200 Subject: [PATCH 277/417] #6195 Fix Flowable.reduce(BiFunction) JavaDoc (#6197) Empty source does not signal NoSuchElementException. --- src/main/java/io/reactivex/Flowable.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index bab8443357..0abe33c93c 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -12130,8 +12130,6 @@ public final Flowable<T> rebatchRequests(int n) { * Publisher into the same function, and so on until all items have been emitted by the finite source Publisher, * and emits the final result from the final call to your function as its sole item. * <p> - * If the source is empty, a {@code NoSuchElementException} is signaled. - * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/reduce.png" alt=""> * <p> * This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate," From e0532b71f7eb6e2973b8c9b155b53a671caa0e9f Mon Sep 17 00:00:00 2001 From: luis-cortes <lac07h@gmail.com> Date: Mon, 3 Sep 2018 08:33:36 -0400 Subject: [PATCH 278/417] Add "error handling" java docs section to from callable & co (#6193) * #6179 Adding Error handling javadocs to Observable#fromCallable(), Single#fromCallable(), and Completable#fromCallable(). * #6179 Adding Error handling javadocs to Maybe#fromAction() and Completable#fromAction(). * #6179 Removing cancellation language since only the `Flowable` type has `cancel()` * #6179 Adding error handling JavaDocs to Flowable#fromCallable() --- src/main/java/io/reactivex/Completable.java | 14 ++++++++++++++ src/main/java/io/reactivex/Flowable.java | 7 +++++++ src/main/java/io/reactivex/Maybe.java | 7 +++++++ src/main/java/io/reactivex/Observable.java | 8 +++++++- src/main/java/io/reactivex/Single.java | 7 +++++++ 5 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 6cf5aa75f4..430440b248 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -396,6 +396,13 @@ public static Completable error(final Throwable error) { * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromAction} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> + * <dd> If the {@link Action} throws an exception, the respective {@link Throwable} is + * delivered to the downstream via {@link CompletableObserver#onError(Throwable)}, + * except when the downstream has disposed this {@code Completable} source. + * In this latter case, the {@code Throwable} is delivered to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}. + * </dd> * </dl> * @param run the runnable to run for each subscriber * @return the new Completable instance @@ -416,6 +423,13 @@ public static Completable fromAction(final Action run) { * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> + * <dd> If the {@link Callable} throws an exception, the respective {@link Throwable} is + * delivered to the downstream via {@link CompletableObserver#onError(Throwable)}, + * except when the downstream has disposed this {@code Completable} source. + * In this latter case, the {@code Throwable} is delivered to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}. + * </dd> * </dl> * @param callable the callable instance to execute for each subscriber * @return the new Completable instance diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 0abe33c93c..42c2082b10 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -1955,6 +1955,13 @@ public static <T> Flowable<T> fromArray(T... items) { * <dd>The operator honors backpressure from downstream.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> + * <dd> If the {@link Callable} throws an exception, the respective {@link Throwable} is + * delivered to the downstream via {@link Subscriber#onError(Throwable)}, + * except when the downstream has canceled this {@code Flowable} source. + * In this latter case, the {@code Throwable} is delivered to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}. + * </dd> * </dl> * * @param supplier diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 8750c83cd2..be9c888762 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -657,6 +657,13 @@ public static <T> Maybe<T> error(Callable<? extends Throwable> supplier) { * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromAction} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> + * <dd> If the {@link Action} throws an exception, the respective {@link Throwable} is + * delivered to the downstream via {@link MaybeObserver#onError(Throwable)}, + * except when the downstream has disposed this {@code Maybe} source. + * In this latter case, the {@code Throwable} is delivered to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}. + * </dd> * </dl> * @param <T> the target type * @param run the runnable to run for each subscriber diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index d1adc46efa..541c15215c 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -1757,8 +1757,14 @@ public static <T> Observable<T> fromArray(T... items) { * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> + * <dd> If the {@link Callable} throws an exception, the respective {@link Throwable} is + * delivered to the downstream via {@link Observer#onError(Throwable)}, + * except when the downstream has disposed this {@code Observable} source. + * In this latter case, the {@code Throwable} is delivered to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}. + * </dd> * </dl> - * * @param supplier * a function, the execution of which should be deferred; {@code fromCallable} will invoke this * function only when an observer subscribes to the ObservableSource that {@code fromCallable} returns diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 51a896c887..dca4eb9ed0 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -583,6 +583,13 @@ public static <T> Single<T> error(final Throwable exception) { * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> + * <dd> If the {@link Callable} throws an exception, the respective {@link Throwable} is + * delivered to the downstream via {@link SingleObserver#onError(Throwable)}, + * except when the downstream has disposed this {@code Single} source. + * In this latter case, the {@code Throwable} is delivered to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}. + * </dd> * </dl> * * @param callable From fbbae6c37bca0a22e32aad6f2901cf65fc460d8a Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 4 Sep 2018 10:28:24 +0200 Subject: [PATCH 279/417] 2.x: Fix toFlowable marbles and descriptions (#6200) * 2.x: Fix toFlowable marbles and descriptions * Adjust wording --- src/main/java/io/reactivex/Flowable.java | 11 ++++++----- src/main/java/io/reactivex/Observable.java | 11 ++++++----- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 42c2082b10..2e9e6c20ba 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -5842,15 +5842,16 @@ public final T blockingSingle(T defaultItem) { } /** - * Returns a {@link Future} representing the single value emitted by this {@code Flowable}. + * Returns a {@link Future} representing the only value emitted by this {@code Flowable}. + * <p> + * <img width="640" height="324" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/Flowable.toFuture.png" alt=""> * <p> * If the {@link Flowable} emits more than one item, {@link java.util.concurrent.Future} will receive an - * {@link java.lang.IllegalArgumentException}. If the {@link Flowable} is empty, {@link java.util.concurrent.Future} - * will receive a {@link java.util.NoSuchElementException}. + * {@link java.lang.IndexOutOfBoundsException}. If the {@link Flowable} is empty, {@link java.util.concurrent.Future} + * will receive a {@link java.util.NoSuchElementException}. The {@code Flowable} source has to terminate in order + * for the returned {@code Future} to terminate as well. * <p> * If the {@code Flowable} may emit more than one item, use {@code Flowable.toList().toFuture()}. - * <p> - * <img width="640" height="395" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/B.toFuture.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator consumes the source {@code Flowable} in an unbounded manner diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 541c15215c..4c11350715 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -5340,15 +5340,16 @@ public final T blockingSingle(T defaultItem) { } /** - * Returns a {@link Future} representing the single value emitted by this {@code Observable}. + * Returns a {@link Future} representing the only value emitted by this {@code Observable}. + * <p> + * <img width="640" height="312" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/toFuture.o.png" alt=""> * <p> * If the {@link Observable} emits more than one item, {@link java.util.concurrent.Future} will receive an - * {@link java.lang.IllegalArgumentException}. If the {@link Observable} is empty, {@link java.util.concurrent.Future} - * will receive an {@link java.util.NoSuchElementException}. + * {@link java.lang.IndexOutOfBoundsException}. If the {@link Observable} is empty, {@link java.util.concurrent.Future} + * will receive an {@link java.util.NoSuchElementException}. The {@code Observable} source has to terminate in order + * for the returned {@code Future} to terminate as well. * <p> * If the {@code Observable} may emit more than one item, use {@code Observable.toList().toFuture()}. - * <p> - * <img width="640" height="389" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/toFuture.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toFuture} does not operate by default on a particular {@link Scheduler}.</dd> From 59454ea47965547e7e218039ed152b591a51e268 Mon Sep 17 00:00:00 2001 From: luis-cortes <lac07h@gmail.com> Date: Tue, 4 Sep 2018 12:08:06 -0400 Subject: [PATCH 280/417] Fix terminology of cancel/dispose in the JavaDocs (#6199) * #6196 Fixing terminology of cancel/dispose in the JavaDocs for Completable. * #6196 Fixing terminology of cancel/dispose in the JavaDocs for Maybe. * #6196 Fixing terminology of cancel/dispose in the JavaDocs for Observable. * #6196 Fixing terminology of cancel/dispose in the JavaDocs for Single. * #6196 Switching from subscribers to observers in `Completable.fromFuture()` JavaDoc --- src/main/java/io/reactivex/Completable.java | 44 ++++++------- src/main/java/io/reactivex/Maybe.java | 40 ++++++------ src/main/java/io/reactivex/Observable.java | 68 ++++++++++----------- src/main/java/io/reactivex/Single.java | 32 +++++----- 4 files changed, 92 insertions(+), 92 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 430440b248..704e74c613 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -90,7 +90,7 @@ * d.dispose(); * </code></pre> * <p> - * Note that by design, subscriptions via {@link #subscribe(CompletableObserver)} can't be cancelled/disposed + * Note that by design, subscriptions via {@link #subscribe(CompletableObserver)} can't be disposed * from the outside (hence the * {@code void} return of the {@link #subscribe(CompletableObserver)} method) and it is the * responsibility of the implementor of the {@code CompletableObserver} to allow this to happen. @@ -105,7 +105,7 @@ public abstract class Completable implements CompletableSource { /** * Returns a Completable which terminates as soon as one of the source Completables - * terminates (normally or with an error) and cancels all other Completables. + * terminates (normally or with an error) and disposes all other Completables. * <p> * <img width="640" height="518" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.ambArray.png" alt=""> * <dl> @@ -133,7 +133,7 @@ public static Completable ambArray(final CompletableSource... sources) { /** * Returns a Completable which terminates as soon as one of the source Completables - * terminates (normally or with an error) and cancels all other Completables. + * terminates (normally or with an error) and disposes all other Completables. * <p> * <img width="640" height="518" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.amb.png" alt=""> * <dl> @@ -306,7 +306,7 @@ public static Completable create(CompletableOnSubscribe source) { /** * Constructs a Completable instance by wrapping the given source callback * <strong>without any safeguards; you should manage the lifecycle and response - * to downstream cancellation/dispose</strong>. + * to downstream disposal</strong>. * <p> * <img width="640" height="260" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.unsafeCreate.png" alt=""> * <dl> @@ -446,7 +446,7 @@ public static Completable fromCallable(final Callable<?> callable) { * <p> * <img width="640" height="628" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromFuture.png" alt=""> * <p> - * Note that cancellation from any of the subscribers to this Completable will cancel the future. + * Note that if any of the observers to this Completable call dispose, this Completable will cancel the future. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromFuture} does not operate by default on a particular {@link Scheduler}.</dd> @@ -594,13 +594,13 @@ public static <T> Completable fromSingle(final SingleSource<T> single) { * <dd>{@code mergeArray} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. + * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are disposed. * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Completable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Completable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeArrayDelayError(CompletableSource...)} to merge sources and terminate only when all source {@code CompletableSource}s * have completed or failed with an error. @@ -634,13 +634,13 @@ public static Completable mergeArray(CompletableSource... sources) { * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. + * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are disposed. * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Completable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Completable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code CompletableSource}s * have completed or failed with an error. @@ -671,13 +671,13 @@ public static Completable merge(Iterable<? extends CompletableSource> sources) { * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. + * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are disposed. * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Completable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Completable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Publisher)} to merge sources and terminate only when all source {@code CompletableSource}s * have completed or failed with an error. @@ -708,13 +708,13 @@ public static Completable merge(Publisher<? extends CompletableSource> sources) * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code CompletableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are cancelled. + * {@code Completable} terminates with that {@code Throwable} and all other source {@code CompletableSource}s are disposed. * If more than one {@code CompletableSource} signals an error, the resulting {@code Completable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Completable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Completable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Publisher, int)} to merge sources and terminate only when all source {@code CompletableSource}s * have completed or failed with an error. @@ -952,7 +952,7 @@ public static <R> Completable using(Callable<R> resourceSupplier, * <p> * <img width="640" height="332" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.using.b.png" alt=""> * <p> - * If this overload performs a lazy cancellation after the terminal event is emitted. + * If this overload performs a lazy disposal after the terminal event is emitted. * Exceptions thrown at this time will be delivered to RxJavaPlugins only. * <dl> * <dt><b>Scheduler:</b></dt> @@ -1585,7 +1585,7 @@ public final Completable doAfterTerminate(final Action onAfterTerminate) { * <dd>{@code doFinally} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.0.1 - experimental - * @param onFinally the action called when this Completable terminates or gets cancelled + * @param onFinally the action called when this Completable terminates or gets disposed * @return the new Completable instance * @since 2.1 */ @@ -1852,7 +1852,7 @@ public final Completable onTerminateDetach() { } /** - * Returns a Completable that repeatedly subscribes to this Completable until cancelled. + * Returns a Completable that repeatedly subscribes to this Completable until disposed. * <p> * <img width="640" height="373" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.repeat.png" alt=""> * <dl> @@ -2155,7 +2155,7 @@ public final Completable hide() { } /** - * Subscribes to this CompletableConsumable and returns a Disposable which can be used to cancel + * Subscribes to this CompletableConsumable and returns a Disposable which can be used to dispose * the subscription. * <p> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.subscribe.png" alt=""> @@ -2163,7 +2163,7 @@ public final Completable hide() { * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * @return the Disposable that allows cancelling the subscription + * @return the Disposable that allows disposing the subscription */ @SchedulerSupport(SchedulerSupport.NONE) public final Disposable subscribe() { @@ -2245,7 +2245,7 @@ public final <E extends CompletableObserver> E subscribeWith(E observer) { * </dl> * @param onComplete the runnable that is called if the Completable completes normally * @param onError the consumer that is called if this Completable emits an error - * @return the Disposable that can be used for cancelling the subscription asynchronously + * @return the Disposable that can be used for disposing the subscription asynchronously * @throws NullPointerException if either callback is null */ @CheckReturnValue @@ -2273,7 +2273,7 @@ public final Disposable subscribe(final Action onComplete, final Consumer<? supe * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param onComplete the runnable called when this Completable completes normally - * @return the Disposable that allows cancelling the subscription + * @return the Disposable that allows disposing the subscription */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -2583,7 +2583,7 @@ public final <T> Single<T> toSingleDefault(final T completionValue) { } /** - * Returns a Completable which makes sure when a subscriber cancels the subscription, the + * Returns a Completable which makes sure when a subscriber disposes the subscription, the * dispose is called on the specified scheduler. * <p> * <img width="640" height="716" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.unsubscribeOn.png" alt=""> @@ -2591,7 +2591,7 @@ public final <T> Single<T> toSingleDefault(final T completionValue) { * <dt><b>Scheduler:</b></dt> * <dd>{@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.</dd> * </dl> - * @param scheduler the target scheduler where to execute the cancellation + * @param scheduler the target scheduler where to execute the disposing * @return the new Completable instance * @throws NullPointerException if scheduler is null */ diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index be9c888762..346d35e16a 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -93,7 +93,7 @@ * d.dispose(); * </code></pre> * <p> - * Note that by design, subscriptions via {@link #subscribe(MaybeObserver)} can't be cancelled/disposed + * Note that by design, subscriptions via {@link #subscribe(MaybeObserver)} can't be disposed * from the outside (hence the * {@code void} return of the {@link #subscribe(MaybeObserver)} method) and it is the * responsibility of the implementor of the {@code MaybeObserver} to allow this to happen. @@ -110,7 +110,7 @@ public abstract class Maybe<T> implements MaybeSource<T> { /** - * Runs multiple MaybeSources and signals the events of the first one that signals (cancelling + * Runs multiple MaybeSources and signals the events of the first one that signals (disposing * the rest). * <p> * <img width="640" height="519" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.amb.png" alt=""> @@ -131,7 +131,7 @@ public static <T> Maybe<T> amb(final Iterable<? extends MaybeSource<? extends T> } /** - * Runs multiple MaybeSources and signals the events of the first one that signals (cancelling + * Runs multiple MaybeSources and signals the events of the first one that signals (disposing * the rest). * <p> * <img width="640" height="519" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.ambArray.png" alt=""> @@ -767,7 +767,7 @@ public static <T> Maybe<T> fromCallable(@NonNull final Callable<? extends T> cal * <p> * <em>Important note:</em> This Maybe is blocking; you cannot dispose it. * <p> - * Unlike 1.x, cancelling the Maybe won't cancel the future. If necessary, one can use composition to achieve the + * Unlike 1.x, disposing the Maybe won't cancel the future. If necessary, one can use composition to achieve the * cancellation effect: {@code futureMaybe.doOnDispose(() -> future.cancel(true));}. * <dl> * <dt><b>Scheduler:</b></dt> @@ -798,7 +798,7 @@ public static <T> Maybe<T> fromFuture(Future<? extends T> future) { * return value of the {@link Future#get} method of that object, by passing the object into the {@code fromFuture} * method. * <p> - * Unlike 1.x, cancelling the Maybe won't cancel the future. If necessary, one can use composition to achieve the + * Unlike 1.x, disposing the Maybe won't cancel the future. If necessary, one can use composition to achieve the * cancellation effect: {@code futureMaybe.doOnCancel(() -> future.cancel(true));}. * <p> * <em>Important note:</em> This Maybe is blocking on the thread it gets subscribed on; you cannot dispose it. @@ -882,7 +882,7 @@ public static <T> Maybe<T> just(T item) { * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -916,7 +916,7 @@ public static <T> Flowable<T> merge(Iterable<? extends MaybeSource<? extends T>> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -950,7 +950,7 @@ public static <T> Flowable<T> merge(Publisher<? extends MaybeSource<? extends T> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -1023,7 +1023,7 @@ public static <T> Maybe<T> merge(MaybeSource<? extends MaybeSource<? extends T>> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -1071,7 +1071,7 @@ public static <T> Flowable<T> merge( * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -1123,7 +1123,7 @@ public static <T> Flowable<T> merge( * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -1174,7 +1174,7 @@ public static <T> Flowable<T> merge( * <dd>{@code mergeArray} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed. * If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -2700,7 +2700,7 @@ public final Maybe<T> doAfterTerminate(Action onAfterTerminate) { * <dd>{@code doFinally} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.0.1 - experimental - * @param onFinally the action called when this Maybe terminates or gets cancelled + * @param onFinally the action called when this Maybe terminates or gets disposed * @return the new Maybe instance * @since 2.1 */ @@ -2718,7 +2718,7 @@ public final Maybe<T> doFinally(Action onFinally) { * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnDispose} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * @param onDispose the action called when the subscription is cancelled (disposed) + * @param onDispose the action called when the subscription is disposed * @throws NullPointerException if onDispose is null * @return the new Maybe instance */ @@ -3499,7 +3499,7 @@ public final Flowable<T> toFlowable() { } /** - * Converts this Maybe into an Observable instance composing cancellation + * Converts this Maybe into an Observable instance composing disposal * through. * <dl> * <dt><b>Scheduler:</b></dt> @@ -3518,7 +3518,7 @@ public final Observable<T> toObservable() { } /** - * Converts this Maybe into a Single instance composing cancellation + * Converts this Maybe into a Single instance composing disposal * through and turning an empty Maybe into a Single that emits the given * value through onSuccess. * <dl> @@ -3536,7 +3536,7 @@ public final Single<T> toSingle(T defaultValue) { } /** - * Converts this Maybe into a Single instance composing cancellation + * Converts this Maybe into a Single instance composing disposal * through and turning an empty Maybe into a signal of NoSuchElementException. * <dl> * <dt><b>Scheduler:</b></dt> @@ -4451,7 +4451,7 @@ public final <U> Maybe<T> timeout(MaybeSource<U> timeoutIndicator) { /** * If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link MaybeSource} signals, - * the current {@code Maybe} is cancelled and the {@code fallback} {@code MaybeSource} subscribed to + * the current {@code Maybe} is disposed and the {@code fallback} {@code MaybeSource} subscribed to * as a continuation. * <dl> * <dt><b>Scheduler:</b></dt> @@ -4496,7 +4496,7 @@ public final <U> Maybe<T> timeout(Publisher<U> timeoutIndicator) { /** * If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link Publisher} signals, - * the current {@code Maybe} is cancelled and the {@code fallback} {@code MaybeSource} subscribed to + * the current {@code Maybe} is disposed and the {@code fallback} {@code MaybeSource} subscribed to * as a continuation. * <dl> * <dt><b>Backpressure:</b></dt> @@ -4527,7 +4527,7 @@ public final <U> Maybe<T> timeout(Publisher<U> timeoutIndicator, MaybeSource<? e * <dt><b>Scheduler:</b></dt> * <dd>{@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.</dd> * </dl> - * @param scheduler the target scheduler where to execute the cancellation + * @param scheduler the target scheduler where to execute the disposal * @return the new Maybe instance * @throws NullPointerException if scheduler is null */ diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 4c11350715..ef3c5ed450 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -53,7 +53,7 @@ * The design of this class was derived from the * <a href="https://github.com/reactive-streams/reactive-streams-jvm">Reactive-Streams design and specification</a> * by removing any backpressure-related infrastructure and implementation detail, replacing the - * {@code org.reactivestreams.Subscription} with {@link Disposable} as the primary means to cancel + * {@code org.reactivestreams.Subscription} with {@link Disposable} as the primary means to dispose of * a flow. * <p> * The {@code Observable} follows the protocol @@ -64,7 +64,7 @@ * the stream can be disposed through the {@code Disposable} instance provided to consumers through * {@code Observer.onSubscribe}. * <p> - * Unlike the {@code Observable} of version 1.x, {@link #subscribe(Observer)} does not allow external cancellation + * Unlike the {@code Observable} of version 1.x, {@link #subscribe(Observer)} does not allow external disposal * of a subscription and the {@code Observer} instance is expected to expose such capability. * <p>Example: * <pre><code> @@ -86,7 +86,7 @@ * }); * * Thread.sleep(500); - * // the sequence now can be cancelled via dispose() + * // the sequence can now be disposed via dispose() * d.dispose(); * </code></pre> * @@ -2054,7 +2054,7 @@ public static <T, S> Observable<T> generate(Callable<S> initialState, final BiCo * {@code onComplete} to signal a value or a terminal event. Signalling multiple {@code onNext} * in a call will make the operator signal {@code IllegalStateException}. * @param disposeState the Consumer that is called with the current state when the generator - * terminates the sequence or it gets cancelled + * terminates the sequence or it gets disposed * @return the new Observable instance */ @CheckReturnValue @@ -2110,7 +2110,7 @@ public static <T, S> Observable<T> generate(Callable<S> initialState, BiFunction * the next invocation. Signalling multiple {@code onNext} * in a call will make the operator signal {@code IllegalStateException}. * @param disposeState the Consumer that is called with the current state when the generator - * terminates the sequence or it gets cancelled + * terminates the sequence or it gets disposed * @return the new Observable instance */ @CheckReturnValue @@ -2698,13 +2698,13 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable, int, int)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. @@ -2745,13 +2745,13 @@ public static <T> Observable<T> merge(Iterable<? extends ObservableSource<? exte * <dd>{@code mergeArray} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeArrayDelayError(int, int, ObservableSource...)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. @@ -2791,13 +2791,13 @@ public static <T> Observable<T> mergeArray(int maxConcurrency, int bufferSize, O * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. @@ -2832,13 +2832,13 @@ public static <T> Observable<T> merge(Iterable<? extends ObservableSource<? exte * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable, int)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. @@ -2877,13 +2877,13 @@ public static <T> Observable<T> merge(Iterable<? extends ObservableSource<? exte * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. @@ -2920,13 +2920,13 @@ public static <T> Observable<T> merge(ObservableSource<? extends ObservableSourc * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(ObservableSource, int)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. @@ -2967,13 +2967,13 @@ public static <T> Observable<T> merge(ObservableSource<? extends ObservableSourc * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(ObservableSource, ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. @@ -3010,13 +3010,13 @@ public static <T> Observable<T> merge(ObservableSource<? extends T> source1, Obs * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(ObservableSource, ObservableSource, ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. @@ -3056,13 +3056,13 @@ public static <T> Observable<T> merge(ObservableSource<? extends T> source1, Obs * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(ObservableSource, ObservableSource, ObservableSource, ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. @@ -3107,13 +3107,13 @@ public static <T> Observable<T> merge( * <dd>{@code mergeArray} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code ObservableSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are cancelled. + * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s - * signaled by source(s) after the returned {@code Observable} has been cancelled or terminated with a + * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeArrayDelayError(ObservableSource...)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. @@ -3909,7 +3909,7 @@ public static Observable<Long> timer(long delay, TimeUnit unit, Scheduler schedu /** * Create an Observable by wrapping an ObservableSource <em>which has to be implemented according * to the Reactive-Streams-based Observable specification by handling - * cancellation correctly; no safeguards are provided by the Observable itself</em>. + * disposal correctly; no safeguards are provided by the Observable itself</em>. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code unsafeCreate} by default doesn't operate on any particular {@link Scheduler}.</dd> @@ -7582,10 +7582,10 @@ public final Observable<T> delaySubscription(long delay, TimeUnit unit, Schedule * <p> * When the upstream signals an {@link Notification#createOnError(Throwable) onError} or * {@link Notification#createOnComplete() onComplete} item, the - * returned Observable cancels the flow and terminates with that type of terminal event: + * returned Observable disposes of the flow and terminates with that type of terminal event: * <pre><code> * Observable.just(createOnNext(1), createOnComplete(), createOnNext(2)) - * .doOnDispose(() -> System.out.println("Cancelled!")); + * .doOnDispose(() -> System.out.println("Disposed!")); * .test() * .assertResult(1); * </code></pre> @@ -7883,7 +7883,7 @@ public final Observable<T> doAfterTerminate(Action onFinally) { * <dd>This operator supports boundary-limited synchronous or asynchronous queue-fusion.</dd> * </dl> * <p>History: 2.0.1 - experimental - * @param onFinally the action called when this Observable terminates or gets cancelled + * @param onFinally the action called when this Observable terminates or gets disposed * @return the new Observable instance * @since 2.1 */ @@ -8046,7 +8046,7 @@ public final Observable<T> doOnError(Consumer<? super Throwable> onError) { /** * Calls the appropriate onXXX method (shared between all Observer) for the lifecycle events of - * the sequence (subscription, cancellation, requesting). + * the sequence (subscription, disposal, requesting). * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnLifecycle.o.png" alt=""> * <dl> @@ -8919,7 +8919,7 @@ public final <R> Observable<R> flatMapSingle(Function<? super T, ? extends Singl * @param onNext * {@link Consumer} to execute for each item. * @return - * a Disposable that allows cancelling an asynchronous sequence + * a Disposable that allows disposing of an asynchronous sequence * @throws NullPointerException * if {@code onNext} is null * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> @@ -8947,7 +8947,7 @@ public final Disposable forEach(Consumer<? super T> onNext) { * @param onNext * {@link Predicate} to execute for each item. * @return - * a Disposable that allows cancelling an asynchronous sequence + * a Disposable that allows disposing of an asynchronous sequence * @throws NullPointerException * if {@code onNext} is null * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> @@ -8971,7 +8971,7 @@ public final Disposable forEachWhile(Predicate<? super T> onNext) { * @param onError * {@link Consumer} to execute when an error is emitted. * @return - * a Disposable that allows cancelling an asynchronous sequence + * a Disposable that allows disposing of an asynchronous sequence * @throws NullPointerException * if {@code onNext} is null, or * if {@code onError} is null @@ -8998,7 +8998,7 @@ public final Disposable forEachWhile(Predicate<? super T> onNext, Consumer<? sup * @param onComplete * {@link Action} to execute when completion is signalled. * @return - * a Disposable that allows cancelling an asynchronous sequence + * a Disposable that allows disposing of an asynchronous sequence * @throws NullPointerException * if {@code onNext} is null, or * if {@code onError} is null, or diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index dca4eb9ed0..8d4013be66 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -97,7 +97,7 @@ * d.dispose(); * </code></pre> * <p> - * Note that by design, subscriptions via {@link #subscribe(SingleObserver)} can't be cancelled/disposed + * Note that by design, subscriptions via {@link #subscribe(SingleObserver)} can't be disposed * from the outside (hence the * {@code void} return of the {@link #subscribe(SingleObserver)} method) and it is the * responsibility of the implementor of the {@code SingleObserver} to allow this to happen. @@ -114,7 +114,7 @@ public abstract class Single<T> implements SingleSource<T> { /** - * Runs multiple SingleSources and signals the events of the first one that signals (cancelling + * Runs multiple SingleSources and signals the events of the first one that signals (disposing * the rest). * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.amb.png" alt=""> @@ -136,7 +136,7 @@ public static <T> Single<T> amb(final Iterable<? extends SingleSource<? extends } /** - * Runs multiple SingleSources and signals the events of the first one that signals (cancelling + * Runs multiple SingleSources and signals the events of the first one that signals (disposing * the rest). * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.ambArray.png" alt=""> @@ -830,7 +830,7 @@ public static <T> Single<T> just(final T item) { * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code SingleSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are disposed. * If more than one {@code SingleSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -867,7 +867,7 @@ public static <T> Flowable<T> merge(Iterable<? extends SingleSource<? extends T> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code SingleSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are disposed. * If more than one {@code SingleSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -938,7 +938,7 @@ public static <T> Single<T> merge(SingleSource<? extends SingleSource<? extends * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code SingleSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are disposed. * If more than one {@code SingleSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -986,7 +986,7 @@ public static <T> Flowable<T> merge( * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code SingleSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are disposed. * If more than one {@code SingleSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -1038,7 +1038,7 @@ public static <T> Flowable<T> merge( * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the source {@code SingleSource}s signal a {@code Throwable} via {@code onError}, the resulting - * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are cancelled. + * {@code Flowable} terminates with that {@code Throwable} and all other source {@code SingleSource}s are disposed. * If more than one {@code SingleSource} signals an error, the resulting {@code Flowable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@code CompositeException} containing two or more of the various error signals. @@ -1374,7 +1374,7 @@ public static <T> Single<T> unsafeCreate(SingleSource<T> onSubscribe) { * to be run by the operator * @param disposer the consumer of the generated resource that is called exactly once for * that particular resource when the generated SingleSource terminates - * (successfully or with an error) or gets cancelled. + * (successfully or with an error) or gets disposed. * @return the new Single instance * @since 2.0 */ @@ -1401,7 +1401,7 @@ public static <T, U> Single<T> using(Callable<U> resourceSupplier, * to be run by the operator * @param disposer the consumer of the generated resource that is called exactly once for * that particular resource when the generated SingleSource terminates - * (successfully or with an error) or gets cancelled. + * (successfully or with an error) or gets disposed. * @param eager * if true, the disposer is called before the terminal event is signalled * if false, the disposer is called after the terminal event is delivered to downstream @@ -1457,7 +1457,7 @@ public static <T> Single<T> wrap(SingleSource<T> source) { * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <p> - * If any of the SingleSources signal an error, all other SingleSources get cancelled and the + * If any of the SingleSources signal an error, all other SingleSources get disposed and the * error emitted to downstream immediately. * <dl> * <dt><b>Scheduler:</b></dt> @@ -1902,7 +1902,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Single<R> zip( * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <p> - * If any of the SingleSources signal an error, all other SingleSources get cancelled and the + * If any of the SingleSources signal an error, all other SingleSources get disposed and the * error emitted to downstream immediately. * <dl> * <dt><b>Scheduler:</b></dt> @@ -2368,7 +2368,7 @@ public final Single<T> doAfterTerminate(Action onAfterTerminate) { * <dd>{@code doFinally} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.0.1 - experimental - * @param onFinally the action called when this Single terminates or gets cancelled + * @param onFinally the action called when this Single terminates or gets disposed * @return the new Single instance * @since 2.1 */ @@ -3629,7 +3629,7 @@ public final Single<T> timeout(long timeout, TimeUnit unit, Scheduler scheduler) /** * Runs the current Single and if it doesn't signal within the specified timeout window, it is - * cancelled and the other SingleSource subscribed to. + * disposed and the other SingleSource subscribed to. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} subscribes to the other SingleSource on the {@link Scheduler} you specify.</dd> @@ -3650,7 +3650,7 @@ public final Single<T> timeout(long timeout, TimeUnit unit, Scheduler scheduler, /** * Runs the current Single and if it doesn't signal within the specified timeout window, it is - * cancelled and the other SingleSource subscribed to. + * disposed and the other SingleSource subscribed to. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} subscribes to the other SingleSource on @@ -3839,7 +3839,7 @@ public final Observable<T> toObservable() { * <dd>{@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.</dd> * </dl> * <p>History: 2.0.9 - experimental - * @param scheduler the target scheduler where to execute the cancellation + * @param scheduler the target scheduler where to execute the disposal * @return the new Single instance * @throws NullPointerException if scheduler is null * @since 2.2 From cc459751031f6122330c08dcc2e57c9b5370cee3 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 6 Sep 2018 09:30:42 +0200 Subject: [PATCH 281/417] Release 2.2.2 --- CHANGES.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index a4dfea7e35..308c8e606b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,23 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.2 - September 6, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.2%7C)) + +#### Bugfixes + + - [Pull 6187](https://github.com/ReactiveX/RxJava/pull/6187): Fix `refCount` termination-reconnect race. + +#### Documentation changes + + - [Pull 6171](https://github.com/ReactiveX/RxJava/pull/6171): Add explanation text to `Undeliverable` & `OnErrorNotImplemented` exceptions. + - [Pull 6174](https://github.com/ReactiveX/RxJava/pull/6174): Auto-clean up RxJavaPlugins JavaDocs HTML. + - [Pull 6175](https://github.com/ReactiveX/RxJava/pull/6175): Explain `null` observer/subscriber return errors from `RxJavaPlugins` in detail. + - [Pull 6180](https://github.com/ReactiveX/RxJava/pull/6180): Update `Additional-Reading.md`. + - [Pull 6180](https://github.com/ReactiveX/RxJava/pull/6180): Fix `Flowable.reduce(BiFunction)` JavaDoc; the operator does not signal `NoSuchElementException`. + - [Pull 6193](https://github.com/ReactiveX/RxJava/pull/6193): Add "error handling" java docs section to `fromCallable` & co. + - [Pull 6199](https://github.com/ReactiveX/RxJava/pull/6199): Fix terminology of cancel/dispose in the JavaDocs. + - [Pull 6200](https://github.com/ReactiveX/RxJava/pull/6200): Fix `toFuture` marbles and descriptions. + ### Version 2.2.1 - August 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.1%7C)) #### API changes From b9c00a8e562e04328dff26d37a4acdd811db174d Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 7 Sep 2018 15:00:30 +0200 Subject: [PATCH 282/417] 2.x: Assert instead of print Undeliverable in some tests (#6205) * 2.x: Assert instead of print Undeliverable in some tests * Fix error count not guaranteed to be 4. --- .../io/reactivex/maybe/MaybeCreateTest.java | 162 +++++++++++------- .../java/io/reactivex/maybe/MaybeTest.java | 144 ++++++++++------ .../observers/SerializedObserverTest.java | 44 +++-- .../subscribers/SerializedSubscriberTest.java | 97 +++++++---- 4 files changed, 271 insertions(+), 176 deletions(-) diff --git a/src/test/java/io/reactivex/maybe/MaybeCreateTest.java b/src/test/java/io/reactivex/maybe/MaybeCreateTest.java index f6d24bd980..90689133d5 100644 --- a/src/test/java/io/reactivex/maybe/MaybeCreateTest.java +++ b/src/test/java/io/reactivex/maybe/MaybeCreateTest.java @@ -15,12 +15,15 @@ import static org.junit.Assert.assertTrue; +import java.util.List; + import org.junit.Test; import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Cancellable; +import io.reactivex.plugins.RxJavaPlugins; public class MaybeCreateTest { @Test(expected = NullPointerException.class) @@ -30,84 +33,111 @@ public void nullArgument() { @Test public void basic() { - final Disposable d = Disposables.empty(); - - Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { - @Override - public void subscribe(MaybeEmitter<Integer> e) throws Exception { - e.setDisposable(d); - - e.onSuccess(1); - e.onError(new TestException()); - e.onSuccess(2); - e.onError(new TestException()); - } - }).test().assertResult(1); - - assertTrue(d.isDisposed()); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); + + Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { + @Override + public void subscribe(MaybeEmitter<Integer> e) throws Exception { + e.setDisposable(d); + + e.onSuccess(1); + e.onError(new TestException()); + e.onSuccess(2); + e.onError(new TestException()); + } + }).test().assertResult(1); + + assertTrue(d.isDisposed()); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicWithCancellable() { - final Disposable d1 = Disposables.empty(); - final Disposable d2 = Disposables.empty(); - - Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { - @Override - public void subscribe(MaybeEmitter<Integer> e) throws Exception { - e.setDisposable(d1); - e.setCancellable(new Cancellable() { - @Override - public void cancel() throws Exception { - d2.dispose(); - } - }); - - e.onSuccess(1); - e.onError(new TestException()); - e.onSuccess(2); - e.onError(new TestException()); - } - }).test().assertResult(1); - - assertTrue(d1.isDisposed()); - assertTrue(d2.isDisposed()); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d1 = Disposables.empty(); + final Disposable d2 = Disposables.empty(); + + Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { + @Override + public void subscribe(MaybeEmitter<Integer> e) throws Exception { + e.setDisposable(d1); + e.setCancellable(new Cancellable() { + @Override + public void cancel() throws Exception { + d2.dispose(); + } + }); + + e.onSuccess(1); + e.onError(new TestException()); + e.onSuccess(2); + e.onError(new TestException()); + } + }).test().assertResult(1); + + assertTrue(d1.isDisposed()); + assertTrue(d2.isDisposed()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicWithError() { - final Disposable d = Disposables.empty(); - - Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { - @Override - public void subscribe(MaybeEmitter<Integer> e) throws Exception { - e.setDisposable(d); - - e.onError(new TestException()); - e.onSuccess(2); - e.onError(new TestException()); - } - }).test().assertFailure(TestException.class); - - assertTrue(d.isDisposed()); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); + + Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { + @Override + public void subscribe(MaybeEmitter<Integer> e) throws Exception { + e.setDisposable(d); + + e.onError(new TestException()); + e.onSuccess(2); + e.onError(new TestException()); + } + }).test().assertFailure(TestException.class); + + assertTrue(d.isDisposed()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicWithCompletion() { - final Disposable d = Disposables.empty(); - - Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { - @Override - public void subscribe(MaybeEmitter<Integer> e) throws Exception { - e.setDisposable(d); - - e.onComplete(); - e.onSuccess(2); - e.onError(new TestException()); - } - }).test().assertComplete(); - - assertTrue(d.isDisposed()); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); + + Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { + @Override + public void subscribe(MaybeEmitter<Integer> e) throws Exception { + e.setDisposable(d); + + e.onComplete(); + e.onSuccess(2); + e.onError(new TestException()); + } + }).test().assertComplete(); + + assertTrue(d.isDisposed()); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test(expected = IllegalArgumentException.class) diff --git a/src/test/java/io/reactivex/maybe/MaybeTest.java b/src/test/java/io/reactivex/maybe/MaybeTest.java index b726b77611..41225a47cc 100644 --- a/src/test/java/io/reactivex/maybe/MaybeTest.java +++ b/src/test/java/io/reactivex/maybe/MaybeTest.java @@ -1496,68 +1496,91 @@ public void nullArgument() { @Test public void basic() { - final Disposable d = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); - Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { - @Override - public void subscribe(MaybeEmitter<Integer> e) throws Exception { - e.setDisposable(d); + Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { + @Override + public void subscribe(MaybeEmitter<Integer> e) throws Exception { + e.setDisposable(d); + + e.onSuccess(1); + e.onError(new TestException()); + e.onSuccess(2); + e.onError(new TestException()); + e.onComplete(); + } + }) + .test() + .assertResult(1); - e.onSuccess(1); - e.onError(new TestException()); - e.onSuccess(2); - e.onError(new TestException()); - e.onComplete(); - } - }) - .test() - .assertResult(1); + assertTrue(d.isDisposed()); - assertTrue(d.isDisposed()); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicWithError() { - final Disposable d = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); - Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { - @Override - public void subscribe(MaybeEmitter<Integer> e) throws Exception { - e.setDisposable(d); + Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { + @Override + public void subscribe(MaybeEmitter<Integer> e) throws Exception { + e.setDisposable(d); - e.onError(new TestException()); - e.onSuccess(2); - e.onError(new TestException()); - e.onComplete(); - } - }) - .test() - .assertFailure(TestException.class); + e.onError(new TestException()); + e.onSuccess(2); + e.onError(new TestException()); + e.onComplete(); + } + }) + .test() + .assertFailure(TestException.class); + + assertTrue(d.isDisposed()); - assertTrue(d.isDisposed()); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test public void basicWithComplete() { - final Disposable d = Disposables.empty(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final Disposable d = Disposables.empty(); - Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { - @Override - public void subscribe(MaybeEmitter<Integer> e) throws Exception { - e.setDisposable(d); + Maybe.<Integer>create(new MaybeOnSubscribe<Integer>() { + @Override + public void subscribe(MaybeEmitter<Integer> e) throws Exception { + e.setDisposable(d); + + e.onComplete(); + e.onSuccess(1); + e.onError(new TestException()); + e.onComplete(); + e.onSuccess(2); + e.onError(new TestException()); + } + }) + .test() + .assertResult(); - e.onComplete(); - e.onSuccess(1); - e.onError(new TestException()); - e.onComplete(); - e.onSuccess(2); - e.onError(new TestException()); - } - }) - .test() - .assertResult(); + assertTrue(d.isDisposed()); - assertTrue(d.isDisposed()); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test(expected = IllegalArgumentException.class) @@ -2359,21 +2382,28 @@ public void accept(Integer v, Throwable e) throws Exception { @Test public void doOnEventError() { - final List<Object> list = new ArrayList<Object>(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final List<Object> list = new ArrayList<Object>(); - TestException ex = new TestException(); + TestException ex = new TestException(); - assertTrue(Maybe.<Integer>error(ex) - .doOnEvent(new BiConsumer<Integer, Throwable>() { - @Override - public void accept(Integer v, Throwable e) throws Exception { - list.add(v); - list.add(e); - } - }) - .subscribe().isDisposed()); + assertTrue(Maybe.<Integer>error(ex) + .doOnEvent(new BiConsumer<Integer, Throwable>() { + @Override + public void accept(Integer v, Throwable e) throws Exception { + list.add(v); + list.add(e); + } + }) + .subscribe().isDisposed()); + + assertEquals(Arrays.asList(null, ex), list); - assertEquals(Arrays.asList(null, ex), list); + TestHelper.assertError(errors, 0, OnErrorNotImplementedException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test diff --git a/src/test/java/io/reactivex/observers/SerializedObserverTest.java b/src/test/java/io/reactivex/observers/SerializedObserverTest.java index a2f0e63ece..f094ad7fc7 100644 --- a/src/test/java/io/reactivex/observers/SerializedObserverTest.java +++ b/src/test/java/io/reactivex/observers/SerializedObserverTest.java @@ -156,6 +156,7 @@ public void testMultiThreadedWithNPEinMiddle() { @Test public void runOutOfOrderConcurrencyTest() { ExecutorService tp = Executors.newFixedThreadPool(20); + List<Throwable> errors = TestHelper.trackPluginErrors(); try { TestConcurrencySubscriber tw = new TestConcurrencySubscriber(); // we need Synchronized + SafeObserver to handle synchronization plus life-cycle @@ -190,6 +191,10 @@ public void runOutOfOrderConcurrencyTest() { @SuppressWarnings("unused") int numNextEvents = tw.assertEvents(null); // no check of type since we don't want to test barging results here, just interleaving behavior // System.out.println("Number of events executed: " + numNextEvents); + + for (int i = 0; i < errors.size(); i++) { + TestHelper.assertUndeliverable(errors, i, RuntimeException.class); + } } catch (Throwable e) { fail("Concurrency test failed: " + e.getMessage()); e.printStackTrace(); @@ -200,6 +205,8 @@ public void runOutOfOrderConcurrencyTest() { } catch (InterruptedException e) { e.printStackTrace(); } + + RxJavaPlugins.reset(); } } @@ -955,24 +962,31 @@ public void onNext(Integer t) { @Test public void testErrorReentry() { - final AtomicReference<Observer<Integer>> serial = new AtomicReference<Observer<Integer>>(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference<Observer<Integer>> serial = new AtomicReference<Observer<Integer>>(); - TestObserver<Integer> to = new TestObserver<Integer>() { - @Override - public void onNext(Integer v) { - serial.get().onError(new TestException()); - serial.get().onError(new TestException()); - super.onNext(v); - } - }; - SerializedObserver<Integer> sobs = new SerializedObserver<Integer>(to); - sobs.onSubscribe(Disposables.empty()); - serial.set(sobs); + TestObserver<Integer> to = new TestObserver<Integer>() { + @Override + public void onNext(Integer v) { + serial.get().onError(new TestException()); + serial.get().onError(new TestException()); + super.onNext(v); + } + }; + SerializedObserver<Integer> sobs = new SerializedObserver<Integer>(to); + sobs.onSubscribe(Disposables.empty()); + serial.set(sobs); - sobs.onNext(1); + sobs.onNext(1); - to.assertValue(1); - to.assertError(TestException.class); + to.assertValue(1); + to.assertError(TestException.class); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test diff --git a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java index 0ecec64e8e..c38105eb68 100644 --- a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java @@ -158,6 +158,7 @@ public void testMultiThreadedWithNPEinMiddle() { @Test public void runOutOfOrderConcurrencyTest() { ExecutorService tp = Executors.newFixedThreadPool(20); + List<Throwable> errors = TestHelper.trackPluginErrors(); try { TestConcurrencySubscriber tw = new TestConcurrencySubscriber(); // we need Synchronized + SafeSubscriber to handle synchronization plus life-cycle @@ -192,6 +193,10 @@ public void runOutOfOrderConcurrencyTest() { @SuppressWarnings("unused") int numNextEvents = tw.assertEvents(null); // no check of type since we don't want to test barging results here, just interleaving behavior // System.out.println("Number of events executed: " + numNextEvents); + + for (int i = 0; i < errors.size(); i++) { + TestHelper.assertUndeliverable(errors, i, RuntimeException.class); + } } catch (Throwable e) { fail("Concurrency test failed: " + e.getMessage()); e.printStackTrace(); @@ -202,6 +207,8 @@ public void runOutOfOrderConcurrencyTest() { } catch (InterruptedException e) { e.printStackTrace(); } + + RxJavaPlugins.reset(); } } @@ -957,24 +964,31 @@ public void onNext(Integer t) { @Test public void testErrorReentry() { - final AtomicReference<Subscriber<Integer>> serial = new AtomicReference<Subscriber<Integer>>(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final AtomicReference<Subscriber<Integer>> serial = new AtomicReference<Subscriber<Integer>>(); - TestSubscriber<Integer> ts = new TestSubscriber<Integer>() { - @Override - public void onNext(Integer v) { - serial.get().onError(new TestException()); - serial.get().onError(new TestException()); - super.onNext(v); - } - }; - SerializedSubscriber<Integer> sobs = new SerializedSubscriber<Integer>(ts); - sobs.onSubscribe(new BooleanSubscription()); - serial.set(sobs); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>() { + @Override + public void onNext(Integer v) { + serial.get().onError(new TestException()); + serial.get().onError(new TestException()); + super.onNext(v); + } + }; + SerializedSubscriber<Integer> sobs = new SerializedSubscriber<Integer>(ts); + sobs.onSubscribe(new BooleanSubscription()); + serial.set(sobs); - sobs.onNext(1); + sobs.onNext(1); - ts.assertValue(1); - ts.assertError(TestException.class); + ts.assertValue(1); + ts.assertError(TestException.class); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } } @Test @@ -1180,38 +1194,45 @@ public void startOnce() { @Test public void onCompleteOnErrorRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { - TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); - final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts); + final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts); - BooleanSubscription bs = new BooleanSubscription(); + BooleanSubscription bs = new BooleanSubscription(); - so.onSubscribe(bs); + so.onSubscribe(bs); - final Throwable ex = new TestException(); + final Throwable ex = new TestException(); - Runnable r1 = new Runnable() { - @Override - public void run() { - so.onError(ex); - } - }; + Runnable r1 = new Runnable() { + @Override + public void run() { + so.onError(ex); + } + }; - Runnable r2 = new Runnable() { - @Override - public void run() { - so.onComplete(); - } - }; + Runnable r2 = new Runnable() { + @Override + public void run() { + so.onComplete(); + } + }; - TestHelper.race(r1, r2); + TestHelper.race(r1, r2); - ts.awaitDone(5, TimeUnit.SECONDS); + ts.awaitDone(5, TimeUnit.SECONDS); - if (ts.completions() != 0) { - ts.assertResult(); - } else { - ts.assertFailure(TestException.class).assertError(ex); + if (ts.completions() != 0) { + ts.assertResult(); + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } else { + ts.assertFailure(TestException.class).assertError(ex); + assertTrue("" + errors, errors.isEmpty()); + } + } finally { + RxJavaPlugins.reset(); } } From 3c773caf327f301e81e60bd0743178dcb7e793e8 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 21 Sep 2018 20:13:25 +0200 Subject: [PATCH 283/417] 2.x JavaDocs: Remove unnecessary 's' from ConnectableObservable (#6220) --- .../io/reactivex/observables/ConnectableObservable.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/observables/ConnectableObservable.java b/src/main/java/io/reactivex/observables/ConnectableObservable.java index 1858397e65..b5e54054b1 100644 --- a/src/main/java/io/reactivex/observables/ConnectableObservable.java +++ b/src/main/java/io/reactivex/observables/ConnectableObservable.java @@ -203,7 +203,7 @@ public final Observable<T> refCount(int subscriberCount, long timeout, TimeUnit * during the lifetime of the returned Observable. If this ConnectableObservable * terminates, the connection is never renewed, no matter how Observers come * and go. Use {@link #refCount()} to renew a connection or dispose an active - * connection when all {@code Observers}s have disposed their {@code Disposable}s. + * connection when all {@code Observer}s have disposed their {@code Disposable}s. * <p> * This overload does not allow disconnecting the connection established via * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload @@ -227,7 +227,7 @@ public Observable<T> autoConnect() { * during the lifetime of the returned Observable. If this ConnectableObservable * terminates, the connection is never renewed, no matter how Observers come * and go. Use {@link #refCount()} to renew a connection or dispose an active - * connection when all {@code Observers}s have disposed their {@code Disposable}s. + * connection when all {@code Observer}s have disposed their {@code Disposable}s. * <p> * This overload does not allow disconnecting the connection established via * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload @@ -255,7 +255,7 @@ public Observable<T> autoConnect(int numberOfSubscribers) { * during the lifetime of the returned Observable. If this ConnectableObservable * terminates, the connection is never renewed, no matter how Observers come * and go. Use {@link #refCount()} to renew a connection or dispose an active - * connection when all {@code Observers}s have disposed their {@code Disposable}s. + * connection when all {@code Observer}s have disposed their {@code Disposable}s. * * @param numberOfSubscribers the number of subscribers to await before calling connect * on the ConnectableObservable. A non-positive value indicates From fd48d56266bf0664568226160516b182e046a62a Mon Sep 17 00:00:00 2001 From: Raiymbek Kapishev <r.kapishev@gmail.com> Date: Sun, 23 Sep 2018 16:12:56 +0400 Subject: [PATCH 284/417] Fix typos (#6223) - Add space on README.md page --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 92bdf2946f..3fcaf292d2 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ The preparation of dataflows by applying various intermediate operators happens ```java Flowable<Integer> flow = Flowable.range(1, 5) -.map(v -> v* v) +.map(v -> v * v) .filter(v -> v % 3 == 0) ; ``` From 1ea1e2abfe7f31a95a7a49cb938a8195216426b7 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sun, 30 Sep 2018 11:38:06 +0200 Subject: [PATCH 285/417] 2.x: Cleanup Observable.flatMap drain logic (#6232) --- .../observable/ObservableFlatMap.java | 40 ++++++----------- .../observable/ObservableFlatMapTest.java | 43 ++++++++++++++++++- 2 files changed, 55 insertions(+), 28 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java index 9039aa78a6..551ceba280 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java @@ -338,23 +338,17 @@ void drainLoop() { if (svq != null) { for (;;) { - U o; - for (;;) { - if (checkTerminate()) { - return; - } - - o = svq.poll(); + if (checkTerminate()) { + return; + } - if (o == null) { - break; - } + U o = svq.poll(); - child.onNext(o); - } if (o == null) { break; } + + child.onNext(o); } } @@ -415,17 +409,10 @@ void drainLoop() { @SuppressWarnings("unchecked") InnerObserver<T, U> is = (InnerObserver<T, U>)inner[j]; - - for (;;) { - if (checkTerminate()) { - return; - } - SimpleQueue<U> q = is.queue; - if (q == null) { - break; - } - U o; + SimpleQueue<U> q = is.queue; + if (q != null) { for (;;) { + U o; try { o = q.poll(); } catch (Throwable ex) { @@ -437,7 +424,10 @@ void drainLoop() { } removeInner(is); innerCompleted = true; - i++; + j++; + if (j == n) { + j = 0; + } continue sourceLoop; } if (o == null) { @@ -450,10 +440,8 @@ void drainLoop() { return; } } - if (o == null) { - break; - } } + boolean innerDone = is.done; SimpleQueue<U> innerQueue = is.queue; if (innerDone && (innerQueue == null || innerQueue.isEmpty())) { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index 22a6889abc..c0cb65abe9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -26,14 +26,14 @@ import io.reactivex.*; import io.reactivex.Observable; import io.reactivex.Observer; -import io.reactivex.disposables.Disposable; +import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; -import io.reactivex.subjects.PublishSubject; +import io.reactivex.subjects.*; public class ObservableFlatMapTest { @Test @@ -1006,4 +1006,43 @@ public void onNext(Integer t) { to.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } + + @Test + public void fusedSourceCrashResumeWithNextSource() { + final UnicastSubject<Integer> fusedSource = UnicastSubject.create(); + TestObserver<Integer> to = new TestObserver<Integer>(); + + ObservableFlatMap.MergeObserver<Integer, Integer> merger = + new ObservableFlatMap.MergeObserver<Integer, Integer>(to, new Function<Integer, Observable<Integer>>() { + @Override + public Observable<Integer> apply(Integer t) + throws Exception { + if (t == 0) { + return fusedSource + .map(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer v) + throws Exception { throw new TestException(); } + }) + .compose(TestHelper.<Integer>observableStripBoundary()); + } + return Observable.range(10 * t, 5); + } + }, true, Integer.MAX_VALUE, 128); + + merger.onSubscribe(Disposables.empty()); + merger.getAndIncrement(); + + merger.onNext(0); + merger.onNext(1); + merger.onNext(2); + + assertTrue(fusedSource.hasObservers()); + + fusedSource.onNext(-1); + + merger.drainLoop(); + + to.assertValuesOnly(10, 11, 12, 13, 14, 20, 21, 22, 23, 24); + } } From 6126752a3a26e084af4cd0e096d77b94ce2a8f94 Mon Sep 17 00:00:00 2001 From: "Artem Zinnatullin :slowpoke" <ceo@artemzin.com> Date: Tue, 2 Oct 2018 00:52:42 -0700 Subject: [PATCH 286/417] Add timeout and unit to TimeoutException message (#6234) * Add timeout and unit to TimeoutException message * New timeout message, add tests --- .../observers/BlockingMultiObserver.java | 4 +- .../internal/observers/FutureObserver.java | 4 +- .../observers/FutureSingleObserver.java | 4 +- .../completable/CompletableTimeout.java | 4 +- .../flowable/FlowableTimeoutTimed.java | 4 +- .../observable/ObservableTimeoutTimed.java | 4 +- .../operators/single/SingleTimeout.java | 14 +++++-- .../subscribers/FutureSubscriber.java | 4 +- .../internal/util/ExceptionHelper.java | 9 +++++ .../observers/BlockingMultiObserverTest.java | 15 ++++++++ .../observers/FutureObserverTest.java | 11 ++++++ .../observers/FutureSingleObserverTest.java | 5 ++- .../completable/CompletableTimeoutTest.java | 3 +- .../flowable/FlowableTimeoutTests.java | 35 ++++++++---------- .../observable/ObservableTimeoutTests.java | 37 ++++++++----------- .../operators/single/SingleTimeoutTest.java | 12 ++++++ .../subscribers/FutureSubscriberTest.java | 11 ++++++ 17 files changed, 125 insertions(+), 55 deletions(-) diff --git a/src/main/java/io/reactivex/internal/observers/BlockingMultiObserver.java b/src/main/java/io/reactivex/internal/observers/BlockingMultiObserver.java index d96f3efa21..2b5f5603e0 100644 --- a/src/main/java/io/reactivex/internal/observers/BlockingMultiObserver.java +++ b/src/main/java/io/reactivex/internal/observers/BlockingMultiObserver.java @@ -19,6 +19,8 @@ import io.reactivex.disposables.Disposable; import io.reactivex.internal.util.*; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; + /** * A combined Observer that awaits the success or error signal via a CountDownLatch. * @param <T> the value type @@ -148,7 +150,7 @@ public Throwable blockingGetError(long timeout, TimeUnit unit) { BlockingHelper.verifyNonBlocking(); if (!await(timeout, unit)) { dispose(); - throw ExceptionHelper.wrapOrThrow(new TimeoutException()); + throw ExceptionHelper.wrapOrThrow(new TimeoutException(timeoutMessage(timeout, unit))); } } catch (InterruptedException ex) { dispose(); diff --git a/src/main/java/io/reactivex/internal/observers/FutureObserver.java b/src/main/java/io/reactivex/internal/observers/FutureObserver.java index b3de7f40b8..9b0d12140a 100644 --- a/src/main/java/io/reactivex/internal/observers/FutureObserver.java +++ b/src/main/java/io/reactivex/internal/observers/FutureObserver.java @@ -23,6 +23,8 @@ import io.reactivex.internal.util.BlockingHelper; import io.reactivex.plugins.RxJavaPlugins; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; + /** * An Observer + Future that expects exactly one upstream value and provides it * via the (blocking) Future API. @@ -92,7 +94,7 @@ public T get(long timeout, TimeUnit unit) throws InterruptedException, Execution if (getCount() != 0) { BlockingHelper.verifyNonBlocking(); if (!await(timeout, unit)) { - throw new TimeoutException(); + throw new TimeoutException(timeoutMessage(timeout, unit)); } } diff --git a/src/main/java/io/reactivex/internal/observers/FutureSingleObserver.java b/src/main/java/io/reactivex/internal/observers/FutureSingleObserver.java index fb3b096855..1ad8242b5c 100644 --- a/src/main/java/io/reactivex/internal/observers/FutureSingleObserver.java +++ b/src/main/java/io/reactivex/internal/observers/FutureSingleObserver.java @@ -22,6 +22,8 @@ import io.reactivex.internal.util.BlockingHelper; import io.reactivex.plugins.RxJavaPlugins; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; + /** * An Observer + Future that expects exactly one upstream value and provides it * via the (blocking) Future API. @@ -91,7 +93,7 @@ public T get(long timeout, TimeUnit unit) throws InterruptedException, Execution if (getCount() != 0) { BlockingHelper.verifyNonBlocking(); if (!await(timeout, unit)) { - throw new TimeoutException(); + throw new TimeoutException(timeoutMessage(timeout, unit)); } } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableTimeout.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableTimeout.java index 90d36ad103..c11daa7342 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableTimeout.java @@ -20,6 +20,8 @@ import io.reactivex.disposables.*; import io.reactivex.plugins.RxJavaPlugins; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; + public final class CompletableTimeout extends Completable { final CompletableSource source; @@ -104,7 +106,7 @@ public void run() { if (once.compareAndSet(false, true)) { set.clear(); if (other == null) { - downstream.onError(new TimeoutException()); + downstream.onError(new TimeoutException(timeoutMessage(timeout, unit))); } else { other.subscribe(new DisposeObserver()); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java index 28f00cfe1b..54a2762dfc 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java @@ -23,6 +23,8 @@ import io.reactivex.internal.subscriptions.*; import io.reactivex.plugins.RxJavaPlugins; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; + public final class FlowableTimeoutTimed<T> extends AbstractFlowableWithUpstream<T, T> { final long timeout; final TimeUnit unit; @@ -134,7 +136,7 @@ public void onTimeout(long idx) { if (compareAndSet(idx, Long.MAX_VALUE)) { SubscriptionHelper.cancel(upstream); - downstream.onError(new TimeoutException()); + downstream.onError(new TimeoutException(timeoutMessage(timeout, unit))); worker.dispose(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java index 7ceda44b73..9e3cb8a945 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTimeoutTimed.java @@ -21,6 +21,8 @@ import io.reactivex.internal.disposables.*; import io.reactivex.plugins.RxJavaPlugins; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; + public final class ObservableTimeoutTimed<T> extends AbstractObservableWithUpstream<T, T> { final long timeout; final TimeUnit unit; @@ -129,7 +131,7 @@ public void onTimeout(long idx) { if (compareAndSet(idx, Long.MAX_VALUE)) { DisposableHelper.dispose(upstream); - downstream.onError(new TimeoutException()); + downstream.onError(new TimeoutException(timeoutMessage(timeout, unit))); worker.dispose(); } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java b/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java index 4c97882d62..ea4212f0ec 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleTimeout.java @@ -21,6 +21,8 @@ import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.plugins.RxJavaPlugins; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; + public final class SingleTimeout<T> extends Single<T> { final SingleSource<T> source; @@ -45,7 +47,7 @@ public SingleTimeout(SingleSource<T> source, long timeout, TimeUnit unit, Schedu @Override protected void subscribeActual(final SingleObserver<? super T> observer) { - TimeoutMainObserver<T> parent = new TimeoutMainObserver<T>(observer, other); + TimeoutMainObserver<T> parent = new TimeoutMainObserver<T>(observer, other, timeout, unit); observer.onSubscribe(parent); DisposableHelper.replace(parent.task, scheduler.scheduleDirect(parent, timeout, unit)); @@ -66,6 +68,10 @@ static final class TimeoutMainObserver<T> extends AtomicReference<Disposable> SingleSource<? extends T> other; + final long timeout; + + final TimeUnit unit; + static final class TimeoutFallbackObserver<T> extends AtomicReference<Disposable> implements SingleObserver<T> { @@ -92,9 +98,11 @@ public void onError(Throwable e) { } } - TimeoutMainObserver(SingleObserver<? super T> actual, SingleSource<? extends T> other) { + TimeoutMainObserver(SingleObserver<? super T> actual, SingleSource<? extends T> other, long timeout, TimeUnit unit) { this.downstream = actual; this.other = other; + this.timeout = timeout; + this.unit = unit; this.task = new AtomicReference<Disposable>(); if (other != null) { this.fallback = new TimeoutFallbackObserver<T>(actual); @@ -112,7 +120,7 @@ public void run() { } SingleSource<? extends T> other = this.other; if (other == null) { - downstream.onError(new TimeoutException()); + downstream.onError(new TimeoutException(timeoutMessage(timeout, unit))); } else { this.other = null; other.subscribe(fallback); diff --git a/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java index 1cc2eb2e09..a559749fb1 100644 --- a/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java @@ -24,6 +24,8 @@ import io.reactivex.internal.util.BlockingHelper; import io.reactivex.plugins.RxJavaPlugins; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; + /** * A Subscriber + Future that expects exactly one upstream value and provides it * via the (blocking) Future API. @@ -93,7 +95,7 @@ public T get(long timeout, TimeUnit unit) throws InterruptedException, Execution if (getCount() != 0) { BlockingHelper.verifyNonBlocking(); if (!await(timeout, unit)) { - throw new TimeoutException(); + throw new TimeoutException(timeoutMessage(timeout, unit)); } } diff --git a/src/main/java/io/reactivex/internal/util/ExceptionHelper.java b/src/main/java/io/reactivex/internal/util/ExceptionHelper.java index 002f2df215..b6fb4e9196 100644 --- a/src/main/java/io/reactivex/internal/util/ExceptionHelper.java +++ b/src/main/java/io/reactivex/internal/util/ExceptionHelper.java @@ -14,6 +14,7 @@ package io.reactivex.internal.util; import java.util.*; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import io.reactivex.exceptions.CompositeException; @@ -121,6 +122,14 @@ public static <E extends Throwable> Exception throwIfThrowable(Throwable e) thro throw (E)e; } + public static String timeoutMessage(long timeout, TimeUnit unit) { + return "The source did not signal an event for " + + timeout + + " " + + unit.toString().toLowerCase() + + " and has been terminated."; + } + static final class Termination extends Throwable { private static final long serialVersionUID = -4649703670690200604L; diff --git a/src/test/java/io/reactivex/internal/observers/BlockingMultiObserverTest.java b/src/test/java/io/reactivex/internal/observers/BlockingMultiObserverTest.java index 6b4238f8f6..793253504b 100644 --- a/src/test/java/io/reactivex/internal/observers/BlockingMultiObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/BlockingMultiObserverTest.java @@ -13,9 +13,11 @@ package io.reactivex.internal.observers; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.junit.Test; @@ -132,4 +134,17 @@ public void run() { assertTrue(bmo.blockingGetError(1, TimeUnit.MINUTES) instanceof TestException); } + + @Test + public void blockingGetErrorTimedOut() { + final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<Integer>(); + + try { + assertNull(bmo.blockingGetError(1, TimeUnit.NANOSECONDS)); + fail("Should have thrown"); + } catch (RuntimeException expected) { + assertEquals(TimeoutException.class, expected.getCause().getClass()); + assertEquals(timeoutMessage(1, TimeUnit.NANOSECONDS), expected.getCause().getMessage()); + } + } } diff --git a/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java b/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java index bf91a78a4e..7ee71945bc 100644 --- a/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/FutureObserverTest.java @@ -13,6 +13,7 @@ package io.reactivex.internal.observers; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; import java.util.*; @@ -352,4 +353,14 @@ public void run() { assertEquals(1, fo.get().intValue()); } + + @Test + public void getTimedOut() throws Exception { + try { + fo.get(1, TimeUnit.NANOSECONDS); + fail("Should have thrown"); + } catch (TimeoutException expected) { + assertEquals(timeoutMessage(1, TimeUnit.NANOSECONDS), expected.getMessage()); + } + } } diff --git a/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java b/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java index 1dc0451434..9cafad4569 100644 --- a/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java +++ b/src/test/java/io/reactivex/internal/observers/FutureSingleObserverTest.java @@ -13,6 +13,7 @@ package io.reactivex.internal.observers; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; import java.util.concurrent.*; @@ -89,8 +90,8 @@ public void timeout() throws Exception { try { f.get(100, TimeUnit.MILLISECONDS); fail("Should have thrown"); - } catch (TimeoutException ex) { - // expected + } catch (TimeoutException expected) { + assertEquals(timeoutMessage(100, TimeUnit.MILLISECONDS), expected.getMessage()); } } diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java index 3df78394f3..a0de2b25aa 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java @@ -13,6 +13,7 @@ package io.reactivex.internal.operators.completable; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; import java.util.List; @@ -40,7 +41,7 @@ public void timeoutException() throws Exception { .timeout(100, TimeUnit.MILLISECONDS, Schedulers.io()) .test() .awaitDone(5, TimeUnit.SECONDS) - .assertFailure(TimeoutException.class); + .assertFailureAndMessage(TimeoutException.class, timeoutMessage(100, TimeUnit.MILLISECONDS)); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java index 8ba33edca7..7e4b97c899 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java @@ -13,6 +13,7 @@ package io.reactivex.internal.operators.flowable; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; @@ -82,26 +83,24 @@ public void shouldNotTimeoutIfSecondOnNextWithinTimeout() { @Test public void shouldTimeoutIfOnNextNotWithinTimeout() { - Subscriber<String> subscriber = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); + TestSubscriber<String> subscriber = new TestSubscriber<String>(); - withTimeout.subscribe(ts); + withTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(TIMEOUT + 1, TimeUnit.SECONDS); - verify(subscriber).onError(any(TimeoutException.class)); - ts.dispose(); + subscriber.assertFailureAndMessage(TimeoutException.class, timeoutMessage(TIMEOUT, TIME_UNIT)); } @Test public void shouldTimeoutIfSecondOnNextNotWithinTimeout() { - Subscriber<String> subscriber = TestHelper.mockSubscriber(); + TestSubscriber<String> subscriber = new TestSubscriber<String>(); TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); withTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); - verify(subscriber).onNext("One"); + subscriber.assertValue("One"); testScheduler.advanceTimeBy(TIMEOUT + 1, TimeUnit.SECONDS); - verify(subscriber).onError(any(TimeoutException.class)); + subscriber.assertFailureAndMessage(TimeoutException.class, timeoutMessage(TIMEOUT, TIME_UNIT), "One"); ts.dispose(); } @@ -235,8 +234,7 @@ public void shouldTimeoutIfSynchronizedFlowableEmitFirstOnNextNotWithinTimeout() final CountDownLatch exit = new CountDownLatch(1); final CountDownLatch timeoutSetuped = new CountDownLatch(1); - final Subscriber<String> subscriber = TestHelper.mockSubscriber(); - final TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); + final TestSubscriber<String> subscriber = new TestSubscriber<String>(); new Thread(new Runnable() { @@ -258,16 +256,14 @@ public void subscribe(Subscriber<? super String> subscriber) { } }).timeout(1, TimeUnit.SECONDS, testScheduler) - .subscribe(ts); + .subscribe(subscriber); } }).start(); timeoutSetuped.await(); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); - InOrder inOrder = inOrder(subscriber); - inOrder.verify(subscriber, times(1)).onError(isA(TimeoutException.class)); - inOrder.verifyNoMoreInteractions(); + subscriber.assertFailureAndMessage(TimeoutException.class, timeoutMessage(1, TimeUnit.SECONDS)); exit.countDown(); // exit the thread } @@ -287,15 +283,12 @@ public void subscribe(Subscriber<? super String> subscriber) { TestScheduler testScheduler = new TestScheduler(); Flowable<String> observableWithTimeout = never.timeout(1000, TimeUnit.MILLISECONDS, testScheduler); - Subscriber<String> subscriber = TestHelper.mockSubscriber(); - TestSubscriber<String> ts = new TestSubscriber<String>(subscriber); - observableWithTimeout.subscribe(ts); + TestSubscriber<String> subscriber = new TestSubscriber<String>(); + observableWithTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(2000, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(subscriber); - inOrder.verify(subscriber).onError(isA(TimeoutException.class)); - inOrder.verifyNoMoreInteractions(); + subscriber.assertFailureAndMessage(TimeoutException.class, timeoutMessage(1000, TimeUnit.MILLISECONDS)); verify(s, times(1)).cancel(); } @@ -548,11 +541,13 @@ public void run() { if (ts.valueCount() != 0) { if (ts.errorCount() != 0) { ts.assertFailure(TimeoutException.class, 1); + ts.assertErrorMessage(timeoutMessage(1, TimeUnit.SECONDS)); } else { ts.assertValuesOnly(1); } } else { ts.assertFailure(TimeoutException.class); + ts.assertErrorMessage(timeoutMessage(1, TimeUnit.SECONDS)); } } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java index 21e8caea84..935922b67c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java @@ -13,6 +13,7 @@ package io.reactivex.internal.operators.observable; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; @@ -81,27 +82,23 @@ public void shouldNotTimeoutIfSecondOnNextWithinTimeout() { @Test public void shouldTimeoutIfOnNextNotWithinTimeout() { - Observer<String> observer = TestHelper.mockObserver(); - TestObserver<String> to = new TestObserver<String>(observer); + TestObserver<String> observer = new TestObserver<String>(); - withTimeout.subscribe(to); + withTimeout.subscribe(observer); testScheduler.advanceTimeBy(TIMEOUT + 1, TimeUnit.SECONDS); - verify(observer).onError(any(TimeoutException.class)); - to.dispose(); + observer.assertFailureAndMessage(TimeoutException.class, timeoutMessage(TIMEOUT, TIME_UNIT)); } @Test public void shouldTimeoutIfSecondOnNextNotWithinTimeout() { - Observer<String> observer = TestHelper.mockObserver(); - TestObserver<String> to = new TestObserver<String>(observer); + TestObserver<String> observer = new TestObserver<String>(); withTimeout.subscribe(observer); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); - verify(observer).onNext("One"); + observer.assertValue("One"); testScheduler.advanceTimeBy(TIMEOUT + 1, TimeUnit.SECONDS); - verify(observer).onError(any(TimeoutException.class)); - to.dispose(); + observer.assertFailureAndMessage(TimeoutException.class, timeoutMessage(TIMEOUT, TIME_UNIT), "One"); } @Test @@ -234,8 +231,7 @@ public void shouldTimeoutIfSynchronizedObservableEmitFirstOnNextNotWithinTimeout final CountDownLatch exit = new CountDownLatch(1); final CountDownLatch timeoutSetuped = new CountDownLatch(1); - final Observer<String> observer = TestHelper.mockObserver(); - final TestObserver<String> to = new TestObserver<String>(observer); + final TestObserver<String> observer = new TestObserver<String>(); new Thread(new Runnable() { @@ -257,16 +253,14 @@ public void subscribe(Observer<? super String> observer) { } }).timeout(1, TimeUnit.SECONDS, testScheduler) - .subscribe(to); + .subscribe(observer); } }).start(); timeoutSetuped.await(); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer, times(1)).onError(isA(TimeoutException.class)); - inOrder.verifyNoMoreInteractions(); + observer.assertFailureAndMessage(TimeoutException.class, timeoutMessage(1, TimeUnit.SECONDS)); exit.countDown(); // exit the thread } @@ -286,15 +280,12 @@ public void subscribe(Observer<? super String> observer) { TestScheduler testScheduler = new TestScheduler(); Observable<String> observableWithTimeout = never.timeout(1000, TimeUnit.MILLISECONDS, testScheduler); - Observer<String> observer = TestHelper.mockObserver(); - TestObserver<String> to = new TestObserver<String>(observer); - observableWithTimeout.subscribe(to); + TestObserver<String> observer = new TestObserver<String>(); + observableWithTimeout.subscribe(observer); testScheduler.advanceTimeBy(2000, TimeUnit.MILLISECONDS); - InOrder inOrder = inOrder(observer); - inOrder.verify(observer).onError(isA(TimeoutException.class)); - inOrder.verifyNoMoreInteractions(); + observer.assertFailureAndMessage(TimeoutException.class, timeoutMessage(1000, TimeUnit.MILLISECONDS)); verify(upstream, times(1)).dispose(); } @@ -547,11 +538,13 @@ public void run() { if (to.valueCount() != 0) { if (to.errorCount() != 0) { to.assertFailure(TimeoutException.class, 1); + to.assertErrorMessage(timeoutMessage(1, TimeUnit.SECONDS)); } else { to.assertValuesOnly(1); } } else { to.assertFailure(TimeoutException.class); + to.assertErrorMessage(timeoutMessage(1, TimeUnit.SECONDS)); } } } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleTimeoutTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleTimeoutTest.java index 37077a6dd2..0acbc7a9ef 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleTimeoutTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleTimeoutTest.java @@ -13,10 +13,12 @@ package io.reactivex.internal.operators.single; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.junit.Test; @@ -209,4 +211,14 @@ public void run() { RxJavaPlugins.reset(); } } + + @Test + public void mainTimedOut() { + Single + .never() + .timeout(1, TimeUnit.NANOSECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertFailureAndMessage(TimeoutException.class, timeoutMessage(1, TimeUnit.NANOSECONDS)); + } } diff --git a/src/test/java/io/reactivex/internal/subscribers/FutureSubscriberTest.java b/src/test/java/io/reactivex/internal/subscribers/FutureSubscriberTest.java index baef7a9176..2aa9ec7a25 100644 --- a/src/test/java/io/reactivex/internal/subscribers/FutureSubscriberTest.java +++ b/src/test/java/io/reactivex/internal/subscribers/FutureSubscriberTest.java @@ -13,6 +13,7 @@ package io.reactivex.internal.subscribers; +import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; import java.util.*; @@ -281,4 +282,14 @@ public void run() { assertEquals(1, fs.get().intValue()); } + + @Test + public void getTimedOut() throws Exception { + try { + fs.get(1, TimeUnit.NANOSECONDS); + fail("Should have thrown"); + } catch (TimeoutException expected) { + assertEquals(timeoutMessage(1, TimeUnit.NANOSECONDS), expected.getMessage()); + } + } } From a04ade55d9a5053de7e5d49dd67edc8e23627db9 Mon Sep 17 00:00:00 2001 From: V <m3sv@users.noreply.github.com> Date: Tue, 2 Oct 2018 19:16:15 +0300 Subject: [PATCH 287/417] Fix docs typos (#6235) --- docs/Combining-Observables.md | 12 +++---- docs/Creating-Observables.md | 20 ++++++------ docs/Mathematical-and-Aggregate-Operators.md | 34 ++++++++++---------- 3 files changed, 33 insertions(+), 33 deletions(-) diff --git a/docs/Combining-Observables.md b/docs/Combining-Observables.md index 0e3796da1f..bcc19f6b0f 100644 --- a/docs/Combining-Observables.md +++ b/docs/Combining-Observables.md @@ -15,7 +15,7 @@ This section explains operators you can use to combine multiple Observables. **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/startwith.html](http://reactivex.io/documentation/operators/startwith.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/startwith.html](http://reactivex.io/documentation/operators/startwith.html) Emit a specified sequence of items before beginning to emit the items from the Observable. @@ -37,7 +37,7 @@ Combines multiple Observables into one. **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/merge.html](http://reactivex.io/documentation/operators/merge.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/merge.html](http://reactivex.io/documentation/operators/merge.html) Combines multiple Observables into one. Any `onError` notifications passed from any of the source observables will immediately be passed through to through to the observers and will terminate the merged `Observable`. @@ -55,7 +55,7 @@ Observable.just(1, 2, 3) **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/merge.html](http://reactivex.io/documentation/operators/merge.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/merge.html](http://reactivex.io/documentation/operators/merge.html) Combines multiple Observables into one. Any `onError` notifications passed from any of the source observables will be withheld until all merged Observables complete, and only then will be passed along to the observers. @@ -75,7 +75,7 @@ Observable.mergeDelayError(observable1, observable2) **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/zip.html](http://reactivex.io/documentation/operators/zip.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/zip.html](http://reactivex.io/documentation/operators/zip.html) Combines sets of items emitted by two or more Observables together via a specified function and emit items based on the results of this function. @@ -94,7 +94,7 @@ firstNames.zipWith(lastNames, (first, last) -> first + " " + last) **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/combinelatest.html](http://reactivex.io/documentation/operators/combinelatest.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/combinelatest.html](http://reactivex.io/documentation/operators/combinelatest.html) When an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function. @@ -124,7 +124,7 @@ Observable.combineLatest(newsRefreshes, weatherRefreshes, **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/switch.html](http://reactivex.io/documentation/operators/switch.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/switch.html](http://reactivex.io/documentation/operators/switch.html) Convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently emitted of those Observables. diff --git a/docs/Creating-Observables.md b/docs/Creating-Observables.md index b167c4d866..4d26bbf2b1 100644 --- a/docs/Creating-Observables.md +++ b/docs/Creating-Observables.md @@ -17,7 +17,7 @@ This page shows methods that create reactive sources, such as `Observable`s. **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/just.html](http://reactivex.io/documentation/operators/just.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/just.html](http://reactivex.io/documentation/operators/just.html) Constructs a reactive type by taking a pre-existing object and emitting that specific object to the downstream consumer upon subscription. @@ -46,7 +46,7 @@ Constructs a sequence from a pre-existing source or generator type. *Note: These static methods use the postfix naming convention (i.e., the argument type is repeated in the method name) to avoid overload resolution ambiguities.* -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/from.html](http://reactivex.io/documentation/operators/from.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/from.html](http://reactivex.io/documentation/operators/from.html) ### fromIterable @@ -203,7 +203,7 @@ observable.subscribe( **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/create.html](http://reactivex.io/documentation/operators/create.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/create.html](http://reactivex.io/documentation/operators/create.html) Construct a **safe** reactive type instance which when subscribed to by a consumer, runs an user-provided function and provides a type-specific `Emitter` for this function to generate the signal(s) the designated business logic requires. This method allows bridging the non-reactive, usually listener/callback-style world, with the reactive world. @@ -239,7 +239,7 @@ executor.shutdown(); **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/defer.html](http://reactivex.io/documentation/operators/defer.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/defer.html](http://reactivex.io/documentation/operators/defer.html) Calls an user-provided `java.util.concurrent.Callable` when a consumer subscribes to the reactive type so that the `Callable` can generate the actual reactive instance to relay signals from towards the consumer. `defer` allows: @@ -266,7 +266,7 @@ observable.subscribe(time -> System.out.println(time)); **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/range.html](http://reactivex.io/documentation/operators/range.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/range.html](http://reactivex.io/documentation/operators/range.html) Generates a sequence of values to each individual consumer. The `range()` method generates `Integer`s, the `rangeLong()` generates `Long`s. @@ -287,7 +287,7 @@ characters.subscribe(character -> System.out.print(character), erro -> error.pri **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/interval.html](http://reactivex.io/documentation/operators/interval.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/interval.html](http://reactivex.io/documentation/operators/interval.html) Periodically generates an infinite, ever increasing numbers (of type `Long`). The `intervalRange` variant generates a limited amount of such numbers. @@ -309,7 +309,7 @@ clock.subscribe(time -> { **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/timer.html](http://reactivex.io/documentation/operators/timer.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/timer.html](http://reactivex.io/documentation/operators/timer.html) After the specified time, this reactive source signals a single `0L` (then completes for `Flowable` and `Observable`). @@ -325,7 +325,7 @@ eggTimer.blockingSubscribe(v -> System.out.println("Egg is ready!")); **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/empty-never-throw.html](http://reactivex.io/documentation/operators/empty-never-throw.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/empty-never-throw.html](http://reactivex.io/documentation/operators/empty-never-throw.html) This type of source signals completion immediately upon subscription. @@ -344,7 +344,7 @@ empty.subscribe( **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/empty-never-throw.html](http://reactivex.io/documentation/operators/empty-never-throw.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/empty-never-throw.html](http://reactivex.io/documentation/operators/empty-never-throw.html) This type of source does not signal any `onNext`, `onSuccess`, `onError` or `onComplete`. This type of reactive source is useful in testing or "disabling" certain sources in combinator operators. @@ -363,7 +363,7 @@ never.subscribe( **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/empty-never-throw.html](http://reactivex.io/documentation/operators/empty-never-throw.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/empty-never-throw.html](http://reactivex.io/documentation/operators/empty-never-throw.html) Signal an error, either pre-existing or generated via a `java.util.concurrent.Callable`, to the consumer. diff --git a/docs/Mathematical-and-Aggregate-Operators.md b/docs/Mathematical-and-Aggregate-Operators.md index 574111ad0e..f6bf79019e 100644 --- a/docs/Mathematical-and-Aggregate-Operators.md +++ b/docs/Mathematical-and-Aggregate-Operators.md @@ -39,7 +39,7 @@ import hu.akarnokd.rxjava2.math.MathFlowable; **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/average.html](http://reactivex.io/documentation/operators/average.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/average.html](http://reactivex.io/documentation/operators/average.html) Calculates the average of `Number`s emitted by an `Observable` and emits this average as a `Double`. @@ -56,7 +56,7 @@ MathObservable.averageDouble(numbers).subscribe((Double avg) -> System.out.print **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/average.html](http://reactivex.io/documentation/operators/average.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/average.html](http://reactivex.io/documentation/operators/average.html) Calculates the average of `Number`s emitted by an `Observable` and emits this average as a `Float`. @@ -73,7 +73,7 @@ MathObservable.averageFloat(numbers).subscribe((Float avg) -> System.out.println **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/max.html](http://reactivex.io/documentation/operators/max.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/max.html](http://reactivex.io/documentation/operators/max.html) Emits the maximum value emitted by a source `Observable`. A `Comparator` can be specified that will be used to compare the elements emitted by the `Observable`. @@ -100,7 +100,7 @@ MathObservable.max(names, Comparator.comparingInt(String::length)) **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/min.html](http://reactivex.io/documentation/operators/min.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/min.html](http://reactivex.io/documentation/operators/min.html) Emits the minimum value emitted by a source `Observable`. A `Comparator` can be specified that will be used to compare the elements emitted by the `Observable`. @@ -117,7 +117,7 @@ MathObservable.min(numbers).subscribe(System.out::println); **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) Adds the `Double`s emitted by an `Observable` and emits this sum. @@ -134,7 +134,7 @@ MathObservable.sumDouble(numbers).subscribe((Double sum) -> System.out.println(s **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) Adds the `Float`s emitted by an `Observable` and emits this sum. @@ -151,7 +151,7 @@ MathObservable.sumFloat(numbers).subscribe((Float sum) -> System.out.println(sum **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) Adds the `Integer`s emitted by an `Observable` and emits this sum. @@ -168,7 +168,7 @@ MathObservable.sumInt(numbers).subscribe((Integer sum) -> System.out.println(sum **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/sum.html](http://reactivex.io/documentation/operators/sum.html) Adds the `Long`s emitted by an `Observable` and emits this sum. @@ -189,7 +189,7 @@ MathObservable.sumLong(numbers).subscribe((Long sum) -> System.out.println(sum)) **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/count.html](http://reactivex.io/documentation/operators/count.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/count.html](http://reactivex.io/documentation/operators/count.html) Counts the number of items emitted by an `Observable` and emits this count as a `Long`. @@ -205,7 +205,7 @@ Observable.just(1, 2, 3).count().subscribe(System.out::println); **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) Apply a function to each emitted item, sequentially, and emit only the final accumulated value. @@ -223,7 +223,7 @@ Observable.range(1, 5) **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) Apply a function to each emitted item, sequentially, and emit only the final accumulated value. @@ -245,7 +245,7 @@ Observable.just(1, 2, 2, 3, 4, 4, 4, 5) **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) Collect items emitted by the source `Observable` into a single mutable data structure and return an `Observable` that emits this structure. @@ -264,7 +264,7 @@ Observable.just("Kirk", "Spock", "Chekov", "Sulu") **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/reduce.html](http://reactivex.io/documentation/operators/reduce.html) Collect items emitted by the source `Observable` into a single mutable data structure and return an `Observable` that emits this structure. @@ -285,7 +285,7 @@ Observable.just('R', 'x', 'J', 'a', 'v', 'a') **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) Collect all items from an `Observable` and emit them as a single `List`. @@ -303,7 +303,7 @@ Observable.just(2, 1, 3) **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) Collect all items from an `Observable` and emit them as a single, sorted `List`. @@ -321,7 +321,7 @@ Observable.just(2, 1, 3) **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) Convert the sequence of items emitted by an `Observable` into a `Map` keyed by a specified key function. @@ -345,7 +345,7 @@ Observable.just(1, 2, 3, 4) **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` -**ReactiveX doumentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/to.html](http://reactivex.io/documentation/operators/to.html) Convert the sequence of items emitted by an `Observable` into a `Collection` that is also a `Map` keyed by a specified key function. From 2ad63c4431c71366b4be6b43d59cb7912f7653fa Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 3 Oct 2018 21:57:24 +0200 Subject: [PATCH 288/417] 2.x: Adjust Undeliverable & OnErrorNotImpl message to use full inner (#6236) --- .../io/reactivex/exceptions/OnErrorNotImplementedException.java | 2 +- .../java/io/reactivex/exceptions/UndeliverableException.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java b/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java index 6fdc42aeec..1cfe421916 100644 --- a/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java +++ b/src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java @@ -48,6 +48,6 @@ public OnErrorNotImplementedException(String message, @NonNull Throwable e) { * the {@code Throwable} to signal; if null, a NullPointerException is constructed */ public OnErrorNotImplementedException(@NonNull Throwable e) { - this("The exception was not handled due to missing onError handler in the subscribe() method call. Further reading: https://github.com/ReactiveX/RxJava/wiki/Error-Handling | " + (e != null ? e.getMessage() : ""), e); + this("The exception was not handled due to missing onError handler in the subscribe() method call. Further reading: https://github.com/ReactiveX/RxJava/wiki/Error-Handling | " + e, e); } } \ No newline at end of file diff --git a/src/main/java/io/reactivex/exceptions/UndeliverableException.java b/src/main/java/io/reactivex/exceptions/UndeliverableException.java index d8bb99ce5c..d3923e0cdd 100644 --- a/src/main/java/io/reactivex/exceptions/UndeliverableException.java +++ b/src/main/java/io/reactivex/exceptions/UndeliverableException.java @@ -28,6 +28,6 @@ public final class UndeliverableException extends IllegalStateException { * @param cause the cause, not null */ public UndeliverableException(Throwable cause) { - super("The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | " + cause.getMessage(), cause); + super("The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | " + cause, cause); } } From 17f6e840e437ac90e81f2f2d369e25d4bcbde9ff Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 9 Oct 2018 15:01:04 +0200 Subject: [PATCH 289/417] 2.x Wiki: Remove mention of i.r.f.Functions (#6241) The `io.reactivex.functions.Functions` utility method has been made internal a long ago and should not be mentioned. --- docs/What's-different-in-2.0.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/What's-different-in-2.0.md b/docs/What's-different-in-2.0.md index 4dbaea04b1..fac50df56d 100644 --- a/docs/What's-different-in-2.0.md +++ b/docs/What's-different-in-2.0.md @@ -294,8 +294,6 @@ We followed the naming convention of Java 8 by defining `io.reactivex.functions. In addition, operators requiring a predicate no longer use `Func1<T, Boolean>` but have a separate, primitive-returning type of `Predicate<T>` (allows better inlining due to no autoboxing). -The `io.reactivex.functions.Functions` utility class offers common function sources and conversions to `Function<Object[], R>`. - # Subscriber The Reactive-Streams specification has its own Subscriber as an interface. This interface is lightweight and combines request management with cancellation into a single interface `org.reactivestreams.Subscription` instead of having `rx.Producer` and `rx.Subscription` separately. This allows creating stream consumers with less internal state than the quite heavy `rx.Subscriber` of 1.x. @@ -969,4 +967,4 @@ Flowable.just(1, 2, 3) .doFinally(() -> System.out.println("Finally")) .take(2) // cancels the above after 2 elements .subscribe(System.out::println); -``` \ No newline at end of file +``` From a1758c4b9ba1f908b50552b92db0845686dbd6a3 Mon Sep 17 00:00:00 2001 From: Dmitry Fisenko <oknesif@gmail.com> Date: Fri, 12 Oct 2018 20:07:34 +0300 Subject: [PATCH 290/417] Add Nullable annotations for blocking methods in Completable (#6244) --- src/main/java/io/reactivex/Completable.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 704e74c613..9911261911 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1227,6 +1227,7 @@ public final boolean blockingAwait(long timeout, TimeUnit unit) { * @return the throwable if this terminated with an error, null otherwise * @throws RuntimeException that wraps an InterruptedException if the wait is interrupted */ + @Nullable @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Throwable blockingGet() { @@ -1250,6 +1251,7 @@ public final Throwable blockingGet() { * @throws RuntimeException that wraps an InterruptedException if the wait is interrupted or * TimeoutException if the specified timeout elapsed before it */ + @Nullable @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Throwable blockingGet(long timeout, TimeUnit unit) { From f78bd953e6d09792d2ba2aa1c3fce0f7c9110810 Mon Sep 17 00:00:00 2001 From: soshial <soshial@users.noreply.github.com> Date: Fri, 19 Oct 2018 11:16:04 +0300 Subject: [PATCH 291/417] Add delaySubscription() methods to Completable #5081 (#6242) * Add delaySubscription() methods to Completable #5081 * fix parameter test and documentation for delaySubscription() * add tests to delayCompletable() * remove mocked observer from delaySubscription() tests for Completable --- src/main/java/io/reactivex/Completable.java | 45 ++++++++++++ .../completable/CompletableDelayTest.java | 72 ++++++++++++++++++- .../ParamValidationCheckerTest.java | 4 ++ 3 files changed, 119 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 9911261911..58eddbfed8 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1390,6 +1390,51 @@ public final Completable delay(final long delay, final TimeUnit unit, final Sche return RxJavaPlugins.onAssembly(new CompletableDelay(this, delay, unit, scheduler, delayError)); } + /** + * Returns a Completable that delays the subscription to the source CompletableSource by a given amount of time. + * <p> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>This version of {@code delaySubscription} operates by default on the {@code computation} {@link Scheduler}.</dd> + * </dl> + * + * @param delay the time to delay the subscription + * @param unit the time unit of {@code delay} + * @return a Completable that delays the subscription to the source CompletableSource by the given amount + * @since 2.2.3 - experimental + * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.COMPUTATION) + public final Completable delaySubscription(long delay, TimeUnit unit) { + return delaySubscription(delay, unit, Schedulers.computation()); + } + + /** + * Returns a Completable that delays the subscription to the source CompletableSource by a given amount of time, + * both waiting and subscribing on a given Scheduler. + * <p> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>You specify which {@link Scheduler} this operator will use.</dd> + * </dl> + * + * @param delay the time to delay the subscription + * @param unit the time unit of {@code delay} + * @param scheduler the Scheduler on which the waiting and subscription will happen + * @return a Completable that delays the subscription to the source CompletableSource by a given + * amount, waiting and subscribing on the given Scheduler + * @since 2.2.3 - experimental + * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> + */ + @CheckReturnValue + @Experimental + @SchedulerSupport(SchedulerSupport.CUSTOM) + public final Completable delaySubscription(long delay, TimeUnit unit, Scheduler scheduler) { + return Completable.timer(delay, unit, scheduler).andThen(this); + } + /** * Returns a Completable which calls the given onComplete callback if this Completable completes. * <p> diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java index 174a520e0f..ea89a32a5f 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java @@ -20,11 +20,14 @@ import org.junit.Test; -import io.reactivex.*; +import io.reactivex.CompletableSource; +import io.reactivex.TestHelper; +import io.reactivex.Completable; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.observers.TestObserver; -import io.reactivex.schedulers.*; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; public class CompletableDelayTest { @@ -120,4 +123,69 @@ public void errorDelayed() { to.assertFailure(TestException.class); } + + @Test + public void errorDelayedSubscription() { + TestScheduler scheduler = new TestScheduler(); + + TestObserver<Void> to = Completable.error(new TestException()) + .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler) + .test(); + + to.assertEmpty(); + + scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); + + to.assertEmpty(); + + scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); + + to.assertFailure(TestException.class); + } + + @Test + public void errorDelayedSubscriptionDisposeBeforeTime() { + TestScheduler scheduler = new TestScheduler(); + + Completable result = Completable.complete() + .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); + TestObserver<Void> to = result.test(); + + to.assertEmpty(); + + scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); + to.dispose(); + + scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); + + to.assertEmpty(); + } + + @Test + public void testDelaySubscriptionDisposeBeforeTime() { + TestScheduler scheduler = new TestScheduler(); + + Completable result = Completable.complete() + .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); + TestObserver<Void> to = result.test(); + + to.assertEmpty(); + scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); + to.dispose(); + scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); + to.assertEmpty(); + } + + @Test + public void testDelaySubscription() { + TestScheduler scheduler = new TestScheduler(); + Completable result = Completable.complete() + .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); + TestObserver<Void> to = result.test(); + + scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); + to.assertEmpty(); + scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); + to.assertResult(); + } } diff --git a/src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java b/src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java index ac078393e1..2d7a9649b8 100644 --- a/src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java +++ b/src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java @@ -261,6 +261,10 @@ public void checkParallelFlowable() { addOverride(new ParamOverride(Completable.class, 0, ParamMode.ANY, "delay", Long.TYPE, TimeUnit.class, Scheduler.class)); addOverride(new ParamOverride(Completable.class, 0, ParamMode.ANY, "delay", Long.TYPE, TimeUnit.class, Scheduler.class, Boolean.TYPE)); + // negative time is considered as zero time + addOverride(new ParamOverride(Completable.class, 0, ParamMode.ANY, "delaySubscription", Long.TYPE, TimeUnit.class)); + addOverride(new ParamOverride(Completable.class, 0, ParamMode.ANY, "delaySubscription", Long.TYPE, TimeUnit.class, Scheduler.class)); + // zero repeat is allowed addOverride(new ParamOverride(Completable.class, 0, ParamMode.NON_NEGATIVE, "repeat", Long.TYPE)); From 2fb950427c717d953c0d72f7419ccb4692db6be4 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 19 Oct 2018 10:54:27 +0200 Subject: [PATCH 292/417] 2.x: Expand and fix Completable.delaySubscription tests (#6252) --- .../CompletableDelaySubscriptionTest.java | 169 ++++++++++++++++++ .../completable/CompletableDelayTest.java | 65 ------- 2 files changed, 169 insertions(+), 65 deletions(-) create mode 100644 src/test/java/io/reactivex/internal/operators/completable/CompletableDelaySubscriptionTest.java diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableDelaySubscriptionTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableDelaySubscriptionTest.java new file mode 100644 index 0000000000..7148233f9d --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableDelaySubscriptionTest.java @@ -0,0 +1,169 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import static org.junit.Assert.*; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import io.reactivex.Completable; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.observers.TestObserver; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subjects.CompletableSubject; + +public class CompletableDelaySubscriptionTest { + + @Test + public void normal() { + final AtomicInteger counter = new AtomicInteger(); + + Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + counter.incrementAndGet(); + } + }) + .delaySubscription(100, TimeUnit.MILLISECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(); + + assertEquals(1, counter.get()); + } + + @Test + public void error() { + final AtomicInteger counter = new AtomicInteger(); + + Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + counter.incrementAndGet(); + + throw new TestException(); + } + }) + .delaySubscription(100, TimeUnit.MILLISECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertFailure(TestException.class); + + assertEquals(1, counter.get()); + } + + @Test + public void disposeBeforeTime() { + TestScheduler scheduler = new TestScheduler(); + + final AtomicInteger counter = new AtomicInteger(); + + Completable result = Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + counter.incrementAndGet(); + } + }) + .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); + TestObserver<Void> to = result.test(); + + to.assertEmpty(); + + scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); + + to.dispose(); + + scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); + + to.assertEmpty(); + + assertEquals(0, counter.get()); + } + + @Test + public void timestep() { + TestScheduler scheduler = new TestScheduler(); + final AtomicInteger counter = new AtomicInteger(); + + Completable result = Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + counter.incrementAndGet(); + } + }) + .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); + + TestObserver<Void> to = result.test(); + + scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); + to.assertEmpty(); + scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); + to.assertResult(); + + assertEquals(1, counter.get()); + } + + @Test + public void timestepError() { + TestScheduler scheduler = new TestScheduler(); + final AtomicInteger counter = new AtomicInteger(); + + Completable result = Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + counter.incrementAndGet(); + + throw new TestException(); + } + }) + .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); + + TestObserver<Void> to = result.test(); + + scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); + + to.assertEmpty(); + + scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); + + to.assertFailure(TestException.class); + + assertEquals(1, counter.get()); + } + + @Test + public void disposeMain() { + CompletableSubject cs = CompletableSubject.create(); + + TestScheduler scheduler = new TestScheduler(); + + TestObserver<Void> to = cs + .delaySubscription(1, TimeUnit.SECONDS, scheduler) + .test(); + + assertFalse(cs.hasObservers()); + + scheduler.advanceTimeBy(1, TimeUnit.SECONDS); + + assertTrue(cs.hasObservers()); + + to.dispose(); + + assertFalse(cs.hasObservers()); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java index ea89a32a5f..be72ce0ad4 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java @@ -123,69 +123,4 @@ public void errorDelayed() { to.assertFailure(TestException.class); } - - @Test - public void errorDelayedSubscription() { - TestScheduler scheduler = new TestScheduler(); - - TestObserver<Void> to = Completable.error(new TestException()) - .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler) - .test(); - - to.assertEmpty(); - - scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); - - to.assertEmpty(); - - scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); - - to.assertFailure(TestException.class); - } - - @Test - public void errorDelayedSubscriptionDisposeBeforeTime() { - TestScheduler scheduler = new TestScheduler(); - - Completable result = Completable.complete() - .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); - TestObserver<Void> to = result.test(); - - to.assertEmpty(); - - scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); - to.dispose(); - - scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); - - to.assertEmpty(); - } - - @Test - public void testDelaySubscriptionDisposeBeforeTime() { - TestScheduler scheduler = new TestScheduler(); - - Completable result = Completable.complete() - .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); - TestObserver<Void> to = result.test(); - - to.assertEmpty(); - scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); - to.dispose(); - scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); - to.assertEmpty(); - } - - @Test - public void testDelaySubscription() { - TestScheduler scheduler = new TestScheduler(); - Completable result = Completable.complete() - .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler); - TestObserver<Void> to = result.test(); - - scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS); - to.assertEmpty(); - scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); - to.assertResult(); - } } From 8654393d7dc84545cc92077bd635e61a915db32e Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 19 Oct 2018 12:26:00 +0200 Subject: [PATCH 293/417] 2.x: Fix flaky sample() backpressure test, improve coverage (#6254) --- .../flowable/FlowableSampleTest.java | 34 ++++++++++++++++--- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java index 12e354cda2..74cbcc24c2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java @@ -13,6 +13,7 @@ package io.reactivex.internal.operators.flowable; +import static org.junit.Assert.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @@ -306,11 +307,20 @@ public void backpressureOverflow() { @Test public void backpressureOverflowWithOtherPublisher() { - BehaviorProcessor.createDefault(1) - .sample(Flowable.timer(1, TimeUnit.MILLISECONDS)) - .test(0L) - .awaitDone(5, TimeUnit.SECONDS) - .assertFailure(MissingBackpressureException.class); + PublishProcessor<Integer> pp1 = PublishProcessor.create(); + PublishProcessor<Integer> pp2 = PublishProcessor.create(); + + TestSubscriber<Integer> ts = pp1 + .sample(pp2) + .test(0L); + + pp1.onNext(1); + pp2.onNext(2); + + ts.assertFailure(MissingBackpressureException.class); + + assertFalse(pp1.hasSubscribers()); + assertFalse(pp2.hasSubscribers()); } @Test @@ -455,5 +465,19 @@ public Flowable<Object> apply(Flowable<Object> f) return f.sample(1, TimeUnit.SECONDS); } }); + + TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { + @Override + public Flowable<Object> apply(Flowable<Object> f) + throws Exception { + return f.sample(PublishProcessor.create()); + } + }); + } + + @Test + public void badRequest() { + TestHelper.assertBadRequestReported(PublishProcessor.create() + .sample(PublishProcessor.create())); } } From 378cbf92c17db3906d3a1ba5b7dc156280f4632b Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 19 Oct 2018 12:49:01 +0200 Subject: [PATCH 294/417] 2.x: Cleanup code style, commas, spaces, docs (#6255) --- .../io/reactivex/parallel/ParallelPerf.java | 2 +- .../operators/flowable/FlowableGroupBy.java | 4 +-- .../internal/queue/MpscLinkedQueue.java | 2 +- .../internal/queue/SpscArrayQueue.java | 4 +-- .../internal/queue/SpscLinkedArrayQueue.java | 28 +++++++++---------- .../internal/schedulers/IoScheduler.java | 1 + .../internal/schedulers/SingleScheduler.java | 2 ++ .../internal/util/ExceptionHelper.java | 2 +- .../processors/UnicastProcessor.java | 2 +- .../reactivex/exceptions/ExceptionsTest.java | 4 +++ .../flowable/FlowableConversionTest.java | 2 +- .../flowable/FlowableErrorHandlingTests.java | 6 ++-- .../reactivex/flowable/FlowableNullTests.java | 2 +- .../flowable/FlowableSubscriberTest.java | 11 ++++---- .../io/reactivex/flowable/FlowableTests.java | 2 +- .../flowable/FlowableBufferTest.java | 4 +-- .../flowable/FlowableCombineLatestTest.java | 4 +-- .../flowable/FlowableConcatTest.java | 4 +-- .../flowable/FlowableDefaultIfEmptyTest.java | 2 +- .../FlowableDistinctUntilChangedTest.java | 4 +-- .../flowable/FlowableDoOnRequestTest.java | 2 +- .../flowable/FlowableFlatMapMaybeTest.java | 3 +- .../flowable/FlowableFlatMapSingleTest.java | 3 +- .../flowable/FlowableFlatMapTest.java | 2 +- .../flowable/FlowableFromIterableTest.java | 2 +- .../flowable/FlowableGroupByTest.java | 8 +++--- .../operators/flowable/FlowableMergeTest.java | 8 +++--- .../flowable/FlowableObserveOnTest.java | 6 ++-- .../flowable/FlowableReduceTest.java | 12 +++++--- .../flowable/FlowableRefCountTest.java | 2 +- .../flowable/FlowableReplayTest.java | 2 +- .../operators/flowable/FlowableRetryTest.java | 6 ++-- .../FlowableRetryWithPredicateTest.java | 4 +-- .../operators/flowable/FlowableScanTest.java | 6 ++-- .../operators/flowable/FlowableSkipTest.java | 2 +- .../flowable/FlowableSwitchIfEmptyTest.java | 2 +- .../flowable/FlowableTakeLastOneTest.java | 2 +- .../flowable/FlowableTakeLastTest.java | 2 +- .../observable/ObservableBufferTest.java | 4 +-- .../ObservableDistinctUntilChangedTest.java | 4 +-- .../ObservableFlatMapMaybeTest.java | 2 +- .../ObservableFlatMapSingleTest.java | 2 +- .../observable/ObservableFlatMapTest.java | 2 +- .../observable/ObservableMergeTest.java | 4 +-- .../observable/ObservableObserveOnTest.java | 2 +- .../observable/ObservableRefCountTest.java | 2 +- .../observable/ObservableReplayTest.java | 2 +- .../observable/ObservableRetryTest.java | 4 +-- .../ObservableRetryWithPredicateTest.java | 4 +-- .../observable/ObservableScanTest.java | 6 ++-- .../observable/ObservableSkipTest.java | 2 +- .../observable/ObservableTakeLastOneTest.java | 2 +- .../observable/ObservableTakeLastTest.java | 2 +- .../observable/ObservableNullTests.java | 2 +- .../reactivex/observable/ObservableTest.java | 2 +- .../reactivex/plugins/RxJavaPluginsTest.java | 2 +- ...ReplayProcessorBoundedConcurrencyTest.java | 1 + .../ReplayProcessorConcurrencyTest.java | 1 + .../processors/UnicastProcessorTest.java | 2 +- .../AbstractSchedulerConcurrencyTests.java | 1 + .../ReplaySubjectBoundedConcurrencyTest.java | 1 + .../ReplaySubjectConcurrencyTest.java | 1 + 62 files changed, 122 insertions(+), 101 deletions(-) diff --git a/src/jmh/java/io/reactivex/parallel/ParallelPerf.java b/src/jmh/java/io/reactivex/parallel/ParallelPerf.java index 1630e82eef..24a0e85954 100644 --- a/src/jmh/java/io/reactivex/parallel/ParallelPerf.java +++ b/src/jmh/java/io/reactivex/parallel/ParallelPerf.java @@ -28,7 +28,7 @@ @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) @Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) -@Fork(value = 1,jvmArgsAppend = { "-XX:MaxInlineLevel=20" }) +@Fork(value = 1, jvmArgsAppend = { "-XX:MaxInlineLevel=20" }) @OutputTimeUnit(TimeUnit.SECONDS) @State(Scope.Thread) public class ParallelPerf implements Function<Integer, Integer> { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java index 14fbc74b99..719645afe9 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java @@ -430,7 +430,7 @@ public boolean isEmpty() { } } - static final class EvictionAction<K, V> implements Consumer<GroupedUnicast<K,V>> { + static final class EvictionAction<K, V> implements Consumer<GroupedUnicast<K, V>> { final Queue<GroupedUnicast<K, V>> evictedGroups; @@ -439,7 +439,7 @@ static final class EvictionAction<K, V> implements Consumer<GroupedUnicast<K,V>> } @Override - public void accept(GroupedUnicast<K,V> value) { + public void accept(GroupedUnicast<K, V> value) { evictedGroups.offer(value); } } diff --git a/src/main/java/io/reactivex/internal/queue/MpscLinkedQueue.java b/src/main/java/io/reactivex/internal/queue/MpscLinkedQueue.java index eddfb306b4..c33147de06 100644 --- a/src/main/java/io/reactivex/internal/queue/MpscLinkedQueue.java +++ b/src/main/java/io/reactivex/internal/queue/MpscLinkedQueue.java @@ -36,7 +36,7 @@ public MpscLinkedQueue() { consumerNode = new AtomicReference<LinkedQueueNode<T>>(); LinkedQueueNode<T> node = new LinkedQueueNode<T>(); spConsumerNode(node); - xchgProducerNode(node);// this ensures correct construction: StoreLoad + xchgProducerNode(node); // this ensures correct construction: StoreLoad } /** diff --git a/src/main/java/io/reactivex/internal/queue/SpscArrayQueue.java b/src/main/java/io/reactivex/internal/queue/SpscArrayQueue.java index 1afa99738f..53ac212600 100644 --- a/src/main/java/io/reactivex/internal/queue/SpscArrayQueue.java +++ b/src/main/java/io/reactivex/internal/queue/SpscArrayQueue.java @@ -89,12 +89,12 @@ public E poll() { final long index = consumerIndex.get(); final int offset = calcElementOffset(index); // local load of field to avoid repeated loads after volatile reads - final E e = lvElement(offset);// LoadLoad + final E e = lvElement(offset); // LoadLoad if (null == e) { return null; } soConsumerIndex(index + 1); // ordered store -> atomic and ordered for size() - soElement(offset, null);// StoreStore + soElement(offset, null); // StoreStore return e; } diff --git a/src/main/java/io/reactivex/internal/queue/SpscLinkedArrayQueue.java b/src/main/java/io/reactivex/internal/queue/SpscLinkedArrayQueue.java index ec874209d0..e5e71e29f4 100644 --- a/src/main/java/io/reactivex/internal/queue/SpscLinkedArrayQueue.java +++ b/src/main/java/io/reactivex/internal/queue/SpscLinkedArrayQueue.java @@ -92,8 +92,8 @@ public boolean offer(final T e) { } private boolean writeToQueue(final AtomicReferenceArray<Object> buffer, final T e, final long index, final int offset) { - soElement(buffer, offset, e);// StoreStore - soProducerIndex(index + 1);// this ensures atomic write of long on 32bit platforms + soElement(buffer, offset, e); // StoreStore + soProducerIndex(index + 1); // this ensures atomic write of long on 32bit platforms return true; } @@ -103,11 +103,11 @@ private void resize(final AtomicReferenceArray<Object> oldBuffer, final long cur final AtomicReferenceArray<Object> newBuffer = new AtomicReferenceArray<Object>(capacity); producerBuffer = newBuffer; producerLookAhead = currIndex + mask - 1; - soElement(newBuffer, offset, e);// StoreStore + soElement(newBuffer, offset, e); // StoreStore soNext(oldBuffer, newBuffer); soElement(oldBuffer, offset, HAS_NEXT); // new buffer is visible after element is // inserted - soProducerIndex(currIndex + 1);// this ensures correctness on 32bit platforms + soProducerIndex(currIndex + 1); // this ensures correctness on 32bit platforms } private void soNext(AtomicReferenceArray<Object> curr, AtomicReferenceArray<Object> next) { @@ -135,11 +135,11 @@ public T poll() { final long index = lpConsumerIndex(); final int mask = consumerMask; final int offset = calcWrappedOffset(index, mask); - final Object e = lvElement(buffer, offset);// LoadLoad + final Object e = lvElement(buffer, offset); // LoadLoad boolean isNextBuffer = e == HAS_NEXT; if (null != e && !isNextBuffer) { - soElement(buffer, offset, null);// StoreStore - soConsumerIndex(index + 1);// this ensures correctness on 32bit platforms + soElement(buffer, offset, null); // StoreStore + soConsumerIndex(index + 1); // this ensures correctness on 32bit platforms return (T) e; } else if (isNextBuffer) { return newBufferPoll(lvNextBufferAndUnlink(buffer, mask + 1), index, mask); @@ -152,10 +152,10 @@ public T poll() { private T newBufferPoll(AtomicReferenceArray<Object> nextBuffer, final long index, final int mask) { consumerBuffer = nextBuffer; final int offsetInNew = calcWrappedOffset(index, mask); - final T n = (T) lvElement(nextBuffer, offsetInNew);// LoadLoad + final T n = (T) lvElement(nextBuffer, offsetInNew); // LoadLoad if (null != n) { - soElement(nextBuffer, offsetInNew, null);// StoreStore - soConsumerIndex(index + 1);// this ensures correctness on 32bit platforms + soElement(nextBuffer, offsetInNew, null); // StoreStore + soConsumerIndex(index + 1); // this ensures correctness on 32bit platforms } return n; } @@ -166,7 +166,7 @@ public T peek() { final long index = lpConsumerIndex(); final int mask = consumerMask; final int offset = calcWrappedOffset(index, mask); - final Object e = lvElement(buffer, offset);// LoadLoad + final Object e = lvElement(buffer, offset); // LoadLoad if (e == HAS_NEXT) { return newBufferPeek(lvNextBufferAndUnlink(buffer, mask + 1), index, mask); } @@ -178,7 +178,7 @@ public T peek() { private T newBufferPeek(AtomicReferenceArray<Object> nextBuffer, final long index, final int mask) { consumerBuffer = nextBuffer; final int offsetInNew = calcWrappedOffset(index, mask); - return (T) lvElement(nextBuffer, offsetInNew);// LoadLoad + return (T) lvElement(nextBuffer, offsetInNew); // LoadLoad } @Override @@ -277,13 +277,13 @@ public boolean offer(T first, T second) { producerBuffer = newBuffer; pi = calcWrappedOffset(p, m); - soElement(newBuffer, pi + 1, second);// StoreStore + soElement(newBuffer, pi + 1, second); // StoreStore soElement(newBuffer, pi, first); soNext(buffer, newBuffer); soElement(buffer, pi, HAS_NEXT); // new buffer is visible after element is - soProducerIndex(p + 2);// this ensures correctness on 32bit platforms + soProducerIndex(p + 2); // this ensures correctness on 32bit platforms } return true; diff --git a/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java b/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java index 662335ef43..423a47898f 100644 --- a/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java @@ -151,6 +151,7 @@ public IoScheduler() { } /** + * Constructs an IoScheduler with the given thread factory and starts the pool of workers. * @param threadFactory thread factory to use for creating worker threads. Note that this takes precedence over any * system properties for configuring new thread creation. Cannot be null. */ diff --git a/src/main/java/io/reactivex/internal/schedulers/SingleScheduler.java b/src/main/java/io/reactivex/internal/schedulers/SingleScheduler.java index d65348aa3c..40a7ce0b85 100644 --- a/src/main/java/io/reactivex/internal/schedulers/SingleScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/SingleScheduler.java @@ -53,6 +53,8 @@ public SingleScheduler() { } /** + * Constructs a SingleScheduler with the given ThreadFactory and prepares the + * single scheduler thread. * @param threadFactory thread factory to use for creating worker threads. Note that this takes precedence over any * system properties for configuring new thread creation. Cannot be null. */ diff --git a/src/main/java/io/reactivex/internal/util/ExceptionHelper.java b/src/main/java/io/reactivex/internal/util/ExceptionHelper.java index b6fb4e9196..ecd970c730 100644 --- a/src/main/java/io/reactivex/internal/util/ExceptionHelper.java +++ b/src/main/java/io/reactivex/internal/util/ExceptionHelper.java @@ -129,7 +129,7 @@ public static String timeoutMessage(long timeout, TimeUnit unit) { + unit.toString().toLowerCase() + " and has been terminated."; } - + static final class Termination extends Throwable { private static final long serialVersionUID = -4649703670690200604L; diff --git a/src/main/java/io/reactivex/processors/UnicastProcessor.java b/src/main/java/io/reactivex/processors/UnicastProcessor.java index 47f02489b4..94547b88fb 100644 --- a/src/main/java/io/reactivex/processors/UnicastProcessor.java +++ b/src/main/java/io/reactivex/processors/UnicastProcessor.java @@ -255,7 +255,7 @@ public static <T> UnicastProcessor<T> create(int capacityHint, Runnable onCancel * @since 2.0 */ UnicastProcessor(int capacityHint) { - this(capacityHint,null, true); + this(capacityHint, null, true); } /** diff --git a/src/test/java/io/reactivex/exceptions/ExceptionsTest.java b/src/test/java/io/reactivex/exceptions/ExceptionsTest.java index 4928f14bf1..e1cff53e29 100644 --- a/src/test/java/io/reactivex/exceptions/ExceptionsTest.java +++ b/src/test/java/io/reactivex/exceptions/ExceptionsTest.java @@ -59,6 +59,7 @@ public void accept(Integer t1) { } /** + * Outdated test: Observer should not suppress errors from onCompleted. * https://github.com/ReactiveX/RxJava/issues/3885 */ @Ignore("v2 components should not throw") @@ -200,6 +201,7 @@ public void onNext(Integer t) { } /** + * Outdated test: throwing from onError handler. * https://github.com/ReactiveX/RxJava/issues/969 */ @Ignore("v2 components should not throw") @@ -237,6 +239,7 @@ public void onNext(Object o) { } /** + * Outdated test: throwing from onError. * https://github.com/ReactiveX/RxJava/issues/2998 * @throws Exception on arbitrary errors */ @@ -276,6 +279,7 @@ public void onNext(GroupedObservable<Integer, Integer> integerIntegerGroupedObse } /** + * Outdated test: throwing from onError. * https://github.com/ReactiveX/RxJava/issues/2998 * @throws Exception on arbitrary errors */ diff --git a/src/test/java/io/reactivex/flowable/FlowableConversionTest.java b/src/test/java/io/reactivex/flowable/FlowableConversionTest.java index a7d908111a..36bcb643f6 100644 --- a/src/test/java/io/reactivex/flowable/FlowableConversionTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableConversionTest.java @@ -206,7 +206,7 @@ public String apply(String a, String n) { public void testConvertToConcurrentQueue() { final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>(null); final AtomicBoolean isFinished = new AtomicBoolean(false); - ConcurrentLinkedQueue<? extends Integer> queue = Flowable.range(0,5) + ConcurrentLinkedQueue<? extends Integer> queue = Flowable.range(0, 5) .flatMap(new Function<Integer, Publisher<Integer>>() { @Override public Publisher<Integer> apply(final Integer i) { diff --git a/src/test/java/io/reactivex/flowable/FlowableErrorHandlingTests.java b/src/test/java/io/reactivex/flowable/FlowableErrorHandlingTests.java index e86aa39266..21f05aa8d4 100644 --- a/src/test/java/io/reactivex/flowable/FlowableErrorHandlingTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableErrorHandlingTests.java @@ -28,7 +28,8 @@ public class FlowableErrorHandlingTests { /** - * Test that an error from a user provided Observer.onNext is handled and emitted to the onError + * Test that an error from a user provided Observer.onNext + * is handled and emitted to the onError. * @throws InterruptedException if the test is interrupted */ @Test @@ -63,7 +64,8 @@ public void onNext(Long args) { } /** - * Test that an error from a user provided Observer.onNext is handled and emitted to the onError + * Test that an error from a user provided Observer.onNext + * is handled and emitted to the onError. * even when done across thread boundaries with observeOn * @throws InterruptedException if the test is interrupted */ diff --git a/src/test/java/io/reactivex/flowable/FlowableNullTests.java b/src/test/java/io/reactivex/flowable/FlowableNullTests.java index 3e9582363b..a9acc4f061 100644 --- a/src/test/java/io/reactivex/flowable/FlowableNullTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableNullTests.java @@ -466,7 +466,7 @@ public void intervalPeriodSchedulerNull() { @Test(expected = NullPointerException.class) public void intervalRangeUnitNull() { - Flowable.intervalRange(1,1, 1, 1, null); + Flowable.intervalRange(1, 1, 1, 1, null); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java index e95d5a9ab2..d0a0e1a88e 100644 --- a/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java @@ -467,7 +467,7 @@ public void onNext(Integer t) { public void testNegativeRequestThrowsIllegalArgumentException() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); - Flowable.just(1,2,3,4).subscribe(new DefaultSubscriber<Integer>() { + Flowable.just(1, 2, 3, 4).subscribe(new DefaultSubscriber<Integer>() { @Override public void onStart() { @@ -498,7 +498,8 @@ public void onNext(Integer t) { @Test public void testOnStartRequestsAreAdditive() { final List<Integer> list = new ArrayList<Integer>(); - Flowable.just(1,2,3,4,5).subscribe(new DefaultSubscriber<Integer>() { + Flowable.just(1, 2, 3, 4, 5) + .subscribe(new DefaultSubscriber<Integer>() { @Override public void onStart() { request(3); @@ -519,13 +520,13 @@ public void onError(Throwable e) { public void onNext(Integer t) { list.add(t); }}); - assertEquals(Arrays.asList(1,2,3,4,5), list); + assertEquals(Arrays.asList(1, 2, 3, 4, 5), list); } @Test public void testOnStartRequestsAreAdditiveAndOverflowBecomesMaxValue() { final List<Integer> list = new ArrayList<Integer>(); - Flowable.just(1,2,3,4,5).subscribe(new DefaultSubscriber<Integer>() { + Flowable.just(1, 2, 3, 4, 5).subscribe(new DefaultSubscriber<Integer>() { @Override public void onStart() { request(2); @@ -546,7 +547,7 @@ public void onError(Throwable e) { public void onNext(Integer t) { list.add(t); }}); - assertEquals(Arrays.asList(1,2,3,4,5), list); + assertEquals(Arrays.asList(1, 2, 3, 4, 5), list); } @Test diff --git a/src/test/java/io/reactivex/flowable/FlowableTests.java b/src/test/java/io/reactivex/flowable/FlowableTests.java index 377254f95e..4a700b5aea 100644 --- a/src/test/java/io/reactivex/flowable/FlowableTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableTests.java @@ -1026,7 +1026,7 @@ public void testAmbWith() { public void testTakeWhileToList() { final int expectedCount = 3; final AtomicInteger count = new AtomicInteger(); - for (int i = 0;i < expectedCount; i++) { + for (int i = 0; i < expectedCount; i++) { Flowable .just(Boolean.TRUE, Boolean.FALSE) .takeWhile(new Predicate<Boolean>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index 00568da3ec..5060c58253 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -2130,7 +2130,7 @@ public Integer apply(Integer integer, Long aLong) { return integer; } }) - .buffer(Flowable.interval(0,200, TimeUnit.MILLISECONDS), + .buffer(Flowable.interval(0, 200, TimeUnit.MILLISECONDS), new Function<Long, Publisher<?>>() { @Override public Publisher<?> apply(Long a) { @@ -2153,7 +2153,7 @@ public Integer apply(Integer integer, Long aLong) { return integer; } }) - .buffer(Flowable.interval(0,100, TimeUnit.MILLISECONDS), + .buffer(Flowable.interval(0, 100, TimeUnit.MILLISECONDS), new Function<Long, Publisher<?>>() { @Override public Publisher<?> apply(Long a) { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java index 1d759a6e44..4443a71759 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java @@ -807,8 +807,8 @@ public Long apply(Long t1, Integer t2) { public void testCombineLatestRequestOverflow() throws InterruptedException { @SuppressWarnings("unchecked") List<Flowable<Integer>> sources = Arrays.asList(Flowable.fromArray(1, 2, 3, 4), - Flowable.fromArray(5,6,7,8)); - Flowable<Integer> f = Flowable.combineLatest(sources,new Function<Object[], Integer>() { + Flowable.fromArray(5, 6, 7, 8)); + Flowable<Integer> f = Flowable.combineLatest(sources, new Function<Object[], Integer>() { @Override public Integer apply(Object[] args) { return (Integer) args[0]; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java index ed0f556b7f..733f3b7cf3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java @@ -779,8 +779,8 @@ public void onError(Throwable e) { @Test public void testRequestOverflowDoesNotStallStream() { - Flowable<Integer> f1 = Flowable.just(1,2,3); - Flowable<Integer> f2 = Flowable.just(4,5,6); + Flowable<Integer> f1 = Flowable.just(1, 2, 3); + Flowable<Integer> f2 = Flowable.just(4, 5, 6); final AtomicBoolean completed = new AtomicBoolean(false); f1.concatWith(f2).subscribe(new DefaultSubscriber<Integer>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDefaultIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDefaultIfEmptyTest.java index fa6b123a15..4c75d500e8 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDefaultIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDefaultIfEmptyTest.java @@ -97,7 +97,7 @@ public void testBackpressureEmpty() { @Test public void testBackpressureNonEmpty() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L); - Flowable.just(1,2,3).defaultIfEmpty(1).subscribe(ts); + Flowable.just(1, 2, 3).defaultIfEmpty(1).subscribe(ts); ts.assertNoValues(); ts.assertNotTerminated(); ts.request(2); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java index 0502283132..7c5eb993e1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java @@ -234,7 +234,7 @@ public void accept(Throwable t) { @Test public void customComparator() { - Flowable<String> source = Flowable.just("a", "b", "B", "A","a", "C"); + Flowable<String> source = Flowable.just("a", "b", "B", "A", "a", "C"); TestSubscriber<String> ts = TestSubscriber.create(); @@ -253,7 +253,7 @@ public boolean test(String a, String b) { @Test public void customComparatorThrows() { - Flowable<String> source = Flowable.just("a", "b", "B", "A","a", "C"); + Flowable<String> source = Flowable.just("a", "b", "B", "A", "a", "C"); TestSubscriber<String> ts = TestSubscriber.create(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnRequestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnRequestTest.java index 1d30f4663c..4502206206 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnRequestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnRequestTest.java @@ -83,7 +83,7 @@ public void onNext(Integer t) { request(t); } }); - assertEquals(Arrays.asList(3L,1L,2L,3L,4L,5L), requests); + assertEquals(Arrays.asList(3L, 1L, 2L, 3L, 4L, 5L), requests); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java index eac6c0503f..aab0940c46 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybeTest.java @@ -261,7 +261,8 @@ public MaybeSource<Integer> apply(Integer v) throws Exception { @Test public void middleError() { - Flowable.fromArray(new String[]{"1","a","2"}).flatMapMaybe(new Function<String, MaybeSource<Integer>>() { + Flowable.fromArray(new String[]{"1", "a", "2"}) + .flatMapMaybe(new Function<String, MaybeSource<Integer>>() { @Override public MaybeSource<Integer> apply(final String s) throws NumberFormatException { //return Maybe.just(Integer.valueOf(s)); //This works diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java index 381d210070..ac137d6c3d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapSingleTest.java @@ -248,7 +248,8 @@ public SingleSource<Integer> apply(Integer v) throws Exception { @Test public void middleError() { - Flowable.fromArray(new String[]{"1","a","2"}).flatMapSingle(new Function<String, SingleSource<Integer>>() { + Flowable.fromArray(new String[]{"1", "a", "2"}) + .flatMapSingle(new Function<String, SingleSource<Integer>>() { @Override public SingleSource<Integer> apply(final String s) throws NumberFormatException { //return Single.just(Integer.valueOf(s)); //This works diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index b05b847c90..bb525b2ddb 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -522,7 +522,7 @@ public Flowable<Integer> apply(Integer t) { @Test public void flatMapIntPassthruAsync() { - for (int i = 0;i < 1000; i++) { + for (int i = 0; i < 1000; i++) { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Flowable.range(1, 1000).flatMap(new Function<Integer, Flowable<Integer>>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java index fdedc6577c..e33556cb4e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java @@ -172,7 +172,7 @@ public void testSubscribeMultipleTimes() { @Test public void testFromIterableRequestOverflow() throws InterruptedException { - Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1,2,3,4)); + Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)); final int expectedCount = 4; final CountDownLatch latch = new CountDownLatch(expectedCount); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index 9b2ae32416..97a0a5ca23 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -2069,10 +2069,10 @@ public Publisher<? extends Object> apply(GroupedFlowable<Integer, Integer> g) th } //not thread safe - private static final class SingleThreadEvictingHashMap<K,V> implements Map<K,V> { + private static final class SingleThreadEvictingHashMap<K, V> implements Map<K, V> { private final List<K> list = new ArrayList<K>(); - private final Map<K,V> map = new HashMap<K,V>(); + private final Map<K, V> map = new HashMap<K, V>(); private final int maxSize; private final Consumer<V> evictedListener; @@ -2175,7 +2175,7 @@ public Map<Integer, Object> apply(final Consumer<Object> notify) throws Exceptio .maximumSize(maxSize) // .removalListener(new RemovalListener<Integer, Object>() { @Override - public void onRemoval(RemovalNotification<Integer,Object> notification) { + public void onRemoval(RemovalNotification<Integer, Object> notification) { try { notify.accept(notification.getValue()); } catch (Exception e) { @@ -2194,7 +2194,7 @@ private static Function<Consumer<Object>, Map<Integer, Object>> createEvictingMa @Override public Map<Integer, Object> apply(final Consumer<Object> notify) throws Exception { - return new SingleThreadEvictingHashMap<Integer,Object>(maxSize, new Consumer<Object>() { + return new SingleThreadEvictingHashMap<Integer, Object>(maxSize, new Consumer<Object>() { @Override public void accept(Object object) { try { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java index fc09bd1dc5..010da8bd69 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java @@ -335,8 +335,8 @@ public void testError2() { // we are using synchronous execution to test this exactly rather than non-deterministic concurrent behavior final Flowable<String> f1 = Flowable.unsafeCreate(new TestErrorFlowable("one", "two", "three")); final Flowable<String> f2 = Flowable.unsafeCreate(new TestErrorFlowable("four", null, "six")); // we expect to lose "six" - final Flowable<String> f3 = Flowable.unsafeCreate(new TestErrorFlowable("seven", "eight", null));// we expect to lose all of these since o2 is done first and fails - final Flowable<String> f4 = Flowable.unsafeCreate(new TestErrorFlowable("nine"));// we expect to lose all of these since o2 is done first and fails + final Flowable<String> f3 = Flowable.unsafeCreate(new TestErrorFlowable("seven", "eight", null)); // we expect to lose all of these since o2 is done first and fails + final Flowable<String> f4 = Flowable.unsafeCreate(new TestErrorFlowable("nine")); // we expect to lose all of these since o2 is done first and fails Flowable<String> m = Flowable.merge(f1, f2, f3, f4); m.subscribe(stringSubscriber); @@ -1269,8 +1269,8 @@ public void run() { @Test public void testMergeRequestOverflow() throws InterruptedException { //do a non-trivial merge so that future optimisations with EMPTY don't invalidate this test - Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1,2)) - .mergeWith(Flowable.fromIterable(Arrays.asList(3,4))); + Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1, 2)) + .mergeWith(Flowable.fromIterable(Arrays.asList(3, 4))); final int expectedCount = 4; final CountDownLatch latch = new CountDownLatch(expectedCount); f.subscribeOn(Schedulers.computation()).subscribe(new DefaultSubscriber<Integer>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java index d4fdbe15db..ca4bd28986 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java @@ -799,7 +799,7 @@ public void onNext(Integer t) { public void testErrorDelayed() { TestScheduler s = new TestScheduler(); - Flowable<Integer> source = Flowable.just(1, 2 ,3) + Flowable<Integer> source = Flowable.just(1, 2, 3) .concatWith(Flowable.<Integer>error(new TestException())); TestSubscriber<Integer> ts = TestSubscriber.create(0); @@ -833,7 +833,7 @@ public void testErrorDelayed() { @Test public void testErrorDelayedAsync() { - Flowable<Integer> source = Flowable.just(1, 2 ,3) + Flowable<Integer> source = Flowable.just(1, 2, 3) .concatWith(Flowable.<Integer>error(new TestException())); TestSubscriber<Integer> ts = TestSubscriber.create(); @@ -1862,7 +1862,7 @@ public void workerNotDisposedPrematurelyAsyncInNormalOut() { static final class TestSubscriberFusedCanceling extends TestSubscriber<Integer> { - public TestSubscriberFusedCanceling() { + TestSubscriberFusedCanceling() { super(); initialFusionMode = QueueFuseable.ANY; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java index e6103b5a7b..37d7012065 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java @@ -388,7 +388,8 @@ public Integer apply(Integer a, Integer b) throws Exception { } /** - * https://gist.github.com/jurna/353a2bd8ff83f0b24f0b5bc772077d61 + * Make sure an asynchronous reduce with flatMap works. + * Original Reactor-Core test case: https://gist.github.com/jurna/353a2bd8ff83f0b24f0b5bc772077d61 */ @Test public void shouldReduceTo10Events() { @@ -414,7 +415,8 @@ public String apply(String l, String r) throws Exception { @Override public void accept(String s) throws Exception { count.incrementAndGet(); - System.out.println("Completed with " + s);} + System.out.println("Completed with " + s); + } }) .toFlowable(); } @@ -425,7 +427,8 @@ public void accept(String s) throws Exception { } /** - * https://gist.github.com/jurna/353a2bd8ff83f0b24f0b5bc772077d61 + * Make sure an asynchronous reduce with flatMap works. + * Original Reactor-Core test case: https://gist.github.com/jurna/353a2bd8ff83f0b24f0b5bc772077d61 */ @Test public void shouldReduceTo10EventsFlowable() { @@ -452,7 +455,8 @@ public String apply(String l, String r) throws Exception { @Override public void accept(String s) throws Exception { count.incrementAndGet(); - System.out.println("Completed with " + s);} + System.out.println("Completed with " + s); + } }) ; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index 6bd46295e3..289170b254 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -537,7 +537,7 @@ public void testUpstreamErrorAllowsRetry() throws InterruptedException { try { final AtomicInteger intervalSubscribed = new AtomicInteger(); Flowable<String> interval = - Flowable.interval(200,TimeUnit.MILLISECONDS) + Flowable.interval(200, TimeUnit.MILLISECONDS) .doOnSubscribe(new Consumer<Subscription>() { @Override public void accept(Subscription s) { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index e20c417da9..0cc39b5c03 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -520,7 +520,7 @@ public void testIssue2191_UnsubscribeSource() throws Exception { Subscriber<Integer> spiedSubscriberAfterConnect = TestHelper.mockSubscriber(); // Flowable under test - Flowable<Integer> source = Flowable.just(1,2); + Flowable<Integer> source = Flowable.just(1, 2); ConnectableFlowable<Integer> replay = source .doOnNext(sourceNext) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java index 8b35cb37f9..8a0a29f8dd 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java @@ -708,7 +708,7 @@ public void testTimeoutWithRetry() { @Test//(timeout = 15000) public void testRetryWithBackpressure() throws InterruptedException { final int NUM_LOOPS = 1; - for (int j = 0;j < NUM_LOOPS; j++) { + for (int j = 0; j < NUM_LOOPS; j++) { final int numRetries = Flowable.bufferSize() * 2; for (int i = 0; i < 400; i++) { Subscriber<String> subscriber = TestHelper.mockSubscriber(); @@ -852,7 +852,7 @@ public String apply(String t1) { return t1; } }) - .flatMap(new Function<GroupedFlowable<String,String>, Flowable<String>>() { + .flatMap(new Function<GroupedFlowable<String, String>, Flowable<String>>() { @Override public Flowable<String> apply(GroupedFlowable<String, String> t1) { return t1.take(1); @@ -897,7 +897,7 @@ public String apply(String t1) { return t1; } }) - .flatMap(new Function<GroupedFlowable<String,String>, Flowable<String>>() { + .flatMap(new Function<GroupedFlowable<String, String>, Flowable<String>>() { @Override public Flowable<String> apply(GroupedFlowable<String, String> t1) { return t1.take(1); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java index f25c276ece..54346a73c0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java @@ -335,7 +335,7 @@ public void accept(Long t) { System.out.println(t); list.add(t); }}); - assertEquals(Arrays.asList(1L,1L,2L,3L), list); + assertEquals(Arrays.asList(1L, 1L, 2L, 3L), list); } @Test @@ -359,7 +359,7 @@ public void accept(Long t) { System.out.println(t); list.add(t); }}); - assertEquals(Arrays.asList(1L,1L,2L,3L), list); + assertEquals(Arrays.asList(1L, 1L, 2L, 3L), list); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java index d12476cf4e..7e761ca53f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java @@ -553,7 +553,7 @@ public Integer apply(Integer n1, Integer n2) throws Exception { @Test public void testScanWithSeedCompletesNormally() { - Flowable.just(1,2,3).scan(0, SUM) + Flowable.just(1, 2, 3).scan(0, SUM) .test() .assertValues(0, 1, 3, 6) .assertComplete(); @@ -562,7 +562,7 @@ public void testScanWithSeedCompletesNormally() { @Test public void testScanWithSeedWhenScanSeedProviderThrows() { final RuntimeException e = new RuntimeException(); - Flowable.just(1,2,3).scanWith(throwingCallable(e), + Flowable.just(1, 2, 3).scanWith(throwingCallable(e), SUM) .test() .assertError(e) @@ -631,7 +631,7 @@ public Integer apply(Integer n1, Integer n2) throws Exception { assertEquals(1, count.get()); } - private static BiFunction<Integer,Integer, Integer> throwingBiFunction(final RuntimeException e) { + private static BiFunction<Integer, Integer, Integer> throwingBiFunction(final RuntimeException e) { return new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer n1, Integer n2) throws Exception { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java index 25d902310b..c2f8c2f40f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java @@ -167,7 +167,7 @@ public void testRequestOverflowDoesNotOccur() { ts.assertTerminated(); ts.assertComplete(); ts.assertNoErrors(); - assertEquals(Arrays.asList(6,7,8,9,10), ts.values()); + assertEquals(Arrays.asList(6, 7, 8, 9, 10), ts.values()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java index 2ab9d75bfd..99ecaaac43 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java @@ -166,7 +166,7 @@ public void testBackpressureNoRequest() { @Test public void testBackpressureOnFirstObservable() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L); - Flowable.just(1,2,3).switchIfEmpty(Flowable.just(4, 5, 6)).subscribe(ts); + Flowable.just(1, 2, 3).switchIfEmpty(Flowable.just(4, 5, 6)).subscribe(ts); ts.assertNotComplete(); ts.assertNoErrors(); ts.assertNoValues(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOneTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOneTest.java index 5da9f37c50..5a94904936 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOneTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOneTest.java @@ -91,7 +91,7 @@ public void testLastWithBackpressure() { public void testTakeLastZeroProcessesAllItemsButIgnoresThem() { final AtomicInteger upstreamCount = new AtomicInteger(); final int num = 10; - long count = Flowable.range(1,num).doOnNext(new Consumer<Integer>() { + long count = Flowable.range(1, num).doOnNext(new Consumer<Integer>() { @Override public void accept(Integer t) { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java index 37f5ee0d1f..b0d1af43c7 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java @@ -292,7 +292,7 @@ public void onNext(Integer integer) { cancel(); } }); - assertEquals(1,count.get()); + assertEquals(1, count.get()); } @Test(timeout = 10000) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 961bb7bfed..43612b228d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -1557,7 +1557,7 @@ public Integer apply(Integer integer, Long aLong) { return integer; } }) - .buffer(Observable.interval(0,200, TimeUnit.MILLISECONDS), + .buffer(Observable.interval(0, 200, TimeUnit.MILLISECONDS), new Function<Long, Observable<?>>() { @Override public Observable<?> apply(Long a) { @@ -1580,7 +1580,7 @@ public Integer apply(Integer integer, Long aLong) { return integer; } }) - .buffer(Observable.interval(0,100, TimeUnit.MILLISECONDS), + .buffer(Observable.interval(0, 100, TimeUnit.MILLISECONDS), new Function<Long, Observable<?>>() { @Override public Observable<?> apply(Long a) { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java index 83ba70675b..b0ba634354 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java @@ -140,7 +140,7 @@ public void testDistinctUntilChangedOfSourceWithExceptionsFromKeySelector() { @Test public void customComparator() { - Observable<String> source = Observable.just("a", "b", "B", "A","a", "C"); + Observable<String> source = Observable.just("a", "b", "B", "A", "a", "C"); TestObserver<String> to = TestObserver.create(); @@ -159,7 +159,7 @@ public boolean test(String a, String b) { @Test public void customComparatorThrows() { - Observable<String> source = Observable.just("a", "b", "B", "A","a", "C"); + Observable<String> source = Observable.just("a", "b", "B", "A", "a", "C"); TestObserver<String> to = TestObserver.create(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybeTest.java index d2f77576a3..56ecedc02b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapMaybeTest.java @@ -188,7 +188,7 @@ public MaybeSource<Integer> apply(Integer v) throws Exception { @Test public void middleError() { - Observable.fromArray(new String[]{"1","a","2"}).flatMapMaybe(new Function<String, MaybeSource<Integer>>() { + Observable.fromArray(new String[]{"1", "a", "2"}).flatMapMaybe(new Function<String, MaybeSource<Integer>>() { @Override public MaybeSource<Integer> apply(final String s) throws NumberFormatException { //return Single.just(Integer.valueOf(s)); //This works diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingleTest.java index 4a56c61795..5226fc594c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapSingleTest.java @@ -175,7 +175,7 @@ public SingleSource<Integer> apply(Integer v) throws Exception { @Test public void middleError() { - Observable.fromArray(new String[]{"1","a","2"}).flatMapSingle(new Function<String, SingleSource<Integer>>() { + Observable.fromArray(new String[]{"1", "a", "2"}).flatMapSingle(new Function<String, SingleSource<Integer>>() { @Override public SingleSource<Integer> apply(final String s) throws NumberFormatException { //return Single.just(Integer.valueOf(s)); //This works diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index c0cb65abe9..efee97f33a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -515,7 +515,7 @@ public Observable<Integer> apply(Integer t) { @Test public void flatMapIntPassthruAsync() { - for (int i = 0;i < 1000; i++) { + for (int i = 0; i < 1000; i++) { TestObserver<Integer> to = new TestObserver<Integer>(); Observable.range(1, 1000).flatMap(new Function<Integer, Observable<Integer>>() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java index fb50ae0f0a..8b69ef593b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java @@ -317,8 +317,8 @@ public void testError2() { // we are using synchronous execution to test this exactly rather than non-deterministic concurrent behavior final Observable<String> o1 = Observable.unsafeCreate(new TestErrorObservable("one", "two", "three")); final Observable<String> o2 = Observable.unsafeCreate(new TestErrorObservable("four", null, "six")); // we expect to lose "six" - final Observable<String> o3 = Observable.unsafeCreate(new TestErrorObservable("seven", "eight", null));// we expect to lose all of these since o2 is done first and fails - final Observable<String> o4 = Observable.unsafeCreate(new TestErrorObservable("nine"));// we expect to lose all of these since o2 is done first and fails + final Observable<String> o3 = Observable.unsafeCreate(new TestErrorObservable("seven", "eight", null)); // we expect to lose all of these since o2 is done first and fails + final Observable<String> o4 = Observable.unsafeCreate(new TestErrorObservable("nine")); // we expect to lose all of these since o2 is done first and fails Observable<String> m = Observable.merge(o1, o2, o3, o4); m.subscribe(stringObserver); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java index 70f047a005..8d948b2592 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java @@ -791,7 +791,7 @@ public void workerNotDisposedPrematurelyAsyncInNormalOut() { static final class TestObserverFusedCanceling extends TestObserver<Integer> { - public TestObserverFusedCanceling() { + TestObserverFusedCanceling() { super(); initialFusionMode = QueueFuseable.ANY; } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index d75498bc69..ea69a1d500 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -516,7 +516,7 @@ public Integer apply(Integer t1, Integer t2) { public void testUpstreamErrorAllowsRetry() throws InterruptedException { final AtomicInteger intervalSubscribed = new AtomicInteger(); Observable<String> interval = - Observable.interval(200,TimeUnit.MILLISECONDS) + Observable.interval(200, TimeUnit.MILLISECONDS) .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable d) { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java index c480a3b1df..5b06f031a2 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java @@ -520,7 +520,7 @@ public void testIssue2191_UnsubscribeSource() throws Exception { Observer<Integer> spiedSubscriberAfterConnect = TestHelper.mockObserver(); // Observable under test - Observable<Integer> source = Observable.just(1,2); + Observable<Integer> source = Observable.just(1, 2); ConnectableObservable<Integer> replay = source .doOnNext(sourceNext) diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java index 010b618c34..5c1cbe0041 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java @@ -801,7 +801,7 @@ public String apply(String t1) { return t1; } }) - .flatMap(new Function<GroupedObservable<String,String>, Observable<String>>() { + .flatMap(new Function<GroupedObservable<String, String>, Observable<String>>() { @Override public Observable<String> apply(GroupedObservable<String, String> t1) { return t1.take(1); @@ -846,7 +846,7 @@ public String apply(String t1) { return t1; } }) - .flatMap(new Function<GroupedObservable<String,String>, Observable<String>>() { + .flatMap(new Function<GroupedObservable<String, String>, Observable<String>>() { @Override public Observable<String> apply(GroupedObservable<String, String> t1) { return t1.take(1); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java index bd03c8874b..72981f705e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java @@ -334,7 +334,7 @@ public void accept(Long t) { System.out.println(t); list.add(t); }}); - assertEquals(Arrays.asList(1L,1L,2L,3L), list); + assertEquals(Arrays.asList(1L, 1L, 2L, 3L), list); } @Test @@ -358,7 +358,7 @@ public void accept(Long t) { System.out.println(t); list.add(t); }}); - assertEquals(Arrays.asList(1L,1L,2L,3L), list); + assertEquals(Arrays.asList(1L, 1L, 2L, 3L), list); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java index 8cd3aa75b6..35df1a462e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java @@ -326,7 +326,7 @@ public void subscribe(Observer<? super Integer> o) { o.onNext(2); o.onError(err2); }}) - .scan(new BiFunction<Integer,Integer,Integer>() { + .scan(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) throws Exception { throw err; @@ -351,7 +351,7 @@ public void subscribe(Observer<? super Integer> o) { o.onNext(2); o.onComplete(); }}) - .scan(new BiFunction<Integer,Integer,Integer>() { + .scan(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) throws Exception { throw err; @@ -374,7 +374,7 @@ public void subscribe(Observer<? super Integer> o) { o.onNext(2); o.onNext(3); }}) - .scan(new BiFunction<Integer,Integer,Integer>() { + .scan(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer t1, Integer t2) throws Exception { count.incrementAndGet(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java index d787de26bf..9b1de8ab4e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java @@ -142,7 +142,7 @@ public void testRequestOverflowDoesNotOccur() { to.assertTerminated(); to.assertComplete(); to.assertNoErrors(); - assertEquals(Arrays.asList(6,7,8,9,10), to.values()); + assertEquals(Arrays.asList(6, 7, 8, 9, 10), to.values()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java index 859e311a2d..7dc3a1cf39 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastOneTest.java @@ -82,7 +82,7 @@ public void run() { public void testTakeLastZeroProcessesAllItemsButIgnoresThem() { final AtomicInteger upstreamCount = new AtomicInteger(); final int num = 10; - long count = Observable.range(1,num).doOnNext(new Consumer<Integer>() { + long count = Observable.range(1, num).doOnNext(new Consumer<Integer>() { @Override public void accept(Integer t) { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java index 27327bffcf..34ab87312b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java @@ -179,7 +179,7 @@ public void onNext(Integer integer) { cancel(); } }); - assertEquals(1,count.get()); + assertEquals(1, count.get()); } @Test diff --git a/src/test/java/io/reactivex/observable/ObservableNullTests.java b/src/test/java/io/reactivex/observable/ObservableNullTests.java index 847b7c0422..d4142b34af 100644 --- a/src/test/java/io/reactivex/observable/ObservableNullTests.java +++ b/src/test/java/io/reactivex/observable/ObservableNullTests.java @@ -546,7 +546,7 @@ public void intervalPeriodSchedulerNull() { @Test(expected = NullPointerException.class) public void intervalRangeUnitNull() { - Observable.intervalRange(1,1, 1, 1, null); + Observable.intervalRange(1, 1, 1, 1, null); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/io/reactivex/observable/ObservableTest.java b/src/test/java/io/reactivex/observable/ObservableTest.java index 1d754c5e68..660c57d49a 100644 --- a/src/test/java/io/reactivex/observable/ObservableTest.java +++ b/src/test/java/io/reactivex/observable/ObservableTest.java @@ -1048,7 +1048,7 @@ public void testAmbWith() { public void testTakeWhileToList() { final int expectedCount = 3; final AtomicInteger count = new AtomicInteger(); - for (int i = 0;i < expectedCount; i++) { + for (int i = 0; i < expectedCount; i++) { Observable .just(Boolean.TRUE, Boolean.FALSE) .takeWhile(new Predicate<Boolean>() { diff --git a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java index cd66ce7b7e..efd4642d7e 100644 --- a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java +++ b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java @@ -269,7 +269,7 @@ public boolean getAsBoolean() throws Exception { fail("Should have thrown InvocationTargetException(IllegalStateException)"); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof IllegalStateException) { - assertEquals("Plugins can't be changed anymore",ex.getCause().getMessage()); + assertEquals("Plugins can't be changed anymore", ex.getCause().getMessage()); } else { fail("Should have thrown InvocationTargetException(IllegalStateException)"); } diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java index 8a26d4d80d..0258488d52 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java @@ -284,6 +284,7 @@ public void run() { } /** + * Make sure emission-subscription races are handled correctly. * https://github.com/ReactiveX/RxJava/issues/1147 */ @Test diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java index 6161c484fa..978c86ebe4 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java @@ -284,6 +284,7 @@ public void run() { } /** + * Make sure emission-subscription races are handled correctly. * https://github.com/ReactiveX/RxJava/issues/1147 */ @Test diff --git a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java index b058d51e16..5bbe6dca75 100644 --- a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java @@ -110,7 +110,7 @@ public void threeArgsFactory() { public void run() { } }; - UnicastProcessor<Integer> ap = UnicastProcessor.create(16, noop,false); + UnicastProcessor<Integer> ap = UnicastProcessor.create(16, noop, false); ap.onNext(1); ap.onError(new RuntimeException()); diff --git a/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java b/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java index 120dee09d7..3605c74679 100644 --- a/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java +++ b/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java @@ -36,6 +36,7 @@ public abstract class AbstractSchedulerConcurrencyTests extends AbstractSchedulerTests { /** + * Make sure canceling through {@code subscribeOn} works. * Bug report: https://github.com/ReactiveX/RxJava/issues/431 * @throws InterruptedException if the test is interrupted */ diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java index 9379e0059f..693fd9a6ee 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectBoundedConcurrencyTest.java @@ -288,6 +288,7 @@ public void run() { } /** + * Make sure emission-subscription races are handled correctly. * https://github.com/ReactiveX/RxJava/issues/1147 */ @Test diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java index bec6a10b2d..67120c49bc 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectConcurrencyTest.java @@ -288,6 +288,7 @@ public void run() { } /** + * Make sure emission-subscription races are handled correctly. * https://github.com/ReactiveX/RxJava/issues/1147 */ @Test From c35874145070eddf6a9b4dd5559e7c8df9490512 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 19 Oct 2018 22:16:32 +0200 Subject: [PATCH 295/417] 2.x: Add C.delaySubscription marble, fix some javadoc (#6257) --- src/main/java/io/reactivex/Completable.java | 2 ++ .../io/reactivex/internal/fuseable/ConditionalSubscriber.java | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 58eddbfed8..486562b483 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1393,6 +1393,7 @@ public final Completable delay(final long delay, final TimeUnit unit, final Sche /** * Returns a Completable that delays the subscription to the source CompletableSource by a given amount of time. * <p> + * <img width="640" height="475" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.delaySubscription.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code delaySubscription} operates by default on the {@code computation} {@link Scheduler}.</dd> @@ -1415,6 +1416,7 @@ public final Completable delaySubscription(long delay, TimeUnit unit) { * Returns a Completable that delays the subscription to the source CompletableSource by a given amount of time, * both waiting and subscribing on a given Scheduler. * <p> + * <img width="640" height="420" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.delaySubscription.ts.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> diff --git a/src/main/java/io/reactivex/internal/fuseable/ConditionalSubscriber.java b/src/main/java/io/reactivex/internal/fuseable/ConditionalSubscriber.java index 086e696571..4535b9c18d 100644 --- a/src/main/java/io/reactivex/internal/fuseable/ConditionalSubscriber.java +++ b/src/main/java/io/reactivex/internal/fuseable/ConditionalSubscriber.java @@ -16,7 +16,7 @@ import io.reactivex.FlowableSubscriber; /** - * A Subscriber with an additional onNextIf(T) method that + * A Subscriber with an additional {@link #tryOnNext(Object)} method that * tells the caller the specified value has been accepted or * not. * @@ -30,6 +30,7 @@ public interface ConditionalSubscriber<T> extends FlowableSubscriber<T> { * Conditionally takes the value. * @param t the value to deliver * @return true if the value has been accepted, false if the value has been rejected + * and the next value can be sent immediately */ boolean tryOnNext(T t); } From be0353cc6334fbb60a285f2f4f4ba88150f099e6 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 23 Oct 2018 11:11:52 +0200 Subject: [PATCH 296/417] Release 2.2.3 --- CHANGES.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 308c8e606b..6c888f8d3a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,24 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.3 - October 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.3%7C)) + +#### API changes + + - [Pull 6242](https://github.com/ReactiveX/RxJava/pull/6242): Add timed `Completable.delaySubscription()` operator. + +#### Documentation changes + + - [Pull 6220](https://github.com/ReactiveX/RxJava/pull/6220): Remove unnecessary 's' from `ConnectableObservable`. + - [Pull 6241](https://github.com/ReactiveX/RxJava/pull/6241): Remove mention of `io.reactivex.functions.Functions` nonexistent utility class. + +#### Other changes + + - [Pull 6232](https://github.com/ReactiveX/RxJava/pull/6232): Cleanup `Observable.flatMap` drain logic. + - [Pull 6234](https://github.com/ReactiveX/RxJava/pull/6234): Add timeout and unit to `TimeoutException` message in the `timeout` operators. + - [Pull 6236](https://github.com/ReactiveX/RxJava/pull/6236): Adjust `UndeliverableException` and `OnErrorNotImplementedException` message to use the full inner exception. + - [Pull 6244](https://github.com/ReactiveX/RxJava/pull/6244): Add `@Nullable` annotations for blocking methods in `Completable`. + ### Version 2.2.2 - September 6, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.2%7C)) #### Bugfixes From 9181cbc54e80f686a41037ad43605389d4f0741d Mon Sep 17 00:00:00 2001 From: Elijah Verdoorn <elijahverdoorn@users.noreply.github.com> Date: Fri, 26 Oct 2018 00:32:26 -0700 Subject: [PATCH 297/417] Add generate examples to Creating-Observables.md in Wiki (#6260) Add documentation and example to the wiki for generate. --- docs/Creating-Observables.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/docs/Creating-Observables.md b/docs/Creating-Observables.md index 4d26bbf2b1..9e0c3b96cd 100644 --- a/docs/Creating-Observables.md +++ b/docs/Creating-Observables.md @@ -199,6 +199,27 @@ observable.subscribe( () -> System.out.println("Done")); ``` +## generate + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/create.html](http://reactivex.io/documentation/operators/create.html) + +Creates a cold, synchronous and stateful generator of values. + +#### generate example: + +```java +int startValue = 1; +int incrementValue = 1; +Flowable<Integer> flowable = Flowable.generate(() -> startValue, (s, emitter) -> { + int nextValue = s + incrementValue; + emitter.onNext(nextValue); + return nextValue; +}); +flowable.subscribe(value -> System.out.println(value)); +``` + ## create **Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` From 1406637753003342f26cec628a9ba5e14b4d5882 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Quentin?= <bjoernQ@users.noreply.github.com> Date: Fri, 26 Oct 2018 16:01:52 +0200 Subject: [PATCH 298/417] =?UTF-8?q?Use=20JUnit's=20assert=20format=20for?= =?UTF-8?q?=20assert=20messages=20to=20enable=20better=20suppor=E2=80=A6?= =?UTF-8?q?=20(#6262)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Use JUnit's assert format for assert messages to enable better support in IDEs * remove unnecessary < and > since it's not matched by IntelliJ's regex --- .../reactivex/observers/BaseTestConsumer.java | 18 +++++++++--------- .../reactivex/observers/TestObserverTest.java | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/observers/BaseTestConsumer.java b/src/main/java/io/reactivex/observers/BaseTestConsumer.java index 2bb9285787..61db5a2356 100644 --- a/src/main/java/io/reactivex/observers/BaseTestConsumer.java +++ b/src/main/java/io/reactivex/observers/BaseTestConsumer.java @@ -351,11 +351,11 @@ public final U assertError(Predicate<Throwable> errorPredicate) { public final U assertValue(T value) { int s = values.size(); if (s != 1) { - throw fail("Expected: " + valueAndClass(value) + ", Actual: " + values); + throw fail("expected: " + valueAndClass(value) + " but was: " + values); } T v = values.get(0); if (!ObjectHelper.equals(value, v)) { - throw fail("Expected: " + valueAndClass(value) + ", Actual: " + valueAndClass(v)); + throw fail("expected: " + valueAndClass(value) + " but was: " + valueAndClass(v)); } return (U)this; } @@ -450,7 +450,7 @@ public final U assertValueAt(int index, T value) { T v = values.get(index); if (!ObjectHelper.equals(value, v)) { - throw fail("Expected: " + valueAndClass(value) + ", Actual: " + valueAndClass(v)); + throw fail("expected: " + valueAndClass(value) + " but was: " + valueAndClass(v)); } return (U)this; } @@ -512,7 +512,7 @@ public static String valueAndClass(Object o) { public final U assertValueCount(int count) { int s = values.size(); if (s != count) { - throw fail("Value counts differ; Expected: " + count + ", Actual: " + s); + throw fail("Value counts differ; expected: " + count + " but was: " + s); } return (U)this; } @@ -535,14 +535,14 @@ public final U assertNoValues() { public final U assertValues(T... values) { int s = this.values.size(); if (s != values.length) { - throw fail("Value count differs; Expected: " + values.length + " " + Arrays.toString(values) - + ", Actual: " + s + " " + this.values); + throw fail("Value count differs; expected: " + values.length + " " + Arrays.toString(values) + + " but was: " + s + " " + this.values); } for (int i = 0; i < s; i++) { T v = this.values.get(i); T u = values[i]; if (!ObjectHelper.equals(u, v)) { - throw fail("Values at position " + i + " differ; Expected: " + valueAndClass(u) + ", Actual: " + valueAndClass(v)); + throw fail("Values at position " + i + " differ; expected: " + valueAndClass(u) + " but was: " + valueAndClass(v)); } } return (U)this; @@ -628,7 +628,7 @@ public final U assertValueSequence(Iterable<? extends T> sequence) { T v = actualIterator.next(); if (!ObjectHelper.equals(u, v)) { - throw fail("Values at position " + i + " differ; Expected: " + valueAndClass(u) + ", Actual: " + valueAndClass(v)); + throw fail("Values at position " + i + " differ; expected: " + valueAndClass(u) + " but was: " + valueAndClass(v)); } i++; } @@ -738,7 +738,7 @@ public final U assertErrorMessage(String message) { Throwable e = errors.get(0); String errorMessage = e.getMessage(); if (!ObjectHelper.equals(message, errorMessage)) { - throw fail("Error message differs; Expected: " + message + ", Actual: " + errorMessage); + throw fail("Error message differs; exptected: " + message + " but was: " + errorMessage); } } else { throw fail("Multiple errors"); diff --git a/src/test/java/io/reactivex/observers/TestObserverTest.java b/src/test/java/io/reactivex/observers/TestObserverTest.java index 2258d15779..d2d81dc77c 100644 --- a/src/test/java/io/reactivex/observers/TestObserverTest.java +++ b/src/test/java/io/reactivex/observers/TestObserverTest.java @@ -1407,7 +1407,7 @@ public void assertValueAtIndexNoMatch() { Observable.just("a", "b", "c").subscribe(to); thrown.expect(AssertionError.class); - thrown.expectMessage("Expected: b (class: String), Actual: c (class: String) (latch = 0, values = 3, errors = 0, completions = 1)"); + thrown.expectMessage("expected: b (class: String) but was: c (class: String) (latch = 0, values = 3, errors = 0, completions = 1)"); to.assertValueAt(2, "b"); } From 1a774e6d775d381937ae360296a88610353fefe6 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sat, 27 Oct 2018 23:08:08 +0200 Subject: [PATCH 299/417] 2.x: Fix cancel/dispose upon upstream switch for some operators (#6258) * 2.x: Fix cancel/dispose upon upstream switch for some operators * Restore star imports --- .../flowable/FlowableConcatArray.java | 1 + .../operators/flowable/FlowableConcatMap.java | 1 + .../FlowableDelaySubscriptionOther.java | 119 +++++----- .../flowable/FlowableOnErrorNext.java | 1 + .../operators/flowable/FlowableRepeat.java | 2 +- .../flowable/FlowableRepeatUntil.java | 2 +- .../flowable/FlowableRepeatWhen.java | 2 + .../flowable/FlowableRetryBiPredicate.java | 2 +- .../flowable/FlowableRetryPredicate.java | 2 +- .../flowable/FlowableSwitchIfEmpty.java | 2 +- .../operators/flowable/FlowableTimeout.java | 1 + .../flowable/FlowableTimeoutTimed.java | 1 + .../observable/ObservableConcatMap.java | 2 +- .../observable/ObservableRepeatWhen.java | 3 +- .../ObservableRetryBiPredicate.java | 2 +- .../observable/ObservableRetryPredicate.java | 2 +- .../observable/ObservableRetryWhen.java | 1 + .../subscriptions/SubscriptionArbiter.java | 11 +- .../flowable/FlowableConcatMapTest.java | 27 ++- .../flowable/FlowableConcatTest.java | 40 +++- .../flowable/FlowableRepeatTest.java | 73 ++++++ .../operators/flowable/FlowableRetryTest.java | 218 +++++++++++++++++- .../FlowableRetryWithPredicateTest.java | 4 +- .../flowable/FlowableSwitchIfEmptyTest.java | 4 +- .../observable/ObservableConcatMapTest.java | 27 ++- .../observable/ObservableConcatTest.java | 39 ++++ .../observable/ObservableRepeatTest.java | 73 ++++++ .../observable/ObservableRetryTest.java | 208 ++++++++++++++++- .../ObservableRetryWithPredicateTest.java | 4 +- .../SubscriptionArbiterTest.java | 144 +++++++++++- 30 files changed, 920 insertions(+), 98 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatArray.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatArray.java index c06cffa80a..4d7cd06c5b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatArray.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatArray.java @@ -59,6 +59,7 @@ static final class ConcatArraySubscriber<T> extends SubscriptionArbiter implemen long produced; ConcatArraySubscriber(Publisher<? extends T>[] sources, boolean delayError, Subscriber<? super T> downstream) { + super(false); this.downstream = downstream; this.sources = sources; this.delayError = delayError; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java index edde82442e..2dc316d1e9 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java @@ -571,6 +571,7 @@ static final class ConcatMapInner<R> long produced; ConcatMapInner(ConcatMapSupport<R> parent) { + super(false); this.parent = parent; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOther.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOther.java index a98892a01c..ea52987d59 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOther.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDelaySubscriptionOther.java @@ -12,10 +12,12 @@ */ package io.reactivex.internal.operators.flowable; +import java.util.concurrent.atomic.*; + import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.internal.subscriptions.SubscriptionArbiter; +import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.plugins.RxJavaPlugins; /** @@ -35,94 +37,105 @@ public FlowableDelaySubscriptionOther(Publisher<? extends T> main, Publisher<U> @Override public void subscribeActual(final Subscriber<? super T> child) { - final SubscriptionArbiter serial = new SubscriptionArbiter(); - child.onSubscribe(serial); + MainSubscriber<T> parent = new MainSubscriber<T>(child, main); + child.onSubscribe(parent); + other.subscribe(parent.other); + } - FlowableSubscriber<U> otherSubscriber = new DelaySubscriber(serial, child); + static final class MainSubscriber<T> extends AtomicLong implements FlowableSubscriber<T>, Subscription { - other.subscribe(otherSubscriber); - } + private static final long serialVersionUID = 2259811067697317255L; + + final Subscriber<? super T> downstream; - final class DelaySubscriber implements FlowableSubscriber<U> { - final SubscriptionArbiter serial; - final Subscriber<? super T> child; - boolean done; + final Publisher<? extends T> main; - DelaySubscriber(SubscriptionArbiter serial, Subscriber<? super T> child) { - this.serial = serial; - this.child = child; + final OtherSubscriber other; + + final AtomicReference<Subscription> upstream; + + MainSubscriber(Subscriber<? super T> downstream, Publisher<? extends T> main) { + this.downstream = downstream; + this.main = main; + this.other = new OtherSubscriber(); + this.upstream = new AtomicReference<Subscription>(); } - @Override - public void onSubscribe(final Subscription s) { - serial.setSubscription(new DelaySubscription(s)); - s.request(Long.MAX_VALUE); + void next() { + main.subscribe(this); } @Override - public void onNext(U t) { - onComplete(); + public void onNext(T t) { + downstream.onNext(t); } @Override - public void onError(Throwable e) { - if (done) { - RxJavaPlugins.onError(e); - return; - } - done = true; - child.onError(e); + public void onError(Throwable t) { + downstream.onError(t); } @Override public void onComplete() { - if (done) { - return; - } - done = true; - - main.subscribe(new OnCompleteSubscriber()); + downstream.onComplete(); } - final class DelaySubscription implements Subscription { - - final Subscription upstream; - - DelaySubscription(Subscription s) { - this.upstream = s; + @Override + public void request(long n) { + if (SubscriptionHelper.validate(n)) { + SubscriptionHelper.deferredRequest(upstream, this, n); } + } - @Override - public void request(long n) { - // ignored - } + @Override + public void cancel() { + SubscriptionHelper.cancel(other); + SubscriptionHelper.cancel(upstream); + } - @Override - public void cancel() { - upstream.cancel(); - } + @Override + public void onSubscribe(Subscription s) { + SubscriptionHelper.deferredSetOnce(upstream, this, s); } - final class OnCompleteSubscriber implements FlowableSubscriber<T> { + final class OtherSubscriber extends AtomicReference<Subscription> implements FlowableSubscriber<Object> { + + private static final long serialVersionUID = -3892798459447644106L; + @Override public void onSubscribe(Subscription s) { - serial.setSubscription(s); + if (SubscriptionHelper.setOnce(this, s)) { + s.request(Long.MAX_VALUE); + } } @Override - public void onNext(T t) { - child.onNext(t); + public void onNext(Object t) { + Subscription s = get(); + if (s != SubscriptionHelper.CANCELLED) { + lazySet(SubscriptionHelper.CANCELLED); + s.cancel(); + next(); + } } @Override public void onError(Throwable t) { - child.onError(t); + Subscription s = get(); + if (s != SubscriptionHelper.CANCELLED) { + downstream.onError(t); + } else { + RxJavaPlugins.onError(t); + } } @Override public void onComplete() { - child.onComplete(); + Subscription s = get(); + if (s != SubscriptionHelper.CANCELLED) { + next(); + } } } - } +} } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java index 4d5b86c880..7110d086e0 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnErrorNext.java @@ -58,6 +58,7 @@ static final class OnErrorNextSubscriber<T> long produced; OnErrorNextSubscriber(Subscriber<? super T> actual, Function<? super Throwable, ? extends Publisher<? extends T>> nextSupplier, boolean allowFatal) { + super(false); this.downstream = actual; this.nextSupplier = nextSupplier; this.allowFatal = allowFatal; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java index f99bc48a20..1bbdd7cd5c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeat.java @@ -29,7 +29,7 @@ public FlowableRepeat(Flowable<T> source, long count) { @Override public void subscribeActual(Subscriber<? super T> s) { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(false); s.onSubscribe(sa); RepeatSubscriber<T> rs = new RepeatSubscriber<T>(s, count != Long.MAX_VALUE ? count - 1 : Long.MAX_VALUE, sa, source); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java index d373a3865d..9c7057af59 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatUntil.java @@ -31,7 +31,7 @@ public FlowableRepeatUntil(Flowable<T> source, BooleanSupplier until) { @Override public void subscribeActual(Subscriber<? super T> s) { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(false); s.onSubscribe(sa); RepeatSubscriber<T> rs = new RepeatSubscriber<T>(s, until, sa, source); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java index c5fac022ad..45f8bfbb1e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java @@ -143,6 +143,7 @@ abstract static class WhenSourceSubscriber<T, U> extends SubscriptionArbiter imp WhenSourceSubscriber(Subscriber<? super T> actual, FlowableProcessor<U> processor, Subscription receiver) { + super(false); this.downstream = actual; this.processor = processor; this.receiver = receiver; @@ -160,6 +161,7 @@ public final void onNext(T t) { } protected final void again(U signal) { + setSubscription(EmptySubscription.INSTANCE); long p = produced; if (p != 0L) { produced = 0L; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java index 662ddb694c..8bc9ba27d0 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryBiPredicate.java @@ -33,7 +33,7 @@ public FlowableRetryBiPredicate( @Override public void subscribeActual(Subscriber<? super T> s) { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(false); s.onSubscribe(sa); RetryBiSubscriber<T> rs = new RetryBiSubscriber<T>(s, predicate, sa, source); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java index 47a8e3d878..8d035aaf95 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryPredicate.java @@ -35,7 +35,7 @@ public FlowableRetryPredicate(Flowable<T> source, @Override public void subscribeActual(Subscriber<? super T> s) { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(false); s.onSubscribe(sa); RetrySubscriber<T> rs = new RetrySubscriber<T>(s, count, predicate, sa, source); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmpty.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmpty.java index f9fc7ebc4c..be8febdf17 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmpty.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmpty.java @@ -43,7 +43,7 @@ static final class SwitchIfEmptySubscriber<T> implements FlowableSubscriber<T> { this.downstream = actual; this.other = other; this.empty = true; - this.arbiter = new SubscriptionArbiter(); + this.arbiter = new SubscriptionArbiter(false); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java index 6d8300f234..eec781bcc3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java @@ -208,6 +208,7 @@ static final class TimeoutFallbackSubscriber<T> extends SubscriptionArbiter TimeoutFallbackSubscriber(Subscriber<? super T> actual, Function<? super T, ? extends Publisher<?>> itemTimeoutIndicator, Publisher<? extends T> fallback) { + super(true); this.downstream = actual; this.itemTimeoutIndicator = itemTimeoutIndicator; this.task = new SequentialDisposable(); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java index 54a2762dfc..d25acdc3e3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java @@ -196,6 +196,7 @@ static final class TimeoutFallbackSubscriber<T> extends SubscriptionArbiter TimeoutFallbackSubscriber(Subscriber<? super T> actual, long timeout, TimeUnit unit, Scheduler.Worker worker, Publisher<? extends T> fallback) { + super(true); this.downstream = actual; this.timeout = timeout; this.unit = unit; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java index 831cfd1c55..a59841d501 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java @@ -244,7 +244,7 @@ static final class InnerObserver<U> extends AtomicReference<Disposable> implemen @Override public void onSubscribe(Disposable d) { - DisposableHelper.set(this, d); + DisposableHelper.replace(this, d); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java index 4b8e194973..af27f2f6d0 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java @@ -92,7 +92,7 @@ static final class RepeatWhenObserver<T> extends AtomicInteger implements Observ @Override public void onSubscribe(Disposable d) { - DisposableHelper.replace(this.upstream, d); + DisposableHelper.setOnce(this.upstream, d); } @Override @@ -109,6 +109,7 @@ public void onError(Throwable e) { @Override public void onComplete() { active = false; + DisposableHelper.replace(upstream, null); signaller.onNext(0); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java index c9be2c75ca..f762142f0b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryBiPredicate.java @@ -58,7 +58,7 @@ static final class RetryBiObserver<T> extends AtomicInteger implements Observer< @Override public void onSubscribe(Disposable d) { - upstream.update(d); + upstream.replace(d); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java index 6fb5d7b665..ee5e074f58 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryPredicate.java @@ -61,7 +61,7 @@ static final class RepeatObserver<T> extends AtomicInteger implements Observer<T @Override public void onSubscribe(Disposable d) { - upstream.update(d); + upstream.replace(d); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryWhen.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryWhen.java index 65a17fe269..0d48ef1239 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryWhen.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRetryWhen.java @@ -102,6 +102,7 @@ public void onNext(T t) { @Override public void onError(Throwable e) { + DisposableHelper.replace(upstream, null); active = false; signaller.onNext(e); } diff --git a/src/main/java/io/reactivex/internal/subscriptions/SubscriptionArbiter.java b/src/main/java/io/reactivex/internal/subscriptions/SubscriptionArbiter.java index 6abda2ce51..2796573392 100644 --- a/src/main/java/io/reactivex/internal/subscriptions/SubscriptionArbiter.java +++ b/src/main/java/io/reactivex/internal/subscriptions/SubscriptionArbiter.java @@ -55,11 +55,14 @@ public class SubscriptionArbiter extends AtomicInteger implements Subscription { final AtomicLong missedProduced; + final boolean cancelOnReplace; + volatile boolean cancelled; protected boolean unbounded; - public SubscriptionArbiter() { + public SubscriptionArbiter(boolean cancelOnReplace) { + this.cancelOnReplace = cancelOnReplace; missedSubscription = new AtomicReference<Subscription>(); missedRequested = new AtomicLong(); missedProduced = new AtomicLong(); @@ -80,7 +83,7 @@ public final void setSubscription(Subscription s) { if (get() == 0 && compareAndSet(0, 1)) { Subscription a = actual; - if (a != null) { + if (a != null && cancelOnReplace) { a.cancel(); } @@ -100,7 +103,7 @@ public final void setSubscription(Subscription s) { } Subscription a = missedSubscription.getAndSet(s); - if (a != null) { + if (a != null && cancelOnReplace) { a.cancel(); } drain(); @@ -240,7 +243,7 @@ final void drainLoop() { } if (ms != null) { - if (a != null) { + if (a != null && cancelOnReplace) { a.cancel(); } actual = ms; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java index ac5c573910..eba09e564f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java @@ -13,14 +13,17 @@ package io.reactivex.internal.operators.flowable; +import static org.junit.Assert.assertEquals; + import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.reactivestreams.Publisher; import io.reactivex.*; import io.reactivex.exceptions.TestException; -import io.reactivex.functions.Function; +import io.reactivex.functions.*; import io.reactivex.internal.operators.flowable.FlowableConcatMap.WeakScalarSubscription; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; @@ -143,4 +146,26 @@ public Publisher<Integer> apply(Integer v) .test() .assertFailure(TestException.class); } + + @Test + public void noCancelPrevious() { + final AtomicInteger counter = new AtomicInteger(); + + Flowable.range(1, 5) + .concatMap(new Function<Integer, Flowable<Integer>>() { + @Override + public Flowable<Integer> apply(Integer v) throws Exception { + return Flowable.just(v).doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + + assertEquals(0, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java index 733f3b7cf3..772f559733 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java @@ -29,7 +29,7 @@ import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.*; -import io.reactivex.functions.Function; +import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; @@ -1627,4 +1627,42 @@ public void subscribe(FlowableEmitter<Integer> s) throws Exception { assertEquals(1, calls[0]); } + + @SuppressWarnings("unchecked") + @Test + public void noCancelPreviousArray() { + final AtomicInteger counter = new AtomicInteger(); + + Flowable<Integer> source = Flowable.just(1).doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + Flowable.concatArray(source, source, source, source, source) + .test() + .assertResult(1, 1, 1, 1, 1); + + assertEquals(0, counter.get()); + } + + @SuppressWarnings("unchecked") + @Test + public void noCancelPreviousIterable() { + final AtomicInteger counter = new AtomicInteger(); + + Flowable<Integer> source = Flowable.just(1).doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + Flowable.concat(Arrays.asList(source, source, source, source, source)) + .test() + .assertResult(1, 1, 1, 1, 1); + + assertEquals(0, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java index 82cec69233..51376bc594 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java @@ -368,4 +368,77 @@ public Flowable<Object> apply(Flowable<Object> handler) throws Exception { .test() .assertResult(1, 2, 3, 1, 2, 3); } + + @Test + public void noCancelPreviousRepeat() { + final AtomicInteger counter = new AtomicInteger(); + + Flowable<Integer> source = Flowable.just(1).doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.repeat(5) + .test() + .assertResult(1, 1, 1, 1, 1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRepeatUntil() { + final AtomicInteger counter = new AtomicInteger(); + + Flowable<Integer> source = Flowable.just(1).doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + final AtomicInteger times = new AtomicInteger(); + + source.repeatUntil(new BooleanSupplier() { + @Override + public boolean getAsBoolean() throws Exception { + return times.getAndIncrement() == 4; + } + }) + .test() + .assertResult(1, 1, 1, 1, 1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRepeatWhen() { + final AtomicInteger counter = new AtomicInteger(); + + Flowable<Integer> source = Flowable.just(1).doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + final AtomicInteger times = new AtomicInteger(); + + source.repeatWhen(new Function<Flowable<Object>, Flowable<?>>() { + @Override + public Flowable<?> apply(Flowable<Object> e) throws Exception { + return e.takeWhile(new Predicate<Object>() { + @Override + public boolean test(Object v) throws Exception { + return times.getAndIncrement() < 4; + } + }); + } + }) + .test() + .assertResult(1, 1, 1, 1, 1); + + assertEquals(0, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java index 8a0a29f8dd..a5dd4918ab 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java @@ -30,6 +30,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.flowables.GroupedFlowable; import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; @@ -355,7 +356,7 @@ public void testRetrySubscribesAgainAfterError() throws Exception { Consumer<Integer> throwException = mock(Consumer.class); doThrow(new RuntimeException()).when(throwException).accept(Mockito.anyInt()); - // create a retrying observable based on a PublishProcessor + // create a retrying Flowable based on a PublishProcessor PublishProcessor<Integer> processor = PublishProcessor.create(); processor // record item @@ -492,7 +493,7 @@ public void cancel() { } @Test - public void testSourceObservableCallsUnsubscribe() throws InterruptedException { + public void testSourceFlowableCallsUnsubscribe() throws InterruptedException { final AtomicInteger subsCount = new AtomicInteger(0); final TestSubscriber<String> ts = new TestSubscriber<String>(); @@ -523,7 +524,7 @@ public void subscribe(Subscriber<? super String> s) { } @Test - public void testSourceObservableRetry1() throws InterruptedException { + public void testSourceFlowableRetry1() throws InterruptedException { final AtomicInteger subsCount = new AtomicInteger(0); final TestSubscriber<String> ts = new TestSubscriber<String>(); @@ -542,7 +543,7 @@ public void subscribe(Subscriber<? super String> s) { } @Test - public void testSourceObservableRetry0() throws InterruptedException { + public void testSourceFlowableRetry0() throws InterruptedException { final AtomicInteger subsCount = new AtomicInteger(0); final TestSubscriber<String> ts = new TestSubscriber<String>(); @@ -566,12 +567,14 @@ static final class SlowFlowable implements Publisher<Long> { final AtomicInteger active = new AtomicInteger(0); final AtomicInteger maxActive = new AtomicInteger(0); final AtomicInteger nextBeforeFailure; + final String context; private final int emitDelay; - SlowFlowable(int emitDelay, int countNext) { + SlowFlowable(int emitDelay, int countNext, String context) { this.emitDelay = emitDelay; this.nextBeforeFailure = new AtomicInteger(countNext); + this.context = context; } @Override @@ -593,7 +596,7 @@ public void cancel() { efforts.getAndIncrement(); active.getAndIncrement(); maxActive.set(Math.max(active.get(), maxActive.get())); - final Thread thread = new Thread() { + final Thread thread = new Thread(context) { @Override public void run() { long nr = 0; @@ -603,7 +606,9 @@ public void run() { if (nextBeforeFailure.getAndDecrement() > 0) { subscriber.onNext(nr++); } else { + active.decrementAndGet(); subscriber.onError(new RuntimeException("expected-failed")); + break; } } } catch (InterruptedException t) { @@ -664,7 +669,7 @@ public void testUnsubscribeAfterError() { Subscriber<Long> subscriber = TestHelper.mockSubscriber(); // Flowable that always fails after 100ms - SlowFlowable so = new SlowFlowable(100, 0); + SlowFlowable so = new SlowFlowable(100, 0, "testUnsubscribeAfterError"); Flowable<Long> f = Flowable.unsafeCreate(so).retry(5); AsyncSubscriber<Long> async = new AsyncSubscriber<Long>(subscriber); @@ -688,7 +693,7 @@ public void testTimeoutWithRetry() { Subscriber<Long> subscriber = TestHelper.mockSubscriber(); // Flowable that sends every 100ms (timeout fails instead) - SlowFlowable sf = new SlowFlowable(100, 10); + SlowFlowable sf = new SlowFlowable(100, 10, "testTimeoutWithRetry"); Flowable<Long> f = Flowable.unsafeCreate(sf).timeout(80, TimeUnit.MILLISECONDS).retry(5); AsyncSubscriber<Long> async = new AsyncSubscriber<Long>(subscriber); @@ -1001,7 +1006,7 @@ public boolean getAsBoolean() throws Exception { } @Test - public void shouldDisposeInnerObservable() { + public void shouldDisposeInnerFlowable() { final PublishProcessor<Object> processor = PublishProcessor.create(); final Disposable disposable = Flowable.error(new RuntimeException("Leak")) .retryWhen(new Function<Flowable<Throwable>, Flowable<Object>>() { @@ -1021,4 +1026,199 @@ public Flowable<Object> apply(Throwable ignore) throws Exception { disposable.dispose(); assertFalse(processor.hasSubscribers()); } + + @Test + public void noCancelPreviousRetry() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Flowable<Integer> source = Flowable.defer(new Callable<Flowable<Integer>>() { + @Override + public Flowable<Integer> call() throws Exception { + if (times.getAndIncrement() < 4) { + return Flowable.error(new TestException()); + } + return Flowable.just(1); + } + }) + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retry(5) + .test() + .assertResult(1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRetryWhile() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Flowable<Integer> source = Flowable.defer(new Callable<Flowable<Integer>>() { + @Override + public Flowable<Integer> call() throws Exception { + if (times.getAndIncrement() < 4) { + return Flowable.error(new TestException()); + } + return Flowable.just(1); + } + }) + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retry(5, Functions.alwaysTrue()) + .test() + .assertResult(1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRetryWhile2() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Flowable<Integer> source = Flowable.defer(new Callable<Flowable<Integer>>() { + @Override + public Flowable<Integer> call() throws Exception { + if (times.getAndIncrement() < 4) { + return Flowable.error(new TestException()); + } + return Flowable.just(1); + } + }) + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retry(new BiPredicate<Integer, Throwable>() { + @Override + public boolean test(Integer a, Throwable b) throws Exception { + return a < 5; + } + }) + .test() + .assertResult(1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRetryUntil() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Flowable<Integer> source = Flowable.defer(new Callable<Flowable<Integer>>() { + @Override + public Flowable<Integer> call() throws Exception { + if (times.getAndIncrement() < 4) { + return Flowable.error(new TestException()); + } + return Flowable.just(1); + } + }) + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retryUntil(new BooleanSupplier() { + @Override + public boolean getAsBoolean() throws Exception { + return false; + } + }) + .test() + .assertResult(1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRepeatWhen() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Flowable<Integer> source = Flowable.defer(new Callable<Flowable<Integer>>() { + @Override + public Flowable<Integer> call() throws Exception { + if (times.get() < 4) { + return Flowable.error(new TestException()); + } + return Flowable.just(1); + } + }).doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retryWhen(new Function<Flowable<Throwable>, Flowable<?>>() { + @Override + public Flowable<?> apply(Flowable<Throwable> e) throws Exception { + return e.takeWhile(new Predicate<Object>() { + @Override + public boolean test(Object v) throws Exception { + return times.getAndIncrement() < 4; + } + }); + } + }) + .test() + .assertResult(1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRepeatWhen2() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Flowable<Integer> source = Flowable.<Integer>error(new TestException()) + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retryWhen(new Function<Flowable<Throwable>, Flowable<?>>() { + @Override + public Flowable<?> apply(Flowable<Throwable> e) throws Exception { + return e.takeWhile(new Predicate<Object>() { + @Override + public boolean test(Object v) throws Exception { + return times.getAndIncrement() < 4; + } + }); + } + }) + .test() + .assertResult(); + + assertEquals(0, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java index 54346a73c0..de31e283a4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java @@ -230,7 +230,7 @@ public void testUnsubscribeAfterError() { Subscriber<Long> subscriber = TestHelper.mockSubscriber(); // Flowable that always fails after 100ms - FlowableRetryTest.SlowFlowable so = new FlowableRetryTest.SlowFlowable(100, 0); + FlowableRetryTest.SlowFlowable so = new FlowableRetryTest.SlowFlowable(100, 0, "testUnsubscribeAfterError"); Flowable<Long> f = Flowable .unsafeCreate(so) .retry(retry5); @@ -256,7 +256,7 @@ public void testTimeoutWithRetry() { Subscriber<Long> subscriber = TestHelper.mockSubscriber(); // Flowable that sends every 100ms (timeout fails instead) - FlowableRetryTest.SlowFlowable so = new FlowableRetryTest.SlowFlowable(100, 10); + FlowableRetryTest.SlowFlowable so = new FlowableRetryTest.SlowFlowable(100, 10, "testTimeoutWithRetry"); Flowable<Long> f = Flowable .unsafeCreate(so) .timeout(80, TimeUnit.MILLISECONDS) diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java index 99ecaaac43..f429d8e172 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchIfEmptyTest.java @@ -127,7 +127,7 @@ public void onNext(Long aLong) { } @Test - public void testSwitchShouldTriggerUnsubscribe() { + public void testSwitchShouldNotTriggerUnsubscribe() { final BooleanSubscription bs = new BooleanSubscription(); Flowable.unsafeCreate(new Publisher<Long>() { @@ -137,7 +137,7 @@ public void subscribe(final Subscriber<? super Long> subscriber) { subscriber.onComplete(); } }).switchIfEmpty(Flowable.<Long>never()).subscribe(); - assertTrue(bs.isCancelled()); + assertFalse(bs.isCancelled()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java index 5c2681a79d..4940d6c857 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapTest.java @@ -13,17 +13,18 @@ package io.reactivex.internal.operators.observable; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.util.List; import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.*; -import io.reactivex.functions.Function; +import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; @@ -498,4 +499,26 @@ public void onNext(Integer t) { to.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } + + @Test + public void noCancelPrevious() { + final AtomicInteger counter = new AtomicInteger(); + + Observable.range(1, 5) + .concatMap(new Function<Integer, ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> apply(Integer v) throws Exception { + return Observable.just(v).doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + + assertEquals(0, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java index fc2a01619b..d47c684cfc 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java @@ -28,6 +28,7 @@ import io.reactivex.Observer; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; import io.reactivex.observers.*; @@ -1155,4 +1156,42 @@ public void onComplete() { assertTrue(disposable[0].isDisposed()); } + + @SuppressWarnings("unchecked") + @Test + public void noCancelPreviousArray() { + final AtomicInteger counter = new AtomicInteger(); + + Observable<Integer> source = Observable.just(1).doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + Observable.concatArray(source, source, source, source, source) + .test() + .assertResult(1, 1, 1, 1, 1); + + assertEquals(0, counter.get()); + } + + @SuppressWarnings("unchecked") + @Test + public void noCancelPreviousIterable() { + final AtomicInteger counter = new AtomicInteger(); + + Observable<Integer> source = Observable.just(1).doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + Observable.concat(Arrays.asList(source, source, source, source, source)) + .test() + .assertResult(1, 1, 1, 1, 1); + + assertEquals(0, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java index 3616ef729f..3afc1f1cc7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java @@ -324,4 +324,77 @@ public Object apply(Object w) throws Exception { .test() .assertFailure(TestException.class, 1, 2, 3); } + + @Test + public void noCancelPreviousRepeat() { + final AtomicInteger counter = new AtomicInteger(); + + Observable<Integer> source = Observable.just(1).doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.repeat(5) + .test() + .assertResult(1, 1, 1, 1, 1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRepeatUntil() { + final AtomicInteger counter = new AtomicInteger(); + + Observable<Integer> source = Observable.just(1).doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + final AtomicInteger times = new AtomicInteger(); + + source.repeatUntil(new BooleanSupplier() { + @Override + public boolean getAsBoolean() throws Exception { + return times.getAndIncrement() == 4; + } + }) + .test() + .assertResult(1, 1, 1, 1, 1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRepeatWhen() { + final AtomicInteger counter = new AtomicInteger(); + + Observable<Integer> source = Observable.just(1).doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + final AtomicInteger times = new AtomicInteger(); + + source.repeatWhen(new Function<Observable<Object>, ObservableSource<?>>() { + @Override + public ObservableSource<?> apply(Observable<Object> e) throws Exception { + return e.takeWhile(new Predicate<Object>() { + @Override + public boolean test(Object v) throws Exception { + return times.getAndIncrement() < 4; + } + }); + } + }) + .test() + .assertResult(1, 1, 1, 1, 1); + + assertEquals(0, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java index 5c1cbe0041..e576479921 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; @@ -29,6 +30,7 @@ import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.observables.GroupedObservable; import io.reactivex.observers.*; @@ -522,11 +524,14 @@ static final class SlowObservable implements ObservableSource<Long> { final AtomicInteger active = new AtomicInteger(0), maxActive = new AtomicInteger(0); final AtomicInteger nextBeforeFailure; + final String context; + private final int emitDelay; - SlowObservable(int emitDelay, int countNext) { + SlowObservable(int emitDelay, int countNext, String context) { this.emitDelay = emitDelay; this.nextBeforeFailure = new AtomicInteger(countNext); + this.context = context; } @Override @@ -542,7 +547,7 @@ public void run() { efforts.getAndIncrement(); active.getAndIncrement(); maxActive.set(Math.max(active.get(), maxActive.get())); - final Thread thread = new Thread() { + final Thread thread = new Thread(context) { @Override public void run() { long nr = 0; @@ -552,7 +557,9 @@ public void run() { if (nextBeforeFailure.getAndDecrement() > 0) { observer.onNext(nr++); } else { + active.decrementAndGet(); observer.onError(new RuntimeException("expected-failed")); + break; } } } catch (InterruptedException t) { @@ -613,7 +620,7 @@ public void testUnsubscribeAfterError() { Observer<Long> observer = TestHelper.mockObserver(); // Observable that always fails after 100ms - SlowObservable so = new SlowObservable(100, 0); + SlowObservable so = new SlowObservable(100, 0, "testUnsubscribeAfterError"); Observable<Long> o = Observable.unsafeCreate(so).retry(5); AsyncObserver<Long> async = new AsyncObserver<Long>(observer); @@ -637,7 +644,7 @@ public void testTimeoutWithRetry() { Observer<Long> observer = TestHelper.mockObserver(); // Observable that sends every 100ms (timeout fails instead) - SlowObservable so = new SlowObservable(100, 10); + SlowObservable so = new SlowObservable(100, 10, "testTimeoutWithRetry"); Observable<Long> o = Observable.unsafeCreate(so).timeout(80, TimeUnit.MILLISECONDS).retry(5); AsyncObserver<Long> async = new AsyncObserver<Long>(observer); @@ -931,4 +938,197 @@ public ObservableSource<Object> apply(Throwable ignore) throws Exception { assertFalse(subject.hasObservers()); } + @Test + public void noCancelPreviousRetry() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Observable<Integer> source = Observable.defer(new Callable<ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> call() throws Exception { + if (times.getAndIncrement() < 4) { + return Observable.error(new TestException()); + } + return Observable.just(1); + } + }) + .doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retry(5) + .test() + .assertResult(1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRetryWhile() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Observable<Integer> source = Observable.defer(new Callable<ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> call() throws Exception { + if (times.getAndIncrement() < 4) { + return Observable.error(new TestException()); + } + return Observable.just(1); + } + }) + .doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retry(5, Functions.alwaysTrue()) + .test() + .assertResult(1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRetryWhile2() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Observable<Integer> source = Observable.defer(new Callable<ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> call() throws Exception { + if (times.getAndIncrement() < 4) { + return Observable.error(new TestException()); + } + return Observable.just(1); + } + }) + .doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retry(new BiPredicate<Integer, Throwable>() { + @Override + public boolean test(Integer a, Throwable b) throws Exception { + return a < 5; + } + }) + .test() + .assertResult(1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRetryUntil() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Observable<Integer> source = Observable.defer(new Callable<ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> call() throws Exception { + if (times.getAndIncrement() < 4) { + return Observable.error(new TestException()); + } + return Observable.just(1); + } + }) + .doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retryUntil(new BooleanSupplier() { + @Override + public boolean getAsBoolean() throws Exception { + return false; + } + }) + .test() + .assertResult(1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRepeatWhen() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Observable<Integer> source = Observable.defer(new Callable<ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> call() throws Exception { + if (times.get() < 4) { + return Observable.error(new TestException()); + } + return Observable.just(1); + } + }).doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retryWhen(new Function<Observable<Throwable>, ObservableSource<?>>() { + @Override + public ObservableSource<?> apply(Observable<Throwable> e) throws Exception { + return e.takeWhile(new Predicate<Object>() { + @Override + public boolean test(Object v) throws Exception { + return times.getAndIncrement() < 4; + } + }); + } + }) + .test() + .assertResult(1); + + assertEquals(0, counter.get()); + } + + @Test + public void noCancelPreviousRepeatWhen2() { + final AtomicInteger counter = new AtomicInteger(); + + final AtomicInteger times = new AtomicInteger(); + + Observable<Integer> source = Observable.<Integer>error(new TestException()).doOnDispose(new Action() { + @Override + public void run() throws Exception { + counter.getAndIncrement(); + } + }); + + source.retryWhen(new Function<Observable<Throwable>, ObservableSource<?>>() { + @Override + public ObservableSource<?> apply(Observable<Throwable> e) throws Exception { + return e.takeWhile(new Predicate<Object>() { + @Override + public boolean test(Object v) throws Exception { + return times.getAndIncrement() < 4; + } + }); + } + }) + .test() + .assertResult(); + + assertEquals(0, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java index 72981f705e..7b0322ab87 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java @@ -229,7 +229,7 @@ public void testUnsubscribeAfterError() { Observer<Long> observer = TestHelper.mockObserver(); // Observable that always fails after 100ms - ObservableRetryTest.SlowObservable so = new ObservableRetryTest.SlowObservable(100, 0); + ObservableRetryTest.SlowObservable so = new ObservableRetryTest.SlowObservable(100, 0, "testUnsubscribeAfterError"); Observable<Long> o = Observable .unsafeCreate(so) .retry(retry5); @@ -255,7 +255,7 @@ public void testTimeoutWithRetry() { Observer<Long> observer = TestHelper.mockObserver(); // Observable that sends every 100ms (timeout fails instead) - ObservableRetryTest.SlowObservable so = new ObservableRetryTest.SlowObservable(100, 10); + ObservableRetryTest.SlowObservable so = new ObservableRetryTest.SlowObservable(100, 10, "testTimeoutWithRetry"); Observable<Long> o = Observable .unsafeCreate(so) .timeout(80, TimeUnit.MILLISECONDS) diff --git a/src/test/java/io/reactivex/internal/subscriptions/SubscriptionArbiterTest.java b/src/test/java/io/reactivex/internal/subscriptions/SubscriptionArbiterTest.java index 02d7d30c0a..426d1779e1 100644 --- a/src/test/java/io/reactivex/internal/subscriptions/SubscriptionArbiterTest.java +++ b/src/test/java/io/reactivex/internal/subscriptions/SubscriptionArbiterTest.java @@ -26,7 +26,7 @@ public class SubscriptionArbiterTest { @Test public void setSubscriptionMissed() { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); @@ -45,7 +45,7 @@ public void setSubscriptionMissed() { @Test public void invalidDeferredRequest() { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(true); List<Throwable> errors = TestHelper.trackPluginErrors(); try { @@ -59,7 +59,7 @@ public void invalidDeferredRequest() { @Test public void unbounded() { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.request(Long.MAX_VALUE); @@ -86,7 +86,7 @@ public void unbounded() { @Test public void cancelled() { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.cancelled = true; BooleanSubscription bs1 = new BooleanSubscription(); @@ -102,7 +102,7 @@ public void cancelled() { @Test public void drainUnbounded() { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); @@ -113,7 +113,7 @@ public void drainUnbounded() { @Test public void drainMissedRequested() { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); @@ -128,7 +128,7 @@ public void drainMissedRequested() { @Test public void drainMissedRequestedProduced() { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); @@ -147,7 +147,7 @@ public void drainMissedRequestedProduced() { public void drainMissedRequestedMoreProduced() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); @@ -169,7 +169,7 @@ public void drainMissedRequestedMoreProduced() { @Test public void missedSubscriptionNoPrior() { - SubscriptionArbiter sa = new SubscriptionArbiter(); + SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); @@ -181,4 +181,130 @@ public void missedSubscriptionNoPrior() { assertSame(bs1, sa.actual); } + + @Test + public void noCancelFastPath() { + SubscriptionArbiter sa = new SubscriptionArbiter(false); + + BooleanSubscription bs1 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); + + sa.setSubscription(bs1); + sa.setSubscription(bs2); + + assertFalse(bs1.isCancelled()); + assertFalse(bs2.isCancelled()); + } + + @Test + public void cancelFastPath() { + SubscriptionArbiter sa = new SubscriptionArbiter(true); + + BooleanSubscription bs1 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); + + sa.setSubscription(bs1); + sa.setSubscription(bs2); + + assertTrue(bs1.isCancelled()); + assertFalse(bs2.isCancelled()); + } + + @Test + public void noCancelSlowPathReplace() { + SubscriptionArbiter sa = new SubscriptionArbiter(false); + + BooleanSubscription bs1 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); + BooleanSubscription bs3 = new BooleanSubscription(); + + sa.setSubscription(bs1); + + sa.getAndIncrement(); + + sa.setSubscription(bs2); + sa.setSubscription(bs3); + + sa.drainLoop(); + + assertFalse(bs1.isCancelled()); + assertFalse(bs2.isCancelled()); + assertFalse(bs3.isCancelled()); + } + + @Test + public void cancelSlowPathReplace() { + SubscriptionArbiter sa = new SubscriptionArbiter(true); + + BooleanSubscription bs1 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); + BooleanSubscription bs3 = new BooleanSubscription(); + + sa.setSubscription(bs1); + + sa.getAndIncrement(); + + sa.setSubscription(bs2); + sa.setSubscription(bs3); + + sa.drainLoop(); + + assertTrue(bs1.isCancelled()); + assertTrue(bs2.isCancelled()); + assertFalse(bs3.isCancelled()); + } + + @Test + public void noCancelSlowPath() { + SubscriptionArbiter sa = new SubscriptionArbiter(false); + + BooleanSubscription bs1 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); + + sa.setSubscription(bs1); + + sa.getAndIncrement(); + + sa.setSubscription(bs2); + + sa.drainLoop(); + + assertFalse(bs1.isCancelled()); + assertFalse(bs2.isCancelled()); + } + + @Test + public void cancelSlowPath() { + SubscriptionArbiter sa = new SubscriptionArbiter(true); + + BooleanSubscription bs1 = new BooleanSubscription(); + BooleanSubscription bs2 = new BooleanSubscription(); + + sa.setSubscription(bs1); + + sa.getAndIncrement(); + + sa.setSubscription(bs2); + + sa.drainLoop(); + + assertTrue(bs1.isCancelled()); + assertFalse(bs2.isCancelled()); + } + + @Test + public void moreProducedViolationFastPath() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + SubscriptionArbiter sa = new SubscriptionArbiter(true); + + sa.produced(2); + + assertEquals(0, sa.requested); + + TestHelper.assertError(errors, 0, IllegalStateException.class, "More produced than requested: -2"); + } finally { + RxJavaPlugins.reset(); + } + } } From 7849fc9f48f91129a3fb511943ea834d7f5a170b Mon Sep 17 00:00:00 2001 From: "Artem Zinnatullin :slowpoke" <ceo@artemzin.com> Date: Sun, 28 Oct 2018 03:06:45 -0700 Subject: [PATCH 300/417] Inline SubscriptionHelper.isCancelled() (#6263) --- .../operators/flowable/BlockingFlowableIterable.java | 2 +- .../internal/operators/flowable/FlowableGroupJoin.java | 4 ++-- .../operators/flowable/FlowablePublishMulticast.java | 2 +- .../internal/operators/flowable/FlowableRepeatWhen.java | 2 +- .../operators/flowable/FlowableSequenceEqualSingle.java | 2 +- .../internal/operators/flowable/FlowableTimeout.java | 2 +- .../operators/flowable/FlowableWithLatestFromMany.java | 2 +- .../operators/maybe/MaybeDelayOtherPublisher.java | 2 +- .../internal/subscribers/ForEachWhileSubscriber.java | 2 +- .../reactivex/internal/subscribers/FutureSubscriber.java | 2 +- .../internal/subscriptions/SubscriptionHelper.java | 8 -------- .../java/io/reactivex/subscribers/ResourceSubscriber.java | 2 +- 12 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java b/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java index 2eaaa5ffd3..af6613b224 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java @@ -179,7 +179,7 @@ public void dispose() { @Override public boolean isDisposed() { - return SubscriptionHelper.isCancelled(get()); + return get() == SubscriptionHelper.CANCELLED; } } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java index c9a2b69adb..7cf3adb7b8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java @@ -411,7 +411,7 @@ public void dispose() { @Override public boolean isDisposed() { - return SubscriptionHelper.isCancelled(get()); + return get() == SubscriptionHelper.CANCELLED; } @Override @@ -462,7 +462,7 @@ public void dispose() { @Override public boolean isDisposed() { - return SubscriptionHelper.isCancelled(get()); + return get() == SubscriptionHelper.CANCELLED; } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java index b68e4cf711..46a2dbd7e3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishMulticast.java @@ -205,7 +205,7 @@ public void dispose() { @Override public boolean isDisposed() { - return SubscriptionHelper.isCancelled(upstream.get()); + return upstream.get() == SubscriptionHelper.CANCELLED; } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java index 45f8bfbb1e..b62254185d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRepeatWhen.java @@ -93,7 +93,7 @@ public void onSubscribe(Subscription s) { public void onNext(Object t) { if (getAndIncrement() == 0) { for (;;) { - if (SubscriptionHelper.isCancelled(upstream.get())) { + if (upstream.get() == SubscriptionHelper.CANCELLED) { return; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java index c37bd0bac9..bcda903c85 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualSingle.java @@ -98,7 +98,7 @@ public void dispose() { @Override public boolean isDisposed() { - return SubscriptionHelper.isCancelled(first.get()); + return first.get() == SubscriptionHelper.CANCELLED; } void cancelAndClear() { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java index eec781bcc3..8363a5d0cb 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java @@ -382,7 +382,7 @@ public void dispose() { @Override public boolean isDisposed() { - return SubscriptionHelper.isCancelled(this.get()); + return this.get() == SubscriptionHelper.CANCELLED; } } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java index d3014113ed..6d6b949c33 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java @@ -133,7 +133,7 @@ void subscribe(Publisher<?>[] others, int n) { WithLatestInnerSubscriber[] subscribers = this.subscribers; AtomicReference<Subscription> upstream = this.upstream; for (int i = 0; i < n; i++) { - if (SubscriptionHelper.isCancelled(upstream.get())) { + if (upstream.get() == SubscriptionHelper.CANCELLED) { return; } others[i].subscribe(subscribers[i]); diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java index 55049d5c95..d3a0f783e2 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java @@ -65,7 +65,7 @@ public void dispose() { @Override public boolean isDisposed() { - return SubscriptionHelper.isCancelled(other.get()); + return other.get() == SubscriptionHelper.CANCELLED; } @Override diff --git a/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java index ebf47f12a6..5e15bea285 100644 --- a/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java @@ -108,6 +108,6 @@ public void dispose() { @Override public boolean isDisposed() { - return SubscriptionHelper.isCancelled(this.get()); + return this.get() == SubscriptionHelper.CANCELLED; } } diff --git a/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java index a559749fb1..4b2c329c97 100644 --- a/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java @@ -65,7 +65,7 @@ public boolean cancel(boolean mayInterruptIfRunning) { @Override public boolean isCancelled() { - return SubscriptionHelper.isCancelled(upstream.get()); + return upstream.get() == SubscriptionHelper.CANCELLED; } @Override diff --git a/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java b/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java index cddd53b8d1..ca19d0d4a3 100644 --- a/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java +++ b/src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java @@ -92,14 +92,6 @@ public static boolean validate(long n) { public static void reportMoreProduced(long n) { RxJavaPlugins.onError(new ProtocolViolationException("More produced than requested: " + n)); } - /** - * Check if the given subscription is the common cancelled subscription. - * @param s the subscription to check - * @return true if the subscription is the common cancelled subscription - */ - public static boolean isCancelled(Subscription s) { - return s == CANCELLED; - } /** * Atomically sets the subscription on the field and cancels the diff --git a/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java b/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java index daa37a024b..220fafd191 100644 --- a/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java +++ b/src/main/java/io/reactivex/subscribers/ResourceSubscriber.java @@ -167,6 +167,6 @@ public final void dispose() { */ @Override public final boolean isDisposed() { - return SubscriptionHelper.isCancelled(upstream.get()); + return upstream.get() == SubscriptionHelper.CANCELLED; } } From 45c0d98105de88bbf73ced44b73acfc3761a6dd1 Mon Sep 17 00:00:00 2001 From: lorenzpahl <l.pahl@outlook.com> Date: Mon, 29 Oct 2018 13:30:46 +0100 Subject: [PATCH 301/417] 2.x: Update Creating Observables docs (#6267) * Add "generate" section to the outline * Fix(image link broken) --- docs/Creating-Observables.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/Creating-Observables.md b/docs/Creating-Observables.md index 9e0c3b96cd..8e31a56528 100644 --- a/docs/Creating-Observables.md +++ b/docs/Creating-Observables.md @@ -7,6 +7,7 @@ This page shows methods that create reactive sources, such as `Observable`s. - [`empty`](#empty) - [`error`](#error) - [`from`](#from) +- [`generate`](#generate) - [`interval`](#interval) - [`just`](#just) - [`never`](#never) @@ -201,7 +202,7 @@ observable.subscribe( ## generate -**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` **ReactiveX documentation:** [http://reactivex.io/documentation/operators/create.html](http://reactivex.io/documentation/operators/create.html) From 76abb7beef3aa0b808cdbe193fd96ef04a5f0903 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 29 Oct 2018 18:17:12 +0100 Subject: [PATCH 302/417] 2.x: Call the doOn{Dispose|Cancel} handler at most once (#6269) --- src/main/java/io/reactivex/Observable.java | 2 +- .../observers/DisposableLambdaObserver.java | 18 ++++++++++------ .../flowable/FlowableDoOnLifecycle.java | 16 ++++++++------ .../flowable/FlowableDoOnLifecycleTest.java | 2 +- .../flowable/FlowableDoOnUnsubscribeTest.java | 21 +++++++++++++++++++ .../observable/ObservableCacheTest.java | 2 +- .../ObservableDoOnUnsubscribeTest.java | 21 +++++++++++++++++++ .../observable/ObservableReplayTest.java | 4 ++-- 8 files changed, 69 insertions(+), 17 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index ef3c5ed450..89468cec2b 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -8046,7 +8046,7 @@ public final Observable<T> doOnError(Consumer<? super Throwable> onError) { /** * Calls the appropriate onXXX method (shared between all Observer) for the lifecycle events of - * the sequence (subscription, disposal, requesting). + * the sequence (subscription, disposal). * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnLifecycle.o.png" alt=""> * <dl> diff --git a/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java b/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java index 7e3941e260..59d7fac2bc 100644 --- a/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java +++ b/src/main/java/io/reactivex/internal/observers/DisposableLambdaObserver.java @@ -61,6 +61,7 @@ public void onNext(T t) { @Override public void onError(Throwable t) { if (upstream != DisposableHelper.DISPOSED) { + upstream = DisposableHelper.DISPOSED; downstream.onError(t); } else { RxJavaPlugins.onError(t); @@ -70,19 +71,24 @@ public void onError(Throwable t) { @Override public void onComplete() { if (upstream != DisposableHelper.DISPOSED) { + upstream = DisposableHelper.DISPOSED; downstream.onComplete(); } } @Override public void dispose() { - try { - onDispose.run(); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - RxJavaPlugins.onError(e); + Disposable d = upstream; + if (d != DisposableHelper.DISPOSED) { + upstream = DisposableHelper.DISPOSED; + try { + onDispose.run(); + } catch (Throwable e) { + Exceptions.throwIfFatal(e); + RxJavaPlugins.onError(e); + } + d.dispose(); } - upstream.dispose(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycle.java index f0d233881d..0c979d2918 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycle.java @@ -108,13 +108,17 @@ public void request(long n) { @Override public void cancel() { - try { - onCancel.run(); - } catch (Throwable e) { - Exceptions.throwIfFatal(e); - RxJavaPlugins.onError(e); + Subscription s = upstream; + if (s != SubscriptionHelper.CANCELLED) { + upstream = SubscriptionHelper.CANCELLED; + try { + onCancel.run(); + } catch (Throwable e) { + Exceptions.throwIfFatal(e); + RxJavaPlugins.onError(e); + } + s.cancel(); } - upstream.cancel(); } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycleTest.java index 3d23930aaa..34578bbfee 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycleTest.java @@ -87,7 +87,7 @@ public void run() throws Exception { ); assertEquals(1, calls[0]); - assertEquals(2, calls[1]); + assertEquals(1, calls[1]); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnUnsubscribeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnUnsubscribeTest.java index 2987102666..de1bd0d57a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnUnsubscribeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnUnsubscribeTest.java @@ -24,6 +24,7 @@ import io.reactivex.Flowable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.*; +import io.reactivex.processors.BehaviorProcessor; import io.reactivex.subscribers.TestSubscriber; public class FlowableDoOnUnsubscribeTest { @@ -148,4 +149,24 @@ public void run() { assertEquals("There should exactly 1 un-subscription events for upper stream", 1, upperCount.get()); assertEquals("There should exactly 1 un-subscription events for lower stream", 1, lowerCount.get()); } + + @Test + public void noReentrantDispose() { + + final AtomicInteger cancelCalled = new AtomicInteger(); + + final BehaviorProcessor<Integer> p = BehaviorProcessor.create(); + p.doOnCancel(new Action() { + @Override + public void run() throws Exception { + cancelCalled.incrementAndGet(); + p.onNext(2); + } + }) + .firstOrError() + .subscribe() + .dispose(); + + assertEquals(1, cancelCalled.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java index 9629946ecb..e2aeb6a3f5 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java @@ -113,7 +113,7 @@ public void testUnsubscribeSource() throws Exception { o.subscribe(); o.subscribe(); o.subscribe(); - verify(unsubscribe, times(1)).run(); + verify(unsubscribe, never()).run(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnUnsubscribeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnUnsubscribeTest.java index 9d2c84db3c..b7df811bac 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnUnsubscribeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnUnsubscribeTest.java @@ -25,6 +25,7 @@ import io.reactivex.disposables.Disposable; import io.reactivex.functions.*; import io.reactivex.observers.TestObserver; +import io.reactivex.subjects.BehaviorSubject; public class ObservableDoOnUnsubscribeTest { @@ -152,4 +153,24 @@ public void run() { assertEquals("There should exactly 1 un-subscription events for upper stream", 1, upperCount.get()); assertEquals("There should exactly 1 un-subscription events for lower stream", 1, lowerCount.get()); } + + @Test + public void noReentrantDispose() { + + final AtomicInteger disposeCalled = new AtomicInteger(); + + final BehaviorSubject<Integer> s = BehaviorSubject.create(); + s.doOnDispose(new Action() { + @Override + public void run() throws Exception { + disposeCalled.incrementAndGet(); + s.onNext(2); + } + }) + .firstOrError() + .subscribe() + .dispose(); + + assertEquals(1, disposeCalled.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java index 5b06f031a2..2592361cd6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java @@ -938,11 +938,11 @@ public void accept(String v) { @Test public void testUnsubscribeSource() throws Exception { Action unsubscribe = mock(Action.class); - Observable<Integer> o = Observable.just(1).doOnDispose(unsubscribe).cache(); + Observable<Integer> o = Observable.just(1).doOnDispose(unsubscribe).replay().autoConnect(); o.subscribe(); o.subscribe(); o.subscribe(); - verify(unsubscribe, times(1)).run(); + verify(unsubscribe, never()).run(); } @Test From feb6db71433893244de853bbe9f977c09e6840ef Mon Sep 17 00:00:00 2001 From: OH JAE HWAN <ojh102@gmail.com> Date: Tue, 30 Oct 2018 23:44:24 +0900 Subject: [PATCH 303/417] Fix broken markdown (#6273) --- docs/How-to-Contribute.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/How-to-Contribute.md b/docs/How-to-Contribute.md index 1b63812764..d7c4a3ceb7 100644 --- a/docs/How-to-Contribute.md +++ b/docs/How-to-Contribute.md @@ -1,18 +1,18 @@ -RxJava is still a work in progress and has a long list of work documented in the [[Issues|https://github.com/ReactiveX/RxJava/issues]]. +RxJava is still a work in progress and has a long list of work documented in the [Issues](https://github.com/ReactiveX/RxJava/issues). If you wish to contribute we would ask that you: -- read [[Rx Design Guidelines|http://blogs.msdn.com/b/rxteam/archive/2010/10/28/rx-design-guidelines.aspx]] +- read [Rx Design Guidelines](http://blogs.msdn.com/b/rxteam/archive/2010/10/28/rx-design-guidelines.aspx) - review existing code and comply with existing patterns and idioms - include unit tests - stick to Rx contracts as defined by the Rx.Net implementation when porting operators (each issue attempts to reference the correct documentation from MSDN) -Information about licensing can be found at: [[CONTRIBUTING|https://github.com/ReactiveX/RxJava/blob/1.x/CONTRIBUTING.md]]. +Information about licensing can be found at: [CONTRIBUTING](https://github.com/ReactiveX/RxJava/blob/2.x/CONTRIBUTING.md). ## How to import the project into Eclipse Two options below: -###Import as Eclipse project +### Import as Eclipse project ./gradlew eclipse @@ -23,7 +23,7 @@ In Eclipse * Right click on the project in Package Explorer, select Properties - Java Compiler - Errors/Warnings - click Enable project specific settings. * Still in Errors/Warnings, go to Deprecated and restricted API and set Forbidden reference (access-rules) to Warning. -###Import as Gradle project +### Import as Gradle project You need the Gradle plugin for Eclipse installed. From fba8b61b08f3f11e588ed2e7f7b3c183eb71eab8 Mon Sep 17 00:00:00 2001 From: lorenzpahl <l.pahl@outlook.com> Date: Tue, 30 Oct 2018 16:20:47 +0100 Subject: [PATCH 304/417] 2.x: Update Error Handling Operators docs (#6266) * Change document structure; update operator list * Add examples * Clarify which handler is invoked * Use consistent wording in the descriptions * Cleanup --- docs/Error-Handling-Operators.md | 284 ++++++++++++++++++++++++++++++- 1 file changed, 277 insertions(+), 7 deletions(-) diff --git a/docs/Error-Handling-Operators.md b/docs/Error-Handling-Operators.md index 8acae59787..0b2eace61f 100644 --- a/docs/Error-Handling-Operators.md +++ b/docs/Error-Handling-Operators.md @@ -1,14 +1,284 @@ -There are a variety of operators that you can use to react to or recover from `onError` notifications from Observables. For example, you might: +There are a variety of operators that you can use to react to or recover from `onError` notifications from reactive sources, such as `Observable`s. For example, you might: 1. swallow the error and switch over to a backup Observable to continue the sequence 1. swallow the error and emit a default item 1. swallow the error and immediately try to restart the failed Observable 1. swallow the error and try to restart the failed Observable after some back-off interval -The following pages explain these operators. +# Outline -* [**`onErrorResumeNext( )`**](http://reactivex.io/documentation/operators/catch.html) — instructs an Observable to emit a sequence of items if it encounters an error -* [**`onErrorReturn( )`**](http://reactivex.io/documentation/operators/catch.html) — instructs an Observable to emit a particular item when it encounters an error -* [**`onExceptionResumeNext( )`**](http://reactivex.io/documentation/operators/catch.html) — instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable) -* [**`retry( )`**](http://reactivex.io/documentation/operators/retry.html) — if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error -* [**`retryWhen( )`**](http://reactivex.io/documentation/operators/retry.html) — if a source Observable emits an error, pass that error to another Observable to determine whether to resubscribe to the source \ No newline at end of file +- [`doOnError`](#doonerror) +- [`onErrorComplete`](#onerrorcomplete) +- [`onErrorResumeNext`](#onerrorresumenext) +- [`onErrorReturn`](#onerrorreturn) +- [`onErrorReturnItem`](#onerrorreturnitem) +- [`onExceptionResumeNext`](#onexceptionresumenext) +- [`retry`](#retry) +- [`retryUntil`](#retryuntil) +- [`retryWhen`](#retrywhen) + +## doOnError + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/do.html](http://reactivex.io/documentation/operators/do.html) + +Instructs a reactive type to invoke the given `io.reactivex.functions.Consumer` when it encounters an error. + +### doOnError example + +```java +Observable.error(new IOException("Something went wrong")) + .doOnError(error -> System.err.println("The error message is: " + error.getMessage())) + .subscribe( + x -> System.out.println("onNext should never be printed!"), + Throwable::printStackTrace, + () -> System.out.println("onComplete should never be printed!")); +``` + +## onErrorComplete + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/catch.html](http://reactivex.io/documentation/operators/catch.html) + +Instructs a reactive type to swallow an error event and replace it by a completion event. + +Optionally, a `io.reactivex.functions.Predicate` can be specified that gives more control over when an error event should be replaced by a completion event, and when not. + +### onErrorComplete example + +```java +Completable.fromAction(() -> { + throw new IOException(); +}).onErrorComplete(error -> { + // Only ignore errors of type java.io.IOException. + return error instanceof IOException; +}).subscribe( + () -> System.out.println("IOException was ignored"), + error -> System.err.println("onError should not be printed!")); +``` + +## onErrorResumeNext + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/catch.html](http://reactivex.io/documentation/operators/catch.html) + +Instructs a reactive type to emit a sequence of items if it encounters an error. + +### onErrorResumeNext example + +```java + Observable<Integer> numbers = Observable.generate(() -> 1, (state, emitter) -> { + emitter.onNext(state); + + return state + 1; +}); + +numbers.scan(Math::multiplyExact) + .onErrorResumeNext(Observable.empty()) + .subscribe( + System.out::println, + error -> System.err.println("onError should not be printed!")); + +// prints: +// 1 +// 2 +// 6 +// 24 +// 120 +// 720 +// 5040 +// 40320 +// 362880 +// 3628800 +// 39916800 +// 479001600 +``` + +## onErrorReturn + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/catch.html](http://reactivex.io/documentation/operators/catch.html) + +Instructs a reactive type to emit the item returned by the specified `io.reactivex.functions.Function` when it encounters an error. + +### onErrorReturn example + +```java +Single.just("2A") + .map(v -> Integer.parseInt(v, 10)) + .onErrorReturn(error -> { + if (error instanceof NumberFormatException) return 0; + else throw new IllegalArgumentException(); + }) + .subscribe( + System.out::println, + error -> System.err.println("onError should not be printed!")); + +// prints 0 +``` + +## onErrorReturnItem + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/catch.html](http://reactivex.io/documentation/operators/catch.html) + +Instructs a reactive type to emit a particular item when it encounters an error. + +### onErrorReturnItem example + +```java +Single.just("2A") + .map(v -> Integer.parseInt(v, 10)) + .onErrorReturnItem(0) + .subscribe( + System.out::println, + error -> System.err.println("onError should not be printed!")); + +// prints 0 +``` + +## onExceptionResumeNext + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/catch.html](http://reactivex.io/documentation/operators/catch.html) + +Instructs a reactive type to continue emitting items after it encounters an `java.lang.Exception`. Unlike [`onErrorResumeNext`](#onerrorresumenext), this one lets other types of `Throwable` continue through. + +### onExceptionResumeNext example + +```java +Observable<String> exception = Observable.<String>error(IOException::new) + .onExceptionResumeNext(Observable.just("This value will be used to recover from the IOException")); + +Observable<String> error = Observable.<String>error(Error::new) + .onExceptionResumeNext(Observable.just("This value will not be used")); + +Observable.concat(exception, error) + .subscribe( + message -> System.out.println("onNext: " + message), + err -> System.err.println("onError: " + err)); + +// prints: +// onNext: This value will be used to recover from the IOException +// onError: java.lang.Error +``` + +## retry + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/retry.html](http://reactivex.io/documentation/operators/retry.html) + +Instructs a reactive type to resubscribe to the source reactive type if it encounters an error in the hopes that it will complete without error. + +### retry example + +```java +Observable<Long> source = Observable.interval(0, 1, TimeUnit.SECONDS) + .flatMap(x -> { + if (x >= 2) return Observable.error(new IOException("Something went wrong!")); + else return Observable.just(x); + }); + +source.retry((retryCount, error) -> retryCount < 3) + .blockingSubscribe( + x -> System.out.println("onNext: " + x), + error -> System.err.println("onError: " + error.getMessage())); + +// prints: +// onNext: 0 +// onNext: 1 +// onNext: 0 +// onNext: 1 +// onNext: 0 +// onNext: 1 +// onError: Something went wrong! +``` + +## retryUntil + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/retry.html](http://reactivex.io/documentation/operators/retry.html) + +Instructs a reactive type to resubscribe to the source reactive type if it encounters an error until the given `io.reactivex.functions.BooleanSupplier` returns `true`. + +### retryUntil example + +```java +LongAdder errorCounter = new LongAdder(); +Observable<Long> source = Observable.interval(0, 1, TimeUnit.SECONDS) + .flatMap(x -> { + if (x >= 2) return Observable.error(new IOException("Something went wrong!")); + else return Observable.just(x); + }) + .doOnError((error) -> errorCounter.increment()); + +source.retryUntil(() -> errorCounter.intValue() >= 3) + .blockingSubscribe( + x -> System.out.println("onNext: " + x), + error -> System.err.println("onError: " + error.getMessage())); + +// prints: +// onNext: 0 +// onNext: 1 +// onNext: 0 +// onNext: 1 +// onNext: 0 +// onNext: 1 +// onError: Something went wrong! +``` + +## retryWhen + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/retry.html](http://reactivex.io/documentation/operators/retry.html) + +Instructs a reactive type to pass any error to another `Observable` or `Flowable` to determine whether to resubscribe to the source. + +### retryWhen example + +```java +Observable<Long> source = Observable.interval(0, 1, TimeUnit.SECONDS) + .flatMap(x -> { + if (x >= 2) return Observable.error(new IOException("Something went wrong!")); + else return Observable.just(x); + }); + +source.retryWhen(errors -> { + return errors.map(error -> 1) + + // Count the number of errors. + .scan(Math::addExact) + + .doOnNext(errorCount -> System.out.println("No. of errors: " + errorCount)) + + // Limit the maximum number of retries. + .takeWhile(errorCount -> errorCount < 3) + + // Signal resubscribe event after some delay. + .flatMapSingle(errorCount -> Single.timer(errorCount, TimeUnit.SECONDS)); +}).blockingSubscribe( + x -> System.out.println("onNext: " + x), + Throwable::printStackTrace, + () -> System.out.println("onComplete")); + +// prints: +// onNext: 0 +// onNext: 1 +// No. of errors: 1 +// onNext: 0 +// onNext: 1 +// No. of errors: 2 +// onNext: 0 +// onNext: 1 +// No. of errors: 3 +// onComplete +``` From c3cfb5ac774a6e08e0d1fdd42dd8c483329f4f23 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 1 Nov 2018 07:31:31 +0100 Subject: [PATCH 305/417] 2.x: Improve the Observable/Flowable cache() operators (#6275) * 2.x: Improve the Observable/Flowable cache() operators * Remove unnecessary casting. * Remove another unnecessary cast. --- src/main/java/io/reactivex/Observable.java | 5 +- .../operators/flowable/FlowableCache.java | 567 +++++++++--------- .../operators/observable/ObservableCache.java | 558 ++++++++--------- .../operators/flowable/FlowableCacheTest.java | 2 +- .../flowable/FlowableReplayTest.java | 4 +- .../observable/ObservableCacheTest.java | 27 +- 6 files changed, 615 insertions(+), 548 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 89468cec2b..c80e8be95d 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -6164,7 +6164,7 @@ public final <B, U extends Collection<? super T>> Observable<U> buffer(Callable< @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Observable<T> cache() { - return ObservableCache.from(this); + return cacheWithInitialCapacity(16); } /** @@ -6222,7 +6222,8 @@ public final Observable<T> cache() { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Observable<T> cacheWithInitialCapacity(int initialCapacity) { - return ObservableCache.from(this, initialCapacity); + ObjectHelper.verifyPositive(initialCapacity, "initialCapacity"); + return RxJavaPlugins.onAssembly(new ObservableCache<T>(this, initialCapacity)); } /** diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java index db4ccecfa1..830b0984ac 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java @@ -19,7 +19,7 @@ import io.reactivex.*; import io.reactivex.internal.subscriptions.SubscriptionHelper; -import io.reactivex.internal.util.*; +import io.reactivex.internal.util.BackpressureHelper; import io.reactivex.plugins.RxJavaPlugins; /** @@ -28,45 +28,93 @@ * * @param <T> the source element type */ -public final class FlowableCache<T> extends AbstractFlowableWithUpstream<T, T> { - /** The cache and replay state. */ - final CacheState<T> state; +public final class FlowableCache<T> extends AbstractFlowableWithUpstream<T, T> +implements FlowableSubscriber<T> { + /** + * The subscription to the source should happen at most once. + */ final AtomicBoolean once; /** - * Private constructor because state needs to be shared between the Observable body and - * the onSubscribe function. - * @param source the upstream source whose signals to cache - * @param capacityHint the capacity hint + * The number of items per cached nodes. + */ + final int capacityHint; + + /** + * The current known array of subscriber state to notify. + */ + final AtomicReference<CacheSubscription<T>[]> subscribers; + + /** + * A shared instance of an empty array of subscribers to avoid creating + * a new empty array when all subscribers cancel. + */ + @SuppressWarnings("rawtypes") + static final CacheSubscription[] EMPTY = new CacheSubscription[0]; + /** + * A shared instance indicating the source has no more events and there + * is no need to remember subscribers anymore. + */ + @SuppressWarnings("rawtypes") + static final CacheSubscription[] TERMINATED = new CacheSubscription[0]; + + /** + * The total number of elements in the list available for reads. + */ + volatile long size; + + /** + * The starting point of the cached items. */ + final Node<T> head; + + /** + * The current tail of the linked structure holding the items. + */ + Node<T> tail; + + /** + * How many items have been put into the tail node so far. + */ + int tailOffset; + + /** + * If {@link #subscribers} is {@link #TERMINATED}, this holds the terminal error if not null. + */ + Throwable error; + + /** + * True if the source has terminated. + */ + volatile boolean done; + + /** + * Constructs an empty, non-connected cache. + * @param source the source to subscribe to for the first incoming subscriber + * @param capacityHint the number of items expected (reduce allocation frequency) + */ + @SuppressWarnings("unchecked") public FlowableCache(Flowable<T> source, int capacityHint) { super(source); - this.state = new CacheState<T>(source, capacityHint); + this.capacityHint = capacityHint; this.once = new AtomicBoolean(); + Node<T> n = new Node<T>(capacityHint); + this.head = n; + this.tail = n; + this.subscribers = new AtomicReference<CacheSubscription<T>[]>(EMPTY); } @Override protected void subscribeActual(Subscriber<? super T> t) { - // we can connect first because we replay everything anyway - ReplaySubscription<T> rp = new ReplaySubscription<T>(t, state); - t.onSubscribe(rp); - - boolean doReplay = true; - if (state.addChild(rp)) { - if (rp.requested.get() == ReplaySubscription.CANCELLED) { - state.removeChild(rp); - doReplay = false; - } - } + CacheSubscription<T> consumer = new CacheSubscription<T>(t, this); + t.onSubscribe(consumer); + add(consumer); - // we ensure a single connection here to save an instance field of AtomicBoolean in state. if (!once.get() && once.compareAndSet(false, true)) { - state.connect(); - } - - if (doReplay) { - rp.replay(); + source.subscribe(this); + } else { + replay(consumer); } } @@ -75,7 +123,7 @@ protected void subscribeActual(Subscriber<? super T> t) { * @return true if already connected */ /* public */boolean isConnected() { - return state.isConnected; + return once.get(); } /** @@ -83,208 +131,248 @@ protected void subscribeActual(Subscriber<? super T> t) { * @return true if the cache has Subscribers */ /* public */ boolean hasSubscribers() { - return state.subscribers.get().length != 0; + return subscribers.get().length != 0; } /** * Returns the number of events currently cached. * @return the number of currently cached event count */ - /* public */ int cachedEventCount() { - return state.size(); + /* public */ long cachedEventCount() { + return size; } /** - * Contains the active child subscribers and the values to replay. - * - * @param <T> the value type of the cached items + * Atomically adds the consumer to the {@link #subscribers} copy-on-write array + * if the source has not yet terminated. + * @param consumer the consumer to add */ - static final class CacheState<T> extends LinkedArrayList implements FlowableSubscriber<T> { - /** The source observable to connect to. */ - final Flowable<T> source; - /** Holds onto the subscriber connected to source. */ - final AtomicReference<Subscription> connection = new AtomicReference<Subscription>(); - /** Guarded by connection (not this). */ - final AtomicReference<ReplaySubscription<T>[]> subscribers; - /** The default empty array of subscribers. */ - @SuppressWarnings("rawtypes") - static final ReplaySubscription[] EMPTY = new ReplaySubscription[0]; - /** The default empty array of subscribers. */ - @SuppressWarnings("rawtypes") - static final ReplaySubscription[] TERMINATED = new ReplaySubscription[0]; - - /** Set to true after connection. */ - volatile boolean isConnected; - /** - * Indicates that the source has completed emitting values or the - * Observable was forcefully terminated. - */ - boolean sourceDone; + void add(CacheSubscription<T> consumer) { + for (;;) { + CacheSubscription<T>[] current = subscribers.get(); + if (current == TERMINATED) { + return; + } + int n = current.length; - @SuppressWarnings("unchecked") - CacheState(Flowable<T> source, int capacityHint) { - super(capacityHint); - this.source = source; - this.subscribers = new AtomicReference<ReplaySubscription<T>[]>(EMPTY); + @SuppressWarnings("unchecked") + CacheSubscription<T>[] next = new CacheSubscription[n + 1]; + System.arraycopy(current, 0, next, 0, n); + next[n] = consumer; + + if (subscribers.compareAndSet(current, next)) { + return; + } } - /** - * Adds a ReplaySubscription to the subscribers array atomically. - * @param p the target ReplaySubscription wrapping a downstream Subscriber with state - * @return true if the ReplaySubscription was added or false if the cache is already terminated - */ - public boolean addChild(ReplaySubscription<T> p) { - // guarding by connection to save on allocating another object - // thus there are two distinct locks guarding the value-addition and child come-and-go - for (;;) { - ReplaySubscription<T>[] a = subscribers.get(); - if (a == TERMINATED) { - return false; - } - int n = a.length; - @SuppressWarnings("unchecked") - ReplaySubscription<T>[] b = new ReplaySubscription[n + 1]; - System.arraycopy(a, 0, b, 0, n); - b[n] = p; - if (subscribers.compareAndSet(a, b)) { - return true; + } + + /** + * Atomically removes the consumer from the {@link #subscribers} copy-on-write array. + * @param consumer the consumer to remove + */ + @SuppressWarnings("unchecked") + void remove(CacheSubscription<T> consumer) { + for (;;) { + CacheSubscription<T>[] current = subscribers.get(); + int n = current.length; + if (n == 0) { + return; + } + + int j = -1; + for (int i = 0; i < n; i++) { + if (current[i] == consumer) { + j = i; + break; } } + + if (j < 0) { + return; + } + CacheSubscription<T>[] next; + + if (n == 1) { + next = EMPTY; + } else { + next = new CacheSubscription[n - 1]; + System.arraycopy(current, 0, next, 0, j); + System.arraycopy(current, j + 1, next, j, n - j - 1); + } + + if (subscribers.compareAndSet(current, next)) { + return; + } + } + } + + /** + * Replays the contents of this cache to the given consumer based on its + * current state and number of items requested by it. + * @param consumer the consumer to continue replaying items to + */ + void replay(CacheSubscription<T> consumer) { + // make sure there is only one replay going on at a time + if (consumer.getAndIncrement() != 0) { + return; } - /** - * Removes the ReplaySubscription (if present) from the subscribers array atomically. - * @param p the target ReplaySubscription wrapping a downstream Subscriber with state - */ - @SuppressWarnings("unchecked") - public void removeChild(ReplaySubscription<T> p) { - for (;;) { - ReplaySubscription<T>[] a = subscribers.get(); - int n = a.length; - if (n == 0) { - return; - } - int j = -1; - for (int i = 0; i < n; i++) { - if (a[i].equals(p)) { - j = i; - break; - } - } - if (j < 0) { - return; - } - ReplaySubscription<T>[] b; - if (n == 1) { - b = EMPTY; + // see if there were more replay request in the meantime + int missed = 1; + // read out state into locals upfront to avoid being re-read due to volatile reads + long index = consumer.index; + int offset = consumer.offset; + Node<T> node = consumer.node; + AtomicLong requested = consumer.requested; + Subscriber<? super T> downstream = consumer.downstream; + int capacity = capacityHint; + + for (;;) { + // first see if the source has terminated, read order matters! + boolean sourceDone = done; + // and if the number of items is the same as this consumer has received + boolean empty = size == index; + + // if the source is done and we have all items so far, terminate the consumer + if (sourceDone && empty) { + // release the node object to avoid leaks through retained consumers + consumer.node = null; + // if error is not null then the source failed + Throwable ex = error; + if (ex != null) { + downstream.onError(ex); } else { - b = new ReplaySubscription[n - 1]; - System.arraycopy(a, 0, b, 0, j); - System.arraycopy(a, j + 1, b, j, n - j - 1); + downstream.onComplete(); } - if (subscribers.compareAndSet(a, b)) { + return; + } + + // there are still items not sent to the consumer + if (!empty) { + // see how many items the consumer has requested in total so far + long consumerRequested = requested.get(); + // MIN_VALUE indicates a cancelled consumer, we stop replaying + if (consumerRequested == Long.MIN_VALUE) { + // release the node object to avoid leaks through retained consumers + consumer.node = null; return; } - } - } + // if the consumer has requested more and there is more, we will emit an item + if (consumerRequested != index) { + + // if the offset in the current node has reached the node capacity + if (offset == capacity) { + // switch to the subsequent node + node = node.next; + // reset the in-node offset + offset = 0; + } - @Override - public void onSubscribe(Subscription s) { - SubscriptionHelper.setOnce(connection, s, Long.MAX_VALUE); - } + // emit the cached item + downstream.onNext(node.values[offset]); - /** - * Connects the cache to the source. - * Make sure this is called only once. - */ - public void connect() { - source.subscribe(this); - isConnected = true; - } + // move the node offset forward + offset++; + // move the total consumed item count forward + index++; - @Override - public void onNext(T t) { - if (!sourceDone) { - Object o = NotificationLite.next(t); - add(o); - for (ReplaySubscription<?> rp : subscribers.get()) { - rp.replay(); + // retry for the next item/terminal event if any + continue; } } - } - @SuppressWarnings("unchecked") - @Override - public void onError(Throwable e) { - if (!sourceDone) { - sourceDone = true; - Object o = NotificationLite.error(e); - add(o); - SubscriptionHelper.cancel(connection); - for (ReplaySubscription<?> rp : subscribers.getAndSet(TERMINATED)) { - rp.replay(); - } - } else { - RxJavaPlugins.onError(e); + // commit the changed references back + consumer.index = index; + consumer.offset = offset; + consumer.node = node; + // release the changes and see if there were more replay request in the meantime + missed = consumer.addAndGet(-missed); + if (missed == 0) { + break; } } + } - @SuppressWarnings("unchecked") - @Override - public void onComplete() { - if (!sourceDone) { - sourceDone = true; - Object o = NotificationLite.complete(); - add(o); - SubscriptionHelper.cancel(connection); - for (ReplaySubscription<?> rp : subscribers.getAndSet(TERMINATED)) { - rp.replay(); - } - } + @Override + public void onSubscribe(Subscription s) { + s.request(Long.MAX_VALUE); + } + + @Override + public void onNext(T t) { + int tailOffset = this.tailOffset; + // if the current tail node is full, create a fresh node + if (tailOffset == capacityHint) { + Node<T> n = new Node<T>(tailOffset); + n.values[0] = t; + this.tailOffset = 1; + tail.next = n; + tail = n; + } else { + tail.values[tailOffset] = t; + this.tailOffset = tailOffset + 1; + } + size++; + for (CacheSubscription<T> consumer : subscribers.get()) { + replay(consumer); + } + } + + @SuppressWarnings("unchecked") + @Override + public void onError(Throwable t) { + if (done) { + RxJavaPlugins.onError(t); + return; + } + error = t; + done = true; + for (CacheSubscription<T> consumer : subscribers.getAndSet(TERMINATED)) { + replay(consumer); + } + } + + @SuppressWarnings("unchecked") + @Override + public void onComplete() { + done = true; + for (CacheSubscription<T> consumer : subscribers.getAndSet(TERMINATED)) { + replay(consumer); } } /** - * Keeps track of the current request amount and the replay position for a child Subscriber. - * - * @param <T> + * Hosts the downstream consumer and its current requested and replay states. + * {@code this} holds the work-in-progress counter for the serialized replay. + * @param <T> the value type */ - static final class ReplaySubscription<T> - extends AtomicInteger implements Subscription { + static final class CacheSubscription<T> extends AtomicInteger + implements Subscription { - private static final long serialVersionUID = -2557562030197141021L; - private static final long CANCELLED = Long.MIN_VALUE; - /** The actual child subscriber. */ - final Subscriber<? super T> child; - /** The cache state object. */ - final CacheState<T> state; + private static final long serialVersionUID = 6770240836423125754L; + + final Subscriber<? super T> downstream; + + final FlowableCache<T> parent; - /** - * Number of items requested and also the cancelled indicator if - * it contains {@link #CANCELLED}. - */ final AtomicLong requested; - /** - * Contains the reference to the buffer segment in replay. - * Accessed after reading state.size() and when emitting == true. - */ - Object[] currentBuffer; - /** - * Contains the index into the currentBuffer where the next value is expected. - * Accessed after reading state.size() and when emitting == true. - */ - int currentIndexInBuffer; - /** - * Contains the absolute index up until the values have been replayed so far. - */ - int index; + Node<T> node; - /** Number of items emitted so far. */ - long emitted; + int offset; - ReplaySubscription(Subscriber<? super T> child, CacheState<T> state) { - this.child = child; - this.state = state; + long index; + + /** + * Constructs a new instance with the actual downstream consumer and + * the parent cache object. + * @param downstream the actual consumer + * @param parent the parent that holds onto the cached items + */ + CacheSubscription(Subscriber<? super T> downstream, FlowableCache<T> parent) { + this.downstream = downstream; + this.parent = parent; + this.node = parent.head; this.requested = new AtomicLong(); } @@ -292,99 +380,38 @@ static final class ReplaySubscription<T> public void request(long n) { if (SubscriptionHelper.validate(n)) { BackpressureHelper.addCancel(requested, n); - replay(); + parent.replay(this); } } @Override public void cancel() { - if (requested.getAndSet(CANCELLED) != CANCELLED) { - state.removeChild(this); + if (requested.getAndSet(Long.MIN_VALUE) != Long.MIN_VALUE) { + parent.remove(this); } } + } + + /** + * Represents a segment of the cached item list as + * part of a linked-node-list structure. + * @param <T> the element type + */ + static final class Node<T> { /** - * Continue replaying available values if there are requests for them. + * The array of values held by this node. */ - public void replay() { - if (getAndIncrement() != 0) { - return; - } - - int missed = 1; - final Subscriber<? super T> child = this.child; - AtomicLong rq = requested; - long e = emitted; - - for (;;) { + final T[] values; - long r = rq.get(); - - if (r == CANCELLED) { - return; - } - - // read the size, if it is non-zero, we can safely read the head and - // read values up to the given absolute index - int s = state.size(); - if (s != 0) { - Object[] b = currentBuffer; - - // latch onto the very first buffer now that it is available. - if (b == null) { - b = state.head(); - currentBuffer = b; - } - final int n = b.length - 1; - int j = index; - int k = currentIndexInBuffer; - - while (j < s && e != r) { - if (rq.get() == CANCELLED) { - return; - } - if (k == n) { - b = (Object[])b[n]; - k = 0; - } - Object o = b[k]; - - if (NotificationLite.accept(o, child)) { - return; - } - - k++; - j++; - e++; - } - - if (rq.get() == CANCELLED) { - return; - } - - if (r == e) { - Object o = b[k]; - if (NotificationLite.isComplete(o)) { - child.onComplete(); - return; - } else - if (NotificationLite.isError(o)) { - child.onError(NotificationLite.getError(o)); - return; - } - } - - index = j; - currentIndexInBuffer = k; - currentBuffer = b; - } + /** + * The next node if not null. + */ + volatile Node<T> next; - emitted = e; - missed = addAndGet(-missed); - if (missed == 0) { - break; - } - } + @SuppressWarnings("unchecked") + Node(int capacityHint) { + this.values = (T[])new Object[capacityHint]; } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java index 3bfe796efc..fdc3477b75 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCache.java @@ -17,10 +17,6 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; -import io.reactivex.internal.disposables.SequentialDisposable; -import io.reactivex.internal.functions.ObjectHelper; -import io.reactivex.internal.util.*; -import io.reactivex.plugins.RxJavaPlugins; /** * An observable which auto-connects to another observable, caches the elements @@ -28,61 +24,94 @@ * * @param <T> the source element type */ -public final class ObservableCache<T> extends AbstractObservableWithUpstream<T, T> { - /** The cache and replay state. */ - final CacheState<T> state; +public final class ObservableCache<T> extends AbstractObservableWithUpstream<T, T> +implements Observer<T> { + /** + * The subscription to the source should happen at most once. + */ final AtomicBoolean once; /** - * Creates a cached Observable with a default capacity hint of 16. - * @param <T> the value type - * @param source the source Observable to cache - * @return the CachedObservable instance + * The number of items per cached nodes. */ - public static <T> Observable<T> from(Observable<T> source) { - return from(source, 16); - } + final int capacityHint; /** - * Creates a cached Observable with the given capacity hint. - * @param <T> the value type - * @param source the source Observable to cache - * @param capacityHint the hint for the internal buffer size - * @return the CachedObservable instance + * The current known array of observer state to notify. */ - public static <T> Observable<T> from(Observable<T> source, int capacityHint) { - ObjectHelper.verifyPositive(capacityHint, "capacityHint"); - CacheState<T> state = new CacheState<T>(source, capacityHint); - return RxJavaPlugins.onAssembly(new ObservableCache<T>(source, state)); - } + final AtomicReference<CacheDisposable<T>[]> observers; + + /** + * A shared instance of an empty array of observers to avoid creating + * a new empty array when all observers dispose. + */ + @SuppressWarnings("rawtypes") + static final CacheDisposable[] EMPTY = new CacheDisposable[0]; + /** + * A shared instance indicating the source has no more events and there + * is no need to remember observers anymore. + */ + @SuppressWarnings("rawtypes") + static final CacheDisposable[] TERMINATED = new CacheDisposable[0]; + + /** + * The total number of elements in the list available for reads. + */ + volatile long size; + + /** + * The starting point of the cached items. + */ + final Node<T> head; + + /** + * The current tail of the linked structure holding the items. + */ + Node<T> tail; + + /** + * How many items have been put into the tail node so far. + */ + int tailOffset; + + /** + * If {@link #observers} is {@link #TERMINATED}, this holds the terminal error if not null. + */ + Throwable error; + + /** + * True if the source has terminated. + */ + volatile boolean done; /** - * Private constructor because state needs to be shared between the Observable body and - * the onSubscribe function. - * @param source the source Observable to cache - * @param state the cache state object + * Constructs an empty, non-connected cache. + * @param source the source to subscribe to for the first incoming observer + * @param capacityHint the number of items expected (reduce allocation frequency) */ - private ObservableCache(Observable<T> source, CacheState<T> state) { + @SuppressWarnings("unchecked") + public ObservableCache(Observable<T> source, int capacityHint) { super(source); - this.state = state; + this.capacityHint = capacityHint; this.once = new AtomicBoolean(); + Node<T> n = new Node<T>(capacityHint); + this.head = n; + this.tail = n; + this.observers = new AtomicReference<CacheDisposable<T>[]>(EMPTY); } @Override protected void subscribeActual(Observer<? super T> t) { - // we can connect first because we replay everything anyway - ReplayDisposable<T> rp = new ReplayDisposable<T>(t, state); - t.onSubscribe(rp); - - state.addChild(rp); + CacheDisposable<T> consumer = new CacheDisposable<T>(t, this); + t.onSubscribe(consumer); + add(consumer); - // we ensure a single connection here to save an instance field of AtomicBoolean in state. if (!once.get() && once.compareAndSet(false, true)) { - state.connect(); + source.subscribe(this); + } else { + replay(consumer); } - - rp.replay(); } /** @@ -90,290 +119,281 @@ protected void subscribeActual(Observer<? super T> t) { * @return true if already connected */ /* public */boolean isConnected() { - return state.isConnected; + return once.get(); } /** * Returns true if there are observers subscribed to this observable. - * @return true if the cache has downstream Observers + * @return true if the cache has observers */ /* public */ boolean hasObservers() { - return state.observers.get().length != 0; + return observers.get().length != 0; } /** * Returns the number of events currently cached. - * @return the current number of elements in the cache + * @return the number of currently cached event count */ - /* public */ int cachedEventCount() { - return state.size(); + /* public */ long cachedEventCount() { + return size; } /** - * Contains the active child observers and the values to replay. - * - * @param <T> + * Atomically adds the consumer to the {@link #observers} copy-on-write array + * if the source has not yet terminated. + * @param consumer the consumer to add */ - static final class CacheState<T> extends LinkedArrayList implements Observer<T> { - /** The source observable to connect to. */ - final Observable<? extends T> source; - /** Holds onto the subscriber connected to source. */ - final SequentialDisposable connection; - /** Guarded by connection (not this). */ - final AtomicReference<ReplayDisposable<T>[]> observers; - /** The default empty array of observers. */ - @SuppressWarnings("rawtypes") - static final ReplayDisposable[] EMPTY = new ReplayDisposable[0]; - /** The default empty array of observers. */ - @SuppressWarnings("rawtypes") - static final ReplayDisposable[] TERMINATED = new ReplayDisposable[0]; - - /** Set to true after connection. */ - volatile boolean isConnected; - /** - * Indicates that the source has completed emitting values or the - * Observable was forcefully terminated. - */ - boolean sourceDone; + void add(CacheDisposable<T> consumer) { + for (;;) { + CacheDisposable<T>[] current = observers.get(); + if (current == TERMINATED) { + return; + } + int n = current.length; - @SuppressWarnings("unchecked") - CacheState(Observable<? extends T> source, int capacityHint) { - super(capacityHint); - this.source = source; - this.observers = new AtomicReference<ReplayDisposable<T>[]>(EMPTY); - this.connection = new SequentialDisposable(); - } - /** - * Adds a ReplayDisposable to the observers array atomically. - * @param p the target ReplayDisposable wrapping a downstream Observer with additional state - * @return true if the disposable was added, false otherwise - */ - public boolean addChild(ReplayDisposable<T> p) { - // guarding by connection to save on allocating another object - // thus there are two distinct locks guarding the value-addition and child come-and-go - for (;;) { - ReplayDisposable<T>[] a = observers.get(); - if (a == TERMINATED) { - return false; - } - int n = a.length; - - @SuppressWarnings("unchecked") - ReplayDisposable<T>[] b = new ReplayDisposable[n + 1]; - System.arraycopy(a, 0, b, 0, n); - b[n] = p; - if (observers.compareAndSet(a, b)) { - return true; - } + @SuppressWarnings("unchecked") + CacheDisposable<T>[] next = new CacheDisposable[n + 1]; + System.arraycopy(current, 0, next, 0, n); + next[n] = consumer; + + if (observers.compareAndSet(current, next)) { + return; } } - /** - * Removes the ReplayDisposable (if present) from the observers array atomically. - * @param p the target ReplayDisposable wrapping a downstream Observer with additional state - */ - @SuppressWarnings("unchecked") - public void removeChild(ReplayDisposable<T> p) { - for (;;) { - ReplayDisposable<T>[] a = observers.get(); - int n = a.length; - if (n == 0) { - return; - } - int j = -1; - for (int i = 0; i < n; i++) { - if (a[i].equals(p)) { - j = i; - break; - } - } - if (j < 0) { - return; - } - ReplayDisposable<T>[] b; - if (n == 1) { - b = EMPTY; - } else { - b = new ReplayDisposable[n - 1]; - System.arraycopy(a, 0, b, 0, j); - System.arraycopy(a, j + 1, b, j, n - j - 1); - } - if (observers.compareAndSet(a, b)) { - return; + } + + /** + * Atomically removes the consumer from the {@link #observers} copy-on-write array. + * @param consumer the consumer to remove + */ + @SuppressWarnings("unchecked") + void remove(CacheDisposable<T> consumer) { + for (;;) { + CacheDisposable<T>[] current = observers.get(); + int n = current.length; + if (n == 0) { + return; + } + + int j = -1; + for (int i = 0; i < n; i++) { + if (current[i] == consumer) { + j = i; + break; } } - } - @Override - public void onSubscribe(Disposable d) { - connection.update(d); + if (j < 0) { + return; + } + CacheDisposable<T>[] next; + + if (n == 1) { + next = EMPTY; + } else { + next = new CacheDisposable[n - 1]; + System.arraycopy(current, 0, next, 0, j); + System.arraycopy(current, j + 1, next, j, n - j - 1); + } + + if (observers.compareAndSet(current, next)) { + return; + } } + } - /** - * Connects the cache to the source. - * Make sure this is called only once. - */ - public void connect() { - source.subscribe(this); - isConnected = true; + /** + * Replays the contents of this cache to the given consumer based on its + * current state and number of items requested by it. + * @param consumer the consumer to continue replaying items to + */ + void replay(CacheDisposable<T> consumer) { + // make sure there is only one replay going on at a time + if (consumer.getAndIncrement() != 0) { + return; } - @Override - public void onNext(T t) { - if (!sourceDone) { - Object o = NotificationLite.next(t); - add(o); - for (ReplayDisposable<?> rp : observers.get()) { - rp.replay(); - } + // see if there were more replay request in the meantime + int missed = 1; + // read out state into locals upfront to avoid being re-read due to volatile reads + long index = consumer.index; + int offset = consumer.offset; + Node<T> node = consumer.node; + Observer<? super T> downstream = consumer.downstream; + int capacity = capacityHint; + + for (;;) { + // if the consumer got disposed, clear the node and quit + if (consumer.disposed) { + consumer.node = null; + return; } - } - @SuppressWarnings("unchecked") - @Override - public void onError(Throwable e) { - if (!sourceDone) { - sourceDone = true; - Object o = NotificationLite.error(e); - add(o); - connection.dispose(); - for (ReplayDisposable<?> rp : observers.getAndSet(TERMINATED)) { - rp.replay(); + // first see if the source has terminated, read order matters! + boolean sourceDone = done; + // and if the number of items is the same as this consumer has received + boolean empty = size == index; + + // if the source is done and we have all items so far, terminate the consumer + if (sourceDone && empty) { + // release the node object to avoid leaks through retained consumers + consumer.node = null; + // if error is not null then the source failed + Throwable ex = error; + if (ex != null) { + downstream.onError(ex); + } else { + downstream.onComplete(); } + return; } - } - @SuppressWarnings("unchecked") - @Override - public void onComplete() { - if (!sourceDone) { - sourceDone = true; - Object o = NotificationLite.complete(); - add(o); - connection.dispose(); - for (ReplayDisposable<?> rp : observers.getAndSet(TERMINATED)) { - rp.replay(); + // there are still items not sent to the consumer + if (!empty) { + // if the offset in the current node has reached the node capacity + if (offset == capacity) { + // switch to the subsequent node + node = node.next; + // reset the in-node offset + offset = 0; } + + // emit the cached item + downstream.onNext(node.values[offset]); + + // move the node offset forward + offset++; + // move the total consumed item count forward + index++; + + // retry for the next item/terminal event if any + continue; + } + + // commit the changed references back + consumer.index = index; + consumer.offset = offset; + consumer.node = node; + // release the changes and see if there were more replay request in the meantime + missed = consumer.addAndGet(-missed); + if (missed == 0) { + break; } } } + @Override + public void onSubscribe(Disposable d) { + // we can't do much with the upstream disposable + } + + @Override + public void onNext(T t) { + int tailOffset = this.tailOffset; + // if the current tail node is full, create a fresh node + if (tailOffset == capacityHint) { + Node<T> n = new Node<T>(tailOffset); + n.values[0] = t; + this.tailOffset = 1; + tail.next = n; + tail = n; + } else { + tail.values[tailOffset] = t; + this.tailOffset = tailOffset + 1; + } + size++; + for (CacheDisposable<T> consumer : observers.get()) { + replay(consumer); + } + } + + @SuppressWarnings("unchecked") + @Override + public void onError(Throwable t) { + error = t; + done = true; + for (CacheDisposable<T> consumer : observers.getAndSet(TERMINATED)) { + replay(consumer); + } + } + + @SuppressWarnings("unchecked") + @Override + public void onComplete() { + done = true; + for (CacheDisposable<T> consumer : observers.getAndSet(TERMINATED)) { + replay(consumer); + } + } + /** - * Keeps track of the current request amount and the replay position for a child Observer. - * - * @param <T> + * Hosts the downstream consumer and its current requested and replay states. + * {@code this} holds the work-in-progress counter for the serialized replay. + * @param <T> the value type */ - static final class ReplayDisposable<T> - extends AtomicInteger + static final class CacheDisposable<T> extends AtomicInteger implements Disposable { - private static final long serialVersionUID = 7058506693698832024L; - /** The actual child subscriber. */ - final Observer<? super T> child; - /** The cache state object. */ - final CacheState<T> state; + private static final long serialVersionUID = 6770240836423125754L; - /** - * Contains the reference to the buffer segment in replay. - * Accessed after reading state.size() and when emitting == true. - */ - Object[] currentBuffer; - /** - * Contains the index into the currentBuffer where the next value is expected. - * Accessed after reading state.size() and when emitting == true. - */ - int currentIndexInBuffer; - /** - * Contains the absolute index up until the values have been replayed so far. - */ - int index; + final Observer<? super T> downstream; - /** Set if the ReplayDisposable has been cancelled/disposed. */ - volatile boolean cancelled; + final ObservableCache<T> parent; - ReplayDisposable(Observer<? super T> child, CacheState<T> state) { - this.child = child; - this.state = state; - } + Node<T> node; - @Override - public boolean isDisposed() { - return cancelled; + int offset; + + long index; + + volatile boolean disposed; + + /** + * Constructs a new instance with the actual downstream consumer and + * the parent cache object. + * @param downstream the actual consumer + * @param parent the parent that holds onto the cached items + */ + CacheDisposable(Observer<? super T> downstream, ObservableCache<T> parent) { + this.downstream = downstream; + this.parent = parent; + this.node = parent.head; } @Override public void dispose() { - if (!cancelled) { - cancelled = true; - state.removeChild(this); + if (!disposed) { + disposed = true; + parent.remove(this); } } - /** - * Continue replaying available values if there are requests for them. - */ - public void replay() { - // make sure there is only a single thread emitting - if (getAndIncrement() != 0) { - return; - } - - final Observer<? super T> child = this.child; - int missed = 1; - - for (;;) { + @Override + public boolean isDisposed() { + return disposed; + } + } - if (cancelled) { - return; - } + /** + * Represents a segment of the cached item list as + * part of a linked-node-list structure. + * @param <T> the element type + */ + static final class Node<T> { - // read the size, if it is non-zero, we can safely read the head and - // read values up to the given absolute index - int s = state.size(); - if (s != 0) { - Object[] b = currentBuffer; - - // latch onto the very first buffer now that it is available. - if (b == null) { - b = state.head(); - currentBuffer = b; - } - final int n = b.length - 1; - int j = index; - int k = currentIndexInBuffer; - - while (j < s) { - if (cancelled) { - return; - } - if (k == n) { - b = (Object[])b[n]; - k = 0; - } - Object o = b[k]; - - if (NotificationLite.accept(o, child)) { - return; - } - - k++; - j++; - } - - if (cancelled) { - return; - } - - index = j; - currentIndexInBuffer = k; - currentBuffer = b; + /** + * The array of values held by this node. + */ + final T[] values; - } + /** + * The next node if not null. + */ + volatile Node<T> next; - missed = addAndGet(-missed); - if (missed == 0) { - break; - } - } + @SuppressWarnings("unchecked") + Node(int capacityHint) { + this.values = (T[])new Object[capacityHint]; } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java index 6a427124bd..4208b18dec 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java @@ -139,7 +139,7 @@ public void testUnsubscribeSource() throws Exception { f.subscribe(); f.subscribe(); f.subscribe(); - verify(unsubscribe, times(1)).run(); + verify(unsubscribe, never()).run(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index 0cc39b5c03..dcf7eea347 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -951,11 +951,11 @@ public void accept(String v) { @Test public void testUnsubscribeSource() throws Exception { Action unsubscribe = mock(Action.class); - Flowable<Integer> f = Flowable.just(1).doOnCancel(unsubscribe).cache(); + Flowable<Integer> f = Flowable.just(1).doOnCancel(unsubscribe).replay().autoConnect(); f.subscribe(); f.subscribe(); f.subscribe(); - verify(unsubscribe, times(1)).run(); + verify(unsubscribe, never()).run(); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java index e2aeb6a3f5..989206f156 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCacheTest.java @@ -35,7 +35,7 @@ public class ObservableCacheTest { @Test public void testColdReplayNoBackpressure() { - ObservableCache<Integer> source = (ObservableCache<Integer>)ObservableCache.from(Observable.range(0, 1000)); + ObservableCache<Integer> source = new ObservableCache<Integer>(Observable.range(0, 1000), 16); assertFalse("Source is connected!", source.isConnected()); @@ -120,7 +120,7 @@ public void testUnsubscribeSource() throws Exception { public void testTake() { TestObserver<Integer> to = new TestObserver<Integer>(); - ObservableCache<Integer> cached = (ObservableCache<Integer>)ObservableCache.from(Observable.range(1, 100)); + ObservableCache<Integer> cached = new ObservableCache<Integer>(Observable.range(1, 1000), 16); cached.take(10).subscribe(to); to.assertNoErrors(); @@ -136,7 +136,7 @@ public void testAsync() { for (int i = 0; i < 100; i++) { TestObserver<Integer> to1 = new TestObserver<Integer>(); - ObservableCache<Integer> cached = (ObservableCache<Integer>)ObservableCache.from(source); + ObservableCache<Integer> cached = new ObservableCache<Integer>(source, 16); cached.observeOn(Schedulers.computation()).subscribe(to1); @@ -160,7 +160,7 @@ public void testAsyncComeAndGo() { Observable<Long> source = Observable.interval(1, 1, TimeUnit.MILLISECONDS) .take(1000) .subscribeOn(Schedulers.io()); - ObservableCache<Long> cached = (ObservableCache<Long>)ObservableCache.from(source); + ObservableCache<Long> cached = new ObservableCache<Long>(source, 16); Observable<Long> output = cached.observeOn(Schedulers.computation()); @@ -351,4 +351,23 @@ public void run() { .assertSubscribed().assertValueCount(500).assertComplete().assertNoErrors(); } } + + @Test + public void cancelledUpFront() { + final AtomicInteger call = new AtomicInteger(); + Observable<Object> f = Observable.fromCallable(new Callable<Object>() { + @Override + public Object call() throws Exception { + return call.incrementAndGet(); + } + }).concatWith(Observable.never()) + .cache(); + + f.test().assertValuesOnly(1); + + f.test(true) + .assertEmpty(); + + assertEquals(1, call.get()); + } } From caefffa27e7c2e8d1a9f09bc51213f77ad5ae93e Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 2 Nov 2018 10:45:24 +0100 Subject: [PATCH 306/417] 2.x: Improve the package docs of i.r.schedulers (#6280) --- src/main/java/io/reactivex/schedulers/package-info.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/schedulers/package-info.java b/src/main/java/io/reactivex/schedulers/package-info.java index 431ca3e8e5..7ba9d63567 100644 --- a/src/main/java/io/reactivex/schedulers/package-info.java +++ b/src/main/java/io/reactivex/schedulers/package-info.java @@ -14,7 +14,9 @@ * limitations under the License. */ /** - * Scheduler implementations, value+time record class and the standard factory class to - * return standard RxJava schedulers or wrap any Executor-based (thread pool) instances. + * Contains notably the factory class of {@link io.reactivex.schedulers.Schedulers Schedulers} providing methods for + * retrieving the standard scheduler instances, the {@link io.reactivex.schedulers.TestScheduler TestScheduler} for testing flows + * with scheduling in a controlled manner and the class {@link io.reactivex.schedulers.Timed Timed} that can hold + * a value and a timestamp associated with it. */ package io.reactivex.schedulers; From 3281b027c7e46c1f0ab9ec7719b5029285920e37 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 5 Nov 2018 11:34:14 +0100 Subject: [PATCH 307/417] 2.x: Fix Observable.flatMap to sustain concurrency level (#6283) --- .../observable/ObservableFlatMap.java | 24 ++++++----- .../flowable/FlowableFlatMapTest.java | 40 +++++++++++++++++++ .../observable/ObservableFlatMapTest.java | 40 +++++++++++++++++++ 3 files changed, 93 insertions(+), 11 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java index 551ceba280..a4766f389d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java @@ -376,7 +376,7 @@ void drainLoop() { return; } - boolean innerCompleted = false; + int innerCompleted = 0; if (n != 0) { long startId = lastId; int index = lastIndex; @@ -423,7 +423,7 @@ void drainLoop() { return; } removeInner(is); - innerCompleted = true; + innerCompleted++; j++; if (j == n) { j = 0; @@ -449,7 +449,7 @@ void drainLoop() { if (checkTerminate()) { return; } - innerCompleted = true; + innerCompleted++; } j++; @@ -461,17 +461,19 @@ void drainLoop() { lastId = inner[j].id; } - if (innerCompleted) { + if (innerCompleted != 0) { if (maxConcurrency != Integer.MAX_VALUE) { - ObservableSource<? extends U> p; - synchronized (this) { - p = sources.poll(); - if (p == null) { - wip--; - continue; + while (innerCompleted-- != 0) { + ObservableSource<? extends U> p; + synchronized (this) { + p = sources.poll(); + if (p == null) { + wip--; + continue; + } } + subscribeInner(p); } - subscribeInner(p); } continue; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index bb525b2ddb..4c1441775b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -1084,4 +1084,44 @@ public void remove() { assertEquals(1, counter.get()); } + + @Test + public void maxConcurrencySustained() { + final PublishProcessor<Integer> pp1 = PublishProcessor.create(); + final PublishProcessor<Integer> pp2 = PublishProcessor.create(); + PublishProcessor<Integer> pp3 = PublishProcessor.create(); + PublishProcessor<Integer> pp4 = PublishProcessor.create(); + + TestSubscriber<Integer> ts = Flowable.just(pp1, pp2, pp3, pp4) + .flatMap(new Function<PublishProcessor<Integer>, Flowable<Integer>>() { + @Override + public Flowable<Integer> apply(PublishProcessor<Integer> v) throws Exception { + return v; + } + }, 2) + .doOnNext(new Consumer<Integer>() { + @Override + public void accept(Integer v) throws Exception { + if (v == 1) { + // this will make sure the drain loop detects two completed + // inner sources and replaces them with fresh ones + pp1.onComplete(); + pp2.onComplete(); + } + } + }) + .test(); + + pp1.onNext(1); + + assertFalse(pp1.hasSubscribers()); + assertFalse(pp2.hasSubscribers()); + assertTrue(pp3.hasSubscribers()); + assertTrue(pp4.hasSubscribers()); + + ts.dispose(); + + assertFalse(pp3.hasSubscribers()); + assertFalse(pp4.hasSubscribers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index efee97f33a..960722060a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -1045,4 +1045,44 @@ public Integer apply(Integer v) to.assertValuesOnly(10, 11, 12, 13, 14, 20, 21, 22, 23, 24); } + + @Test + public void maxConcurrencySustained() { + final PublishSubject<Integer> ps1 = PublishSubject.create(); + final PublishSubject<Integer> ps2 = PublishSubject.create(); + PublishSubject<Integer> ps3 = PublishSubject.create(); + PublishSubject<Integer> ps4 = PublishSubject.create(); + + TestObserver<Integer> to = Observable.just(ps1, ps2, ps3, ps4) + .flatMap(new Function<PublishSubject<Integer>, ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> apply(PublishSubject<Integer> v) throws Exception { + return v; + } + }, 2) + .doOnNext(new Consumer<Integer>() { + @Override + public void accept(Integer v) throws Exception { + if (v == 1) { + // this will make sure the drain loop detects two completed + // inner sources and replaces them with fresh ones + ps1.onComplete(); + ps2.onComplete(); + } + } + }) + .test(); + + ps1.onNext(1); + + assertFalse(ps1.hasObservers()); + assertFalse(ps2.hasObservers()); + assertTrue(ps3.hasObservers()); + assertTrue(ps4.hasObservers()); + + to.dispose(); + + assertFalse(ps3.hasObservers()); + assertFalse(ps4.hasObservers()); + } } From 64783120ef3ba616f03cd3d217310e0dfe788a65 Mon Sep 17 00:00:00 2001 From: pawellozinski <pawel.lozinski@gmail.com> Date: Mon, 5 Nov 2018 13:41:00 +0100 Subject: [PATCH 308/417] 2.x: Expose the Keep-Alive value of the IO Scheduler as System property. (#6279) (#6287) --- .../io/reactivex/internal/schedulers/IoScheduler.java | 9 ++++++++- src/main/java/io/reactivex/schedulers/Schedulers.java | 2 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java b/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java index 423a47898f..d806321bf3 100644 --- a/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java @@ -34,7 +34,11 @@ public final class IoScheduler extends Scheduler { private static final String EVICTOR_THREAD_NAME_PREFIX = "RxCachedWorkerPoolEvictor"; static final RxThreadFactory EVICTOR_THREAD_FACTORY; - private static final long KEEP_ALIVE_TIME = 60; + /** The name of the system property for setting the keep-alive time (in seconds) for this Scheduler workers. */ + private static final String KEY_KEEP_ALIVE_TIME = "rx2.io-keep-alive-time"; + public static final long KEEP_ALIVE_TIME_DEFAULT = 60; + + private static final long KEEP_ALIVE_TIME; private static final TimeUnit KEEP_ALIVE_UNIT = TimeUnit.SECONDS; static final ThreadWorker SHUTDOWN_THREAD_WORKER; @@ -45,7 +49,10 @@ public final class IoScheduler extends Scheduler { private static final String KEY_IO_PRIORITY = "rx2.io-priority"; static final CachedWorkerPool NONE; + static { + KEEP_ALIVE_TIME = Long.getLong(KEY_KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_DEFAULT); + SHUTDOWN_THREAD_WORKER = new ThreadWorker(new RxThreadFactory("RxCachedThreadSchedulerShutdown")); SHUTDOWN_THREAD_WORKER.dispose(); diff --git a/src/main/java/io/reactivex/schedulers/Schedulers.java b/src/main/java/io/reactivex/schedulers/Schedulers.java index 1332a3a019..d3febba3ac 100644 --- a/src/main/java/io/reactivex/schedulers/Schedulers.java +++ b/src/main/java/io/reactivex/schedulers/Schedulers.java @@ -29,6 +29,7 @@ * <p> * <strong>Supported system properties ({@code System.getProperty()}):</strong> * <ul> + * <li>{@code rx2.io-keep-alive-time} (long): sets the keep-alive time of the {@link #io()} Scheduler workers, default is {@link IoScheduler#KEEP_ALIVE_TIME_DEFAULT}</li> * <li>{@code rx2.io-priority} (int): sets the thread priority of the {@link #io()} Scheduler, default is {@link Thread#NORM_PRIORITY}</li> * <li>{@code rx2.computation-threads} (int): sets the number of threads in the {@link #computation()} Scheduler, default is the number of available CPUs</li> * <li>{@code rx2.computation-priority} (int): sets the thread priority of the {@link #computation()} Scheduler, default is {@link Thread#NORM_PRIORITY}</li> @@ -155,6 +156,7 @@ public static Scheduler computation() { * before the {@link Schedulers} class is referenced in your code. * <p><strong>Supported system properties ({@code System.getProperty()}):</strong> * <ul> + * <li>{@code rx2.io-keep-alive-time} (long): sets the keep-alive time of the {@link #io()} Scheduler workers, default is {@link IoScheduler#KEEP_ALIVE_TIME_DEFAULT}</li> * <li>{@code rx2.io-priority} (int): sets the thread priority of the {@link #io()} Scheduler, default is {@link Thread#NORM_PRIORITY}</li> * </ul> * <p> From bc9d59441c189ede38b986ba9839017719126f37 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 6 Nov 2018 08:57:05 +0100 Subject: [PATCH 309/417] 2.x: Add materialize() and dematerialize() (#6278) * 2.x: Add materialize() and dematerialize() * Add remaining test cases * Correct dematerialize javadoc * Use dematerialize selector fix some docs --- src/main/java/io/reactivex/Completable.java | 23 +++- src/main/java/io/reactivex/Maybe.java | 20 ++++ src/main/java/io/reactivex/Single.java | 57 ++++++++++ .../completable/CompletableMaterialize.java | 40 +++++++ .../operators/maybe/MaybeMaterialize.java | 40 +++++++ .../mixed/MaterializeSingleObserver.java | 71 ++++++++++++ .../operators/single/SingleDematerialize.java | 105 +++++++++++++++++ .../operators/single/SingleMaterialize.java | 40 +++++++ .../CompletableMaterializeTest.java | 58 ++++++++++ .../operators/maybe/MaybeMaterializeTest.java | 67 +++++++++++ .../single/SingleDematerializeTest.java | 107 ++++++++++++++++++ .../single/SingleMaterializeTest.java | 58 ++++++++++ 12 files changed, 685 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/reactivex/internal/operators/completable/CompletableMaterialize.java create mode 100644 src/main/java/io/reactivex/internal/operators/maybe/MaybeMaterialize.java create mode 100644 src/main/java/io/reactivex/internal/operators/mixed/MaterializeSingleObserver.java create mode 100644 src/main/java/io/reactivex/internal/operators/single/SingleDematerialize.java create mode 100644 src/main/java/io/reactivex/internal/operators/single/SingleMaterialize.java create mode 100644 src/test/java/io/reactivex/internal/operators/completable/CompletableMaterializeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/maybe/MaybeMaterializeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/single/SingleDematerializeTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/single/SingleMaterializeTest.java diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 486562b483..948d8aecde 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -26,7 +26,7 @@ import io.reactivex.internal.operators.completable.*; import io.reactivex.internal.operators.maybe.*; import io.reactivex.internal.operators.mixed.*; -import io.reactivex.internal.operators.single.SingleDelayWithCompletable; +import io.reactivex.internal.operators.single.*; import io.reactivex.internal.util.ExceptionHelper; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; @@ -1782,6 +1782,27 @@ public final Completable lift(final CompletableOperator onLift) { return RxJavaPlugins.onAssembly(new CompletableLift(this, onLift)); } + /** + * Maps the signal types of this Completable into a {@link Notification} of the same kind + * and emits it as a single success value to downstream. + * <p> + * <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/materialize.png" alt=""> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code materialize} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * @param <T> the intended target element type of the notification + * @return the new Single instance + * @since 2.2.4 - experimental + * @see Single#dematerialize(Function) + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final <T> Single<Notification<T>> materialize() { + return RxJavaPlugins.onAssembly(new CompletableMaterialize<T>(this)); + } + /** * Returns a Completable which subscribes to this and the other Completable and completes * when both of them complete or one emits an error. diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 346d35e16a..b1d34260f1 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3377,6 +3377,26 @@ public final <R> Maybe<R> map(Function<? super T, ? extends R> mapper) { return RxJavaPlugins.onAssembly(new MaybeMap<T, R>(this, mapper)); } + /** + * Maps the signal types of this Maybe into a {@link Notification} of the same kind + * and emits it as a single success value to downstream. + * <p> + * <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/materialize.png" alt=""> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code materialize} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * @return the new Single instance + * @since 2.2.4 - experimental + * @see Single#dematerialize(Function) + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final Single<Notification<T>> materialize() { + return RxJavaPlugins.onAssembly(new MaybeMaterialize<T>(this)); + } + /** * Flattens this and another Maybe into a single Flowable, without any transformation. * <p> diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 8d4013be66..168c9c216a 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2302,6 +2302,43 @@ public final Single<T> delaySubscription(long time, TimeUnit unit, Scheduler sch return delaySubscription(Observable.timer(time, unit, scheduler)); } + /** + * Maps the {@link Notification} success value of this Single back into normal + * {@code onSuccess}, {@code onError} or {@code onComplete} signals as a + * {@link Maybe} source. + * <p> + * The intended use of the {@code selector} function is to perform a + * type-safe identity mapping (see example) on a source that is already of type + * {@code Notification<T>}. The Java language doesn't allow + * limiting instance methods to a certain generic argument shape, therefore, + * a function is used to ensure the conversion remains type safe. + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code dematerialize} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * <p> + * Example: + * <pre><code> + * Single.just(Notification.createOnNext(1)) + * .dematerialize(notification -> notification) + * .test() + * .assertResult(1); + * </code></pre> + * @param <R> the result type + * @param selector the function called with the success item and should + * return a {@link Notification} instance. + * @return the new Maybe instance + * @since 2.2.4 - experimental + * @see #materialize() + */ + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @Experimental + public final <R> Maybe<R> dematerialize(Function<? super T, Notification<R>> selector) { + ObjectHelper.requireNonNull(selector, "selector is null"); + return RxJavaPlugins.onAssembly(new SingleDematerialize<T, R>(this, selector)); + } + /** * Calls the specified consumer with the success item after this item has been emitted to the downstream. * <p> @@ -2871,6 +2908,26 @@ public final <R> Single<R> map(Function<? super T, ? extends R> mapper) { return RxJavaPlugins.onAssembly(new SingleMap<T, R>(this, mapper)); } + /** + * Maps the signal types of this Single into a {@link Notification} of the same kind + * and emits it as a single success value to downstream. + * <p> + * <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/materialize.png" alt=""> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code materialize} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * @return the new Single instance + * @since 2.2.4 - experimental + * @see #dematerialize(Function) + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final Single<Notification<T>> materialize() { + return RxJavaPlugins.onAssembly(new SingleMaterialize<T>(this)); + } + /** * Signals true if the current Single signals a success value that is Object-equals with the value * provided. diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableMaterialize.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableMaterialize.java new file mode 100644 index 0000000000..5eda7f6ae2 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableMaterialize.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.internal.operators.mixed.MaterializeSingleObserver; + +/** + * Turn the signal types of a Completable source into a single Notification of + * equal kind. + * + * @param <T> the element type of the source + * @since 2.2.4 - experimental + */ +@Experimental +public final class CompletableMaterialize<T> extends Single<Notification<T>> { + + final Completable source; + + public CompletableMaterialize(Completable source) { + this.source = source; + } + + @Override + protected void subscribeActual(SingleObserver<? super Notification<T>> observer) { + source.subscribe(new MaterializeSingleObserver<T>(observer)); + } +} diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeMaterialize.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeMaterialize.java new file mode 100644 index 0000000000..2b74829ba1 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeMaterialize.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.maybe; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.internal.operators.mixed.MaterializeSingleObserver; + +/** + * Turn the signal types of a Maybe source into a single Notification of + * equal kind. + * + * @param <T> the element type of the source + * @since 2.2.4 - experimental + */ +@Experimental +public final class MaybeMaterialize<T> extends Single<Notification<T>> { + + final Maybe<T> source; + + public MaybeMaterialize(Maybe<T> source) { + this.source = source; + } + + @Override + protected void subscribeActual(SingleObserver<? super Notification<T>> observer) { + source.subscribe(new MaterializeSingleObserver<T>(observer)); + } +} diff --git a/src/main/java/io/reactivex/internal/operators/mixed/MaterializeSingleObserver.java b/src/main/java/io/reactivex/internal/operators/mixed/MaterializeSingleObserver.java new file mode 100644 index 0000000000..ef8a87076d --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/mixed/MaterializeSingleObserver.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.mixed; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; + +/** + * A consumer that implements the consumer types of Maybe, Single and Completable + * and turns their signals into Notifications for a SingleObserver. + * @param <T> the element type of the source + * @since 2.2.4 - experimental + */ +@Experimental +public final class MaterializeSingleObserver<T> +implements SingleObserver<T>, MaybeObserver<T>, CompletableObserver, Disposable { + + final SingleObserver<? super Notification<T>> downstream; + + Disposable upstream; + + public MaterializeSingleObserver(SingleObserver<? super Notification<T>> downstream) { + this.downstream = downstream; + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + this.upstream = d; + downstream.onSubscribe(this); + } + } + + @Override + public void onComplete() { + downstream.onSuccess(Notification.<T>createOnComplete()); + } + + @Override + public void onSuccess(T t) { + downstream.onSuccess(Notification.<T>createOnNext(t)); + } + + @Override + public void onError(Throwable e) { + downstream.onSuccess(Notification.<T>createOnError(e)); + } + + @Override + public boolean isDisposed() { + return upstream.isDisposed(); + } + + @Override + public void dispose() { + upstream.dispose(); + } +} diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDematerialize.java b/src/main/java/io/reactivex/internal/operators/single/SingleDematerialize.java new file mode 100644 index 0000000000..2e402b05da --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDematerialize.java @@ -0,0 +1,105 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.single; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; + +/** + * Maps the success value of the source to a Notification, then + * maps it back to the corresponding signal type. + * @param <T> the element type of the source + * @param <R> the element type of the Notification and result + * @since 2.2.4 - experimental + */ +@Experimental +public final class SingleDematerialize<T, R> extends Maybe<R> { + + final Single<T> source; + + final Function<? super T, Notification<R>> selector; + + public SingleDematerialize(Single<T> source, Function<? super T, Notification<R>> selector) { + this.source = source; + this.selector = selector; + } + + @Override + protected void subscribeActual(MaybeObserver<? super R> observer) { + source.subscribe(new DematerializeObserver<T, R>(observer, selector)); + } + + static final class DematerializeObserver<T, R> implements SingleObserver<T>, Disposable { + + final MaybeObserver<? super R> downstream; + + final Function<? super T, Notification<R>> selector; + + Disposable upstream; + + DematerializeObserver(MaybeObserver<? super R> downstream, + Function<? super T, Notification<R>> selector) { + this.downstream = downstream; + this.selector = selector; + } + + @Override + public void dispose() { + upstream.dispose(); + } + + @Override + public boolean isDisposed() { + return upstream.isDisposed(); + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.validate(upstream, d)) { + upstream = d; + downstream.onSubscribe(this); + } + } + + @Override + public void onSuccess(T t) { + Notification<R> notification; + + try { + notification = ObjectHelper.requireNonNull(selector.apply(t), "The selector returned a null Notification"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + downstream.onError(ex); + return; + } + if (notification.isOnNext()) { + downstream.onSuccess(notification.getValue()); + } else if (notification.isOnComplete()) { + downstream.onComplete(); + } else { + downstream.onError(notification.getError()); + } + } + + @Override + public void onError(Throwable e) { + downstream.onError(e); + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleMaterialize.java b/src/main/java/io/reactivex/internal/operators/single/SingleMaterialize.java new file mode 100644 index 0000000000..e22b64865d --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/single/SingleMaterialize.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.single; + +import io.reactivex.*; +import io.reactivex.annotations.Experimental; +import io.reactivex.internal.operators.mixed.MaterializeSingleObserver; + +/** + * Turn the signal types of a Single source into a single Notification of + * equal kind. + * + * @param <T> the element type of the source + * @since 2.2.4 - experimental + */ +@Experimental +public final class SingleMaterialize<T> extends Single<Notification<T>> { + + final Single<T> source; + + public SingleMaterialize(Single<T> source) { + this.source = source; + } + + @Override + protected void subscribeActual(SingleObserver<? super Notification<T>> observer) { + source.subscribe(new MaterializeSingleObserver<T>(observer)); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableMaterializeTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableMaterializeTest.java new file mode 100644 index 0000000000..aec11e5a61 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableMaterializeTest.java @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.subjects.CompletableSubject; + +public class CompletableMaterializeTest { + + @Test + @SuppressWarnings("unchecked") + public void error() { + TestException ex = new TestException(); + Completable.error(ex) + .materialize() + .test() + .assertResult(Notification.createOnError(ex)); + } + + @Test + @SuppressWarnings("unchecked") + public void empty() { + Completable.complete() + .materialize() + .test() + .assertResult(Notification.createOnComplete()); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeCompletableToSingle(new Function<Completable, SingleSource<Notification<Object>>>() { + @Override + public SingleSource<Notification<Object>> apply(Completable v) throws Exception { + return v.materialize(); + } + }); + } + + @Test + public void dispose() { + TestHelper.checkDisposed(CompletableSubject.create().materialize()); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeMaterializeTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMaterializeTest.java new file mode 100644 index 0000000000..f429ecddf2 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeMaterializeTest.java @@ -0,0 +1,67 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.maybe; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.subjects.MaybeSubject; + +public class MaybeMaterializeTest { + + @Test + @SuppressWarnings("unchecked") + public void success() { + Maybe.just(1) + .materialize() + .test() + .assertResult(Notification.createOnNext(1)); + } + + @Test + @SuppressWarnings("unchecked") + public void error() { + TestException ex = new TestException(); + Maybe.error(ex) + .materialize() + .test() + .assertResult(Notification.createOnError(ex)); + } + + @Test + @SuppressWarnings("unchecked") + public void empty() { + Maybe.empty() + .materialize() + .test() + .assertResult(Notification.createOnComplete()); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeMaybeToSingle(new Function<Maybe<Object>, SingleSource<Notification<Object>>>() { + @Override + public SingleSource<Notification<Object>> apply(Maybe<Object> v) throws Exception { + return v.materialize(); + } + }); + } + + @Test + public void dispose() { + TestHelper.checkDisposed(MaybeSubject.create().materialize()); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleDematerializeTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleDematerializeTest.java new file mode 100644 index 0000000000..abfbe2151a --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/single/SingleDematerializeTest.java @@ -0,0 +1,107 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.single; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.internal.functions.Functions; +import io.reactivex.subjects.SingleSubject; + +public class SingleDematerializeTest { + + @Test + public void success() { + Single.just(Notification.createOnNext(1)) + .dematerialize(Functions.<Notification<Integer>>identity()) + .test() + .assertResult(1); + } + + @Test + public void empty() { + Single.just(Notification.<Integer>createOnComplete()) + .dematerialize(Functions.<Notification<Integer>>identity()) + .test() + .assertResult(); + } + + @Test + public void error() { + Single.<Notification<Integer>>error(new TestException()) + .dematerialize(Functions.<Notification<Integer>>identity()) + .test() + .assertFailure(TestException.class); + } + + @Test + public void errorNotification() { + Single.just(Notification.<Integer>createOnError(new TestException())) + .dematerialize(Functions.<Notification<Integer>>identity()) + .test() + .assertFailure(TestException.class); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeSingleToMaybe(new Function<Single<Object>, MaybeSource<Object>>() { + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public MaybeSource<Object> apply(Single<Object> v) throws Exception { + return v.dematerialize((Function)Functions.identity()); + } + }); + } + + @Test + public void dispose() { + TestHelper.checkDisposed(SingleSubject.<Notification<Integer>>create().dematerialize(Functions.<Notification<Integer>>identity())); + } + + @Test + public void selectorCrash() { + Single.just(Notification.createOnNext(1)) + .dematerialize(new Function<Notification<Integer>, Notification<Integer>>() { + @Override + public Notification<Integer> apply(Notification<Integer> v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void selectorNull() { + Single.just(Notification.createOnNext(1)) + .dematerialize(Functions.justFunction((Notification<Integer>)null)) + .test() + .assertFailure(NullPointerException.class); + } + + @Test + public void selectorDifferentType() { + Single.just(Notification.createOnNext(1)) + .dematerialize(new Function<Notification<Integer>, Notification<String>>() { + @Override + public Notification<String> apply(Notification<Integer> v) throws Exception { + return Notification.createOnNext("Value-" + 1); + } + }) + .test() + .assertResult("Value-1"); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleMaterializeTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleMaterializeTest.java new file mode 100644 index 0000000000..3a97155978 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/single/SingleMaterializeTest.java @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.single; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Function; +import io.reactivex.subjects.SingleSubject; + +public class SingleMaterializeTest { + + @Test + @SuppressWarnings("unchecked") + public void success() { + Single.just(1) + .materialize() + .test() + .assertResult(Notification.createOnNext(1)); + } + + @Test + @SuppressWarnings("unchecked") + public void error() { + TestException ex = new TestException(); + Maybe.error(ex) + .materialize() + .test() + .assertResult(Notification.createOnError(ex)); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeSingle(new Function<Single<Object>, SingleSource<Notification<Object>>>() { + @Override + public SingleSource<Notification<Object>> apply(Single<Object> v) throws Exception { + return v.materialize(); + } + }); + } + + @Test + public void dispose() { + TestHelper.checkDisposed(SingleSubject.create().materialize()); + } +} From acd5466c4440961da905d0c1c0e78752bda155ef Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 6 Nov 2018 09:17:27 +0100 Subject: [PATCH 310/417] 2.x: Add dematerialize(selector), deprecate old (#6281) * 2.x: Add dematerialize(selector), deprecate old * Restore full coverage * Fix parameter naming --- src/main/java/io/reactivex/Flowable.java | 73 +++++++++++++++++-- src/main/java/io/reactivex/Observable.java | 65 ++++++++++++++++- .../flowable/FlowableDematerialize.java | 51 +++++++++---- .../observable/ObservableDematerialize.java | 51 +++++++++---- .../io/reactivex/flowable/FlowableTests.java | 9 ++- .../flowable/FlowableDematerializeTest.java | 60 +++++++++++++++ .../ObservableDematerializeTest.java | 60 +++++++++++++++ .../reactivex/observable/ObservableTest.java | 7 +- 8 files changed, 335 insertions(+), 41 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 2e9e6c20ba..a45063f506 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -27,7 +27,7 @@ import io.reactivex.internal.fuseable.*; import io.reactivex.internal.operators.flowable.*; import io.reactivex.internal.operators.mixed.*; -import io.reactivex.internal.operators.observable.ObservableFromPublisher; +import io.reactivex.internal.operators.observable.*; import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.internal.subscribers.*; import io.reactivex.internal.util.*; @@ -8484,6 +8484,7 @@ public final Flowable<T> delaySubscription(long delay, TimeUnit unit, Scheduler * <pre><code> * Flowable.just(createOnNext(1), createOnComplete(), createOnNext(2)) * .doOnCancel(() -> System.out.println("Cancelled!")); + * .dematerialize() * .test() * .assertResult(1); * </code></pre> @@ -8491,6 +8492,7 @@ public final Flowable<T> delaySubscription(long delay, TimeUnit unit, Scheduler * with the same event. * <pre><code> * Flowable.just(createOnNext(1), createOnNext(2)) + * .dematerialize() * .test() * .assertResult(1, 2); * </code></pre> @@ -8508,14 +8510,74 @@ public final Flowable<T> delaySubscription(long delay, TimeUnit unit, Scheduler * @return a Flowable that emits the items and notifications embedded in the {@link Notification} objects * emitted by the source Publisher * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Dematerialize</a> + * @see #dematerialize(Function) + * @deprecated in 2.2.4; inherently type-unsafe as it overrides the output generic type. Use {@link #dematerialize(Function)} instead. */ @CheckReturnValue - @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.PASS_THROUGH) + @Deprecated + @SuppressWarnings({ "unchecked", "rawtypes" }) public final <T2> Flowable<T2> dematerialize() { - @SuppressWarnings("unchecked") - Flowable<Notification<T2>> m = (Flowable<Notification<T2>>)this; - return RxJavaPlugins.onAssembly(new FlowableDematerialize<T2>(m)); + return RxJavaPlugins.onAssembly(new FlowableDematerialize(this, Functions.identity())); + } + + /** + * Returns a Flowable that reverses the effect of {@link #materialize materialize} by transforming the + * {@link Notification} objects extracted from the source items via a selector function + * into their respective {@code Subscriber} signal types. + * <p> + * <img width="640" height="335" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/dematerialize.png" alt=""> + * <p> + * The intended use of the {@code selector} function is to perform a + * type-safe identity mapping (see example) on a source that is already of type + * {@code Notification<T>}. The Java language doesn't allow + * limiting instance methods to a certain generic argument shape, therefore, + * a function is used to ensure the conversion remains type safe. + * <p> + * When the upstream signals an {@link Notification#createOnError(Throwable) onError} or + * {@link Notification#createOnComplete() onComplete} item, the + * returned Flowable cancels of the flow and terminates with that type of terminal event: + * <pre><code> + * Flowable.just(createOnNext(1), createOnComplete(), createOnNext(2)) + * .doOnCancel(() -> System.out.println("Canceled!")); + * .dematerialize(notification -> notification) + * .test() + * .assertResult(1); + * </code></pre> + * If the upstream signals {@code onError} or {@code onComplete} directly, the flow is terminated + * with the same event. + * <pre><code> + * Flowable.just(createOnNext(1), createOnNext(2)) + * .dematerialize(notification -> notification) + * .test() + * .assertResult(1, 2); + * </code></pre> + * If this behavior is not desired, the completion can be suppressed by applying {@link #concatWith(Publisher)} + * with a {@link #never()} source. + * <dl> + * <dt><b>Backpressure:</b></dt> + * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s + * backpressure behavior.</dd> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code dematerialize} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * + * @param <R> the output value type + * @param selector function that returns the upstream item and should return a Notification to signal + * the corresponding {@code Subscriber} event to the downstream. + * @return a Flowable that emits the items and notifications embedded in the {@link Notification} objects + * selected from the items emitted by the source Flowable + * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Dematerialize</a> + * @since 2.2.4 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + @BackpressureSupport(BackpressureKind.PASS_THROUGH) + public final <R> Flowable<R> dematerialize(Function<? super T, Notification<R>> selector) { + ObjectHelper.requireNonNull(selector, "selector is null"); + return RxJavaPlugins.onAssembly(new FlowableDematerialize<T, R>(this, selector)); } /** @@ -11069,6 +11131,7 @@ public final <R> Flowable<R> map(Function<? super T, ? extends R> mapper) { * @return a Flowable that emits items that are the result of materializing the items and notifications * of the source Publisher * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Materialize</a> + * @see #dematerialize(Function) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index c80e8be95d..db3530069a 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7587,6 +7587,7 @@ public final Observable<T> delaySubscription(long delay, TimeUnit unit, Schedule * <pre><code> * Observable.just(createOnNext(1), createOnComplete(), createOnNext(2)) * .doOnDispose(() -> System.out.println("Disposed!")); + * .dematerialize() * .test() * .assertResult(1); * </code></pre> @@ -7594,6 +7595,7 @@ public final Observable<T> delaySubscription(long delay, TimeUnit unit, Schedule * with the same event. * <pre><code> * Observable.just(createOnNext(1), createOnNext(2)) + * .dematerialize() * .test() * .assertResult(1, 2); * </code></pre> @@ -7608,13 +7610,69 @@ public final Observable<T> delaySubscription(long delay, TimeUnit unit, Schedule * @return an Observable that emits the items and notifications embedded in the {@link Notification} objects * emitted by the source ObservableSource * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Dematerialize</a> + * @see #dematerialize(Function) + * @deprecated in 2.2.4; inherently type-unsafe as it overrides the output generic type. Use {@link #dematerialize(Function)} instead. */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) + @Deprecated + @SuppressWarnings({ "unchecked", "rawtypes" }) public final <T2> Observable<T2> dematerialize() { - @SuppressWarnings("unchecked") - Observable<Notification<T2>> m = (Observable<Notification<T2>>)this; - return RxJavaPlugins.onAssembly(new ObservableDematerialize<T2>(m)); + return RxJavaPlugins.onAssembly(new ObservableDematerialize(this, Functions.identity())); + } + + /** + * Returns an Observable that reverses the effect of {@link #materialize materialize} by transforming the + * {@link Notification} objects extracted from the source items via a selector function + * into their respective {@code Observer} signal types. + * <p> + * <img width="640" height="335" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/dematerialize.png" alt=""> + * <p> + * The intended use of the {@code selector} function is to perform a + * type-safe identity mapping (see example) on a source that is already of type + * {@code Notification<T>}. The Java language doesn't allow + * limiting instance methods to a certain generic argument shape, therefore, + * a function is used to ensure the conversion remains type safe. + * <p> + * When the upstream signals an {@link Notification#createOnError(Throwable) onError} or + * {@link Notification#createOnComplete() onComplete} item, the + * returned Observable disposes of the flow and terminates with that type of terminal event: + * <pre><code> + * Observable.just(createOnNext(1), createOnComplete(), createOnNext(2)) + * .doOnDispose(() -> System.out.println("Disposed!")); + * .dematerialize(notification -> notification) + * .test() + * .assertResult(1); + * </code></pre> + * If the upstream signals {@code onError} or {@code onComplete} directly, the flow is terminated + * with the same event. + * <pre><code> + * Observable.just(createOnNext(1), createOnNext(2)) + * .dematerialize(notification -> notification) + * .test() + * .assertResult(1, 2); + * </code></pre> + * If this behavior is not desired, the completion can be suppressed by applying {@link #concatWith(ObservableSource)} + * with a {@link #never()} source. + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code dematerialize} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * + * @param <R> the output value type + * @param selector function that returns the upstream item and should return a Notification to signal + * the corresponding {@code Observer} event to the downstream. + * @return an Observable that emits the items and notifications embedded in the {@link Notification} objects + * selected from the items emitted by the source ObservableSource + * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Dematerialize</a> + * @since 2.2.4 - experimental + */ + @Experimental + @CheckReturnValue + @SchedulerSupport(SchedulerSupport.NONE) + public final <R> Observable<R> dematerialize(Function<? super T, Notification<R>> selector) { + ObjectHelper.requireNonNull(selector, "selector is null"); + return RxJavaPlugins.onAssembly(new ObservableDematerialize<T, R>(this, selector)); } /** @@ -9620,6 +9678,7 @@ public final <R> Observable<R> map(Function<? super T, ? extends R> mapper) { * @return an Observable that emits items that are the result of materializing the items and notifications * of the source ObservableSource * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Materialize</a> + * @see #dematerialize(Function) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java index 930f5aaee6..5fe5211834 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java @@ -16,29 +16,39 @@ import org.reactivestreams.*; import io.reactivex.*; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; +import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.plugins.RxJavaPlugins; -public final class FlowableDematerialize<T> extends AbstractFlowableWithUpstream<Notification<T>, T> { +public final class FlowableDematerialize<T, R> extends AbstractFlowableWithUpstream<T, R> { - public FlowableDematerialize(Flowable<Notification<T>> source) { + final Function<? super T, ? extends Notification<R>> selector; + + public FlowableDematerialize(Flowable<T> source, Function<? super T, ? extends Notification<R>> selector) { super(source); + this.selector = selector; } @Override - protected void subscribeActual(Subscriber<? super T> s) { - source.subscribe(new DematerializeSubscriber<T>(s)); + protected void subscribeActual(Subscriber<? super R> subscriber) { + source.subscribe(new DematerializeSubscriber<T, R>(subscriber, selector)); } - static final class DematerializeSubscriber<T> implements FlowableSubscriber<Notification<T>>, Subscription { - final Subscriber<? super T> downstream; + static final class DematerializeSubscriber<T, R> implements FlowableSubscriber<T>, Subscription { + + final Subscriber<? super R> downstream; + + final Function<? super T, ? extends Notification<R>> selector; boolean done; Subscription upstream; - DematerializeSubscriber(Subscriber<? super T> downstream) { + DematerializeSubscriber(Subscriber<? super R> downstream, Function<? super T, ? extends Notification<R>> selector) { this.downstream = downstream; + this.selector = selector; } @Override @@ -50,22 +60,35 @@ public void onSubscribe(Subscription s) { } @Override - public void onNext(Notification<T> t) { + public void onNext(T item) { if (done) { - if (t.isOnError()) { - RxJavaPlugins.onError(t.getError()); + if (item instanceof Notification) { + Notification<?> notification = (Notification<?>)item; + if (notification.isOnError()) { + RxJavaPlugins.onError(notification.getError()); + } } return; } - if (t.isOnError()) { + + Notification<R> notification; + + try { + notification = ObjectHelper.requireNonNull(selector.apply(item), "The selector returned a null Notification"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); upstream.cancel(); - onError(t.getError()); + onError(ex); + return; } - else if (t.isOnComplete()) { + if (notification.isOnError()) { + upstream.cancel(); + onError(notification.getError()); + } else if (notification.isOnComplete()) { upstream.cancel(); onComplete(); } else { - downstream.onNext(t.getValue()); + downstream.onNext(notification.getValue()); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java index 9e79e8eba4..2f864152ee 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java @@ -15,29 +15,38 @@ import io.reactivex.*; import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Function; import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.plugins.RxJavaPlugins; -public final class ObservableDematerialize<T> extends AbstractObservableWithUpstream<Notification<T>, T> { +public final class ObservableDematerialize<T, R> extends AbstractObservableWithUpstream<T, R> { - public ObservableDematerialize(ObservableSource<Notification<T>> source) { + final Function<? super T, ? extends Notification<R>> selector; + + public ObservableDematerialize(ObservableSource<T> source, Function<? super T, ? extends Notification<R>> selector) { super(source); + this.selector = selector; } @Override - public void subscribeActual(Observer<? super T> t) { - source.subscribe(new DematerializeObserver<T>(t)); + public void subscribeActual(Observer<? super R> observer) { + source.subscribe(new DematerializeObserver<T, R>(observer, selector)); } - static final class DematerializeObserver<T> implements Observer<Notification<T>>, Disposable { - final Observer<? super T> downstream; + static final class DematerializeObserver<T, R> implements Observer<T>, Disposable { + final Observer<? super R> downstream; + + final Function<? super T, ? extends Notification<R>> selector; boolean done; Disposable upstream; - DematerializeObserver(Observer<? super T> downstream) { + DematerializeObserver(Observer<? super R> downstream, Function<? super T, ? extends Notification<R>> selector) { this.downstream = downstream; + this.selector = selector; } @Override @@ -60,22 +69,36 @@ public boolean isDisposed() { } @Override - public void onNext(Notification<T> t) { + public void onNext(T item) { if (done) { - if (t.isOnError()) { - RxJavaPlugins.onError(t.getError()); + if (item instanceof Notification) { + Notification<?> notification = (Notification<?>)item; + if (notification.isOnError()) { + RxJavaPlugins.onError(notification.getError()); + } } return; } - if (t.isOnError()) { + + Notification<R> notification; + + try { + notification = ObjectHelper.requireNonNull(selector.apply(item), "The selector returned a null Notification"); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.dispose(); + onError(ex); + return; + } + if (notification.isOnError()) { upstream.dispose(); - onError(t.getError()); + onError(notification.getError()); } - else if (t.isOnComplete()) { + else if (notification.isOnComplete()) { upstream.dispose(); onComplete(); } else { - downstream.onNext(t.getValue()); + downstream.onNext(notification.getValue()); } } diff --git a/src/test/java/io/reactivex/flowable/FlowableTests.java b/src/test/java/io/reactivex/flowable/FlowableTests.java index 4a700b5aea..fa8026da6c 100644 --- a/src/test/java/io/reactivex/flowable/FlowableTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableTests.java @@ -14,22 +14,24 @@ package io.reactivex.flowable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; -import io.reactivex.Observable; import org.junit.*; import org.mockito.InOrder; import org.reactivestreams.*; import io.reactivex.*; +import io.reactivex.Observable; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.*; import io.reactivex.flowables.ConnectableFlowable; import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.*; @@ -341,7 +343,8 @@ public void testOnSubscribeFails() { @Test public void testMaterializeDematerializeChaining() { Flowable<Integer> obs = Flowable.just(1); - Flowable<Integer> chained = obs.materialize().dematerialize(); + Flowable<Integer> chained = obs.materialize() + .dematerialize(Functions.<Notification<Integer>>identity()); Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); @@ -1076,7 +1079,7 @@ public void testErrorThrownIssue1685() { Flowable.error(new RuntimeException("oops")) .materialize() .delay(1, TimeUnit.SECONDS) - .dematerialize() + .dematerialize(Functions.<Notification<Object>>identity()) .subscribe(processor); processor.subscribe(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java index f83510f830..66fd932dcc 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java @@ -24,12 +24,57 @@ import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; +import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.subscribers.TestSubscriber; +@SuppressWarnings("deprecation") public class FlowableDematerializeTest { + @Test + public void simpleSelector() { + Flowable<Notification<Integer>> notifications = Flowable.just(1, 2).materialize(); + Flowable<Integer> dematerialize = notifications.dematerialize(Functions.<Notification<Integer>>identity()); + + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + + dematerialize.subscribe(subscriber); + + verify(subscriber, times(1)).onNext(1); + verify(subscriber, times(1)).onNext(2); + verify(subscriber, times(1)).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + } + + @Test + public void selectorCrash() { + Flowable.just(1, 2) + .materialize() + .dematerialize(new Function<Notification<Integer>, Notification<Object>>() { + @Override + public Notification<Object> apply(Notification<Integer> v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void selectorNull() { + Flowable.just(1, 2) + .materialize() + .dematerialize(new Function<Notification<Integer>, Notification<Object>>() { + @Override + public Notification<Object> apply(Notification<Integer> v) throws Exception { + return null; + } + }) + .test() + .assertFailure(NullPointerException.class); + } + @Test public void testDematerialize1() { Flowable<Notification<Integer>> notifications = Flowable.just(1, 2).materialize(); @@ -176,4 +221,19 @@ protected void subscribeActual(Subscriber<? super Object> subscriber) { RxJavaPlugins.reset(); } } + + @Test + public void nonNotificationInstanceAfterDispose() { + new Flowable<Object>() { + @Override + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(Notification.createOnComplete()); + subscriber.onNext(1); + } + } + .dematerialize() + .test() + .assertResult(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java index a5017c68c4..d815a70ea5 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java @@ -24,11 +24,56 @@ import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; +import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; +@SuppressWarnings("deprecation") public class ObservableDematerializeTest { + @Test + public void simpleSelector() { + Observable<Notification<Integer>> notifications = Observable.just(1, 2).materialize(); + Observable<Integer> dematerialize = notifications.dematerialize(Functions.<Notification<Integer>>identity()); + + Observer<Integer> observer = TestHelper.mockObserver(); + + dematerialize.subscribe(observer); + + verify(observer, times(1)).onNext(1); + verify(observer, times(1)).onNext(2); + verify(observer, times(1)).onComplete(); + verify(observer, never()).onError(any(Throwable.class)); + } + + @Test + public void selectorCrash() { + Observable.just(1, 2) + .materialize() + .dematerialize(new Function<Notification<Integer>, Notification<Object>>() { + @Override + public Notification<Object> apply(Notification<Integer> v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void selectorNull() { + Observable.just(1, 2) + .materialize() + .dematerialize(new Function<Notification<Integer>, Notification<Object>>() { + @Override + public Notification<Object> apply(Notification<Integer> v) throws Exception { + return null; + } + }) + .test() + .assertFailure(NullPointerException.class); + } + @Test public void testDematerialize1() { Observable<Notification<Integer>> notifications = Observable.just(1, 2).materialize(); @@ -175,4 +220,19 @@ protected void subscribeActual(Observer<? super Object> observer) { RxJavaPlugins.reset(); } } + + @Test + public void nonNotificationInstanceAfterDispose() { + new Observable<Object>() { + @Override + protected void subscribeActual(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(Notification.createOnComplete()); + observer.onNext(1); + } + } + .dematerialize() + .test() + .assertResult(); + } } diff --git a/src/test/java/io/reactivex/observable/ObservableTest.java b/src/test/java/io/reactivex/observable/ObservableTest.java index 660c57d49a..ab915ffa53 100644 --- a/src/test/java/io/reactivex/observable/ObservableTest.java +++ b/src/test/java/io/reactivex/observable/ObservableTest.java @@ -14,6 +14,7 @@ package io.reactivex.observable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; @@ -28,6 +29,7 @@ import io.reactivex.Observer; import io.reactivex.disposables.*; import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.observables.ConnectableObservable; import io.reactivex.observers.*; import io.reactivex.schedulers.*; @@ -357,7 +359,8 @@ public void testOnSubscribeFails() { @Test public void testMaterializeDematerializeChaining() { Observable<Integer> obs = Observable.just(1); - Observable<Integer> chained = obs.materialize().dematerialize(); + Observable<Integer> chained = obs.materialize() + .dematerialize(Functions.<Notification<Integer>>identity()); Observer<Integer> observer = TestHelper.mockObserver(); @@ -1096,7 +1099,7 @@ public void testErrorThrownIssue1685() { Observable.error(new RuntimeException("oops")) .materialize() .delay(1, TimeUnit.SECONDS) - .dematerialize() + .dematerialize(Functions.<Notification<Object>>identity()) .subscribe(subject); subject.subscribe(); From 55f3bb2a366c5667c682021fe56726479f29bc3b Mon Sep 17 00:00:00 2001 From: Zac Sweers <pandanomic@gmail.com> Date: Sun, 11 Nov 2018 04:06:38 -0800 Subject: [PATCH 311/417] Add missing onSubscribe null-checks to NPE docs on Flowable/Observable subscribe (#6301) Happened to notice these today --- src/main/java/io/reactivex/Flowable.java | 3 ++- src/main/java/io/reactivex/Observable.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index a45063f506..ca4ca72b34 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -14461,7 +14461,8 @@ public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super T * @throws NullPointerException * if {@code onNext} is null, or * if {@code onError} is null, or - * if {@code onComplete} is null + * if {@code onComplete} is null, or + * if {@code onSubscribe} is null * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ @CheckReturnValue diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index db3530069a..8ab4059642 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -12119,7 +12119,8 @@ public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super T * @throws NullPointerException * if {@code onNext} is null, or * if {@code onError} is null, or - * if {@code onComplete} is null + * if {@code onComplete} is null, or + * if {@code onSubscribe} is null * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ @CheckReturnValue From 2334d880a18d95161aa5d07657104e8639b23b3c Mon Sep 17 00:00:00 2001 From: lorenzpahl <l.pahl@outlook.com> Date: Sun, 11 Nov 2018 21:58:02 +0100 Subject: [PATCH 312/417] Fix(incorrect image placement) (#6303) --- src/main/java/io/reactivex/Flowable.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index ca4ca72b34..666c7c765d 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -18043,7 +18043,7 @@ public final <U, R> Flowable<R> zipWith(Iterable<U> other, BiFunction<? super T * <br>To work around this termination property, * use {@link #doOnCancel(Action)} as well or use {@code using()} to do cleanup in case of completion * or cancellation. - * + * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> @@ -18090,7 +18090,7 @@ public final <U, R> Flowable<R> zipWith(Publisher<? extends U> other, BiFunction * <br>To work around this termination property, * use {@link #doOnCancel(Action)} as well or use {@code using()} to do cleanup in case of completion * or cancellation. - * + * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> @@ -18140,7 +18140,7 @@ public final <U, R> Flowable<R> zipWith(Publisher<? extends U> other, * <br>To work around this termination property, * use {@link #doOnCancel(Action)} as well or use {@code using()} to do cleanup in case of completion * or cancellation. - * + * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> From 390b7b0633ddbec364d2f78e624be5312a6ef198 Mon Sep 17 00:00:00 2001 From: lorenzpahl <l.pahl@outlook.com> Date: Mon, 12 Nov 2018 09:54:06 +0100 Subject: [PATCH 313/417] 2.x: Update Transforming Observables docs (#6291) * Change document structure; revise descriptions * Add examples * Add more operators --- docs/Transforming-Observables.md | 787 ++++++++++++++++++++++++++++++- 1 file changed, 777 insertions(+), 10 deletions(-) diff --git a/docs/Transforming-Observables.md b/docs/Transforming-Observables.md index aa7b53e89f..3a3d94cd2e 100644 --- a/docs/Transforming-Observables.md +++ b/docs/Transforming-Observables.md @@ -1,10 +1,777 @@ -This page shows operators with which you can transform items that are emitted by an Observable. - -* [**`map( )`**](http://reactivex.io/documentation/operators/map.html) — transform the items emitted by an Observable by applying a function to each of them -* [**`flatMap( )`, `concatMap( )`, and `flatMapIterable( )`**](http://reactivex.io/documentation/operators/flatmap.html) — transform the items emitted by an Observable into Observables (or Iterables), then flatten this into a single Observable -* [**`switchMap( )`**](http://reactivex.io/documentation/operators/flatmap.html) — transform the items emitted by an Observable into Observables, and mirror those items emitted by the most-recently transformed Observable -* [**`scan( )`**](http://reactivex.io/documentation/operators/scan.html) — apply a function to each item emitted by an Observable, sequentially, and emit each successive value -* [**`groupBy( )`**](http://reactivex.io/documentation/operators/groupby.html) — divide an Observable into a set of Observables that emit groups of items from the original Observable, organized by key -* [**`buffer( )`**](http://reactivex.io/documentation/operators/buffer.html) — periodically gather items from an Observable into bundles and emit these bundles rather than emitting the items one at a time -* [**`window( )`**](http://reactivex.io/documentation/operators/window.html) — periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time -* [**`cast( )`**](http://reactivex.io/documentation/operators/map.html) — cast all items from the source Observable into a particular type before reemitting them \ No newline at end of file +This page shows operators with which you can transform items that are emitted by reactive sources, such as `Observable`s. + +# Outline + +- [`buffer`](#buffer) +- [`cast`](#cast) +- [`concatMap`](#concatmap) +- [`concatMapCompletable`](#concatmapcompletable) +- [`concatMapCompletableDelayError`](#concatmapcompletabledelayerror) +- [`concatMapDelayError`](#concatmapdelayerror) +- [`concatMapEager`](#concatmapeager) +- [`concatMapEagerDelayError`](#concatmapeagerdelayerror) +- [`concatMapIterable`](#concatmapiterable) +- [`concatMapMaybe`](#concatmapmaybe) +- [`concatMapMaybeDelayError`](#concatmapmaybedelayerror) +- [`concatMapSingle`](#concatmapsingle) +- [`concatMapSingleDelayError`](#concatmapsingledelayerror) +- [`flatMap`](#flatmap) +- [`flatMapCompletable`](#flatmapcompletable) +- [`flatMapIterable`](#flatmapiterable) +- [`flatMapMaybe`](#flatmapmaybe) +- [`flatMapObservable`](#flatmapobservable) +- [`flatMapPublisher`](#flatmappublisher) +- [`flatMapSingle`](#flatmapsingle) +- [`flatMapSingleElement`](#flatmapsingleelement) +- [`flattenAsFlowable`](#flattenasflowable) +- [`flattenAsObservable`](#flattenasobservable) +- [`groupBy`](#groupby) +- [`map`](#map) +- [`scan`](#scan) +- [`switchMap`](#switchmap) +- [`window`](#window) + +## buffer + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/buffer.html](http://reactivex.io/documentation/operators/buffer.html) + +Collects the items emitted by a reactive source into buffers, and emits these buffers. + +### buffer example + +```java +Observable.range(0, 10) + .buffer(4) + .subscribe((List<Integer> buffer) -> System.out.println(buffer)); + +// prints: +// [0, 1, 2, 3] +// [4, 5, 6, 7] +// [8, 9] +``` + +## cast + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/map.html](http://reactivex.io/documentation/operators/map.html) + +Converts each item emitted by a reactive source to the specified type, and emits these items. + +### cast example + +```java +Observable<Number> numbers = Observable.just(1, 4.0, 3f, 7, 12, 4.6, 5); + +numbers.filter((Number x) -> Integer.class.isInstance(x)) + .cast(Integer.class) + .subscribe((Integer x) -> System.out.println(x)); + +// prints: +// 1 +// 7 +// 12 +// 5 +``` + +## concatMap + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a reactive source, and emits the items that result from concatenating the results of these function applications. + +### concatMap example + +```java +Observable.range(0, 5) + .concatMap(i -> { + long delay = Math.round(Math.random() * 2); + + return Observable.timer(delay, TimeUnit.SECONDS).map(n -> i); + }) + .blockingSubscribe(System.out::print); + +// prints 01234 +``` + +## concatMapCompletable + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `io.reactivex.CompletableSource`, subscribes to them one at a time and returns a `Completable` that completes when all sources completed. + +### concatMapCompletable example + +```java +Observable<Integer> source = Observable.just(2, 1, 3); +Completable completable = source.concatMapCompletable(x -> { + return Completable.timer(x, TimeUnit.SECONDS) + .doOnComplete(() -> System.out.println("Info: Processing of item \"" + x + "\" completed")); + }); + +completable.doOnComplete(() -> System.out.println("Info: Processing of all items completed")) + .blockingAwait(); + +// prints: +// Info: Processing of item "2" completed +// Info: Processing of item "1" completed +// Info: Processing of item "3" completed +// Info: Processing of all items completed +``` + +## concatMapCompletableDelayError + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `io.reactivex.CompletableSource`, subscribes to them one at a time and returns a `Completable` that completes when all sources completed. Any errors from the sources will be delayed until all of them terminate. + +### concatMapCompletableDelayError example + +```java +Observable<Integer> source = Observable.just(2, 1, 3); +Completable completable = source.concatMapCompletableDelayError(x -> { + if (x.equals(2)) { + return Completable.error(new IOException("Processing of item \"" + x + "\" failed!")); + } else { + return Completable.timer(1, TimeUnit.SECONDS) + .doOnComplete(() -> System.out.println("Info: Processing of item \"" + x + "\" completed")); + } +}); + +completable.doOnError(error -> System.out.println("Error: " + error.getMessage())) + .onErrorComplete() + .blockingAwait(); + +// prints: +// Info: Processing of item "1" completed +// Info: Processing of item "3" completed +// Error: Processing of item "2" failed! +``` + +## concatMapDelayError + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a reactive source, and emits the items that result from concatenating the results of these function applications. Any errors from the sources will be delayed until all of them terminate. + +### concatMapDelayError example + +```java +Observable.intervalRange(1, 3, 0, 1, TimeUnit.SECONDS) + .concatMapDelayError(x -> { + if (x.equals(1L)) return Observable.error(new IOException("Something went wrong!")); + else return Observable.just(x, x * x); + }) + .blockingSubscribe( + x -> System.out.println("onNext: " + x), + error -> System.out.println("onError: " + error.getMessage())); + +// prints: +// onNext: 2 +// onNext: 4 +// onNext: 3 +// onNext: 9 +// onError: Something went wrong! +``` + +## concatMapEager + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a reactive source, and emits the items that result from concatenating the results of these function applications. Unlike [`concatMap`](#concatmap), this operator eagerly subscribes to all sources. + +### concatMapEager example + +```java +Observable.range(0, 5) + .concatMapEager(i -> { + long delay = Math.round(Math.random() * 3); + + return Observable.timer(delay, TimeUnit.SECONDS) + .map(n -> i) + .doOnNext(x -> System.out.println("Info: Finished processing item " + x)); + }) + .blockingSubscribe(i -> System.out.println("onNext: " + i)); + +// prints (lines beginning with "Info..." can be displayed in a different order): +// Info: Finished processing item 2 +// Info: Finished processing item 0 +// onNext: 0 +// Info: Finished processing item 1 +// onNext: 1 +// onNext: 2 +// Info: Finished processing item 3 +// Info: Finished processing item 4 +// onNext: 3 +// onNext: 4 +``` + +## concatMapEagerDelayError + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a reactive source, and emits the items that result from concatenating the results of these function applications. A `boolean` value must be specified, which if `true` indicates that all errors from all sources will be delayed until the end, otherwise if `false`, an error from the main source will be signalled when the current source terminates. Unlike [concatMapDelayError](#concatmapdelayerror), this operator eagerly subscribes to all sources. + +### concatMapEagerDelayError example + +```java +Observable<Integer> source = Observable.create(emitter -> { + emitter.onNext(1); + emitter.onNext(2); + emitter.onError(new Error("Fatal error!")); +}); + +source.doOnError(error -> System.out.println("Info: Error from main source " + error.getMessage())) + .concatMapEagerDelayError(x -> { + return Observable.timer(1, TimeUnit.SECONDS).map(n -> x) + .doOnSubscribe(it -> System.out.println("Info: Processing of item \"" + x + "\" started")); + }, true) + .blockingSubscribe( + x -> System.out.println("onNext: " + x), + error -> System.out.println("onError: " + error.getMessage())); + +// prints: +// Info: Processing of item "1" started +// Info: Processing of item "2" started +// Info: Error from main source Fatal error! +// onNext: 1 +// onNext: 2 +// onError: Fatal error! +``` + +## concatMapIterable + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `java.lang.Iterable`, and emits the items that result from concatenating the results of these function applications. + +### concatMapIterable example + +```java +Observable.just("A", "B", "C") + .concatMapIterable(item -> List.of(item, item, item)) + .subscribe(System.out::print); + +// prints AAABBBCCC +``` + +## concatMapMaybe + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `io.reactivex.MaybeSource`, and emits the items that result from concatenating these `MaybeSource`s. + +### concatMapMaybe example + +```java +Observable.just("5", "3,14", "2.71", "FF") + .concatMapMaybe(v -> { + return Maybe.fromCallable(() -> Double.parseDouble(v)) + .doOnError(e -> System.out.println("Info: The value \"" + v + "\" could not be parsed.")) + + // Ignore values that can not be parsed. + .onErrorComplete(); + }) + .subscribe(x -> System.out.println("onNext: " + x)); + +// prints: +// onNext: 5.0 +// Info: The value "3,14" could not be parsed. +// onNext: 2.71 +// Info: The value "FF" could not be parsed. +``` + +## concatMapMaybeDelayError + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `io.reactivex.MaybeSource`, and emits the items that result from concatenating these `MaybeSource`s. Any errors from the sources will be delayed until all of them terminate. + +### concatMapMaybeDelayError example + +```java +DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd.MM.uuuu"); +Observable.just("04.03.2018", "12-08-2018", "06.10.2018", "01.12.2018") + .concatMapMaybeDelayError(date -> { + return Maybe.fromCallable(() -> LocalDate.parse(date, dateFormatter)); + }) + .subscribe( + localDate -> System.out.println("onNext: " + localDate), + error -> System.out.println("onError: " + error.getMessage())); + +// prints: +// onNext: 2018-03-04 +// onNext: 2018-10-06 +// onNext: 2018-12-01 +// onError: Text '12-08-2018' could not be parsed at index 2 +``` + +## concatMapSingle + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `io.reactivex.SingleSource`, and emits the items that result from concatenating these ``SingleSource`s. + +### concatMapSingle example + +```java +Observable.just("5", "3,14", "2.71", "FF") + .concatMapSingle(v -> { + return Single.fromCallable(() -> Double.parseDouble(v)) + .doOnError(e -> System.out.println("Info: The value \"" + v + "\" could not be parsed.")) + + // Return a default value if the given value can not be parsed. + .onErrorReturnItem(42.0); + }) + .subscribe(x -> System.out.println("onNext: " + x)); + +// prints: +// onNext: 5.0 +// Info: The value "3,14" could not be parsed. +// onNext: 42.0 +// onNext: 2.71 +// Info: The value "FF" could not be parsed. +// onNext: 42.0 +``` + +## concatMapSingleDelayError + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `io.reactivex.SingleSource`, and emits the items that result from concatenating the results of these function applications. Any errors from the sources will be delayed until all of them terminate. + +### concatMapSingleDelayError example + +```java +DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd.MM.uuuu"); +Observable.just("24.03.2018", "12-08-2018", "06.10.2018", "01.12.2018") + .concatMapSingleDelayError(date -> { + return Single.fromCallable(() -> LocalDate.parse(date, dateFormatter)); + }) + .subscribe( + localDate -> System.out.println("onNext: " + localDate), + error -> System.out.println("onError: " + error.getMessage())); + +// prints: +// onNext: 2018-03-24 +// onNext: 2018-10-06 +// onNext: 2018-12-01 +// onError: Text '12-08-2018' could not be parsed at index 2 +``` + +## flatMap + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a reactive source, and emits the items that result from merging the results of these function applications. + +### flatMap example + +```java +Observable.just("A", "B", "C") + .flatMap(a -> { + return Observable.intervalRange(1, 3, 0, 1, TimeUnit.SECONDS) + .map(b -> '(' + a + ", " + b + ')'); + }) + .blockingSubscribe(System.out::println); + +// prints (not necessarily in this order): +// (A, 1) +// (C, 1) +// (B, 1) +// (A, 2) +// (C, 2) +// (B, 2) +// (A, 3) +// (C, 3) +// (B, 3) +``` + +## flatMapCompletable + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `io.reactivex.CompletableSource`, and returns a `Completable` that completes when all sources completed. + +### flatMapCompletable example + +```java +Observable<Integer> source = Observable.just(2, 1, 3); +Completable completable = source.flatMapCompletable(x -> { + return Completable.timer(x, TimeUnit.SECONDS) + .doOnComplete(() -> System.out.println("Info: Processing of item \"" + x + "\" completed")); +}); + +completable.doOnComplete(() -> System.out.println("Info: Processing of all items completed")) + .blockingAwait(); + +// prints: +// Info: Processing of item "1" completed +// Info: Processing of item "2" completed +// Info: Processing of item "3" completed +// Info: Processing of all items completed +``` + +## flatMapIterable + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `java.lang.Iterable`, and emits the elements from these `Iterable`s. + +### flatMapIterable example + +```java +Observable.just(1, 2, 3, 4) + .flatMapIterable(x -> { + switch (x % 4) { + case 1: + return List.of("A"); + case 2: + return List.of("B", "B"); + case 3: + return List.of("C", "C", "C"); + default: + return List.of(); + } + }) + .subscribe(System.out::println); + +// prints: +// A +// B +// B +// C +// C +// C +``` + +## flatMapMaybe + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `io.reactivex.MaybeSource`, and emits the items that result from merging these `MaybeSource`s. + +### flatMapMaybe example + +```java +Observable.just(9.0, 16.0, -4.0) + .flatMapMaybe(x -> { + if (x.compareTo(0.0) < 0) return Maybe.empty(); + else return Maybe.just(Math.sqrt(x)); + }) + .subscribe( + System.out::println, + Throwable::printStackTrace, + () -> System.out.println("onComplete")); + +// prints: +// 3.0 +// 4.0 +// onComplete +``` + +## flatMapObservable + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to the item emitted by a `Maybe` or `Single`, where that function returns an `io.reactivex.ObservableSource`, and returns an `Observable` that emits the items emitted by this `ObservableSource`. + +### flatMapObservable example + +```java +Single<String> source = Single.just("Kirk, Spock, Chekov, Sulu"); +Observable<String> names = source.flatMapObservable(text -> { + return Observable.fromArray(text.split(",")) + .map(String::strip); +}); + +names.subscribe(name -> System.out.println("onNext: " + name)); + +// prints: +// onNext: Kirk +// onNext: Spock +// onNext: Chekov +// onNext: Sulu +``` + +## flatMapPublisher + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to the item emitted by a `Maybe` or `Single`, where that function returns an `org.reactivestreams.Publisher`, and returns a `Flowable` that emits the items emitted by this `Publisher`. + +### flatMapPublisher example + +```java +Single<String> source = Single.just("Kirk, Spock, Chekov, Sulu"); +Flowable<String> names = source.flatMapPublisher(text -> { + return Flowable.fromArray(text.split(",")) + .map(String::strip); +}); + +names.subscribe(name -> System.out.println("onNext: " + name)); + +// prints: +// onNext: Kirk +// onNext: Spock +// onNext: Chekov +// onNext: Sulu +``` + +## flatMapSingle + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a `io.reactivex.SingleSource`, and emits the items that result from merging these `SingleSource`s. + +### flatMapSingle example + +```java +Observable.just(4, 2, 1, 3) + .flatMapSingle(x -> Single.timer(x, TimeUnit.SECONDS).map(i -> x)) + .blockingSubscribe(System.out::print); + +// prints 1234 +``` + +*Note:* `Maybe::flatMapSingle` returns a `Single` that signals an error notification if the `Maybe` source is empty: + +```java +Maybe<Object> emptySource = Maybe.empty(); +Single<Object> result = emptySource.flatMapSingle(x -> Single.just(x)); +result.subscribe( + x -> System.out.println("onSuccess will not be printed!"), + error -> System.out.println("onError: Source was empty!")); + +// prints: +// onError: Source was empty! +``` + +Use [`Maybe::flatMapSingleElement`](#flatmapsingleelement) -- which returns a `Maybe` -- if you don't want this behaviour. + +## flatMapSingleElement + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to the item emitted by a `Maybe`, where that function returns a `io.reactivex.SingleSource`, and returns a `Maybe` that either emits the item emitted by this `SingleSource` or completes if the source `Maybe` just completes. + +### flatMapSingleElement example + +```java +Maybe<Integer> source = Maybe.just(-42); +Maybe<Integer> result = source.flatMapSingleElement(x -> { + return Single.just(Math.abs(x)); +}); + +result.subscribe(System.out::println); + +// prints 42 +``` + +## flattenAsFlowable + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to the item emitted by a `Maybe` or `Single`, where that function returns a `java.lang.Iterable`, and returns a `Flowable` that emits the elements from this `Iterable`. + +### flattenAsFlowable example + +```java +Single<Double> source = Single.just(2.0); +Flowable<Double> flowable = source.flattenAsFlowable(x -> { + return List.of(x, Math.pow(x, 2), Math.pow(x, 3)); +}); + +flowable.subscribe(x -> System.out.println("onNext: " + x)); + +// prints: +// onNext: 2.0 +// onNext: 4.0 +// onNext: 8.0 +``` + +## flattenAsObservable + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to the item emitted by a `Maybe` or `Single`, where that function returns a `java.lang.Iterable`, and returns an `Observable` that emits the elements from this `Iterable`. + +### flattenAsObservable example + +```java +Single<Double> source = Single.just(2.0); +Observable<Double> observable = source.flattenAsObservable(x -> { + return List.of(x, Math.pow(x, 2), Math.pow(x, 3)); +}); + +observable.subscribe(x -> System.out.println("onNext: " + x)); + +// prints: +// onNext: 2.0 +// onNext: 4.0 +// onNext: 8.0 +``` + +## groupBy + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/groupby.html](http://reactivex.io/documentation/operators/groupby.html) + +Groups the items emitted by a reactive source according to a specified criterion, and emits these grouped items as a `GroupedObservable` or `GroupedFlowable`. + +### groupBy example + +```java +Observable<String> animals = Observable.just( + "Tiger", "Elephant", "Cat", "Chameleon", "Frog", "Fish", "Turtle", "Flamingo"); + +animals.groupBy(animal -> animal.charAt(0), String::toUpperCase) + .concatMapSingle(Observable::toList) + .subscribe(System.out::println); + +// prints: +// [TIGER, TURTLE] +// [ELEPHANT] +// [CAT, CHAMELEON] +// [FROG, FISH, FLAMINGO] +``` + +## map + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/map.html](http://reactivex.io/documentation/operators/map.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source and emits the results of these function applications. + +### map example + +```java +Observable.just(1, 2, 3) + .map(x -> x * x) + .subscribe(System.out::println); + +// prints: +// 1 +// 4 +// 9 +``` + +## scan + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/scan.html](http://reactivex.io/documentation/operators/scan.html) + +Applies the given `io.reactivex.functions.BiFunction` to a seed value and the first item emitted by a reactive source, then feeds the result of that function application along with the second item emitted by the reactive source into the same function, and so on until all items have been emitted by the reactive source, emitting each intermediate result. + +### scan example + +```java +Observable.just(5, 3, 8, 1, 7) + .scan(0, (partialSum, x) -> partialSum + x) + .subscribe(System.out::println); + +// prints: +// 0 +// 5 +// 8 +// 16 +// 17 +// 24 +``` + +## switchMap + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/flatmap.html](http://reactivex.io/documentation/operators/flatmap.html) + +Applies the given `io.reactivex.functions.Function` to each item emitted by a reactive source, where that function returns a reactive source, and emits the items emitted by the most recently projected of these reactive sources. + +### switchMap example + +```java +Observable.interval(0, 1, TimeUnit.SECONDS) + .switchMap(x -> { + return Observable.interval(0, 750, TimeUnit.MILLISECONDS) + .map(y -> x); + }) + .takeWhile(x -> x < 3) + .blockingSubscribe(System.out::print); + +// prints 001122 +``` + +## window + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/window.html](http://reactivex.io/documentation/operators/window.html) + +Collects the items emitted by a reactive source into windows, and emits these windows as a `Flowable` or `Observable`. + +### window example + +```java +Observable.range(1, 10) + + // Create windows containing at most 2 items, and skip 3 items before starting a new window. + .window(2, 3) + .flatMapSingle(window -> { + return window.map(String::valueOf) + .reduce(new StringJoiner(", ", "[", "]"), StringJoiner::add); + }) + .subscribe(System.out::println); + +// prints: +// [1, 2] +// [4, 5] +// [7, 8] +// [10] +``` From 6afd2b8d6c96ae9f76f5dc4802b9e8385c7b12ee Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 12 Nov 2018 10:26:14 +0100 Subject: [PATCH 314/417] 2.x: Fix refCount eager disconnect not resetting the connection (#6297) * 2.x: Fix refCount eager disconnect not resetting the connection * Remove unnecessary comment. --- .../operators/flowable/FlowableRefCount.java | 13 ++++++++++++- .../operators/observable/ObservableRefCount.java | 14 +++++++++++++- .../operators/flowable/FlowableRefCountTest.java | 15 +++++++++++++++ .../observable/ObservableRefCountTest.java | 15 +++++++++++++++ 4 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java index f966f01365..bc11aa5425 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java @@ -141,7 +141,11 @@ void timeout(RefConnection rc) { if (source instanceof Disposable) { ((Disposable)source).dispose(); } else if (source instanceof ResettableConnectable) { - ((ResettableConnectable)source).resetIf(connectionObject); + if (connectionObject == null) { + rc.disconnectedEarly = true; + } else { + ((ResettableConnectable)source).resetIf(connectionObject); + } } } } @@ -160,6 +164,8 @@ static final class RefConnection extends AtomicReference<Disposable> boolean connected; + boolean disconnectedEarly; + RefConnection(FlowableRefCount<?> parent) { this.parent = parent; } @@ -172,6 +178,11 @@ public void run() { @Override public void accept(Disposable t) throws Exception { DisposableHelper.replace(this, t); + synchronized (parent) { + if (disconnectedEarly) { + ((ResettableConnectable)parent.source).resetIf(t); + } + } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java index 3dced24de6..5abc174350 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java @@ -135,10 +135,15 @@ void timeout(RefConnection rc) { connection = null; Disposable connectionObject = rc.get(); DisposableHelper.dispose(rc); + if (source instanceof Disposable) { ((Disposable)source).dispose(); } else if (source instanceof ResettableConnectable) { - ((ResettableConnectable)source).resetIf(connectionObject); + if (connectionObject == null) { + rc.disconnectedEarly = true; + } else { + ((ResettableConnectable)source).resetIf(connectionObject); + } } } } @@ -157,6 +162,8 @@ static final class RefConnection extends AtomicReference<Disposable> boolean connected; + boolean disconnectedEarly; + RefConnection(ObservableRefCount<?> parent) { this.parent = parent; } @@ -169,6 +176,11 @@ public void run() { @Override public void accept(Disposable t) throws Exception { DisposableHelper.replace(this, t); + synchronized (parent) { + if (disconnectedEarly) { + ((ResettableConnectable)parent.source).resetIf(t); + } + } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index 289170b254..673a0f4add 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -1394,4 +1394,19 @@ public void timeoutDisposesSource() { assertTrue(((Disposable)o.source).isDisposed()); } + + @Test + public void disconnectBeforeConnect() { + BehaviorProcessor<Integer> processor = BehaviorProcessor.create(); + + Flowable<Integer> flowable = processor + .replay(1) + .refCount(); + + flowable.takeUntil(Flowable.just(1)).test(); + + processor.onNext(2); + + flowable.take(1).test().assertResult(2); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index ea69a1d500..0f0d930d8d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -1345,4 +1345,19 @@ public void timeoutDisposesSource() { assertTrue(((Disposable)o.source).isDisposed()); } + + @Test + public void disconnectBeforeConnect() { + BehaviorSubject<Integer> subject = BehaviorSubject.create(); + + Observable<Integer> observable = subject + .replay(1) + .refCount(); + + observable.takeUntil(Observable.just(1)).test(); + + subject.onNext(2); + + observable.take(1).test().assertResult(2); + } } From e82b82edf874e69ed51896987a4c987d3f5af9f2 Mon Sep 17 00:00:00 2001 From: punitd <punitdama@gmail.com> Date: Tue, 13 Nov 2018 19:46:50 +0530 Subject: [PATCH 315/417] Javadoc : Explain explicitly about non-concurrency for Emitter interface methods (#6305) --- src/main/java/io/reactivex/Emitter.java | 5 +++++ src/main/java/io/reactivex/Flowable.java | 25 ++++++++++++++++++++++ src/main/java/io/reactivex/Observable.java | 25 ++++++++++++++++++++++ 3 files changed, 55 insertions(+) diff --git a/src/main/java/io/reactivex/Emitter.java b/src/main/java/io/reactivex/Emitter.java index 2f60f90478..0d95e80dcf 100644 --- a/src/main/java/io/reactivex/Emitter.java +++ b/src/main/java/io/reactivex/Emitter.java @@ -17,6 +17,11 @@ /** * Base interface for emitting signals in a push-fashion in various generator-like source * operators (create, generate). + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently. Calling them from multiple threads is not supported and leads to an + * undefined behavior. * * @param <T> the value type emitted */ diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 666c7c765d..da4f800670 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -2210,6 +2210,11 @@ public static <T> Flowable<T> fromPublisher(final Publisher<? extends T> source) /** * Returns a cold, synchronous, stateless and backpressure-aware generator of values. + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently and only while the function body is executing. Calling them from multiple threads + * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors downstream backpressure.</dd> @@ -2236,6 +2241,11 @@ public static <T> Flowable<T> generate(final Consumer<Emitter<T>> generator) { /** * Returns a cold, synchronous, stateful and backpressure-aware generator of values. + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently and only while the function body is executing. Calling them from multiple threads + * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors downstream backpressure.</dd> @@ -2263,6 +2273,11 @@ public static <T, S> Flowable<T> generate(Callable<S> initialState, final BiCons /** * Returns a cold, synchronous, stateful and backpressure-aware generator of values. + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently and only while the function body is executing. Calling them from multiple threads + * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors downstream backpressure.</dd> @@ -2292,6 +2307,11 @@ public static <T, S> Flowable<T> generate(Callable<S> initialState, final BiCons /** * Returns a cold, synchronous, stateful and backpressure-aware generator of values. + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently and only while the function body is executing. Calling them from multiple threads + * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors downstream backpressure.</dd> @@ -2318,6 +2338,11 @@ public static <T, S> Flowable<T> generate(Callable<S> initialState, BiFunction<S /** * Returns a cold, synchronous, stateful and backpressure-aware generator of values. + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently and only while the function body is executing. Calling them from multiple threads + * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors downstream backpressure.</dd> diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 8ab4059642..c022a0f9fa 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -1992,6 +1992,11 @@ public static <T> Observable<T> fromPublisher(Publisher<? extends T> publisher) * Returns a cold, synchronous and stateless generator of values. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/generate.2.png" alt=""> + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently and only while the function body is executing. Calling them from multiple threads + * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code generate} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2016,6 +2021,11 @@ public static <T> Observable<T> generate(final Consumer<Emitter<T>> generator) { * Returns a cold, synchronous and stateful generator of values. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/generate.2.png" alt=""> + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently and only while the function body is executing. Calling them from multiple threads + * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code generate} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2041,6 +2051,11 @@ public static <T, S> Observable<T> generate(Callable<S> initialState, final BiCo * Returns a cold, synchronous and stateful generator of values. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/generate.2.png" alt=""> + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently and only while the function body is executing. Calling them from multiple threads + * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code generate} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2071,6 +2086,11 @@ public static <T, S> Observable<T> generate( * Returns a cold, synchronous and stateful generator of values. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/generate.2.png" alt=""> + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently and only while the function body is executing. Calling them from multiple threads + * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code generate} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2096,6 +2116,11 @@ public static <T, S> Observable<T> generate(Callable<S> initialState, BiFunction * Returns a cold, synchronous and stateful generator of values. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/generate.2.png" alt=""> + * <p> + * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and + * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, + * never concurrently and only while the function body is executing. Calling them from multiple threads + * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code generate} does not operate by default on a particular {@link Scheduler}.</dd> From f800b30f044497ea11f23986d3d6260e7ea69f2b Mon Sep 17 00:00:00 2001 From: Purnima Kamath <git.pkamath2@gmail.com> Date: Fri, 16 Nov 2018 21:52:03 +0800 Subject: [PATCH 316/417] Javadoc updates for RXJava Issue 6289 (#6308) * Javadoc updates for RXJava Issue 6289 * With review comments on issue 6289 --- src/main/java/io/reactivex/Flowable.java | 47 ++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index da4f800670..c3c48e3c95 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -10345,6 +10345,14 @@ public final Disposable forEachWhile(final Predicate<? super T> onNext, final Co * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedPublisher}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #ignoreElements} to them. + * <p> + * Note that the {@link GroupedFlowable}s should be subscribed to as soon as possible, otherwise, + * the unconsumed groups may starve other groups due to the internal backpressure + * coordination of the {@code groupBy} operator. Such hangs can be usually avoided by using + * {@link #flatMap(Function, int)} or {@link #concatMapEager(Function, int, int)} and overriding the default maximum concurrency + * value to be greater or equal to the expected number of groups, possibly using + * {@code Integer.MAX_VALUE} if the number of expected groups is unknown. + * * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Both the returned and its inner {@code Publisher}s honor backpressure and the source {@code Publisher} @@ -10385,6 +10393,13 @@ public final <K> Flowable<GroupedFlowable<K, T>> groupBy(Function<? super T, ? e * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedPublisher}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #ignoreElements} to them. + * <p> + * Note that the {@link GroupedFlowable}s should be subscribed to as soon as possible, otherwise, + * the unconsumed groups may starve other groups due to the internal backpressure + * coordination of the {@code groupBy} operator. Such hangs can be usually avoided by using + * {@link #flatMap(Function, int)} or {@link #concatMapEager(Function, int, int)} and overriding the default maximum concurrency + * value to be greater or equal to the expected number of groups, possibly using + * {@code Integer.MAX_VALUE} if the number of expected groups is unknown. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Both the returned and its inner {@code Publisher}s honor backpressure and the source {@code Publisher} @@ -10428,6 +10443,14 @@ public final <K> Flowable<GroupedFlowable<K, T>> groupBy(Function<? super T, ? e * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedPublisher}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #ignoreElements} to them. + * <p> + * Note that the {@link GroupedFlowable}s should be subscribed to as soon as possible, otherwise, + * the unconsumed groups may starve other groups due to the internal backpressure + * coordination of the {@code groupBy} operator. Such hangs can be usually avoided by using + * {@link #flatMap(Function, int)} or {@link #concatMapEager(Function, int, int)} and overriding the default maximum concurrency + * value to be greater or equal to the expected number of groups, possibly using + * {@code Integer.MAX_VALUE} if the number of expected groups is unknown. + * * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Both the returned and its inner {@code Publisher}s honor backpressure and the source {@code Publisher} @@ -10473,6 +10496,14 @@ public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedPublisher}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #ignoreElements} to them. + * <p> + * Note that the {@link GroupedFlowable}s should be subscribed to as soon as possible, otherwise, + * the unconsumed groups may starve other groups due to the internal backpressure + * coordination of the {@code groupBy} operator. Such hangs can be usually avoided by using + * {@link #flatMap(Function, int)} or {@link #concatMapEager(Function, int, int)} and overriding the default maximum concurrency + * value to be greater or equal to the expected number of groups, possibly using + * {@code Integer.MAX_VALUE} if the number of expected groups is unknown. + * * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Both the returned and its inner {@code Publisher}s honor backpressure and the source {@code Publisher} @@ -10521,6 +10552,14 @@ public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedPublisher}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #ignoreElements} to them. + * <p> + * Note that the {@link GroupedFlowable}s should be subscribed to as soon as possible, otherwise, + * the unconsumed groups may starve other groups due to the internal backpressure + * coordination of the {@code groupBy} operator. Such hangs can be usually avoided by using + * {@link #flatMap(Function, int)} or {@link #concatMapEager(Function, int, int)} and overriding the default maximum concurrency + * value to be greater or equal to the expected number of groups, possibly using + * {@code Integer.MAX_VALUE} if the number of expected groups is unknown. + * * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Both the returned and its inner {@code Publisher}s honor backpressure and the source {@code Publisher} @@ -10617,6 +10656,14 @@ public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedFlowable}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #ignoreElements} to them. + * <p> + * Note that the {@link GroupedFlowable}s should be subscribed to as soon as possible, otherwise, + * the unconsumed groups may starve other groups due to the internal backpressure + * coordination of the {@code groupBy} operator. Such hangs can be usually avoided by using + * {@link #flatMap(Function, int)} or {@link #concatMapEager(Function, int, int)} and overriding the default maximum concurrency + * value to be greater or equal to the expected number of groups, possibly using + * {@code Integer.MAX_VALUE} if the number of expected groups is unknown. + * * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Both the returned and its inner {@code GroupedFlowable}s honor backpressure and the source {@code Publisher} From 7058126ad4763a0ba6bcbf8433792f04426f5a77 Mon Sep 17 00:00:00 2001 From: punitd <punitdama@gmail.com> Date: Fri, 16 Nov 2018 22:30:17 +0530 Subject: [PATCH 317/417] Javadoc: explain that distinctUntilChanged requires non-mutating data to work as expected (#6311) * Javadoc : Explain distinctUntilChanged requires non-mutating data type in flow(Observable) Add few tests for scenarios related to mutable data type flow in distinctUntilChanged() methods for Observable * Javadoc : Explain distinctUntilChanged requires non-mutating data type in flow(Flowable) Add few tests for scenarios related to mutable data type flow in distinctUntilChanged() methods for Flowable * Remove tests and fix typo in javadoc --- src/main/java/io/reactivex/Flowable.java | 21 +++++++++++++++++++++ src/main/java/io/reactivex/Observable.java | 21 +++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index c3c48e3c95..d484f9da69 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -8740,6 +8740,13 @@ public final <K> Flowable<T> distinct(Function<? super T, K> keySelector, * <p> * Note that the operator always retains the latest item from upstream regardless of the comparison result * and uses it in the next comparison with the next upstream item. + * <p> + * Note that if element type {@code T} in the flow is mutable, the comparison of the previous and current + * item may yield unexpected results if the items are mutated externally. Common cases are mutable + * {@code CharSequence}s or {@code List}s where the objects will actually have the same + * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. + * To avoid such situation, it is recommended that mutable data is converted to an immutable one, + * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -8776,6 +8783,13 @@ public final Flowable<T> distinctUntilChanged() { * <p> * Note that the operator always retains the latest key from upstream regardless of the comparison result * and uses it in the next comparison with the next key derived from the next upstream item. + * <p> + * Note that if element type {@code T} in the flow is mutable, the comparison of the previous and current + * item may yield unexpected results if the items are mutated externally. Common cases are mutable + * {@code CharSequence}s or {@code List}s where the objects will actually have the same + * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. + * To avoid such situation, it is recommended that mutable data is converted to an immutable one, + * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -8808,6 +8822,13 @@ public final <K> Flowable<T> distinctUntilChanged(Function<? super T, K> keySele * <p> * Note that the operator always retains the latest item from upstream regardless of the comparison result * and uses it in the next comparison with the next upstream item. + * <p> + * Note that if element type {@code T} in the flow is mutable, the comparison of the previous and current + * item may yield unexpected results if the items are mutated externally. Common cases are mutable + * {@code CharSequence}s or {@code List}s where the objects will actually have the same + * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. + * To avoid such situation, it is recommended that mutable data is converted to an immutable one, + * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index c022a0f9fa..41f10e395f 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7824,6 +7824,13 @@ public final <K> Observable<T> distinct(Function<? super T, K> keySelector, Call * <p> * Note that the operator always retains the latest item from upstream regardless of the comparison result * and uses it in the next comparison with the next upstream item. + * <p> + * Note that if element type {@code T} in the flow is mutable, the comparison of the previous and current + * item may yield unexpected results if the items are mutated externally. Common cases are mutable + * {@code CharSequence}s or {@code List}s where the objects will actually have the same + * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. + * To avoid such situation, it is recommended that mutable data is converted to an immutable one, + * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> @@ -7856,6 +7863,13 @@ public final Observable<T> distinctUntilChanged() { * <p> * Note that the operator always retains the latest key from upstream regardless of the comparison result * and uses it in the next comparison with the next key derived from the next upstream item. + * <p> + * Note that if element type {@code T} in the flow is mutable, the comparison of the previous and current + * item may yield unexpected results if the items are mutated externally. Common cases are mutable + * {@code CharSequence}s or {@code List}s where the objects will actually have the same + * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. + * To avoid such situation, it is recommended that mutable data is converted to an immutable one, + * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> @@ -7884,6 +7898,13 @@ public final <K> Observable<T> distinctUntilChanged(Function<? super T, K> keySe * <p> * Note that the operator always retains the latest item from upstream regardless of the comparison result * and uses it in the next comparison with the next upstream item. + * <p> + * Note that if element type {@code T} in the flow is mutable, the comparison of the previous and current + * item may yield unexpected results if the items are mutated externally. Common cases are mutable + * {@code CharSequence}s or {@code List}s where the objects will actually have the same + * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. + * To avoid such situation, it is recommended that mutable data is converted to an immutable one, + * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> From ac3b5b195b8abf6086c21c7601ff5d054e0041d4 Mon Sep 17 00:00:00 2001 From: punitd <punitdama@gmail.com> Date: Mon, 19 Nov 2018 22:07:23 +0530 Subject: [PATCH 318/417] Change javadoc explanation for Mutable List (#6314) --- src/main/java/io/reactivex/Flowable.java | 6 +++--- src/main/java/io/reactivex/Observable.java | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index d484f9da69..18ed618512 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -8746,7 +8746,7 @@ public final <K> Flowable<T> distinct(Function<? super T, K> keySelector, * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. + * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -8789,7 +8789,7 @@ public final Flowable<T> distinctUntilChanged() { * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. + * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -8828,7 +8828,7 @@ public final <K> Flowable<T> distinctUntilChanged(Function<? super T, K> keySele * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. + * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 41f10e395f..ef177b5c6a 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7830,7 +7830,7 @@ public final <K> Observable<T> distinct(Function<? super T, K> keySelector, Call * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. + * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> @@ -7869,7 +7869,7 @@ public final Observable<T> distinctUntilChanged() { * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. + * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> @@ -7904,7 +7904,7 @@ public final <K> Observable<T> distinctUntilChanged(Function<? super T, K> keySe * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(Collections::unmodifiableList)`. + * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> From 3e4ae3856f184d5783d34ffc5c468d91e67d77d8 Mon Sep 17 00:00:00 2001 From: Philip Leonard <phillyleonard@gmail.com> Date: Fri, 23 Nov 2018 08:41:07 +0100 Subject: [PATCH 319/417] Fix Flowable#toObservable backpressure support (#6321) --- src/main/java/io/reactivex/Flowable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 18ed618512..1115eba74e 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -16983,7 +16983,7 @@ public final <K, V> Single<Map<K, Collection<V>>> toMultimap( * @since 2.0 */ @CheckReturnValue - @BackpressureSupport(BackpressureKind.NONE) + @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Observable<T> toObservable() { return RxJavaPlugins.onAssembly(new ObservableFromPublisher<T>(this)); From 6ae765a899969682263acef757480df95b026783 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 23 Nov 2018 08:43:18 +0100 Subject: [PATCH 320/417] Release 2.2.4 --- CHANGES.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 6c888f8d3a..dd1266c545 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,46 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.4 - November 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.4%7C)) + +#### API changes + + - [Pull 6278](https://github.com/ReactiveX/RxJava/pull/6278): Add `Maybe`/`Single`/`Completable` `materialize` operator, + - [Pull 6278](https://github.com/ReactiveX/RxJava/pull/6278): Add `Single.dematerialize(selector)` operator. + - [Pull 6281](https://github.com/ReactiveX/RxJava/pull/6281): Add `Flowable`/`Observable` `dematerialize(selector)` operator. + +#### Bugfixes + + - [Pull 6258](https://github.com/ReactiveX/RxJava/pull/6258): Fix cancel/dispose upon upstream switch for some operators. + - [Pull 6269](https://github.com/ReactiveX/RxJava/pull/6269): Call the `doOn{Dispose|Cancel}` handler at most once. + - [Pull 6283](https://github.com/ReactiveX/RxJava/pull/6283): Fix `Observable.flatMap` to sustain concurrency level. + - [Pull 6297](https://github.com/ReactiveX/RxJava/pull/6297): Fix refCount eager disconnect not resetting the connection. + +#### Documentation changes + + - [Pull 6280](https://github.com/ReactiveX/RxJava/pull/6280): Improve the package docs of `io.reactivex.schedulers`. + - [Pull 6301](https://github.com/ReactiveX/RxJava/pull/6301): Add missing `onSubscribe` null-checks to NPE docs on `Flowable`/`Observable` `subscribe`. + - [Pull 6303](https://github.com/ReactiveX/RxJava/pull/6303): Fix incorrect image placement in `Flowable.zip` docs. + - [Pull 6305](https://github.com/ReactiveX/RxJava/pull/6305): Explain the non-concurrency requirement of the `Emitter` interface methods. + - [Pull 6308](https://github.com/ReactiveX/RxJava/pull/6308): Explain the need to consume both the group sequence and each group specifically with `Flowable.groupBy`. + - [Pull 6311](https://github.com/ReactiveX/RxJava/pull/6311): Explain that `distinctUntilChanged` requires non-mutating data to work as expected. + +#### Wiki changes + + - [Pull 6260](https://github.com/ReactiveX/RxJava/pull/6260): Add `generate` examples to `Creating-Observables.md`. + - [Pull 6267](https://github.com/ReactiveX/RxJava/pull/6267): Fix `Creating-Observables.md` docs stlye mistake. + - [Pull 6273](https://github.com/ReactiveX/RxJava/pull/6273): Fix broken markdown of `How-to-Contribute.md`. + - [Pull 6266](https://github.com/ReactiveX/RxJava/pull/6266): Update Error Handling Operators docs. + - [Pull 6291](https://github.com/ReactiveX/RxJava/pull/6291): Update Transforming Observables docs. + +#### Other changes + + - [Pull 6262](https://github.com/ReactiveX/RxJava/pull/6262): Use JUnit's assert format for assert messages for better IDE interoperation. + - [Pull 6263](https://github.com/ReactiveX/RxJava/pull/6263): Inline `SubscriptionHelper.isCancelled()`. + - [Pull 6275](https://github.com/ReactiveX/RxJava/pull/6275): Improve the `Observable`/`Flowable` `cache()` operators. + - [Pull 6287](https://github.com/ReactiveX/RxJava/pull/6287): Expose the Keep-Alive value of the IO `Scheduler` as System property. + - [Pull 6321](https://github.com/ReactiveX/RxJava/pull/6321): Fix `Flowable.toObservable` backpressure annotation. + ### Version 2.2.3 - October 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.3%7C)) #### API changes From bc40695e4073ee806de460947958d4c6edca632b Mon Sep 17 00:00:00 2001 From: hoangnam2261 <31692990+hoangnam2261@users.noreply.github.com> Date: Mon, 10 Dec 2018 16:18:15 +0700 Subject: [PATCH 321/417] #6323 Java 8 version for Problem-Solving-Examples-in-RxJava (#6324) * #6323 Java 8 version for Project Euler problem * #6323 Java 8 version for Generate the Fibonacci Sequence * #6323 Java 8 version for Project Euler problem - Fix name of variable * #6324 Fixing for code review. --- docs/Problem-Solving-Examples-in-RxJava.md | 62 +++++++++++++++++++--- 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/docs/Problem-Solving-Examples-in-RxJava.md b/docs/Problem-Solving-Examples-in-RxJava.md index 1b41c2a122..6b848ae693 100644 --- a/docs/Problem-Solving-Examples-in-RxJava.md +++ b/docs/Problem-Solving-Examples-in-RxJava.md @@ -1,4 +1,4 @@ -This page will present some elementary RxJava puzzles and walk through some solutions (using the Groovy language implementation of RxJava) as a way of introducing you to some of the RxJava operators. +This page will present some elementary RxJava puzzles and walk through some solutions as a way of introducing you to some of the RxJava operators. # Project Euler problem #1 @@ -7,10 +7,22 @@ There used to be a site called "Project Euler" that presented a series of mathem > If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. There are several ways we could go about this with RxJava. We might, for instance, begin by going through all of the natural numbers below 1000 with [`range`](Creating-Observables#range) and then [`filter`](Filtering-Observables#filter) out those that are not a multiple either of 3 or of 5: +### Java +```java +Observable<Integer> threesAndFives = Observable.range(1, 999).filter(e -> e % 3 == 0 || e % 5 == 0); +``` +### Groovy ````groovy def threesAndFives = Observable.range(1,999).filter({ !((it % 3) && (it % 5)) }); ```` Or, we could generate two Observable sequences, one containing the multiples of three and the other containing the multiples of five (by [`map`](https://github.com/Netflix/RxJava/wiki/Transforming-Observables#map)ping each value onto its appropriate multiple), making sure to only generating new multiples while they are less than 1000 (the [`takeWhile`](Conditional-and-Boolean-Operators#takewhile-and-takewhilewithindex) operator will help here), and then [`merge`](Combining-Observables#merge) these sets: +### Java +```java +Observable<Integer> threes = Observable.range(1, 999).map(e -> e * 3).takeWhile(e -> e < 1000); +Observable<Integer> fives = Observable.range(1, 999).map(e -> e * 5).takeWhile(e -> e < 1000); +Observable<Integer> threesAndFives = Observable.merge(threes, fives).distinct(); +``` +### Groovy ````groovy def threes = Observable.range(1,999).map({it*3}).takeWhile({it<1000}); def fives = Observable.range(1,999).map({it*5}).takeWhile({it<1000}); @@ -21,6 +33,11 @@ Don't forget the [`distinct`](Filtering-Observables#distinct) operator here, oth Next, we want to sum up the numbers in the resulting sequence. If you have installed the optional `rxjava-math` module, this is elementary: just use an operator like [`sumInteger` or `sumLong`](Mathematical-and-Aggregate-Operators#suminteger-sumlong-sumfloat-and-sumdouble) on the `threesAndFives` Observable. But what if you don't have this module? How could you use standard RxJava operators to sum up a sequence and emit that sum? There are a number of operators that reduce a sequence emitted by a source Observable to a single value emitted by the resulting Observable. Most of the ones that are not in the `rxjava-math` module emit boolean evaluations of the sequence; we want something that can emit a number. The [`reduce`](Mathematical-and-Aggregate-Operators#reduce) operator will do the job: +### Java +```java +Single<Integer> summer = threesAndFives.reduce(0, (a, b) -> a + b); +``` +### Groovy ````groovy def summer = threesAndFives.reduce(0, { a, b -> a+b }); ```` @@ -38,6 +55,12 @@ Here is how `reduce` gets the job done. It starts with 0 as a seed. Then, with e </tbody> </table> Finally, we want to see the result. This means we must [subscribe](Observable#onnext-oncompleted-and-onerror) to the Observable we have constructed: + +### Java +```java +summer.subscribe(System.out::print); +``` +### Groovy ````groovy summer.subscribe({println(it);}); ```` @@ -47,11 +70,24 @@ summer.subscribe({println(it);}); How could you create an Observable that emits [the Fibonacci sequence](http://en.wikipedia.org/wiki/Fibonacci_number)? The most direct way would be to use the [`create`](Creating-Observables#wiki-create) operator to make an Observable "from scratch," and then use a traditional loop within the closure you pass to that operator to generate the sequence. Something like this: +### Java +```java +Observable<Integer> fibonacci = Observable.create(emitter -> { + int f1 = 0, f2 = 1, f = 1; + while (!emitter.isDisposed()) { + emitter.onNext(f); + f = f1 + f2; + f1 = f2; + f2 = f; + } +}); +``` +### Groovy ````groovy -def fibonacci = Observable.create({ observer -> - def f1=0; f2=1, f=1; - while(!observer.isUnsubscribed() { - observer.onNext(f); +def fibonacci = Observable.create({ emitter -> + def f1=0, f2=1, f=1; + while(!emitter.isDisposed()) { + emitter.onNext(f); f = f1+f2; f1 = f2; f2 = f; @@ -61,7 +97,16 @@ def fibonacci = Observable.create({ observer -> But this is a little too much like ordinary linear programming. Is there some way we can instead create this sequence by composing together existing Observable operators? Here's an option that does this: -```` +### Java +```java +Observable<Integer> fibonacci = + Observable.fromArray(0) + .repeat() + .scan(new int[]{0, 1}, (a, b) -> new int[]{a[1], a[0] + a[1]}) + .map(a -> a[1]); +``` +### Groovy +````groovy def fibonacci = Observable.from(0).repeat().scan([0,1], { a,b -> [a[1], a[0]+a[1]] }).map({it[1]}); ```` It's a little [janky](http://www.urbandictionary.com/define.php?term=janky). Let's walk through it: @@ -73,6 +118,11 @@ This has the effect of emitting the following sequence of items: `[0,1], [1,1], The second item in this array describes the Fibonacci sequence. We can use `map` to reduce the sequence to just that item. To print out a portion of this sequence (using either method), you would use code like the following: +### Java +```java +fibonacci.take(15).subscribe(System.out::println); +``` +### Groovy ````groovy fibonnaci.take(15).subscribe({println(it)})]; ```` From 1e4e966e5f848aaf931cb43db77c36a92ab62885 Mon Sep 17 00:00:00 2001 From: lorenzpahl <l.pahl@outlook.com> Date: Wed, 19 Dec 2018 10:41:09 +0100 Subject: [PATCH 322/417] 2.x: Update Filtering Observables docs (#6343) * Update operator list; revise descriptions * Add examples --- docs/Filtering-Observables.md | 782 +++++++++++++++++++++++++++++++++- 1 file changed, 760 insertions(+), 22 deletions(-) diff --git a/docs/Filtering-Observables.md b/docs/Filtering-Observables.md index 7e12d91094..620800dc8c 100644 --- a/docs/Filtering-Observables.md +++ b/docs/Filtering-Observables.md @@ -1,22 +1,760 @@ -This page shows operators you can use to filter and select items emitted by Observables. - -* [**`filter( )`**](http://reactivex.io/documentation/operators/filter.html) — filter items emitted by an Observable -* [**`takeLast( )`**](http://reactivex.io/documentation/operators/takelast.html) — only emit the last _n_ items emitted by an Observable -* [**`last( )`**](http://reactivex.io/documentation/operators/last.html) — emit only the last item emitted by an Observable -* [**`lastOrDefault( )`**](http://reactivex.io/documentation/operators/last.html) — emit only the last item emitted by an Observable, or a default value if the source Observable is empty -* [**`takeLastBuffer( )`**](http://reactivex.io/documentation/operators/takelast.html) — emit the last _n_ items emitted by an Observable, as a single list item -* [**`skip( )`**](http://reactivex.io/documentation/operators/skip.html) — ignore the first _n_ items emitted by an Observable -* [**`skipLast( )`**](http://reactivex.io/documentation/operators/skiplast.html) — ignore the last _n_ items emitted by an Observable -* [**`take( )`**](http://reactivex.io/documentation/operators/take.html) — emit only the first _n_ items emitted by an Observable -* [**`first( )` and `takeFirst( )`**](http://reactivex.io/documentation/operators/first.html) — emit only the first item emitted by an Observable, or the first item that meets some condition -* [**`firstOrDefault( )`**](http://reactivex.io/documentation/operators/first.html) — emit only the first item emitted by an Observable, or the first item that meets some condition, or a default value if the source Observable is empty -* [**`elementAt( )`**](http://reactivex.io/documentation/operators/elementat.html) — emit item _n_ emitted by the source Observable -* [**`elementAtOrDefault( )`**](http://reactivex.io/documentation/operators/elementat.html) — emit item _n_ emitted by the source Observable, or a default item if the source Observable emits fewer than _n_ items -* [**`sample( )` or `throttleLast( )`**](http://reactivex.io/documentation/operators/sample.html) — emit the most recent items emitted by an Observable within periodic time intervals -* [**`throttleFirst( )`**](http://reactivex.io/documentation/operators/sample.html) — emit the first items emitted by an Observable within periodic time intervals -* [**`throttleWithTimeout( )` or `debounce( )`**](http://reactivex.io/documentation/operators/debounce.html) — only emit an item from the source Observable after a particular timespan has passed without the Observable emitting any other items -* [**`timeout( )`**](http://reactivex.io/documentation/operators/timeout.html) — emit items from a source Observable, but issue an exception if no item is emitted in a specified timespan -* [**`distinct( )`**](http://reactivex.io/documentation/operators/distinct.html) — suppress duplicate items emitted by the source Observable -* [**`distinctUntilChanged( )`**](http://reactivex.io/documentation/operators/distinct.html) — suppress duplicate consecutive items emitted by the source Observable -* [**`ofType( )`**](http://reactivex.io/documentation/operators/filter.html) — emit only those items from the source Observable that are of a particular class -* [**`ignoreElements( )`**](http://reactivex.io/documentation/operators/ignoreelements.html) — discard the items emitted by the source Observable and only pass through the error or completed notification +This page shows operators you can use to filter and select items emitted by reactive sources, such as `Observable`s. + +# Outline + +- [`debounce`](#debounce) +- [`distinct`](#distinct) +- [`distinctUntilChanged`](#distinctuntilchanged) +- [`elementAt`](#elementat) +- [`elementAtOrError`](#elementatorerror) +- [`filter`](#filter) +- [`first`](#first) +- [`firstElement`](#firstelement) +- [`firstOrError`](#firstorerror) +- [`ignoreElement`](#ignoreelement) +- [`ignoreElements`](#ignoreelements) +- [`last`](#last) +- [`lastElement`](#lastelement) +- [`lastOrError`](#lastorerror) +- [`ofType`](#oftype) +- [`sample`](#sample) +- [`skip`](#skip) +- [`skipLast`](#skiplast) +- [`take`](#take) +- [`takeLast`](#takelast) +- [`throttleFirst`](#throttlefirst) +- [`throttleLast`](#throttlelast) +- [`throttleLatest`](#throttlelatest) +- [`throttleWithTimeout`](#throttlewithtimeout) +- [`timeout`](#timeout) + +## debounce + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/debounce.html](http://reactivex.io/documentation/operators/debounce.html) + +Drops items emitted by a reactive source that are followed by newer items before the given timeout value expires. The timer resets on each emission. + +This operator keeps track of the most recent emitted item, and emits this item only when enough time has passed without the source emitting any other items. + +### debounce example + +```java +// Diagram: +// -A--------------B----C-D-------------------E-|----> +// a---------1s +// b---------1s +// c---------1s +// d---------1s +// e-|----> +// -----------A---------------------D-----------E-|--> + +Observable<String> source = Observable.create(emitter -> { + emitter.onNext("A"); + + Thread.sleep(1_500); + emitter.onNext("B"); + + Thread.sleep(500); + emitter.onNext("C"); + + Thread.sleep(250); + emitter.onNext("D"); + + Thread.sleep(2_000); + emitter.onNext("E"); + emitter.onComplete(); +}); + +source.subscribeOn(Schedulers.io()) + .debounce(1, TimeUnit.SECONDS) + .blockingSubscribe( + item -> System.out.println("onNext: " + item), + Throwable::printStackTrace, + () -> System.out.println("onComplete")); + +// prints: +// onNext: A +// onNext: D +// onNext: E +// onComplete +``` + +## distinct + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/distinct.html](http://reactivex.io/documentation/operators/distinct.html) + +Filters a reactive source by only emitting items that are distinct by comparison from previous items. A `io.reactivex.functions.Function` can be specified that projects each item emitted by the source into a new value that will be used for comparison with previous projected values. + +### distinct example + +```java +Observable.just(2, 3, 4, 4, 2, 1) + .distinct() + .subscribe(System.out::println); + +// prints: +// 2 +// 3 +// 4 +// 1 +``` + +## distinctUntilChanged + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/distinct.html](http://reactivex.io/documentation/operators/distinct.html) + +Filters a reactive source by only emitting items that are distinct by comparison from their immediate predecessors. A `io.reactivex.functions.Function` can be specified that projects each item emitted by the source into a new value that will be used for comparison with previous projected values. Alternatively, a `io.reactivex.functions.BiPredicate` can be specified that is used as the comparator function to compare immediate predecessors with each other. + +### distinctUntilChanged example + +```java +Observable.just(1, 1, 2, 1, 2, 3, 3, 4) + .distinctUntilChanged() + .subscribe(System.out::println); + +// prints: +// 1 +// 2 +// 1 +// 2 +// 3 +// 4 +``` + +## elementAt + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/elementat.html](http://reactivex.io/documentation/operators/elementat.html) + +Emits the single item at the specified zero-based index in a sequence of emissions from a reactive source. A default item can be specified that will be emitted if the specified index is not within the sequence. + +### elementAt example + +```java +Observable<Long> source = Observable.<Long, Long>generate(() -> 1L, (state, emitter) -> { + emitter.onNext(state); + + return state + 1L; +}).scan((product, x) -> product * x); + +Maybe<Long> element = source.elementAt(5); +element.subscribe(System.out::println); + +// prints 720 +``` + +## elementAtOrError + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/elementat.html](http://reactivex.io/documentation/operators/elementat.html) + +Emits the single item at the specified zero-based index in a sequence of emissions from a reactive source, or signals a `java.util.NoSuchElementException` if the specified index is not within the sequence. + +### elementAtOrError example + +```java +Observable<String> source = Observable.just("Kirk", "Spock", "Chekov", "Sulu"); +Single<String> element = source.elementAtOrError(4); + +element.subscribe( + name -> System.out.println("onSuccess will not be printed!"), + error -> System.out.println("onError: " + error)); + +// prints: +// onError: java.util.NoSuchElementException +``` + +## filter + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/filter.html](http://reactivex.io/documentation/operators/filter.html) + +Filters items emitted by a reactive source by only emitting those that satisfy a specified predicate. + +### filter example + +```java +Observable.just(1, 2, 3, 4, 5, 6) + .filter(x -> x % 2 == 0) + .subscribe(System.out::println); + +// prints: +// 2 +// 4 +// 6 +``` + +## first + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/first.html](http://reactivex.io/documentation/operators/first.html) + +Emits only the first item emitted by a reactive source, or emits the given default item if the source completes without emitting an item. This differs from [`firstElement`](#firstelement) in that this operator returns a `Single` whereas [`firstElement`](#firstelement) returns a `Maybe`. + +### first example + +```java +Observable<String> source = Observable.just("A", "B", "C"); +Single<String> firstOrDefault = source.first("D"); + +firstOrDefault.subscribe(System.out::println); + +// prints A +``` + +## firstElement + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/first.html](http://reactivex.io/documentation/operators/first.html) + +Emits only the first item emitted by a reactive source, or just completes if the source completes without emitting an item. This differs from [`first`](#first) in that this operator returns a `Maybe` whereas [`first`](#first) returns a `Single`. + +### firstElement example + +```java +Observable<String> source = Observable.just("A", "B", "C"); +Maybe<String> first = source.firstElement(); + +first.subscribe(System.out::println); + +// prints A +``` + +## firstOrError + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/first.html](http://reactivex.io/documentation/operators/first.html) + +Emits only the first item emitted by a reactive source, or signals a `java.util.NoSuchElementException` if the source completes without emitting an item. + +### firstOrError example + +```java +Observable<String> emptySource = Observable.empty(); +Single<String> firstOrError = emptySource.firstOrError(); + +firstOrError.subscribe( + element -> System.out.println("onSuccess will not be printed!"), + error -> System.out.println("onError: " + error)); + +// prints: +// onError: java.util.NoSuchElementException +``` + +## ignoreElement + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/ignoreelements.html](http://reactivex.io/documentation/operators/ignoreelements.html) + +Ignores the single item emitted by a `Single` or `Maybe` source, and returns a `Completable` that signals only the error or completion event from the the source. + +### ignoreElement example + +```java +Single<Long> source = Single.timer(1, TimeUnit.SECONDS); +Completable completable = source.ignoreElement(); + +completable.doOnComplete(() -> System.out.println("Done!")) + .blockingAwait(); + +// prints (after 1 second): +// Done! +``` + +## ignoreElements + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/ignoreelements.html](http://reactivex.io/documentation/operators/ignoreelements.html) + +Ignores all items from the `Observable` or `Flowable` source, and returns a `Completable` that signals only the error or completion event from the source. + +### ignoreElements example + +```java +Observable<Long> source = Observable.intervalRange(1, 5, 1, 1, TimeUnit.SECONDS); +Completable completable = source.ignoreElements(); + +completable.doOnComplete(() -> System.out.println("Done!")) + .blockingAwait(); + +// prints (after 5 seconds): +// Done! +``` + +## last + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/last.html](http://reactivex.io/documentation/operators/last.html) + +Emits only the last item emitted by a reactive source, or emits the given default item if the source completes without emitting an item. This differs from [`lastElement`](#lastelement) in that this operator returns a `Single` whereas [`lastElement`](#lastelement) returns a `Maybe`. + +### last example + +```java +Observable<String> source = Observable.just("A", "B", "C"); +Single<String> lastOrDefault = source.last("D"); + +lastOrDefault.subscribe(System.out::println); + +// prints C +``` + +## lastElement + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/last.html](http://reactivex.io/documentation/operators/last.html) + +Emits only the last item emitted by a reactive source, or just completes if the source completes without emitting an item. This differs from [`last`](#last) in that this operator returns a `Maybe` whereas [`last`](#last) returns a `Single`. + +### lastElement example + +```java +Observable<String> source = Observable.just("A", "B", "C"); +Maybe<String> last = source.lastElement(); + +last.subscribe(System.out::println); + +// prints C +``` + +## lastOrError + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/last.html](http://reactivex.io/documentation/operators/last.html) + +Emits only the last item emitted by a reactive source, or signals a `java.util.NoSuchElementException` if the source completes without emitting an item. + +### lastOrError example + +```java +Observable<String> emptySource = Observable.empty(); +Single<String> lastOrError = emptySource.lastOrError(); + +lastOrError.subscribe( + element -> System.out.println("onSuccess will not be printed!"), + error -> System.out.println("onError: " + error)); + +// prints: +// onError: java.util.NoSuchElementException +``` + +## ofType + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/filter.html](http://reactivex.io/documentation/operators/filter.html) + +Filters items emitted by a reactive source by only emitting those of the specified type. + +### ofType example + +```java +Observable<Number> numbers = Observable.just(1, 4.0, 3, 2.71, 2f, 7); +Observable<Integer> integers = numbers.ofType(Integer.class); + +integers.subscribe((Integer x) -> System.out.println(x)); + +// prints: +// 1 +// 3 +// 7 +``` + +## sample + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/sample.html](http://reactivex.io/documentation/operators/sample.html) + +Filters items emitted by a reactive source by only emitting the most recently emitted item within periodic time intervals. + +### sample example + +```java +// Diagram: +// -A----B-C-------D-----E-|--> +// -0s-----c--1s---d----2s-|--> +// -----------C---------D--|--> + +Observable<String> source = Observable.create(emitter -> { + emitter.onNext("A"); + + Thread.sleep(500); + emitter.onNext("B"); + + Thread.sleep(200); + emitter.onNext("C"); + + Thread.sleep(800); + emitter.onNext("D"); + + Thread.sleep(600); + emitter.onNext("E"); + emitter.onComplete(); +}); + +source.subscribeOn(Schedulers.io()) + .sample(1, TimeUnit.SECONDS) + .blockingSubscribe( + item -> System.out.println("onNext: " + item), + Throwable::printStackTrace, + () -> System.out.println("onComplete")); + +// prints: +// onNext: C +// onNext: D +// onComplete +``` + +## skip + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/skip.html](http://reactivex.io/documentation/operators/skip.html) + +Drops the first *n* items emitted by a reactive source, and emits the remaining items. + +### skip example + +```java +Observable<Integer> source = Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + +source.skip(4) + .subscribe(System.out::println); + +// prints: +// 5 +// 6 +// 7 +// 8 +// 9 +// 10 +``` + +## skipLast + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/skiplast.html](http://reactivex.io/documentation/operators/skiplast.html) + +Drops the last *n* items emitted by a reactive source, and emits the remaining items. + +### skipLast example + +```java +Observable<Integer> source = Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + +source.skipLast(4) + .subscribe(System.out::println); + +// prints: +// 1 +// 2 +// 3 +// 4 +// 5 +// 6 +``` + +## take + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/take.html](http://reactivex.io/documentation/operators/take.html) + +Emits only the first *n* items emitted by a reactive source. + +### take example + +```java +Observable<Integer> source = Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + +source.take(4) + .subscribe(System.out::println); + +// prints: +// 1 +// 2 +// 3 +// 4 +``` + +## takeLast + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/takelast.html](http://reactivex.io/documentation/operators/takelast.html) + +Emits only the last *n* items emitted by a reactive source. + +### takeLast example + +```java +Observable<Integer> source = Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + +source.takeLast(4) + .subscribe(System.out::println); + +// prints: +// 7 +// 8 +// 9 +// 10 +``` + +## throttleFirst + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/sample.html](http://reactivex.io/documentation/operators/sample.html) + +Emits only the first item emitted by a reactive source during sequential time windows of a specified duration. + +### throttleFirst example + +```java +// Diagram: +// -A----B-C-------D-----E-|--> +// a---------1s +// d-------|--> +// -A--------------D-------|--> + +Observable<String> source = Observable.create(emitter -> { + emitter.onNext("A"); + + Thread.sleep(500); + emitter.onNext("B"); + + Thread.sleep(200); + emitter.onNext("C"); + + Thread.sleep(800); + emitter.onNext("D"); + + Thread.sleep(600); + emitter.onNext("E"); + emitter.onComplete(); +}); + +source.subscribeOn(Schedulers.io()) + .throttleFirst(1, TimeUnit.SECONDS) + .blockingSubscribe( + item -> System.out.println("onNext: " + item), + Throwable::printStackTrace, + () -> System.out.println("onComplete")); + +// prints: +// onNext: A +// onNext: D +// onComplete +``` + +## throttleLast + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/sample.html](http://reactivex.io/documentation/operators/sample.html) + +Emits only the last item emitted by a reactive source during sequential time windows of a specified duration. + +### throttleLast example + +```java +// Diagram: +// -A----B-C-------D-----E-|--> +// -0s-----c--1s---d----2s-|--> +// -----------C---------D--|--> + +Observable<String> source = Observable.create(emitter -> { + emitter.onNext("A"); + + Thread.sleep(500); + emitter.onNext("B"); + + Thread.sleep(200); + emitter.onNext("C"); + + Thread.sleep(800); + emitter.onNext("D"); + + Thread.sleep(600); + emitter.onNext("E"); + emitter.onComplete(); +}); + +source.subscribeOn(Schedulers.io()) + .throttleLast(1, TimeUnit.SECONDS) + .blockingSubscribe( + item -> System.out.println("onNext: " + item), + Throwable::printStackTrace, + () -> System.out.println("onComplete")); + +// prints: +// onNext: C +// onNext: D +// onComplete +``` + +## throttleLatest + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/sample.html](http://reactivex.io/documentation/operators/sample.html) + +Emits the next item emitted by a reactive source, then periodically emits the latest item (if any) when the specified timeout elapses between them. + +### throttleLatest example + +```java +// Diagram: +// -A----B-C-------D-----E-|--> +// -a------c--1s +// -----d----1s +// -e-|--> +// -A---------C---------D--|--> + +Observable<String> source = Observable.create(emitter -> { + emitter.onNext("A"); + + Thread.sleep(500); + emitter.onNext("B"); + + Thread.sleep(200); + emitter.onNext("C"); + + Thread.sleep(800); + emitter.onNext("D"); + + Thread.sleep(600); + emitter.onNext("E"); + emitter.onComplete(); +}); + +source.subscribeOn(Schedulers.io()) + .throttleLatest(1, TimeUnit.SECONDS) + .blockingSubscribe( + item -> System.out.println("onNext: " + item), + Throwable::printStackTrace, + () -> System.out.println("onComplete")); + +// prints: +// onNext: A +// onNext: C +// onNext: D +// onComplete +``` + +## throttleWithTimeout + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/debounce.html](http://reactivex.io/documentation/operators/debounce.html) + +> Alias to [debounce](#debounce) + +Drops items emitted by a reactive source that are followed by newer items before the given timeout value expires. The timer resets on each emission. + +### throttleWithTimeout example + +```java +// Diagram: +// -A--------------B----C-D-------------------E-|----> +// a---------1s +// b---------1s +// c---------1s +// d---------1s +// e-|----> +// -----------A---------------------D-----------E-|--> + +Observable<String> source = Observable.create(emitter -> { + emitter.onNext("A"); + + Thread.sleep(1_500); + emitter.onNext("B"); + + Thread.sleep(500); + emitter.onNext("C"); + + Thread.sleep(250); + emitter.onNext("D"); + + Thread.sleep(2_000); + emitter.onNext("E"); + emitter.onComplete(); +}); + +source.subscribeOn(Schedulers.io()) + .throttleWithTimeout(1, TimeUnit.SECONDS) + .blockingSubscribe( + item -> System.out.println("onNext: " + item), + Throwable::printStackTrace, + () -> System.out.println("onComplete")); + +// prints: +// onNext: A +// onNext: D +// onNext: E +// onComplete +``` + +## timeout + +**Available in:** ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Flowable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Observable`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Maybe`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Single`, ![image](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png) `Completable` + +**ReactiveX documentation:** [http://reactivex.io/documentation/operators/timeout.html](http://reactivex.io/documentation/operators/timeout.html) + +Emits the items from the `Observable` or `Flowable` source, but terminates with a `java.util.concurrent.TimeoutException` if the next item is not emitted within the specified timeout duration starting from the previous item. For `Maybe`, `Single` and `Completable` the specified timeout duration specifies the maximum time to wait for a success or completion event to arrive. If the `Maybe`, `Single` or `Completable` does not complete within the given time a `java.util.concurrent.TimeoutException` will be emitted. + +### timeout example + +```java +// Diagram: +// -A-------B---C-----------D-|--> +// a---------1s +// b---------1s +// c---------1s +// -A-------B---C---------X------> + +Observable<String> source = Observable.create(emitter -> { + emitter.onNext("A"); + + Thread.sleep(800); + emitter.onNext("B"); + + Thread.sleep(400); + emitter.onNext("C"); + + Thread.sleep(1200); + emitter.onNext("D"); + emitter.onComplete(); +}); + +source.timeout(1, TimeUnit.SECONDS) + .subscribe( + item -> System.out.println("onNext: " + item), + error -> System.out.println("onError: " + error), + () -> System.out.println("onComplete will not be printed!")); + +// prints: +// onNext: A +// onNext: B +// onNext: C +// onError: java.util.concurrent.TimeoutException: The source did not signal an event for 1 seconds and has been terminated. +``` From 913e80046194b2f679e4213335c7a17cfa74c1e0 Mon Sep 17 00:00:00 2001 From: lorenzpahl <l.pahl@outlook.com> Date: Wed, 19 Dec 2018 10:57:54 +0100 Subject: [PATCH 323/417] Fix: use correct return type in Javadoc documentation (#6344) --- src/main/java/io/reactivex/Flowable.java | 8 ++++---- src/main/java/io/reactivex/Observable.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 1115eba74e..77964b0fad 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -9289,7 +9289,7 @@ public final Maybe<T> elementAt(long index) { } /** - * Returns a Flowable that emits the item found at a specified index in a sequence of emissions from + * Returns a Single that emits the item found at a specified index in a sequence of emissions from * this Flowable, or a default item if that index is out of range. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/elementAtOrDefault.png" alt=""> @@ -9305,7 +9305,7 @@ public final Maybe<T> elementAt(long index) { * the zero-based index of the item to retrieve * @param defaultItem * the default item - * @return a Flowable that emits the item at the specified position in the sequence emitted by the source + * @return a Single that emits the item at the specified position in the sequence emitted by the source * Publisher, or the default item if that index is outside the bounds of the source sequence * @throws IndexOutOfBoundsException * if {@code index} is less than 0 @@ -9323,7 +9323,7 @@ public final Single<T> elementAt(long index, T defaultItem) { } /** - * Returns a Flowable that emits the item found at a specified index in a sequence of emissions from + * Returns a Single that emits the item found at a specified index in a sequence of emissions from * this Flowable or signals a {@link NoSuchElementException} if this Flowable has fewer elements than index. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/elementAtOrDefault.png" alt=""> @@ -9337,7 +9337,7 @@ public final Single<T> elementAt(long index, T defaultItem) { * * @param index * the zero-based index of the item to retrieve - * @return a Flowable that emits the item at the specified position in the sequence emitted by the source + * @return a Single that emits the item at the specified position in the sequence emitted by the source * Publisher, or the default item if that index is outside the bounds of the source sequence * @throws IndexOutOfBoundsException * if {@code index} is less than 0 diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index ef177b5c6a..541c20b1f4 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -9507,7 +9507,7 @@ public final Maybe<T> lastElement() { * * @param defaultItem * the default item to emit if the source ObservableSource is empty - * @return an Observable that emits only the last item emitted by the source ObservableSource, or a default item + * @return a Single that emits only the last item emitted by the source ObservableSource, or a default item * if the source ObservableSource is empty * @see <a href="http://reactivex.io/documentation/operators/last.html">ReactiveX operators documentation: Last</a> */ From 3481ed1eee9bbdda77435d2c5f698c714ea2fea3 Mon Sep 17 00:00:00 2001 From: Abhimithra Karthikeya <karthikeya.surabhi@gmail.com> Date: Wed, 19 Dec 2018 15:53:43 +0530 Subject: [PATCH 324/417] Adding NonNull annotation (#6313) --- src/main/java/io/reactivex/Completable.java | 56 ++++++ src/main/java/io/reactivex/Flowable.java | 210 ++++++++++++++++++++ src/main/java/io/reactivex/Maybe.java | 101 ++++++++++ src/main/java/io/reactivex/Observable.java | 49 +++++ src/main/java/io/reactivex/Single.java | 87 ++++++++ 5 files changed, 503 insertions(+) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 948d8aecde..9d8325e3b6 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -118,6 +118,7 @@ public abstract class Completable implements CompletableSource { * @throws NullPointerException if sources is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable ambArray(final CompletableSource... sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -146,6 +147,7 @@ public static Completable ambArray(final CompletableSource... sources) { * @throws NullPointerException if sources is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable amb(final Iterable<? extends CompletableSource> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -164,6 +166,7 @@ public static Completable amb(final Iterable<? extends CompletableSource> source * @return a Completable instance that completes immediately */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable complete() { return RxJavaPlugins.onAssembly(CompletableEmpty.INSTANCE); @@ -182,6 +185,7 @@ public static Completable complete() { * @throws NullPointerException if sources is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable concatArray(CompletableSource... sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -207,6 +211,7 @@ public static Completable concatArray(CompletableSource... sources) { * @throws NullPointerException if sources is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable concat(Iterable<? extends CompletableSource> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -253,6 +258,7 @@ public static Completable concat(Publisher<? extends CompletableSource> sources) * @throws NullPointerException if sources is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) public static Completable concat(Publisher<? extends CompletableSource> sources, int prefetch) { @@ -297,6 +303,7 @@ public static Completable concat(Publisher<? extends CompletableSource> sources, * @see Cancellable */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable create(CompletableOnSubscribe source) { ObjectHelper.requireNonNull(source, "source is null"); @@ -319,6 +326,7 @@ public static Completable create(CompletableOnSubscribe source) { * @throws NullPointerException if source is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable unsafeCreate(CompletableSource source) { ObjectHelper.requireNonNull(source, "source is null"); @@ -340,6 +348,7 @@ public static Completable unsafeCreate(CompletableSource source) { * @return the Completable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable defer(final Callable<? extends CompletableSource> completableSupplier) { ObjectHelper.requireNonNull(completableSupplier, "completableSupplier"); @@ -363,6 +372,7 @@ public static Completable defer(final Callable<? extends CompletableSource> comp * @throws NullPointerException if errorSupplier is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable error(final Callable<? extends Throwable> errorSupplier) { ObjectHelper.requireNonNull(errorSupplier, "errorSupplier is null"); @@ -382,6 +392,7 @@ public static Completable error(final Callable<? extends Throwable> errorSupplie * @throws NullPointerException if error is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable error(final Throwable error) { ObjectHelper.requireNonNull(error, "error is null"); @@ -409,6 +420,7 @@ public static Completable error(final Throwable error) { * @throws NullPointerException if run is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable fromAction(final Action run) { ObjectHelper.requireNonNull(run, "run is null"); @@ -435,6 +447,7 @@ public static Completable fromAction(final Action run) { * @return the new Completable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable fromCallable(final Callable<?> callable) { ObjectHelper.requireNonNull(callable, "callable is null"); @@ -455,6 +468,7 @@ public static Completable fromCallable(final Callable<?> callable) { * @return the new Completable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable fromFuture(final Future<?> future) { ObjectHelper.requireNonNull(future, "future is null"); @@ -479,6 +493,7 @@ public static Completable fromFuture(final Future<?> future) { * @since 2.2 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Completable fromMaybe(final MaybeSource<T> maybe) { ObjectHelper.requireNonNull(maybe, "maybe is null"); @@ -499,6 +514,7 @@ public static <T> Completable fromMaybe(final MaybeSource<T> maybe) { * @throws NullPointerException if run is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable fromRunnable(final Runnable run) { ObjectHelper.requireNonNull(run, "run is null"); @@ -520,6 +536,7 @@ public static Completable fromRunnable(final Runnable run) { * @throws NullPointerException if flowable is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Completable fromObservable(final ObservableSource<T> observable) { ObjectHelper.requireNonNull(observable, "observable is null"); @@ -556,6 +573,7 @@ public static <T> Completable fromObservable(final ObservableSource<T> observabl * @see #create(CompletableOnSubscribe) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Completable fromPublisher(final Publisher<T> publisher) { @@ -578,6 +596,7 @@ public static <T> Completable fromPublisher(final Publisher<T> publisher) { * @throws NullPointerException if single is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Completable fromSingle(final SingleSource<T> single) { ObjectHelper.requireNonNull(single, "single is null"); @@ -612,6 +631,7 @@ public static <T> Completable fromSingle(final SingleSource<T> single) { * @see #mergeArrayDelayError(CompletableSource...) */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable mergeArray(CompletableSource... sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -652,6 +672,7 @@ public static Completable mergeArray(CompletableSource... sources) { * @see #mergeDelayError(Iterable) */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable merge(Iterable<? extends CompletableSource> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -753,6 +774,7 @@ public static Completable merge(Publisher<? extends CompletableSource> sources, * @throws IllegalArgumentException if maxConcurrency is less than 1 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) private static Completable merge0(Publisher<? extends CompletableSource> sources, int maxConcurrency, boolean delayErrors) { @@ -776,6 +798,7 @@ private static Completable merge0(Publisher<? extends CompletableSource> sources * @throws NullPointerException if sources is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable mergeArrayDelayError(CompletableSource... sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -797,6 +820,7 @@ public static Completable mergeArrayDelayError(CompletableSource... sources) { * @throws NullPointerException if sources is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable mergeDelayError(Iterable<? extends CompletableSource> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -902,6 +926,7 @@ public static Completable timer(long delay, TimeUnit unit) { * @return the new Completable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public static Completable timer(final long delay, final TimeUnit unit, final Scheduler scheduler) { ObjectHelper.requireNonNull(unit, "unit is null"); @@ -968,6 +993,7 @@ public static <R> Completable using(Callable<R> resourceSupplier, * @return the new Completable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <R> Completable using( final Callable<R> resourceSupplier, @@ -995,6 +1021,7 @@ public static <R> Completable using( * @throws NullPointerException if source is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static Completable wrap(CompletableSource source) { ObjectHelper.requireNonNull(source, "source is null"); @@ -1019,6 +1046,7 @@ public static Completable wrap(CompletableSource source) { * @throws NullPointerException if other is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable ambWith(CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -1042,6 +1070,7 @@ public final Completable ambWith(CompletableSource other) { * @throws NullPointerException if next is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <T> Observable<T> andThen(ObservableSource<T> next) { ObjectHelper.requireNonNull(next, "next is null"); @@ -1068,6 +1097,7 @@ public final <T> Observable<T> andThen(ObservableSource<T> next) { * @throws NullPointerException if next is null */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <T> Flowable<T> andThen(Publisher<T> next) { @@ -1092,6 +1122,7 @@ public final <T> Flowable<T> andThen(Publisher<T> next) { * @return Single that composes this Completable and next */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <T> Single<T> andThen(SingleSource<T> next) { ObjectHelper.requireNonNull(next, "next is null"); @@ -1115,6 +1146,7 @@ public final <T> Single<T> andThen(SingleSource<T> next) { * @return Maybe that composes this Completable and next */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <T> Maybe<T> andThen(MaybeSource<T> next) { ObjectHelper.requireNonNull(next, "next is null"); @@ -1207,6 +1239,7 @@ public final void blockingAwait() { * @throws RuntimeException wrapping an InterruptedException if the current thread is interrupted */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final boolean blockingAwait(long timeout, TimeUnit unit) { ObjectHelper.requireNonNull(unit, "unit is null"); @@ -1320,6 +1353,7 @@ public final Completable compose(CompletableTransformer transformer) { * @see #andThen(Publisher) */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable concatWith(CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -1383,6 +1417,7 @@ public final Completable delay(long delay, TimeUnit unit, Scheduler scheduler) { * @throws NullPointerException if unit or scheduler is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Completable delay(final long delay, final TimeUnit unit, final Scheduler scheduler, final boolean delayError) { ObjectHelper.requireNonNull(unit, "unit is null"); @@ -1514,6 +1549,7 @@ public final Completable doOnError(Consumer<? super Throwable> onError) { * @throws NullPointerException if onEvent is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable doOnEvent(final Consumer<? super Throwable> onEvent) { ObjectHelper.requireNonNull(onEvent, "onEvent is null"); @@ -1535,6 +1571,7 @@ public final Completable doOnEvent(final Consumer<? super Throwable> onEvent) { * @return the new Completable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) private Completable doOnLifecycle( final Consumer<? super Disposable> onSubscribe, @@ -1639,6 +1676,7 @@ public final Completable doAfterTerminate(final Action onAfterTerminate) { * @since 2.1 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable doFinally(Action onFinally) { ObjectHelper.requireNonNull(onFinally, "onFinally is null"); @@ -1776,6 +1814,7 @@ public final Completable doFinally(Action onFinally) { * @see #compose(CompletableTransformer) */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable lift(final CompletableOperator onLift) { ObjectHelper.requireNonNull(onLift, "onLift is null"); @@ -1817,6 +1856,7 @@ public final <T> Single<Notification<T>> materialize() { * @throws NullPointerException if other is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable mergeWith(CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -1836,6 +1876,7 @@ public final Completable mergeWith(CompletableSource other) { * @throws NullPointerException if scheduler is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Completable observeOn(final Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); @@ -1873,6 +1914,7 @@ public final Completable onErrorComplete() { * @return the new Completable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable onErrorComplete(final Predicate<? super Throwable> predicate) { ObjectHelper.requireNonNull(predicate, "predicate is null"); @@ -1895,6 +1937,7 @@ public final Completable onErrorComplete(final Predicate<? super Throwable> pred * @return the new Completable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable onErrorResumeNext(final Function<? super Throwable, ? extends CompletableSource> errorMapper) { ObjectHelper.requireNonNull(errorMapper, "errorMapper is null"); @@ -2153,6 +2196,7 @@ public final Completable retryWhen(Function<? super Flowable<Throwable>, ? exten * @throws NullPointerException if other is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable startWith(CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2174,6 +2218,7 @@ public final Completable startWith(CompletableSource other) { * @throws NullPointerException if other is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <T> Observable<T> startWith(Observable<T> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2197,6 +2242,7 @@ public final <T> Observable<T> startWith(Observable<T> other) { * @throws NullPointerException if other is null */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <T> Flowable<T> startWith(Publisher<T> other) { @@ -2319,6 +2365,7 @@ public final <E extends CompletableObserver> E subscribeWith(E observer) { * @throws NullPointerException if either callback is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Disposable subscribe(final Action onComplete, final Consumer<? super Throwable> onError) { ObjectHelper.requireNonNull(onError, "onError is null"); @@ -2346,6 +2393,7 @@ public final Disposable subscribe(final Action onComplete, final Consumer<? supe * @return the Disposable that allows disposing the subscription */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Disposable subscribe(final Action onComplete) { ObjectHelper.requireNonNull(onComplete, "onComplete is null"); @@ -2369,6 +2417,7 @@ public final Disposable subscribe(final Action onComplete) { * @throws NullPointerException if scheduler is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Completable subscribeOn(final Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); @@ -2395,6 +2444,7 @@ public final Completable subscribeOn(final Scheduler scheduler) { * @since 2.2 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable takeUntil(CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2439,6 +2489,7 @@ public final Completable timeout(long timeout, TimeUnit unit) { * @throws NullPointerException if unit or other is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Completable timeout(long timeout, TimeUnit unit, CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2486,6 +2537,7 @@ public final Completable timeout(long timeout, TimeUnit unit, Scheduler schedule * @throws NullPointerException if unit, scheduler or other is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Completable timeout(long timeout, TimeUnit unit, Scheduler scheduler, CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2509,6 +2561,7 @@ public final Completable timeout(long timeout, TimeUnit unit, Scheduler schedule * @throws NullPointerException if unit or scheduler */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) private Completable timeout0(long timeout, TimeUnit unit, Scheduler scheduler, CompletableSource other) { ObjectHelper.requireNonNull(unit, "unit is null"); @@ -2625,6 +2678,7 @@ public final <T> Observable<T> toObservable() { * @throws NullPointerException if completionValueSupplier is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <T> Single<T> toSingle(final Callable<? extends T> completionValueSupplier) { ObjectHelper.requireNonNull(completionValueSupplier, "completionValueSupplier is null"); @@ -2646,6 +2700,7 @@ public final <T> Single<T> toSingle(final Callable<? extends T> completionValueS * @throws NullPointerException if completionValue is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <T> Single<T> toSingleDefault(final T completionValue) { ObjectHelper.requireNonNull(completionValue, "completionValue is null"); @@ -2666,6 +2721,7 @@ public final <T> Single<T> toSingleDefault(final T completionValue) { * @throws NullPointerException if scheduler is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Completable unsubscribeOn(final Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 77964b0fad..0b33a191a2 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -87,6 +87,7 @@ public abstract class Flowable<T> implements Publisher<T> { * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> amb(Iterable<? extends Publisher<? extends T>> sources) { @@ -116,6 +117,7 @@ public static <T> Flowable<T> amb(Iterable<? extends Publisher<? extends T>> sou * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> ambArray(Publisher<? extends T>... sources) { @@ -269,6 +271,7 @@ public static <T, R> Flowable<R> combineLatest(Function<? super Object[], ? exte */ @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) public static <T, R> Flowable<R> combineLatest(Publisher<? extends T>[] sources, Function<? super Object[], ? extends R> combiner, int bufferSize) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -366,6 +369,7 @@ public static <T, R> Flowable<R> combineLatest(Iterable<? extends Publisher<? ex */ @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) public static <T, R> Flowable<R> combineLatest(Iterable<? extends Publisher<? extends T>> sources, Function<? super Object[], ? extends R> combiner, int bufferSize) { @@ -556,6 +560,7 @@ public static <T, R> Flowable<R> combineLatestDelayError(Function<? super Object */ @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) public static <T, R> Flowable<R> combineLatestDelayError(Publisher<? extends T>[] sources, Function<? super Object[], ? extends R> combiner, int bufferSize) { @@ -747,6 +752,7 @@ public static <T1, T2, R> Flowable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, R> Flowable<R> combineLatest( @@ -799,6 +805,7 @@ public static <T1, T2, T3, R> Flowable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, R> Flowable<R> combineLatest( @@ -855,6 +862,7 @@ public static <T1, T2, T3, T4, R> Flowable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, R> Flowable<R> combineLatest( @@ -916,6 +924,7 @@ public static <T1, T2, T3, T4, T5, R> Flowable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, R> Flowable<R> combineLatest( @@ -981,6 +990,7 @@ public static <T1, T2, T3, T4, T5, T6, R> Flowable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, R> Flowable<R> combineLatest( @@ -1051,6 +1061,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, R> Flowable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Flowable<R> combineLatest( @@ -1125,6 +1136,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Flowable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Flowable<R> combineLatest( @@ -1166,6 +1178,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Flowable<R> combineLatest( */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concat(Iterable<? extends Publisher<? extends T>> sources) { @@ -1261,6 +1274,7 @@ public static <T> Flowable<T> concat(Publisher<? extends Publisher<? extends T>> */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concat(Publisher<? extends T> source1, Publisher<? extends T> source2) { @@ -1297,6 +1311,7 @@ public static <T> Flowable<T> concat(Publisher<? extends T> source1, Publisher<? */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concat( @@ -1338,6 +1353,7 @@ public static <T> Flowable<T> concat( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concat( @@ -1470,6 +1486,7 @@ public static <T> Flowable<T> concatArrayEager(Publisher<? extends T>... sources * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -1564,6 +1581,7 @@ public static <T> Flowable<T> concatArrayEagerDelayError(int maxConcurrency, int */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concatDelayError(Iterable<? extends Publisher<? extends T>> sources) { @@ -1668,6 +1686,7 @@ public static <T> Flowable<T> concatEager(Publisher<? extends Publisher<? extend * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -1727,6 +1746,7 @@ public static <T> Flowable<T> concatEager(Iterable<? extends Publisher<? extends * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -1784,6 +1804,7 @@ public static <T> Flowable<T> concatEager(Iterable<? extends Publisher<? extends * @see Cancellable */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> create(FlowableOnSubscribe<T> source, BackpressureStrategy mode) { @@ -1820,6 +1841,7 @@ public static <T> Flowable<T> create(FlowableOnSubscribe<T> source, Backpressure * @see <a href="http://reactivex.io/documentation/operators/defer.html">ReactiveX operators documentation: Defer</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> defer(Callable<? extends Publisher<? extends T>> supplier) { @@ -1874,6 +1896,7 @@ public static <T> Flowable<T> empty() { * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> error(Callable<? extends Throwable> supplier) { @@ -1902,6 +1925,7 @@ public static <T> Flowable<T> error(Callable<? extends Throwable> supplier) { * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> error(final Throwable throwable) { @@ -1929,6 +1953,7 @@ public static <T> Flowable<T> error(final Throwable throwable) { * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> fromArray(T... items) { @@ -1974,6 +1999,7 @@ public static <T> Flowable<T> fromArray(T... items) { * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> fromCallable(Callable<? extends T> supplier) { @@ -2010,6 +2036,7 @@ public static <T> Flowable<T> fromCallable(Callable<? extends T> supplier) { * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> fromFuture(Future<? extends T> future) { @@ -2050,6 +2077,7 @@ public static <T> Flowable<T> fromFuture(Future<? extends T> future) { * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> fromFuture(Future<? extends T> future, long timeout, TimeUnit unit) { @@ -2095,6 +2123,7 @@ public static <T> Flowable<T> fromFuture(Future<? extends T> future, long timeou */ @SuppressWarnings({ "unchecked", "cast" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public static <T> Flowable<T> fromFuture(Future<? extends T> future, long timeout, TimeUnit unit, Scheduler scheduler) { @@ -2133,6 +2162,7 @@ public static <T> Flowable<T> fromFuture(Future<? extends T> future, long timeou */ @SuppressWarnings({ "cast", "unchecked" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public static <T> Flowable<T> fromFuture(Future<? extends T> future, Scheduler scheduler) { @@ -2161,6 +2191,7 @@ public static <T> Flowable<T> fromFuture(Future<? extends T> future, Scheduler s * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> fromIterable(Iterable<? extends T> source) { @@ -2196,6 +2227,7 @@ public static <T> Flowable<T> fromIterable(Iterable<? extends T> source) { * @see #create(FlowableOnSubscribe, BackpressureStrategy) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @@ -2230,6 +2262,7 @@ public static <T> Flowable<T> fromPublisher(final Publisher<? extends T> source) * @return the new Flowable instance */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> generate(final Consumer<Emitter<T>> generator) { @@ -2263,6 +2296,7 @@ public static <T> Flowable<T> generate(final Consumer<Emitter<T>> generator) { * @return the new Flowable instance */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T, S> Flowable<T> generate(Callable<S> initialState, final BiConsumer<S, Emitter<T>> generator) { @@ -2297,6 +2331,7 @@ public static <T, S> Flowable<T> generate(Callable<S> initialState, final BiCons * @return the new Flowable instance */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T, S> Flowable<T> generate(Callable<S> initialState, final BiConsumer<S, Emitter<T>> generator, @@ -2363,6 +2398,7 @@ public static <T, S> Flowable<T> generate(Callable<S> initialState, BiFunction<S * @return the new Flowable instance */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T, S> Flowable<T> generate(Callable<S> initialState, BiFunction<S, Emitter<T>, S> generator, Consumer<? super S> disposeState) { @@ -2432,6 +2468,7 @@ public static Flowable<Long> interval(long initialDelay, long period, TimeUnit u * @since 1.0.12 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public static Flowable<Long> interval(long initialDelay, long period, TimeUnit unit, Scheduler scheduler) { @@ -2539,6 +2576,7 @@ public static Flowable<Long> intervalRange(long start, long count, long initialD * @return the new Flowable instance */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public static Flowable<Long> intervalRange(long start, long count, long initialDelay, long period, TimeUnit unit, Scheduler scheduler) { @@ -2590,6 +2628,7 @@ public static Flowable<Long> intervalRange(long start, long count, long initialD * @see #fromIterable(Iterable) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item) { @@ -2619,6 +2658,7 @@ public static <T> Flowable<T> just(T item) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2) { @@ -2652,6 +2692,7 @@ public static <T> Flowable<T> just(T item1, T item2) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3) { @@ -2688,6 +2729,7 @@ public static <T> Flowable<T> just(T item1, T item2, T item3) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4) { @@ -2727,6 +2769,7 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5) { @@ -2769,6 +2812,7 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5) */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, T item6) { @@ -2814,6 +2858,7 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7) { @@ -2862,6 +2907,7 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8) { @@ -2913,6 +2959,7 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8, T item9) { @@ -2967,6 +3014,7 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8, T item9, T item10) { @@ -3357,6 +3405,7 @@ public static <T> Flowable<T> mergeArray(Publisher<? extends T>... sources) { */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> merge(Publisher<? extends T> source1, Publisher<? extends T> source2) { @@ -3406,6 +3455,7 @@ public static <T> Flowable<T> merge(Publisher<? extends T> source1, Publisher<? */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> merge(Publisher<? extends T> source1, Publisher<? extends T> source2, Publisher<? extends T> source3) { @@ -3458,6 +3508,7 @@ public static <T> Flowable<T> merge(Publisher<? extends T> source1, Publisher<? */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> merge( @@ -3767,6 +3818,7 @@ public static <T> Flowable<T> mergeArrayDelayError(Publisher<? extends T>... sou */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> mergeDelayError(Publisher<? extends T> source1, Publisher<? extends T> source2) { @@ -3809,6 +3861,7 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends T> source1, Pu */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> mergeDelayError(Publisher<? extends T> source1, Publisher<? extends T> source2, Publisher<? extends T> source3) { @@ -3854,6 +3907,7 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends T> source1, Pu */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> mergeDelayError( @@ -4069,6 +4123,7 @@ public static <T> Single<Boolean> sequenceEqual(Publisher<? extends T> source1, * @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<Boolean> sequenceEqual(Publisher<? extends T> source1, Publisher<? extends T> source2, @@ -4319,6 +4374,7 @@ public static Flowable<Long> timer(long delay, TimeUnit unit) { * @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public static Flowable<Long> timer(long delay, TimeUnit unit, Scheduler scheduler) { @@ -4347,6 +4403,7 @@ public static Flowable<Long> timer(long delay, TimeUnit unit, Scheduler schedule * instead. */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.NONE) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> unsafeCreate(Publisher<T> onSubscribe) { @@ -4420,6 +4477,7 @@ public static <T, D> Flowable<T> using(Callable<? extends D> resourceSupplier, * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public static <T, D> Flowable<T> using(Callable<? extends D> resourceSupplier, @@ -4476,6 +4534,7 @@ public static <T, D> Flowable<T> using(Callable<? extends D> resourceSupplier, * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Flowable<R> zip(Iterable<? extends Publisher<? extends T>> sources, Function<? super Object[], ? extends R> zipper) { @@ -4530,6 +4589,7 @@ public static <T, R> Flowable<R> zip(Iterable<? extends Publisher<? extends T>> */ @SuppressWarnings({ "rawtypes", "unchecked", "cast" }) @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Flowable<R> zip(Publisher<? extends Publisher<? extends T>> sources, @@ -4588,6 +4648,7 @@ public static <T, R> Flowable<R> zip(Publisher<? extends Publisher<? extends T>> */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, R> Flowable<R> zip( @@ -4649,6 +4710,7 @@ public static <T1, T2, R> Flowable<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, R> Flowable<R> zip( @@ -4711,6 +4773,7 @@ public static <T1, T2, R> Flowable<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, R> Flowable<R> zip( @@ -4775,6 +4838,7 @@ public static <T1, T2, R> Flowable<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, R> Flowable<R> zip( @@ -4843,6 +4907,7 @@ public static <T1, T2, T3, R> Flowable<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, R> Flowable<R> zip( @@ -4916,6 +4981,7 @@ public static <T1, T2, T3, T4, R> Flowable<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, R> Flowable<R> zip( @@ -4992,6 +5058,7 @@ public static <T1, T2, T3, T4, T5, R> Flowable<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, R> Flowable<R> zip( @@ -5072,6 +5139,7 @@ public static <T1, T2, T3, T4, T5, T6, R> Flowable<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, R> Flowable<R> zip( @@ -5157,6 +5225,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, R> Flowable<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Flowable<R> zip( @@ -5246,6 +5315,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Flowable<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Flowable<R> zip( @@ -5316,6 +5386,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Flowable<R> zip( * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Flowable<R> zipArray(Function<? super Object[], ? extends R> zipper, @@ -5378,6 +5449,7 @@ public static <T, R> Flowable<R> zipArray(Function<? super Object[], ? extends R * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Flowable<R> zipIterable(Iterable<? extends Publisher<? extends T>> sources, @@ -5413,6 +5485,7 @@ public static <T, R> Flowable<R> zipIterable(Iterable<? extends Publisher<? exte * @see <a href="http://reactivex.io/documentation/operators/all.html">ReactiveX operators documentation: All</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Single<Boolean> all(Predicate<? super T> predicate) { @@ -5442,6 +5515,7 @@ public final Single<Boolean> all(Predicate<? super T> predicate) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> ambWith(Publisher<? extends T> other) { @@ -5473,6 +5547,7 @@ public final Flowable<T> ambWith(Publisher<? extends T> other) { * @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Single<Boolean> any(Predicate<? super T> predicate) { @@ -6203,6 +6278,7 @@ public final Flowable<List<T>> buffer(int count, int skip) { * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U extends Collection<? super T>> Flowable<U> buffer(int count, int skip, Callable<U> bufferSupplier) { @@ -6352,6 +6428,7 @@ public final Flowable<List<T>> buffer(long timespan, long timeskip, TimeUnit uni * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public final <U extends Collection<? super T>> Flowable<U> buffer(long timespan, long timeskip, TimeUnit unit, @@ -6965,6 +7042,7 @@ public final Flowable<T> cacheWithInitialCapacity(int initialCapacity) { * @see <a href="http://reactivex.io/documentation/operators/map.html">ReactiveX operators documentation: Map</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<U> cast(final Class<U> clazz) { @@ -7002,6 +7080,7 @@ public final <U> Flowable<U> cast(final Class<U> clazz) { * @see <a href="http://reactivex.io/documentation/operators/reduce.html">ReactiveX operators documentation: Reduce</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Single<U> collect(Callable<? extends U> initialItemSupplier, BiConsumer<? super U, ? super T> collector) { @@ -7040,6 +7119,7 @@ public final <U> Single<U> collect(Callable<? extends U> initialItemSupplier, Bi * @see <a href="http://reactivex.io/documentation/operators/reduce.html">ReactiveX operators documentation: Reduce</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Single<U> collectInto(final U initialItem, BiConsumer<? super U, ? super T> collector) { @@ -7137,6 +7217,7 @@ public final <R> Flowable<R> concatMap(Function<? super T, ? extends Publisher<? * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> concatMap(Function<? super T, ? extends Publisher<? extends R>> mapper, int prefetch) { @@ -7205,6 +7286,7 @@ public final Completable concatMapCompletable(Function<? super T, ? extends Comp * @since 2.2 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) public final Completable concatMapCompletable(Function<? super T, ? extends CompletableSource> mapper, int prefetch) { @@ -7307,6 +7389,7 @@ public final Completable concatMapCompletableDelayError(Function<? super T, ? ex * @since 2.2 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) public final Completable concatMapCompletableDelayError(Function<? super T, ? extends CompletableSource> mapper, boolean tillTheEnd, int prefetch) { @@ -7370,6 +7453,7 @@ public final <R> Flowable<R> concatMapDelayError(Function<? super T, ? extends P * @return the new Publisher instance with the concatenation behavior */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> concatMapDelayError(Function<? super T, ? extends Publisher<? extends R>> mapper, @@ -7437,6 +7521,7 @@ public final <R> Flowable<R> concatMapEager(Function<? super T, ? extends Publis * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> concatMapEager(Function<? super T, ? extends Publisher<? extends R>> mapper, @@ -7506,6 +7591,7 @@ public final <R> Flowable<R> concatMapEagerDelayError(Function<? super T, ? exte * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> concatMapEagerDelayError(Function<? super T, ? extends Publisher<? extends R>> mapper, @@ -7570,6 +7656,7 @@ public final <U> Flowable<U> concatMapIterable(Function<? super T, ? extends Ite * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<U> concatMapIterable(final Function<? super T, ? extends Iterable<? extends U>> mapper, int prefetch) { @@ -7638,6 +7725,7 @@ public final <R> Flowable<R> concatMapMaybe(Function<? super T, ? extends MaybeS * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> concatMapMaybe(Function<? super T, ? extends MaybeSource<? extends R>> mapper, int prefetch) { @@ -7748,6 +7836,7 @@ public final <R> Flowable<R> concatMapMaybeDelayError(Function<? super T, ? exte * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> concatMapMaybeDelayError(Function<? super T, ? extends MaybeSource<? extends R>> mapper, boolean tillTheEnd, int prefetch) { @@ -7816,6 +7905,7 @@ public final <R> Flowable<R> concatMapSingle(Function<? super T, ? extends Singl * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> concatMapSingle(Function<? super T, ? extends SingleSource<? extends R>> mapper, int prefetch) { @@ -7926,6 +8016,7 @@ public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? ext * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean tillTheEnd, int prefetch) { @@ -7955,6 +8046,7 @@ public final <R> Flowable<R> concatMapSingleDelayError(Function<? super T, ? ext * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> concatWith(Publisher<? extends T> other) { @@ -8059,6 +8151,7 @@ public final Flowable<T> concatWith(@NonNull CompletableSource other) { * @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Single<Boolean> contains(final Object item) { @@ -8114,6 +8207,7 @@ public final Single<Long> count() { * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<T> debounce(Function<? super T, ? extends Publisher<U>> debounceIndicator) { @@ -8187,6 +8281,7 @@ public final Flowable<T> debounce(long timeout, TimeUnit unit) { * @see #throttleWithTimeout(long, TimeUnit, Scheduler) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> debounce(long timeout, TimeUnit unit, Scheduler scheduler) { @@ -8217,6 +8312,7 @@ public final Flowable<T> debounce(long timeout, TimeUnit unit, Scheduler schedul * @see <a href="http://reactivex.io/documentation/operators/defaultifempty.html">ReactiveX operators documentation: DefaultIfEmpty</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> defaultIfEmpty(T defaultItem) { @@ -8252,6 +8348,7 @@ public final Flowable<T> defaultIfEmpty(T defaultItem) { * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<T> delay(final Function<? super T, ? extends Publisher<U>> itemDelayIndicator) { @@ -8367,6 +8464,7 @@ public final Flowable<T> delay(long delay, TimeUnit unit, Scheduler scheduler) { * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> delay(long delay, TimeUnit unit, Scheduler scheduler, boolean delayError) { @@ -8435,6 +8533,7 @@ public final <U, V> Flowable<T> delay(Publisher<U> subscriptionIndicator, * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<T> delaySubscription(Publisher<U> subscriptionIndicator) { @@ -8598,6 +8697,7 @@ public final <T2> Flowable<T2> dematerialize() { */ @Experimental @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.PASS_THROUGH) public final <R> Flowable<R> dematerialize(Function<? super T, Notification<R>> selector) { @@ -9011,6 +9111,7 @@ public final Flowable<T> doOnComplete(Action onComplete) { * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) private Flowable<T> doOnEach(Consumer<? super T> onNext, Consumer<? super Throwable> onError, @@ -9040,6 +9141,7 @@ private Flowable<T> doOnEach(Consumer<? super T> onNext, Consumer<? super Throwa * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> doOnEach(final Consumer<? super Notification<T>> onNotification) { @@ -9076,6 +9178,7 @@ public final Flowable<T> doOnEach(final Consumer<? super Notification<T>> onNoti * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> doOnEach(final Subscriber<? super T> subscriber) { @@ -9138,6 +9241,7 @@ public final Flowable<T> doOnError(Consumer<? super Throwable> onError) { * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> doOnLifecycle(final Consumer<? super Subscription> onSubscribe, @@ -9312,6 +9416,7 @@ public final Maybe<T> elementAt(long index) { * @see <a href="http://reactivex.io/documentation/operators/elementat.html">ReactiveX operators documentation: ElementAt</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> elementAt(long index, T defaultItem) { @@ -9373,6 +9478,7 @@ public final Single<T> elementAtOrError(long index) { * @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> filter(Predicate<? super T> predicate) { @@ -9629,6 +9735,7 @@ public final <R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<? e * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapper, @@ -9677,6 +9784,7 @@ public final <R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<? e * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> flatMap( @@ -9723,6 +9831,7 @@ public final <R> Flowable<R> flatMap( * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> flatMap( @@ -9893,6 +10002,7 @@ public final <U, R> Flowable<R> flatMap(Function<? super T, ? extends Publisher< * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U, R> Flowable<R> flatMap(final Function<? super T, ? extends Publisher<? extends U>> mapper, @@ -9981,6 +10091,7 @@ public final Completable flatMapCompletable(Function<? super T, ? extends Comple * @return the new Completable instance */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Completable flatMapCompletable(Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors, int maxConcurrency) { @@ -10045,6 +10156,7 @@ public final <U> Flowable<U> flatMapIterable(final Function<? super T, ? extends * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<U> flatMapIterable(final Function<? super T, ? extends Iterable<? extends U>> mapper, int bufferSize) { @@ -10081,6 +10193,7 @@ public final <U> Flowable<U> flatMapIterable(final Function<? super T, ? extends * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U, V> Flowable<V> flatMapIterable(final Function<? super T, ? extends Iterable<? extends U>> mapper, @@ -10123,6 +10236,7 @@ public final <U, V> Flowable<V> flatMapIterable(final Function<? super T, ? exte * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U, V> Flowable<V> flatMapIterable(final Function<? super T, ? extends Iterable<? extends U>> mapper, @@ -10172,6 +10286,7 @@ public final <R> Flowable<R> flatMapMaybe(Function<? super T, ? extends MaybeSou * @return the new Flowable instance */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> flatMapMaybe(Function<? super T, ? extends MaybeSource<? extends R>> mapper, boolean delayErrors, int maxConcurrency) { @@ -10220,6 +10335,7 @@ public final <R> Flowable<R> flatMapSingle(Function<? super T, ? extends SingleS * @return the new Flowable instance */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> flatMapSingle(Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean delayErrors, int maxConcurrency) { @@ -10340,6 +10456,7 @@ public final Disposable forEachWhile(Predicate<? super T> onNext, Consumer<? sup * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.NONE) @SchedulerSupport(SchedulerSupport.NONE) public final Disposable forEachWhile(final Predicate<? super T> onNext, final Consumer<? super Throwable> onError, @@ -10611,6 +10728,7 @@ public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, * @see <a href="http://reactivex.io/documentation/operators/groupby.html">ReactiveX operators documentation: GroupBy</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, ? extends K> keySelector, @@ -10723,6 +10841,7 @@ public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, ? extends K> keySelector, @@ -10772,6 +10891,7 @@ public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(Function<? super T, * @see <a href="http://reactivex.io/documentation/operators/join.html">ReactiveX operators documentation: Join</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.NONE) public final <TRight, TLeftEnd, TRightEnd, R> Flowable<R> groupJoin( @@ -10893,6 +11013,7 @@ public final Single<Boolean> isEmpty() { * @see <a href="http://reactivex.io/documentation/operators/join.html">ReactiveX operators documentation: Join</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.NONE) public final <TRight, TLeftEnd, TRightEnd, R> Flowable<R> join( @@ -10950,6 +11071,7 @@ public final Maybe<T> lastElement() { * @see <a href="http://reactivex.io/documentation/operators/last.html">ReactiveX operators documentation: Last</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> last(T defaultItem) { @@ -11127,6 +11249,7 @@ public final Single<T> lastOrError() { * @see #compose(FlowableTransformer) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> lift(FlowableOperator<? extends R, ? super T> lifter) { @@ -11201,6 +11324,7 @@ public final Flowable<T> limit(long count) { * @see <a href="http://reactivex.io/documentation/operators/map.html">ReactiveX operators documentation: Map</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> map(Function<? super T, ? extends R> mapper) { @@ -11254,6 +11378,7 @@ public final Flowable<Notification<T>> materialize() { * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> mergeWith(Publisher<? extends T> other) { @@ -11281,6 +11406,7 @@ public final Flowable<T> mergeWith(Publisher<? extends T> other) { * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> mergeWith(@NonNull SingleSource<? extends T> other) { @@ -11309,6 +11435,7 @@ public final Flowable<T> mergeWith(@NonNull SingleSource<? extends T> other) { * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> mergeWith(@NonNull MaybeSource<? extends T> other) { @@ -11334,6 +11461,7 @@ public final Flowable<T> mergeWith(@NonNull MaybeSource<? extends T> other) { * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> mergeWith(@NonNull CompletableSource other) { @@ -11446,6 +11574,7 @@ public final Flowable<T> observeOn(Scheduler scheduler, boolean delayError) { * @see #observeOn(Scheduler, boolean) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> observeOn(Scheduler scheduler, boolean delayError, int bufferSize) { @@ -11473,6 +11602,7 @@ public final Flowable<T> observeOn(Scheduler scheduler, boolean delayError, int * @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<U> ofType(final Class<U> clazz) { @@ -11649,6 +11779,7 @@ public final Flowable<T> onBackpressureBuffer(int capacity, boolean delayError, * @since 1.1.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> onBackpressureBuffer(int capacity, boolean delayError, boolean unbounded, @@ -11720,6 +11851,7 @@ public final Flowable<T> onBackpressureBuffer(int capacity, Action onOverflow) { * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> onBackpressureBuffer(long capacity, Action onOverflow, BackpressureOverflowStrategy overflowStrategy) { @@ -11776,6 +11908,7 @@ public final Flowable<T> onBackpressureDrop() { * @since 1.1.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> onBackpressureDrop(Consumer<? super T> onDrop) { @@ -11851,6 +11984,7 @@ public final Flowable<T> onBackpressureLatest() { * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> onErrorResumeNext(Function<? super Throwable, ? extends Publisher<? extends T>> resumeFunction) { @@ -11894,6 +12028,7 @@ public final Flowable<T> onErrorResumeNext(Function<? super Throwable, ? extends * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> onErrorResumeNext(final Publisher<? extends T> next) { @@ -11933,6 +12068,7 @@ public final Flowable<T> onErrorResumeNext(final Publisher<? extends T> next) { * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> onErrorReturn(Function<? super Throwable, ? extends T> valueSupplier) { @@ -11972,6 +12108,7 @@ public final Flowable<T> onErrorReturn(Function<? super Throwable, ? extends T> * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> onErrorReturnItem(final T item) { @@ -12018,6 +12155,7 @@ public final Flowable<T> onErrorReturnItem(final T item) { * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> onExceptionResumeNext(final Publisher<? extends T> next) { @@ -12226,6 +12364,7 @@ public final <R> Flowable<R> publish(Function<? super Flowable<T>, ? extends Pub * @see <a href="http://reactivex.io/documentation/operators/publish.html">ReactiveX operators documentation: Publish</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> publish(Function<? super Flowable<T>, ? extends Publisher<? extends R>> selector, int prefetch) { @@ -12320,6 +12459,7 @@ public final Flowable<T> rebatchRequests(int n) { * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> reduce(BiFunction<T, T, T> reducer) { @@ -12381,6 +12521,7 @@ public final Maybe<T> reduce(BiFunction<T, T, T> reducer) { * @see #reduceWith(Callable, BiFunction) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Single<R> reduce(R seed, BiFunction<R, ? super T, R> reducer) { @@ -12425,6 +12566,7 @@ public final <R> Single<R> reduce(R seed, BiFunction<R, ? super T, R> reducer) { * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Single<R> reduceWith(Callable<R> seedSupplier, BiFunction<R, ? super T, R> reducer) { @@ -12512,6 +12654,7 @@ public final Flowable<T> repeat(long times) { * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> repeatUntil(BooleanSupplier stop) { @@ -12542,6 +12685,7 @@ public final Flowable<T> repeatUntil(BooleanSupplier stop) { * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> repeatWhen(final Function<? super Flowable<Object>, ? extends Publisher<?>> handler) { @@ -12600,6 +12744,7 @@ public final ConnectableFlowable<T> replay() { * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> replay(Function<? super Flowable<T>, ? extends Publisher<R>> selector) { @@ -12638,6 +12783,7 @@ public final <R> Flowable<R> replay(Function<? super Flowable<T>, ? extends Publ * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> replay(Function<? super Flowable<T>, ? extends Publisher<R>> selector, final int bufferSize) { @@ -12728,6 +12874,7 @@ public final <R> Flowable<R> replay(Function<? super Flowable<T>, ? extends Publ * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public final <R> Flowable<R> replay(Function<? super Flowable<T>, ? extends Publisher<R>> selector, final int bufferSize, final long time, final TimeUnit unit, final Scheduler scheduler) { @@ -12772,6 +12919,7 @@ public final <R> Flowable<R> replay(Function<? super Flowable<T>, ? extends Publ * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public final <R> Flowable<R> replay(final Function<? super Flowable<T>, ? extends Publisher<R>> selector, final int bufferSize, final Scheduler scheduler) { @@ -12851,6 +12999,7 @@ public final <R> Flowable<R> replay(Function<? super Flowable<T>, ? extends Publ * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public final <R> Flowable<R> replay(Function<? super Flowable<T>, ? extends Publisher<R>> selector, final long time, final TimeUnit unit, final Scheduler scheduler) { @@ -12887,6 +13036,7 @@ public final <R> Flowable<R> replay(Function<? super Flowable<T>, ? extends Publ * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public final <R> Flowable<R> replay(final Function<? super Flowable<T>, ? extends Publisher<R>> selector, final Scheduler scheduler) { @@ -13195,6 +13345,7 @@ public final Flowable<T> retry() { * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> retry(BiPredicate<? super Integer, ? super Throwable> predicate) { @@ -13252,6 +13403,7 @@ public final Flowable<T> retry(long count) { * @return the new Flowable instance */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> retry(long times, Predicate<? super Throwable> predicate) { @@ -13296,6 +13448,7 @@ public final Flowable<T> retry(Predicate<? super Throwable> predicate) { * @return the new Flowable instance */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> retryUntil(final BooleanSupplier stop) { @@ -13381,6 +13534,7 @@ public final Flowable<T> retryUntil(final BooleanSupplier stop) { * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> retryWhen( @@ -13504,6 +13658,7 @@ public final Flowable<T> sample(long period, TimeUnit unit, boolean emitLast) { * @see #throttleLast(long, TimeUnit, Scheduler) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> sample(long period, TimeUnit unit, Scheduler scheduler) { @@ -13544,6 +13699,7 @@ public final Flowable<T> sample(long period, TimeUnit unit, Scheduler scheduler) * @since 2.1 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> sample(long period, TimeUnit unit, Scheduler scheduler, boolean emitLast) { @@ -13575,6 +13731,7 @@ public final Flowable<T> sample(long period, TimeUnit unit, Scheduler scheduler, * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<T> sample(Publisher<U> sampler) { @@ -13612,6 +13769,7 @@ public final <U> Flowable<T> sample(Publisher<U> sampler) { * @since 2.1 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<T> sample(Publisher<U> sampler, boolean emitLast) { @@ -13644,6 +13802,7 @@ public final <U> Flowable<T> sample(Publisher<U> sampler, boolean emitLast) { * @see <a href="http://reactivex.io/documentation/operators/scan.html">ReactiveX operators documentation: Scan</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> scan(BiFunction<T, T, T> accumulator) { @@ -13697,6 +13856,7 @@ public final Flowable<T> scan(BiFunction<T, T, T> accumulator) { * @see <a href="http://reactivex.io/documentation/operators/scan.html">ReactiveX operators documentation: Scan</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> scan(final R initialValue, BiFunction<R, ? super T, R> accumulator) { @@ -13736,6 +13896,7 @@ public final <R> Flowable<R> scan(final R initialValue, BiFunction<R, ? super T, * @see <a href="http://reactivex.io/documentation/operators/scan.html">ReactiveX operators documentation: Scan</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> scanWith(Callable<R> seedSupplier, BiFunction<R, ? super T, R> accumulator) { @@ -13847,6 +14008,7 @@ public final Maybe<T> singleElement() { * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX operators documentation: First</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> single(T defaultItem) { @@ -14168,6 +14330,7 @@ public final Flowable<T> skipLast(long time, TimeUnit unit, Scheduler scheduler, * @see <a href="http://reactivex.io/documentation/operators/skiplast.html">ReactiveX operators documentation: SkipLast</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> skipLast(long time, TimeUnit unit, Scheduler scheduler, boolean delayError, int bufferSize) { @@ -14201,6 +14364,7 @@ public final Flowable<T> skipLast(long time, TimeUnit unit, Scheduler scheduler, * @see <a href="http://reactivex.io/documentation/operators/skipuntil.html">ReactiveX operators documentation: SkipUntil</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<T> skipUntil(Publisher<U> other) { @@ -14228,6 +14392,7 @@ public final <U> Flowable<T> skipUntil(Publisher<U> other) { * @see <a href="http://reactivex.io/documentation/operators/skipwhile.html">ReactiveX operators documentation: SkipWhile</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> skipWhile(Predicate<? super T> predicate) { @@ -14283,6 +14448,7 @@ public final Flowable<T> sorted() { * @return a Flowable that emits the items emitted by the source Publisher in sorted order */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> sorted(Comparator<? super T> sortFunction) { @@ -14340,6 +14506,7 @@ public final Flowable<T> startWith(Iterable<? extends T> items) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> startWith(Publisher<? extends T> other) { @@ -14369,6 +14536,7 @@ public final Flowable<T> startWith(Publisher<? extends T> other) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> startWith(T value) { @@ -14559,6 +14727,7 @@ public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super T * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, @@ -14719,6 +14888,7 @@ public final <E extends Subscriber<? super T>> E subscribeWith(E subscriber) { * @see #subscribeOn(Scheduler, boolean) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> subscribeOn(@NonNull Scheduler scheduler) { @@ -14756,6 +14926,7 @@ public final Flowable<T> subscribeOn(@NonNull Scheduler scheduler) { * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> subscribeOn(@NonNull Scheduler scheduler, boolean requestOn) { @@ -14786,6 +14957,7 @@ public final Flowable<T> subscribeOn(@NonNull Scheduler scheduler, boolean reque * @since 1.1.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> switchIfEmpty(Publisher<? extends T> other) { @@ -14899,6 +15071,7 @@ public final <R> Flowable<R> switchMap(Function<? super T, ? extends Publisher<? * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Completable switchMapCompletable(@NonNull Function<? super T, ? extends CompletableSource> mapper) { @@ -14945,6 +15118,7 @@ public final Completable switchMapCompletable(@NonNull Function<? super T, ? ext * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Completable switchMapCompletableDelayError(@NonNull Function<? super T, ? extends CompletableSource> mapper) { @@ -15071,6 +15245,7 @@ <R> Flowable<R> switchMap0(Function<? super T, ? extends Publisher<? extends R>> * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> switchMapMaybe(@NonNull Function<? super T, ? extends MaybeSource<? extends R>> mapper) { @@ -15101,6 +15276,7 @@ public final <R> Flowable<R> switchMapMaybe(@NonNull Function<? super T, ? exten * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> switchMapMaybeDelayError(@NonNull Function<? super T, ? extends MaybeSource<? extends R>> mapper) { @@ -15141,6 +15317,7 @@ public final <R> Flowable<R> switchMapMaybeDelayError(@NonNull Function<? super * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> switchMapSingle(@NonNull Function<? super T, ? extends SingleSource<? extends R>> mapper) { @@ -15171,6 +15348,7 @@ public final <R> Flowable<R> switchMapSingle(@NonNull Function<? super T, ? exte * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> switchMapSingleDelayError(@NonNull Function<? super T, ? extends SingleSource<? extends R>> mapper) { @@ -15414,6 +15592,7 @@ public final Flowable<T> takeLast(long count, long time, TimeUnit unit, Schedule * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> takeLast(long count, long time, TimeUnit unit, Scheduler scheduler, boolean delayError, int bufferSize) { @@ -15625,6 +15804,7 @@ public final Flowable<T> takeLast(long time, TimeUnit unit, Scheduler scheduler, * @since 1.1.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> takeUntil(Predicate<? super T> stopPredicate) { @@ -15654,6 +15834,7 @@ public final Flowable<T> takeUntil(Predicate<? super T> stopPredicate) { * @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<T> takeUntil(Publisher<U> other) { @@ -15682,6 +15863,7 @@ public final <U> Flowable<T> takeUntil(Publisher<U> other) { * @see Flowable#takeUntil(Predicate) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> takeWhile(Predicate<? super T> predicate) { @@ -15746,6 +15928,7 @@ public final Flowable<T> throttleFirst(long windowDuration, TimeUnit unit) { * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> throttleFirst(long skipDuration, TimeUnit unit, Scheduler scheduler) { @@ -15965,6 +16148,7 @@ public final Flowable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler s * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler scheduler, boolean emitLast) { @@ -16218,6 +16402,7 @@ public final <V> Flowable<T> timeout(Function<? super T, ? extends Publisher<V>> * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <V> Flowable<T> timeout(Function<? super T, ? extends Publisher<V>> itemTimeoutIndicator, Flowable<? extends T> other) { @@ -16280,6 +16465,7 @@ public final Flowable<T> timeout(long timeout, TimeUnit timeUnit) { * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Flowable<T> timeout(long timeout, TimeUnit timeUnit, Publisher<? extends T> other) { @@ -16316,6 +16502,7 @@ public final Flowable<T> timeout(long timeout, TimeUnit timeUnit, Publisher<? ex * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> timeout(long timeout, TimeUnit timeUnit, Scheduler scheduler, Publisher<? extends T> other) { @@ -16387,6 +16574,7 @@ public final Flowable<T> timeout(long timeout, TimeUnit timeUnit, Scheduler sche * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <U, V> Flowable<T> timeout(Publisher<U> firstTimeoutIndicator, @@ -16432,6 +16620,7 @@ public final <U, V> Flowable<T> timeout(Publisher<U> firstTimeoutIndicator, * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U, V> Flowable<T> timeout( @@ -16556,6 +16745,7 @@ public final Flowable<Timed<T>> timestamp(TimeUnit unit) { * @see <a href="http://reactivex.io/documentation/operators/timestamp.html">ReactiveX operators documentation: Timestamp</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) // Supplied scheduler is only used for creating timestamps. public final Flowable<Timed<T>> timestamp(final TimeUnit unit, final Scheduler scheduler) { @@ -16726,6 +16916,7 @@ public final <U extends Collection<? super T>> Single<U> toList(Callable<U> coll * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <K> Single<Map<K, T>> toMap(final Function<? super T, ? extends K> keySelector) { @@ -16764,6 +16955,7 @@ public final <K> Single<Map<K, T>> toMap(final Function<? super T, ? extends K> * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <K, V> Single<Map<K, V>> toMap(final Function<? super T, ? extends K> keySelector, final Function<? super T, ? extends V> valueSelector) { @@ -16802,6 +16994,7 @@ public final <K, V> Single<Map<K, V>> toMap(final Function<? super T, ? extends * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <K, V> Single<Map<K, V>> toMap(final Function<? super T, ? extends K> keySelector, @@ -16915,6 +17108,7 @@ public final <K, V> Single<Map<K, Collection<V>>> toMultimap(Function<? super T, * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final <K, V> Single<Map<K, Collection<V>>> toMultimap( @@ -17046,6 +17240,7 @@ public final Single<List<T>> toSortedList() { * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Single<List<T>> toSortedList(final Comparator<? super T> comparator) { @@ -17081,6 +17276,7 @@ public final Single<List<T>> toSortedList(final Comparator<? super T> comparator * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final Single<List<T>> toSortedList(final Comparator<? super T> comparator, int capacityHint) { @@ -17142,6 +17338,7 @@ public final Single<List<T>> toSortedList(int capacityHint) { * @see <a href="http://reactivex.io/documentation/operators/subscribeon.html">ReactiveX operators documentation: SubscribeOn</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> unsubscribeOn(Scheduler scheduler) { @@ -17352,6 +17549,7 @@ public final Flowable<Flowable<T>> window(long timespan, long timeskip, TimeUnit * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<Flowable<T>> window(long timespan, long timeskip, TimeUnit unit, Scheduler scheduler, int bufferSize) { @@ -17630,6 +17828,7 @@ public final Flowable<Flowable<T>> window(long timespan, TimeUnit unit, * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<Flowable<T>> window( @@ -17698,6 +17897,7 @@ public final <B> Flowable<Flowable<T>> window(Publisher<B> boundaryIndicator) { * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.NONE) public final <B> Flowable<Flowable<T>> window(Publisher<B> boundaryIndicator, int bufferSize) { @@ -17774,6 +17974,7 @@ public final <U, V> Flowable<Flowable<T>> window( * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.NONE) public final <U, V> Flowable<Flowable<T>> window( @@ -17847,6 +18048,7 @@ public final <B> Flowable<Flowable<T>> window(Callable<? extends Publisher<B>> b * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.ERROR) @SchedulerSupport(SchedulerSupport.NONE) public final <B> Flowable<Flowable<T>> window(Callable<? extends Publisher<B>> boundaryIndicatorSupplier, int bufferSize) { @@ -17884,6 +18086,7 @@ public final <B> Flowable<Flowable<T>> window(Callable<? extends Publisher<B>> b * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <U, R> Flowable<R> withLatestFrom(Publisher<? extends U> other, @@ -17921,6 +18124,7 @@ public final <U, R> Flowable<R> withLatestFrom(Publisher<? extends U> other, * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <T1, T2, R> Flowable<R> withLatestFrom(Publisher<T1> source1, Publisher<T2> source2, @@ -17960,6 +18164,7 @@ public final <T1, T2, R> Flowable<R> withLatestFrom(Publisher<T1> source1, Publi * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <T1, T2, T3, R> Flowable<R> withLatestFrom( @@ -18004,6 +18209,7 @@ public final <T1, T2, T3, R> Flowable<R> withLatestFrom( * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <T1, T2, T3, T4, R> Flowable<R> withLatestFrom( @@ -18042,6 +18248,7 @@ public final <T1, T2, T3, T4, R> Flowable<R> withLatestFrom( * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> withLatestFrom(Publisher<?>[] others, Function<? super Object[], R> combiner) { @@ -18074,6 +18281,7 @@ public final <R> Flowable<R> withLatestFrom(Publisher<?>[] others, Function<? su * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> withLatestFrom(Iterable<? extends Publisher<?>> others, Function<? super Object[], R> combiner) { @@ -18113,6 +18321,7 @@ public final <R> Flowable<R> withLatestFrom(Iterable<? extends Publisher<?>> oth * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U, R> Flowable<R> zipWith(Iterable<U> other, BiFunction<? super T, ? super U, ? extends R> zipper) { @@ -18161,6 +18370,7 @@ public final <U, R> Flowable<R> zipWith(Iterable<U> other, BiFunction<? super T * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U, R> Flowable<R> zipWith(Publisher<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper) { diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index b1d34260f1..773021a028 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -124,6 +124,7 @@ public abstract class Maybe<T> implements MaybeSource<T> { * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> amb(final Iterable<? extends MaybeSource<? extends T>> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -174,6 +175,7 @@ public static <T> Maybe<T> ambArray(final MaybeSource<? extends T>... sources) { */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concat(Iterable<? extends MaybeSource<? extends T>> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -201,6 +203,7 @@ public static <T> Flowable<T> concat(Iterable<? extends MaybeSource<? extends T> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T> Flowable<T> concat(MaybeSource<? extends T> source1, MaybeSource<? extends T> source2) { @@ -232,6 +235,7 @@ public static <T> Flowable<T> concat(MaybeSource<? extends T> source1, MaybeSour */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T> Flowable<T> concat( @@ -267,6 +271,7 @@ public static <T> Flowable<T> concat( */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T> Flowable<T> concat( @@ -322,6 +327,7 @@ public static <T> Flowable<T> concat(Publisher<? extends MaybeSource<? extends T */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Flowable<T> concat(Publisher<? extends MaybeSource<? extends T>> sources, int prefetch) { @@ -346,6 +352,7 @@ public static <T> Flowable<T> concat(Publisher<? extends MaybeSource<? extends T */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T> Flowable<T> concatArray(MaybeSource<? extends T>... sources) { @@ -434,6 +441,7 @@ public static <T> Flowable<T> concatArrayEager(MaybeSource<? extends T>... sourc @SuppressWarnings({ "unchecked", "rawtypes" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concatDelayError(Iterable<? extends MaybeSource<? extends T>> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -557,6 +565,7 @@ public static <T> Flowable<T> concatEager(Publisher<? extends MaybeSource<? exte * @see Cancellable */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> create(MaybeOnSubscribe<T> onSubscribe) { ObjectHelper.requireNonNull(onSubscribe, "onSubscribe is null"); @@ -576,6 +585,7 @@ public static <T> Maybe<T> create(MaybeOnSubscribe<T> onSubscribe) { * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> defer(final Callable<? extends MaybeSource<? extends T>> maybeSupplier) { ObjectHelper.requireNonNull(maybeSupplier, "maybeSupplier is null"); @@ -620,6 +630,7 @@ public static <T> Maybe<T> empty() { * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> error(Throwable exception) { ObjectHelper.requireNonNull(exception, "exception is null"); @@ -645,6 +656,7 @@ public static <T> Maybe<T> error(Throwable exception) { * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> error(Callable<? extends Throwable> supplier) { ObjectHelper.requireNonNull(supplier, "errorSupplier is null"); @@ -671,6 +683,7 @@ public static <T> Maybe<T> error(Callable<? extends Throwable> supplier) { * @throws NullPointerException if run is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> fromAction(final Action run) { ObjectHelper.requireNonNull(run, "run is null"); @@ -690,6 +703,7 @@ public static <T> Maybe<T> fromAction(final Action run) { * @throws NullPointerException if completable is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> fromCompletable(CompletableSource completableSource) { ObjectHelper.requireNonNull(completableSource, "completableSource is null"); @@ -709,6 +723,7 @@ public static <T> Maybe<T> fromCompletable(CompletableSource completableSource) * @throws NullPointerException if single is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> fromSingle(SingleSource<T> singleSource) { ObjectHelper.requireNonNull(singleSource, "singleSource is null"); @@ -750,6 +765,7 @@ public static <T> Maybe<T> fromSingle(SingleSource<T> singleSource) { * @return a new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> fromCallable(@NonNull final Callable<? extends T> callable) { ObjectHelper.requireNonNull(callable, "callable is null"); @@ -783,6 +799,7 @@ public static <T> Maybe<T> fromCallable(@NonNull final Callable<? extends T> cal * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> fromFuture(Future<? extends T> future) { ObjectHelper.requireNonNull(future, "future is null"); @@ -820,6 +837,7 @@ public static <T> Maybe<T> fromFuture(Future<? extends T> future) { * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> fromFuture(Future<? extends T> future, long timeout, TimeUnit unit) { ObjectHelper.requireNonNull(future, "future is null"); @@ -840,6 +858,7 @@ public static <T> Maybe<T> fromFuture(Future<? extends T> future, long timeout, * @throws NullPointerException if run is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> fromRunnable(final Runnable run) { ObjectHelper.requireNonNull(run, "run is null"); @@ -866,6 +885,7 @@ public static <T> Maybe<T> fromRunnable(final Runnable run) { * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> just(T item) { ObjectHelper.requireNonNull(item, "item is null"); @@ -970,6 +990,7 @@ public static <T> Flowable<T> merge(Publisher<? extends MaybeSource<? extends T> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Flowable<T> merge(Publisher<? extends MaybeSource<? extends T>> sources, int maxConcurrency) { @@ -1002,6 +1023,7 @@ public static <T> Flowable<T> merge(Publisher<? extends MaybeSource<? extends T> * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Maybe<T> merge(MaybeSource<? extends MaybeSource<? extends T>> source) { @@ -1047,6 +1069,7 @@ public static <T> Maybe<T> merge(MaybeSource<? extends MaybeSource<? extends T>> */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T> Flowable<T> merge( @@ -1097,6 +1120,7 @@ public static <T> Flowable<T> merge( */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T> Flowable<T> merge( @@ -1151,6 +1175,7 @@ public static <T> Flowable<T> merge( */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T> Flowable<T> merge( @@ -1193,6 +1218,7 @@ public static <T> Flowable<T> merge( */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T> Flowable<T> mergeArray(MaybeSource<? extends T>... sources) { @@ -1347,6 +1373,7 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends MaybeSource<? @SuppressWarnings({ "unchecked", "rawtypes" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> mergeDelayError(Publisher<? extends MaybeSource<? extends T>> sources, int maxConcurrency) { ObjectHelper.requireNonNull(sources, "source is null"); @@ -1385,6 +1412,7 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends MaybeSource<? @SuppressWarnings({ "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> mergeDelayError(MaybeSource<? extends T> source1, MaybeSource<? extends T> source2) { ObjectHelper.requireNonNull(source1, "source1 is null"); @@ -1426,6 +1454,7 @@ public static <T> Flowable<T> mergeDelayError(MaybeSource<? extends T> source1, @SuppressWarnings({ "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> mergeDelayError(MaybeSource<? extends T> source1, MaybeSource<? extends T> source2, MaybeSource<? extends T> source3) { @@ -1471,6 +1500,7 @@ public static <T> Flowable<T> mergeDelayError(MaybeSource<? extends T> source1, @SuppressWarnings({ "unchecked" }) @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> mergeDelayError( MaybeSource<? extends T> source1, MaybeSource<? extends T> source2, @@ -1554,6 +1584,7 @@ public static <T> Single<Boolean> sequenceEqual(MaybeSource<? extends T> source1 * @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<Boolean> sequenceEqual(MaybeSource<? extends T> source1, MaybeSource<? extends T> source2, BiPredicate<? super T, ? super T> isEqual) { @@ -1604,6 +1635,7 @@ public static Maybe<Long> timer(long delay, TimeUnit unit) { * @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public static Maybe<Long> timer(long delay, TimeUnit unit, Scheduler scheduler) { ObjectHelper.requireNonNull(unit, "unit is null"); @@ -1624,6 +1656,7 @@ public static Maybe<Long> timer(long delay, TimeUnit unit, Scheduler scheduler) * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> unsafeCreate(MaybeSource<T> onSubscribe) { if (onSubscribe instanceof Maybe) { @@ -1690,6 +1723,7 @@ public static <T, D> Maybe<T> using(Callable<? extends D> resourceSupplier, * @see <a href="http://reactivex.io/documentation/operators/using.html">ReactiveX operators documentation: Using</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, D> Maybe<T> using(Callable<? extends D> resourceSupplier, Function<? super D, ? extends MaybeSource<? extends T>> sourceSupplier, @@ -1712,6 +1746,7 @@ public static <T, D> Maybe<T> using(Callable<? extends D> resourceSupplier, * @return the Maybe wrapper or the source cast to Maybe (if possible) */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Maybe<T> wrap(MaybeSource<T> source) { if (source instanceof Maybe) { @@ -1749,6 +1784,7 @@ public static <T> Maybe<T> wrap(MaybeSource<T> source) { * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Maybe<R> zip(Iterable<? extends MaybeSource<? extends T>> sources, Function<? super Object[], ? extends R> zipper) { ObjectHelper.requireNonNull(zipper, "zipper is null"); @@ -1783,6 +1819,7 @@ public static <T, R> Maybe<R> zip(Iterable<? extends MaybeSource<? extends T>> s */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, R> Maybe<R> zip( MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, @@ -1822,6 +1859,7 @@ public static <T1, T2, R> Maybe<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, R> Maybe<R> zip( MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3, @@ -1865,6 +1903,7 @@ public static <T1, T2, T3, R> Maybe<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, R> Maybe<R> zip( MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3, @@ -1913,6 +1952,7 @@ public static <T1, T2, T3, T4, R> Maybe<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, R> Maybe<R> zip( MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3, @@ -1965,6 +2005,7 @@ public static <T1, T2, T3, T4, T5, R> Maybe<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, R> Maybe<R> zip( MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3, @@ -2021,6 +2062,7 @@ public static <T1, T2, T3, T4, T5, T6, R> Maybe<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, R> Maybe<R> zip( MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3, @@ -2082,6 +2124,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, R> Maybe<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Maybe<R> zip( MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3, @@ -2147,6 +2190,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Maybe<R> zip( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Maybe<R> zip( MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3, @@ -2194,6 +2238,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Maybe<R> zip( * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Maybe<R> zipArray(Function<? super Object[], ? extends R> zipper, MaybeSource<? extends T>... sources) { @@ -2227,6 +2272,7 @@ public static <T, R> Maybe<R> zipArray(Function<? super Object[], ? extends R> z */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> ambWith(MaybeSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2335,6 +2381,7 @@ public final Maybe<T> cache() { * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Maybe<U> cast(final Class<? extends U> clazz) { ObjectHelper.requireNonNull(clazz, "clazz is null"); @@ -2383,6 +2430,7 @@ public final <R> Maybe<R> compose(MaybeTransformer<? super T, ? extends R> trans * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Maybe<R> concatMap(Function<? super T, ? extends MaybeSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -2409,6 +2457,7 @@ public final <R> Maybe<R> concatMap(Function<? super T, ? extends MaybeSource<? */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> concatWith(MaybeSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2432,6 +2481,7 @@ public final Flowable<T> concatWith(MaybeSource<? extends T> other) { * @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<Boolean> contains(final Object item) { ObjectHelper.requireNonNull(item, "item is null"); @@ -2480,6 +2530,7 @@ public final Single<Long> count() { * @see <a href="http://reactivex.io/documentation/operators/defaultifempty.html">ReactiveX operators documentation: DefaultIfEmpty</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> defaultIfEmpty(T defaultItem) { ObjectHelper.requireNonNull(defaultItem, "item is null"); @@ -2529,6 +2580,7 @@ public final Maybe<T> delay(long delay, TimeUnit unit) { * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<T> delay(long delay, TimeUnit unit, Scheduler scheduler) { ObjectHelper.requireNonNull(unit, "unit is null"); @@ -2559,6 +2611,7 @@ public final Maybe<T> delay(long delay, TimeUnit unit, Scheduler scheduler) { * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) public final <U, V> Maybe<T> delay(Publisher<U> delayIndicator) { @@ -2584,6 +2637,7 @@ public final <U, V> Maybe<T> delay(Publisher<U> delayIndicator) { */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Maybe<T> delaySubscription(Publisher<U> subscriptionIndicator) { ObjectHelper.requireNonNull(subscriptionIndicator, "subscriptionIndicator is null"); @@ -2652,6 +2706,7 @@ public final Maybe<T> delaySubscription(long delay, TimeUnit unit, Scheduler sch * @since 2.1 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) { ObjectHelper.requireNonNull(onAfterSuccess, "doAfterSuccess is null"); @@ -2676,6 +2731,7 @@ public final Maybe<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) { * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doAfterTerminate(Action onAfterTerminate) { return RxJavaPlugins.onAssembly(new MaybePeek<T>(this, @@ -2705,6 +2761,7 @@ public final Maybe<T> doAfterTerminate(Action onAfterTerminate) { * @since 2.1 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doFinally(Action onFinally) { ObjectHelper.requireNonNull(onFinally, "onFinally is null"); @@ -2723,6 +2780,7 @@ public final Maybe<T> doFinally(Action onFinally) { * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnDispose(Action onDispose) { return RxJavaPlugins.onAssembly(new MaybePeek<T>(this, @@ -2750,6 +2808,7 @@ public final Maybe<T> doOnDispose(Action onDispose) { * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnComplete(Action onComplete) { return RxJavaPlugins.onAssembly(new MaybePeek<T>(this, @@ -2775,6 +2834,7 @@ public final Maybe<T> doOnComplete(Action onComplete) { * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnError(Consumer<? super Throwable> onError) { return RxJavaPlugins.onAssembly(new MaybePeek<T>(this, @@ -2819,6 +2879,7 @@ public final Maybe<T> doOnEvent(BiConsumer<? super T, ? super Throwable> onEvent * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnSubscribe(Consumer<? super Disposable> onSubscribe) { return RxJavaPlugins.onAssembly(new MaybePeek<T>(this, @@ -2844,6 +2905,7 @@ public final Maybe<T> doOnSubscribe(Consumer<? super Disposable> onSubscribe) { * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doOnSuccess(Consumer<? super T> onSuccess) { return RxJavaPlugins.onAssembly(new MaybePeek<T>(this, @@ -2874,6 +2936,7 @@ public final Maybe<T> doOnSuccess(Consumer<? super T> onSuccess) { * @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> filter(Predicate<? super T> predicate) { ObjectHelper.requireNonNull(predicate, "predicate is null"); @@ -2898,6 +2961,7 @@ public final Maybe<T> filter(Predicate<? super T> predicate) { * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Maybe<R> flatMap(Function<? super T, ? extends MaybeSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -2926,6 +2990,7 @@ public final <R> Maybe<R> flatMap(Function<? super T, ? extends MaybeSource<? ex * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Maybe<R> flatMap( Function<? super T, ? extends MaybeSource<? extends R>> onSuccessMapper, @@ -2960,6 +3025,7 @@ public final <R> Maybe<R> flatMap( * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U, R> Maybe<R> flatMap(Function<? super T, ? extends MaybeSource<? extends U>> mapper, BiFunction<? super T, ? super U, ? extends R> resultSelector) { @@ -2990,6 +3056,7 @@ public final <U, R> Maybe<R> flatMap(Function<? super T, ? extends MaybeSource<? */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<U> flattenAsFlowable(final Function<? super T, ? extends Iterable<? extends U>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -3014,6 +3081,7 @@ public final <U> Flowable<U> flattenAsFlowable(final Function<? super T, ? exten * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Observable<U> flattenAsObservable(final Function<? super T, ? extends Iterable<? extends U>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -3037,6 +3105,7 @@ public final <U> Observable<U> flattenAsObservable(final Function<? super T, ? e * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Observable<R> flatMapObservable(Function<? super T, ? extends ObservableSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -3064,6 +3133,7 @@ public final <R> Observable<R> flatMapObservable(Function<? super T, ? extends O */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> flatMapPublisher(Function<? super T, ? extends Publisher<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -3089,6 +3159,7 @@ public final <R> Flowable<R> flatMapPublisher(Function<? super T, ? extends Publ * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Single<R> flatMapSingle(final Function<? super T, ? extends SingleSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -3116,6 +3187,7 @@ public final <R> Single<R> flatMapSingle(final Function<? super T, ? extends Sin * @since 2.1 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Maybe<R> flatMapSingleElement(final Function<? super T, ? extends SingleSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -3139,6 +3211,7 @@ public final <R> Maybe<R> flatMapSingleElement(final Function<? super T, ? exten * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable flatMapCompletable(final Function<? super T, ? extends CompletableSource> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -3348,6 +3421,7 @@ public final Single<Boolean> isEmpty() { * @see #compose(MaybeTransformer) */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Maybe<R> lift(final MaybeOperator<? extends R, ? super T> lift) { ObjectHelper.requireNonNull(lift, "onLift is null"); @@ -3371,6 +3445,7 @@ public final <R> Maybe<R> lift(final MaybeOperator<? extends R, ? super T> lift) * @see <a href="http://reactivex.io/documentation/operators/map.html">ReactiveX operators documentation: Map</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Maybe<R> map(Function<? super T, ? extends R> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -3418,6 +3493,7 @@ public final Single<Notification<T>> materialize() { */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> mergeWith(MaybeSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -3443,6 +3519,7 @@ public final Flowable<T> mergeWith(MaybeSource<? extends T> other) { * @see #subscribeOn */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<T> observeOn(final Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); @@ -3466,6 +3543,7 @@ public final Maybe<T> observeOn(final Scheduler scheduler) { * @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Maybe<U> ofType(final Class<U> clazz) { ObjectHelper.requireNonNull(clazz, "clazz is null"); @@ -3486,6 +3564,7 @@ public final <U> Maybe<U> ofType(final Class<U> clazz) { * @return the value returned by the convert function */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> R to(Function<? super Maybe<T>, R> convert) { try { @@ -3549,6 +3628,7 @@ public final Observable<T> toObservable() { * @return the new Single instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> toSingle(T defaultValue) { ObjectHelper.requireNonNull(defaultValue, "defaultValue is null"); @@ -3597,6 +3677,7 @@ public final Maybe<T> onErrorComplete() { * @return the new Completable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onErrorComplete(final Predicate<? super Throwable> predicate) { ObjectHelper.requireNonNull(predicate, "predicate is null"); @@ -3624,6 +3705,7 @@ public final Maybe<T> onErrorComplete(final Predicate<? super Throwable> predica * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onErrorResumeNext(final MaybeSource<? extends T> next) { ObjectHelper.requireNonNull(next, "next is null"); @@ -3650,6 +3732,7 @@ public final Maybe<T> onErrorResumeNext(final MaybeSource<? extends T> next) { * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onErrorResumeNext(Function<? super Throwable, ? extends MaybeSource<? extends T>> resumeFunction) { ObjectHelper.requireNonNull(resumeFunction, "resumeFunction is null"); @@ -3676,6 +3759,7 @@ public final Maybe<T> onErrorResumeNext(Function<? super Throwable, ? extends Ma * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onErrorReturn(Function<? super Throwable, ? extends T> valueSupplier) { ObjectHelper.requireNonNull(valueSupplier, "valueSupplier is null"); @@ -3701,6 +3785,7 @@ public final Maybe<T> onErrorReturn(Function<? super Throwable, ? extends T> val * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onErrorReturnItem(final T item) { ObjectHelper.requireNonNull(item, "item is null"); @@ -3730,6 +3815,7 @@ public final Maybe<T> onErrorReturnItem(final T item) { * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> onExceptionResumeNext(final MaybeSource<? extends T> next) { ObjectHelper.requireNonNull(next, "next is null"); @@ -3970,6 +4056,7 @@ public final Maybe<T> retry(Predicate<? super Throwable> predicate) { * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> retryUntil(final BooleanSupplier stop) { ObjectHelper.requireNonNull(stop, "stop is null"); @@ -4152,6 +4239,7 @@ public final Disposable subscribe(Consumer<? super T> onSuccess, Consumer<? supe * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Disposable subscribe(Consumer<? super T> onSuccess, Consumer<? super Throwable> onError, Action onComplete) { @@ -4208,6 +4296,7 @@ public final void subscribe(MaybeObserver<? super T> observer) { * @see #observeOn */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<T> subscribeOn(Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); @@ -4260,6 +4349,7 @@ public final <E extends MaybeObserver<? super T>> E subscribeWith(E observer) { * alternate MaybeSource if the source Maybe is empty. */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> switchIfEmpty(MaybeSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -4283,6 +4373,7 @@ public final Maybe<T> switchIfEmpty(MaybeSource<? extends T> other) { * @since 2.2 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> switchIfEmpty(SingleSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -4308,6 +4399,7 @@ public final Single<T> switchIfEmpty(SingleSource<? extends T> other) { * @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Maybe<T> takeUntil(MaybeSource<U> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -4337,6 +4429,7 @@ public final <U> Maybe<T> takeUntil(MaybeSource<U> other) { */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Maybe<T> takeUntil(Publisher<U> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -4388,6 +4481,7 @@ public final Maybe<T> timeout(long timeout, TimeUnit timeUnit) { * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Maybe<T> timeout(long timeout, TimeUnit timeUnit, MaybeSource<? extends T> fallback) { ObjectHelper.requireNonNull(fallback, "other is null"); @@ -4417,6 +4511,7 @@ public final Maybe<T> timeout(long timeout, TimeUnit timeUnit, MaybeSource<? ext * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<T> timeout(long timeout, TimeUnit timeUnit, Scheduler scheduler, MaybeSource<? extends T> fallback) { ObjectHelper.requireNonNull(fallback, "fallback is null"); @@ -4463,6 +4558,7 @@ public final Maybe<T> timeout(long timeout, TimeUnit timeUnit, Scheduler schedul * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Maybe<T> timeout(MaybeSource<U> timeoutIndicator) { ObjectHelper.requireNonNull(timeoutIndicator, "timeoutIndicator is null"); @@ -4484,6 +4580,7 @@ public final <U> Maybe<T> timeout(MaybeSource<U> timeoutIndicator) { * @return the new Maybe instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Maybe<T> timeout(MaybeSource<U> timeoutIndicator, MaybeSource<? extends T> fallback) { ObjectHelper.requireNonNull(timeoutIndicator, "timeoutIndicator is null"); @@ -4508,6 +4605,7 @@ public final <U> Maybe<T> timeout(MaybeSource<U> timeoutIndicator, MaybeSource<? */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Maybe<T> timeout(Publisher<U> timeoutIndicator) { ObjectHelper.requireNonNull(timeoutIndicator, "timeoutIndicator is null"); @@ -4533,6 +4631,7 @@ public final <U> Maybe<T> timeout(Publisher<U> timeoutIndicator) { */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Maybe<T> timeout(Publisher<U> timeoutIndicator, MaybeSource<? extends T> fallback) { ObjectHelper.requireNonNull(timeoutIndicator, "timeoutIndicator is null"); @@ -4552,6 +4651,7 @@ public final <U> Maybe<T> timeout(Publisher<U> timeoutIndicator, MaybeSource<? e * @throws NullPointerException if scheduler is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Maybe<T> unsubscribeOn(final Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); @@ -4585,6 +4685,7 @@ public final Maybe<T> unsubscribeOn(final Scheduler scheduler) { * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U, R> Maybe<R> zipWith(MaybeSource<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper) { ObjectHelper.requireNonNull(other, "other is null"); diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 541c20b1f4..fdd8b29a92 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -116,6 +116,7 @@ public abstract class Observable<T> implements ObservableSource<T> { * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> amb(Iterable<? extends ObservableSource<? extends T>> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -142,6 +143,7 @@ public static <T> Observable<T> amb(Iterable<? extends ObservableSource<? extend */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> ambArray(ObservableSource<? extends T>... sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -289,6 +291,7 @@ public static <T, R> Observable<R> combineLatest(Iterable<? extends ObservableSo * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Observable<R> combineLatest(Iterable<? extends ObservableSource<? extends T>> sources, Function<? super Object[], ? extends R> combiner, int bufferSize) { @@ -381,6 +384,7 @@ public static <T, R> Observable<R> combineLatest(ObservableSource<? extends T>[] * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Observable<R> combineLatest(ObservableSource<? extends T>[] sources, Function<? super Object[], ? extends R> combiner, int bufferSize) { @@ -426,6 +430,7 @@ public static <T, R> Observable<R> combineLatest(ObservableSource<? extends T>[] */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, R> Observable<R> combineLatest( ObservableSource<? extends T1> source1, ObservableSource<? extends T2> source2, @@ -468,6 +473,7 @@ public static <T1, T2, R> Observable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, R> Observable<R> combineLatest( ObservableSource<? extends T1> source1, ObservableSource<? extends T2> source2, @@ -515,6 +521,7 @@ public static <T1, T2, T3, R> Observable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, R> Observable<R> combineLatest( ObservableSource<? extends T1> source1, ObservableSource<? extends T2> source2, @@ -566,6 +573,7 @@ public static <T1, T2, T3, T4, R> Observable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, R> Observable<R> combineLatest( ObservableSource<? extends T1> source1, ObservableSource<? extends T2> source2, @@ -622,6 +630,7 @@ public static <T1, T2, T3, T4, T5, R> Observable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, R> Observable<R> combineLatest( ObservableSource<? extends T1> source1, ObservableSource<? extends T2> source2, @@ -682,6 +691,7 @@ public static <T1, T2, T3, T4, T5, T6, R> Observable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> combineLatest( ObservableSource<? extends T1> source1, ObservableSource<? extends T2> source2, @@ -747,6 +757,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> combineLatest( ObservableSource<? extends T1> source1, ObservableSource<? extends T2> source2, @@ -816,6 +827,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> combineLatest( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Observable<R> combineLatest( ObservableSource<? extends T1> source1, ObservableSource<? extends T2> source2, @@ -962,6 +974,7 @@ public static <T, R> Observable<R> combineLatestDelayError(Function<? super Obje * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Observable<R> combineLatestDelayError(ObservableSource<? extends T>[] sources, Function<? super Object[], ? extends R> combiner, int bufferSize) { @@ -1057,6 +1070,7 @@ public static <T, R> Observable<R> combineLatestDelayError(Iterable<? extends Ob * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Observable<R> combineLatestDelayError(Iterable<? extends ObservableSource<? extends T>> sources, Function<? super Object[], ? extends R> combiner, int bufferSize) { @@ -1084,6 +1098,7 @@ public static <T, R> Observable<R> combineLatestDelayError(Iterable<? extends Ob */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> concat(Iterable<? extends ObservableSource<? extends T>> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -1134,6 +1149,7 @@ public static <T> Observable<T> concat(ObservableSource<? extends ObservableSour */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> concat(ObservableSource<? extends ObservableSource<? extends T>> sources, int prefetch) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -1162,6 +1178,7 @@ public static <T> Observable<T> concat(ObservableSource<? extends ObservableSour */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> concat(ObservableSource<? extends T> source1, ObservableSource<? extends T> source2) { ObjectHelper.requireNonNull(source1, "source1 is null"); @@ -1192,6 +1209,7 @@ public static <T> Observable<T> concat(ObservableSource<? extends T> source1, Ob */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> concat( ObservableSource<? extends T> source1, ObservableSource<? extends T> source2, @@ -1227,6 +1245,7 @@ public static <T> Observable<T> concat( */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> concat( ObservableSource<? extends T> source1, ObservableSource<? extends T> source2, @@ -1410,6 +1429,7 @@ public static <T> Observable<T> concatArrayEagerDelayError(int maxConcurrency, i * @return the new ObservableSource with the concatenating behavior */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> concatDelayError(Iterable<? extends ObservableSource<? extends T>> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -1455,6 +1475,7 @@ public static <T> Observable<T> concatDelayError(ObservableSource<? extends Obse */ @SuppressWarnings({ "rawtypes", "unchecked" }) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> concatDelayError(ObservableSource<? extends ObservableSource<? extends T>> sources, int prefetch, boolean tillTheEnd) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -1607,6 +1628,7 @@ public static <T> Observable<T> concatEager(Iterable<? extends ObservableSource< * @see Cancellable */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> create(ObservableOnSubscribe<T> source) { ObjectHelper.requireNonNull(source, "source is null"); @@ -1638,6 +1660,7 @@ public static <T> Observable<T> create(ObservableOnSubscribe<T> source) { * @see <a href="http://reactivex.io/documentation/operators/defer.html">ReactiveX operators documentation: Defer</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> defer(Callable<? extends ObservableSource<? extends T>> supplier) { ObjectHelper.requireNonNull(supplier, "supplier is null"); @@ -1686,6 +1709,7 @@ public static <T> Observable<T> empty() { * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> error(Callable<? extends Throwable> errorSupplier) { ObjectHelper.requireNonNull(errorSupplier, "errorSupplier is null"); @@ -1711,6 +1735,7 @@ public static <T> Observable<T> error(Callable<? extends Throwable> errorSupplie * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> error(final Throwable exception) { ObjectHelper.requireNonNull(exception, "e is null"); @@ -1735,6 +1760,7 @@ public static <T> Observable<T> error(final Throwable exception) { */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) + @NonNull public static <T> Observable<T> fromArray(T... items) { ObjectHelper.requireNonNull(items, "items is null"); if (items.length == 0) { @@ -1775,6 +1801,7 @@ public static <T> Observable<T> fromArray(T... items) { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> fromCallable(Callable<? extends T> supplier) { ObjectHelper.requireNonNull(supplier, "supplier is null"); @@ -1808,6 +1835,7 @@ public static <T> Observable<T> fromCallable(Callable<? extends T> supplier) { * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> fromFuture(Future<? extends T> future) { ObjectHelper.requireNonNull(future, "future is null"); @@ -1845,6 +1873,7 @@ public static <T> Observable<T> fromFuture(Future<? extends T> future) { * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> fromFuture(Future<? extends T> future, long timeout, TimeUnit unit) { ObjectHelper.requireNonNull(future, "future is null"); @@ -1886,6 +1915,7 @@ public static <T> Observable<T> fromFuture(Future<? extends T> future, long time * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public static <T> Observable<T> fromFuture(Future<? extends T> future, long timeout, TimeUnit unit, Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); @@ -1921,6 +1951,7 @@ public static <T> Observable<T> fromFuture(Future<? extends T> future, long time * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public static <T> Observable<T> fromFuture(Future<? extends T> future, Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); @@ -1946,6 +1977,7 @@ public static <T> Observable<T> fromFuture(Future<? extends T> future, Scheduler * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> fromIterable(Iterable<? extends T> source) { ObjectHelper.requireNonNull(source, "source is null"); @@ -1982,6 +2014,7 @@ public static <T> Observable<T> fromIterable(Iterable<? extends T> source) { */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> fromPublisher(Publisher<? extends T> publisher) { ObjectHelper.requireNonNull(publisher, "publisher is null"); @@ -2010,6 +2043,7 @@ public static <T> Observable<T> fromPublisher(Publisher<? extends T> publisher) * @return the new Observable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> generate(final Consumer<Emitter<T>> generator) { ObjectHelper.requireNonNull(generator, "generator is null"); @@ -2041,6 +2075,7 @@ public static <T> Observable<T> generate(final Consumer<Emitter<T>> generator) { * @return the new Observable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, S> Observable<T> generate(Callable<S> initialState, final BiConsumer<S, Emitter<T>> generator) { ObjectHelper.requireNonNull(generator, "generator is null"); @@ -2073,6 +2108,7 @@ public static <T, S> Observable<T> generate(Callable<S> initialState, final BiCo * @return the new Observable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, S> Observable<T> generate( final Callable<S> initialState, @@ -2139,6 +2175,7 @@ public static <T, S> Observable<T> generate(Callable<S> initialState, BiFunction * @return the new Observable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, S> Observable<T> generate(Callable<S> initialState, BiFunction<S, Emitter<T>, S> generator, Consumer<? super S> disposeState) { @@ -2199,6 +2236,7 @@ public static Observable<Long> interval(long initialDelay, long period, TimeUnit * @since 1.0.12 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public static Observable<Long> interval(long initialDelay, long period, TimeUnit unit, Scheduler scheduler) { ObjectHelper.requireNonNull(unit, "unit is null"); @@ -2295,6 +2333,7 @@ public static Observable<Long> intervalRange(long start, long count, long initia * @return the new Observable instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public static Observable<Long> intervalRange(long start, long count, long initialDelay, long period, TimeUnit unit, Scheduler scheduler) { if (count < 0) { @@ -2344,6 +2383,7 @@ public static Observable<Long> intervalRange(long start, long count, long initia * @see #fromIterable(Iterable) */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item) { ObjectHelper.requireNonNull(item, "The item is null"); @@ -2370,6 +2410,7 @@ public static <T> Observable<T> just(T item) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2) { ObjectHelper.requireNonNull(item1, "The first item is null"); @@ -2400,6 +2441,7 @@ public static <T> Observable<T> just(T item1, T item2) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3) { ObjectHelper.requireNonNull(item1, "The first item is null"); @@ -2433,6 +2475,7 @@ public static <T> Observable<T> just(T item1, T item2, T item3) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4) { ObjectHelper.requireNonNull(item1, "The first item is null"); @@ -2469,6 +2512,7 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4) { */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5) { ObjectHelper.requireNonNull(item1, "The first item is null"); @@ -2508,6 +2552,7 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5, T item6) { ObjectHelper.requireNonNull(item1, "The first item is null"); @@ -2550,6 +2595,7 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7) { ObjectHelper.requireNonNull(item1, "The first item is null"); @@ -2595,6 +2641,7 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8) { ObjectHelper.requireNonNull(item1, "The first item is null"); @@ -2643,6 +2690,7 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8, T item9) { ObjectHelper.requireNonNull(item1, "The first item is null"); @@ -2694,6 +2742,7 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 */ @SuppressWarnings("unchecked") @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8, T item9, T item10) { ObjectHelper.requireNonNull(item1, "The first item is null"); diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 168c9c216a..f41d69a80c 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -129,6 +129,7 @@ public abstract class Single<T> implements SingleSource<T> { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> amb(final Iterable<? extends SingleSource<? extends T>> sources) { ObjectHelper.requireNonNull(sources, "sources is null"); @@ -180,6 +181,7 @@ public static <T> Single<T> ambArray(final SingleSource<? extends T>... sources) * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) public static <T> Flowable<T> concat(Iterable<? extends SingleSource<? extends T>> sources) { @@ -201,6 +203,7 @@ public static <T> Flowable<T> concat(Iterable<? extends SingleSource<? extends T * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Observable<T> concat(ObservableSource<? extends SingleSource<? extends T>> sources) { @@ -226,6 +229,7 @@ public static <T> Observable<T> concat(ObservableSource<? extends SingleSource<? * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concat(Publisher<? extends SingleSource<? extends T>> sources) { @@ -251,6 +255,7 @@ public static <T> Flowable<T> concat(Publisher<? extends SingleSource<? extends * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -280,6 +285,7 @@ public static <T> Flowable<T> concat(Publisher<? extends SingleSource<? extends * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @@ -313,6 +319,7 @@ public static <T> Flowable<T> concat( * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @@ -350,6 +357,7 @@ public static <T> Flowable<T> concat( * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @@ -381,6 +389,7 @@ public static <T> Flowable<T> concat( * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -406,6 +415,7 @@ public static <T> Flowable<T> concatArray(SingleSource<? extends T>... sources) */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concatArrayEager(SingleSource<? extends T>... sources) { return Flowable.fromArray(sources).concatMapEager(SingleInternalHelper.<T>toFlowable()); @@ -433,6 +443,7 @@ public static <T> Flowable<T> concatArrayEager(SingleSource<? extends T>... sour */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concatEager(Publisher<? extends SingleSource<? extends T>> sources) { return Flowable.fromPublisher(sources).concatMapEager(SingleInternalHelper.<T>toFlowable()); @@ -458,6 +469,7 @@ public static <T> Flowable<T> concatEager(Publisher<? extends SingleSource<? ext */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> concatEager(Iterable<? extends SingleSource<? extends T>> sources) { return Flowable.fromIterable(sources).concatMapEager(SingleInternalHelper.<T>toFlowable()); @@ -500,6 +512,7 @@ public static <T> Flowable<T> concatEager(Iterable<? extends SingleSource<? exte * @see Cancellable */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> create(SingleOnSubscribe<T> source) { ObjectHelper.requireNonNull(source, "source is null"); @@ -521,6 +534,7 @@ public static <T> Single<T> create(SingleOnSubscribe<T> source) { * @return the new Single instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> defer(final Callable<? extends SingleSource<? extends T>> singleSupplier) { ObjectHelper.requireNonNull(singleSupplier, "singleSupplier is null"); @@ -541,6 +555,7 @@ public static <T> Single<T> defer(final Callable<? extends SingleSource<? extend * @return the new Single instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> error(final Callable<? extends Throwable> errorSupplier) { ObjectHelper.requireNonNull(errorSupplier, "errorSupplier is null"); @@ -566,6 +581,7 @@ public static <T> Single<T> error(final Callable<? extends Throwable> errorSuppl * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> error(final Throwable exception) { ObjectHelper.requireNonNull(exception, "error is null"); @@ -599,6 +615,7 @@ public static <T> Single<T> error(final Throwable exception) { * @return a {@link Single} whose {@link SingleObserver}s' subscriptions trigger an invocation of the given function. */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> fromCallable(final Callable<? extends T> callable) { ObjectHelper.requireNonNull(callable, "callable is null"); @@ -763,6 +780,7 @@ public static <T> Single<T> fromFuture(Future<? extends T> future, Scheduler sch */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> fromPublisher(final Publisher<? extends T> publisher) { ObjectHelper.requireNonNull(publisher, "publisher is null"); @@ -786,6 +804,7 @@ public static <T> Single<T> fromPublisher(final Publisher<? extends T> publisher * @return the new Single instance */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> fromObservable(ObservableSource<? extends T> observableSource) { ObjectHelper.requireNonNull(observableSource, "observableSource is null"); @@ -813,6 +832,7 @@ public static <T> Single<T> fromObservable(ObservableSource<? extends T> observa */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) + @NonNull public static <T> Single<T> just(final T item) { ObjectHelper.requireNonNull(item, "value is null"); return RxJavaPlugins.onAssembly(new SingleJust<T>(item)); @@ -849,6 +869,7 @@ public static <T> Single<T> just(final T item) { * @see #mergeDelayError(Iterable) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> merge(Iterable<? extends SingleSource<? extends T>> sources) { @@ -886,6 +907,7 @@ public static <T> Flowable<T> merge(Iterable<? extends SingleSource<? extends T> * @since 2.0 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -917,6 +939,7 @@ public static <T> Flowable<T> merge(Publisher<? extends SingleSource<? extends T * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Single<T> merge(SingleSource<? extends SingleSource<? extends T>> source) { @@ -961,6 +984,7 @@ public static <T> Single<T> merge(SingleSource<? extends SingleSource<? extends * @see #mergeDelayError(SingleSource, SingleSource) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @@ -1011,6 +1035,7 @@ public static <T> Flowable<T> merge( * @see #mergeDelayError(SingleSource, SingleSource, SingleSource) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @@ -1065,6 +1090,7 @@ public static <T> Flowable<T> merge( * @see #mergeDelayError(SingleSource, SingleSource, SingleSource, SingleSource) */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @@ -1096,6 +1122,7 @@ public static <T> Flowable<T> merge( * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> mergeDelayError(Iterable<? extends SingleSource<? extends T>> sources) { @@ -1119,6 +1146,7 @@ public static <T> Flowable<T> mergeDelayError(Iterable<? extends SingleSource<? * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -1153,6 +1181,7 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends SingleSource<? * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @@ -1192,6 +1221,7 @@ public static <T> Flowable<T> mergeDelayError( * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @@ -1235,6 +1265,7 @@ public static <T> Flowable<T> mergeDelayError( * @since 2.2 */ @CheckReturnValue + @NonNull @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @@ -1305,6 +1336,7 @@ public static Single<Long> timer(long delay, TimeUnit unit) { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public static Single<Long> timer(final long delay, final TimeUnit unit, final Scheduler scheduler) { ObjectHelper.requireNonNull(unit, "unit is null"); @@ -1327,6 +1359,7 @@ public static Single<Long> timer(final long delay, final TimeUnit unit, final Sc * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<Boolean> equals(final SingleSource<? extends T> first, final SingleSource<? extends T> second) { // NOPMD ObjectHelper.requireNonNull(first, "first is null"); @@ -1350,6 +1383,7 @@ public static <T> Single<Boolean> equals(final SingleSource<? extends T> first, * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> unsafeCreate(SingleSource<T> onSubscribe) { ObjectHelper.requireNonNull(onSubscribe, "onSubscribe is null"); @@ -1409,6 +1443,7 @@ public static <T, U> Single<T> using(Callable<U> resourceSupplier, * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, U> Single<T> using( final Callable<U> resourceSupplier, @@ -1434,6 +1469,7 @@ public static <T, U> Single<T> using( * @return the Single wrapper or the source cast to Single (if possible) */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> wrap(SingleSource<T> source) { ObjectHelper.requireNonNull(source, "source is null"); @@ -1473,6 +1509,7 @@ public static <T> Single<T> wrap(SingleSource<T> source) { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Single<R> zip(final Iterable<? extends SingleSource<? extends T>> sources, Function<? super Object[], ? extends R> zipper) { ObjectHelper.requireNonNull(zipper, "zipper is null"); @@ -1504,6 +1541,7 @@ public static <T, R> Single<R> zip(final Iterable<? extends SingleSource<? exten * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T1, T2, R> Single<R> zip( @@ -1542,6 +1580,7 @@ public static <T1, T2, R> Single<R> zip( * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T1, T2, T3, R> Single<R> zip( @@ -1585,6 +1624,7 @@ public static <T1, T2, T3, R> Single<R> zip( * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T1, T2, T3, T4, R> Single<R> zip( @@ -1632,6 +1672,7 @@ public static <T1, T2, T3, T4, R> Single<R> zip( * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T1, T2, T3, T4, T5, R> Single<R> zip( @@ -1684,6 +1725,7 @@ public static <T1, T2, T3, T4, T5, R> Single<R> zip( * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T1, T2, T3, T4, T5, T6, R> Single<R> zip( @@ -1740,6 +1782,7 @@ public static <T1, T2, T3, T4, T5, T6, R> Single<R> zip( * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T1, T2, T3, T4, T5, T6, T7, R> Single<R> zip( @@ -1801,6 +1844,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, R> Single<R> zip( * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Single<R> zip( @@ -1866,6 +1910,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Single<R> zip( * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Single<R> zip( @@ -1918,6 +1963,7 @@ public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Single<R> zip( * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, R> Single<R> zipArray(Function<? super Object[], ? extends R> zipper, SingleSource<? extends T>... sources) { ObjectHelper.requireNonNull(zipper, "zipper is null"); @@ -1942,6 +1988,7 @@ public static <T, R> Single<R> zipArray(Function<? super Object[], ? extends R> * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public final Single<T> ambWith(SingleSource<? extends T> other) { @@ -2048,6 +2095,7 @@ public final Single<T> cache() { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Single<U> cast(final Class<? extends U> clazz) { ObjectHelper.requireNonNull(clazz, "clazz is null"); @@ -2166,6 +2214,7 @@ public final Single<T> delay(final long time, final TimeUnit unit, final Schedul * @since 2.2 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Single<T> delay(final long time, final TimeUnit unit, final Scheduler scheduler, boolean delayError) { ObjectHelper.requireNonNull(unit, "unit is null"); @@ -2188,6 +2237,7 @@ public final Single<T> delay(final long time, final TimeUnit unit, final Schedul * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> delaySubscription(CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2210,6 +2260,7 @@ public final Single<T> delaySubscription(CompletableSource other) { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Single<T> delaySubscription(SingleSource<U> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2232,6 +2283,7 @@ public final <U> Single<T> delaySubscription(SingleSource<U> other) { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Single<T> delaySubscription(ObservableSource<U> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2259,6 +2311,7 @@ public final <U> Single<T> delaySubscription(ObservableSource<U> other) { */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Single<T> delaySubscription(Publisher<U> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -2332,6 +2385,7 @@ public final Single<T> delaySubscription(long time, TimeUnit unit, Scheduler sch * @see #materialize() */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) @Experimental public final <R> Maybe<R> dematerialize(Function<? super T, Notification<R>> selector) { @@ -2356,6 +2410,7 @@ public final <R> Maybe<R> dematerialize(Function<? super T, Notification<R>> sel * @since 2.1 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) { ObjectHelper.requireNonNull(onAfterSuccess, "doAfterSuccess is null"); @@ -2384,6 +2439,7 @@ public final Single<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) { * @since 2.1 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> doAfterTerminate(Action onAfterTerminate) { ObjectHelper.requireNonNull(onAfterTerminate, "onAfterTerminate is null"); @@ -2410,6 +2466,7 @@ public final Single<T> doAfterTerminate(Action onAfterTerminate) { * @since 2.1 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> doFinally(Action onFinally) { ObjectHelper.requireNonNull(onFinally, "onFinally is null"); @@ -2431,6 +2488,7 @@ public final Single<T> doFinally(Action onFinally) { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> doOnSubscribe(final Consumer<? super Disposable> onSubscribe) { ObjectHelper.requireNonNull(onSubscribe, "onSubscribe is null"); @@ -2452,6 +2510,7 @@ public final Single<T> doOnSubscribe(final Consumer<? super Disposable> onSubscr * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> doOnSuccess(final Consumer<? super T> onSuccess) { ObjectHelper.requireNonNull(onSuccess, "onSuccess is null"); @@ -2470,6 +2529,7 @@ public final Single<T> doOnSuccess(final Consumer<? super T> onSuccess) { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> doOnEvent(final BiConsumer<? super T, ? super Throwable> onEvent) { ObjectHelper.requireNonNull(onEvent, "onEvent is null"); @@ -2491,6 +2551,7 @@ public final Single<T> doOnEvent(final BiConsumer<? super T, ? super Throwable> * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> doOnError(final Consumer<? super Throwable> onError) { ObjectHelper.requireNonNull(onError, "onError is null"); @@ -2513,6 +2574,7 @@ public final Single<T> doOnError(final Consumer<? super Throwable> onError) { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> doOnDispose(final Action onDispose) { ObjectHelper.requireNonNull(onDispose, "onDispose is null"); @@ -2537,6 +2599,7 @@ public final Single<T> doOnDispose(final Action onDispose) { * @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> filter(Predicate<? super T> predicate) { ObjectHelper.requireNonNull(predicate, "predicate is null"); @@ -2560,6 +2623,7 @@ public final Maybe<T> filter(Predicate<? super T> predicate) { * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Single<R> flatMap(Function<? super T, ? extends SingleSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -2583,6 +2647,7 @@ public final <R> Single<R> flatMap(Function<? super T, ? extends SingleSource<? * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Maybe<R> flatMapMaybe(final Function<? super T, ? extends MaybeSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -2611,6 +2676,7 @@ public final <R> Maybe<R> flatMapMaybe(final Function<? super T, ? extends Maybe */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> flatMapPublisher(Function<? super T, ? extends Publisher<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -2639,6 +2705,7 @@ public final <R> Flowable<R> flatMapPublisher(Function<? super T, ? extends Publ */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<U> flattenAsFlowable(final Function<? super T, ? extends Iterable<? extends U>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -2663,6 +2730,7 @@ public final <U> Flowable<U> flattenAsFlowable(final Function<? super T, ? exten * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <U> Observable<U> flattenAsObservable(final Function<? super T, ? extends Iterable<? extends U>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -2686,6 +2754,7 @@ public final <U> Observable<U> flattenAsObservable(final Function<? super T, ? e * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Observable<R> flatMapObservable(Function<? super T, ? extends ObservableSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -2710,6 +2779,7 @@ public final <R> Observable<R> flatMapObservable(Function<? super T, ? extends O * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Completable flatMapCompletable(final Function<? super T, ? extends CompletableSource> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -2879,6 +2949,7 @@ public final T blockingGet() { * @see #compose(SingleTransformer) */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Single<R> lift(final SingleOperator<? extends R, ? super T> lift) { ObjectHelper.requireNonNull(lift, "onLift is null"); @@ -2902,6 +2973,7 @@ public final <R> Single<R> lift(final SingleOperator<? extends R, ? super T> lif * @see <a href="http://reactivex.io/documentation/operators/map.html">ReactiveX operators documentation: Map</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Single<R> map(Function<? super T, ? extends R> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); @@ -2959,6 +3031,7 @@ public final Single<Boolean> contains(Object value) { * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<Boolean> contains(final Object value, final BiPredicate<Object, Object> comparer) { ObjectHelper.requireNonNull(value, "value is null"); @@ -3012,6 +3085,7 @@ public final Flowable<T> mergeWith(SingleSource<? extends T> other) { * @see #subscribeOn */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Single<T> observeOn(final Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); @@ -3045,6 +3119,7 @@ public final Single<T> observeOn(final Scheduler scheduler) { * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> onErrorReturn(final Function<Throwable, ? extends T> resumeFunction) { ObjectHelper.requireNonNull(resumeFunction, "resumeFunction is null"); @@ -3064,6 +3139,7 @@ public final Single<T> onErrorReturn(final Function<Throwable, ? extends T> resu * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> onErrorReturnItem(final T value) { ObjectHelper.requireNonNull(value, "value is null"); @@ -3098,6 +3174,7 @@ public final Single<T> onErrorReturnItem(final T value) { * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> onErrorResumeNext(final Single<? extends T> resumeSingleInCaseOfError) { ObjectHelper.requireNonNull(resumeSingleInCaseOfError, "resumeSingleInCaseOfError is null"); @@ -3133,6 +3210,7 @@ public final Single<T> onErrorResumeNext(final Single<? extends T> resumeSingleI * @since .20 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> onErrorResumeNext( final Function<? super Throwable, ? extends SingleSource<? extends T>> resumeFunctionInCaseOfError) { @@ -3419,6 +3497,7 @@ public final Disposable subscribe() { * if {@code onCallback} is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Disposable subscribe(final BiConsumer<? super T, ? super Throwable> onCallback) { ObjectHelper.requireNonNull(onCallback, "onCallback is null"); @@ -3472,6 +3551,7 @@ public final Disposable subscribe(Consumer<? super T> onSuccess) { * if {@code onError} is null */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Disposable subscribe(final Consumer<? super T> onSuccess, final Consumer<? super Throwable> onError) { ObjectHelper.requireNonNull(onSuccess, "onSuccess is null"); @@ -3560,6 +3640,7 @@ public final <E extends SingleObserver<? super T>> E subscribeWith(E observer) { * @see #observeOn */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Single<T> subscribeOn(final Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); @@ -3584,6 +3665,7 @@ public final Single<T> subscribeOn(final Scheduler scheduler) { * @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> takeUntil(final CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -3615,6 +3697,7 @@ public final Single<T> takeUntil(final CompletableSource other) { */ @BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <E> Single<T> takeUntil(final Publisher<E> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -3640,6 +3723,7 @@ public final <E> Single<T> takeUntil(final Publisher<E> other) { * @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a> */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <E> Single<T> takeUntil(final SingleSource<? extends E> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -3699,6 +3783,7 @@ public final Single<T> timeout(long timeout, TimeUnit unit, Scheduler scheduler) * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Single<T> timeout(long timeout, TimeUnit unit, Scheduler scheduler, SingleSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -3724,6 +3809,7 @@ public final Single<T> timeout(long timeout, TimeUnit unit, Scheduler scheduler, * @since 2.0 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Single<T> timeout(long timeout, TimeUnit unit, SingleSource<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); @@ -3902,6 +3988,7 @@ public final Observable<T> toObservable() { * @since 2.2 */ @CheckReturnValue + @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public final Single<T> unsubscribeOn(final Scheduler scheduler) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); From 5278124db4a93b8f59cee4e3baa9e864601637fd Mon Sep 17 00:00:00 2001 From: Igor Suhorukov <igor.suhorukov@gmail.com> Date: Wed, 19 Dec 2018 13:42:56 +0300 Subject: [PATCH 325/417] Replace indexed loop with for-each java5 syntax (#6335) * Replace indexed loop with for-each java5 syntax * Restore code as per @akarnokd code review * Keep empty lines as per @akarnokd code review --- .../reactivex/internal/operators/parallel/ParallelJoin.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java b/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java index b248cde69f..975c151729 100644 --- a/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java +++ b/src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java @@ -110,15 +110,13 @@ public void cancel() { } void cancelAll() { - for (int i = 0; i < subscribers.length; i++) { - JoinInnerSubscriber<T> s = subscribers[i]; + for (JoinInnerSubscriber<T> s : subscribers) { s.cancel(); } } void cleanup() { - for (int i = 0; i < subscribers.length; i++) { - JoinInnerSubscriber<T> s = subscribers[i]; + for (JoinInnerSubscriber<T> s : subscribers) { s.queue = null; } } From 5aef7fee1add9bd0d64a38f1f671eeac3abe0db0 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 24 Dec 2018 15:40:50 +0100 Subject: [PATCH 326/417] Javadoc: fix examples using markdown instead of @code (#6346) --- src/main/java/io/reactivex/Flowable.java | 6 +++--- src/main/java/io/reactivex/Observable.java | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 0b33a191a2..aea0ed9951 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -8846,7 +8846,7 @@ public final <K> Flowable<T> distinct(Function<? super T, K> keySelector, * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. + * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -8889,7 +8889,7 @@ public final Flowable<T> distinctUntilChanged() { * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. + * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s @@ -8928,7 +8928,7 @@ public final <K> Flowable<T> distinctUntilChanged(Function<? super T, K> keySele * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. + * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index fdd8b29a92..50060d353d 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7879,7 +7879,7 @@ public final <K> Observable<T> distinct(Function<? super T, K> keySelector, Call * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. + * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> @@ -7918,7 +7918,7 @@ public final Observable<T> distinctUntilChanged() { * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. + * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> @@ -7953,7 +7953,7 @@ public final <K> Observable<T> distinctUntilChanged(Function<? super T, K> keySe * {@code CharSequence}s or {@code List}s where the objects will actually have the same * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same. * To avoid such situation, it is recommended that mutable data is converted to an immutable one, - * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`. + * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> From 4f0cdca8ffe6c2700337a20c03e9c09bf5357a5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yusuf=20K=2E=20=C3=96zcan?= <yusufkozcan@gmail.com> Date: Sat, 29 Dec 2018 01:11:52 +0300 Subject: [PATCH 327/417] Update outdated java example in wiki #6331 (#6351) * Update outdated java example in wiki #6331 * update wiki page similar to README * keep the original example --- docs/How-To-Use-RxJava.md | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/docs/How-To-Use-RxJava.md b/docs/How-To-Use-RxJava.md index d10274d959..16d156caa9 100644 --- a/docs/How-To-Use-RxJava.md +++ b/docs/How-To-Use-RxJava.md @@ -11,15 +11,20 @@ You can find additional code examples in the `/src/examples` folders of each [la ### Java ```java -public static void hello(String... names) { - Observable.from(names).subscribe(new Action1<String>() { - - @Override - public void call(String s) { - System.out.println("Hello " + s + "!"); - } +public static void hello(String... args) { + Flowable.fromArray(args).subscribe(s -> System.out.println("Hello " + s + "!")); +} +``` - }); +If your platform doesn't support Java 8 lambdas (yet), you have to create an inner class of ```Consumer``` manually: +```java +public static void hello(String... args) { + Flowable.fromArray(args).subscribe(new Consumer<String>() { + @Override + public void accept(String s) { + System.out.println("Hello " + s + "!"); + } + }); } ``` @@ -397,4 +402,4 @@ myModifiedObservable = myObservable.onErrorResumeNext({ t -> Throwable myThrowable = myCustomizedThrowableCreator(t); return (Observable.error(myThrowable)); }); -``` \ No newline at end of file +``` From 537fa263233a2a3234bbb8bd052f89b648fad2da Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 31 Dec 2018 10:57:09 +0100 Subject: [PATCH 328/417] Release 2.2.5 --- CHANGES.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index dd1266c545..57b421fc21 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,24 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.5 - December 31, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.5%7C)) + +#### Documentation changes + + - [Pull 6344](https://github.com/ReactiveX/RxJava/pull/6344): Use correct return type in JavaDocs documentation in `elementAtOrDefault`. + - [Pull 6346](https://github.com/ReactiveX/RxJava/pull/6346): Fix JavaDoc examples using markdown instead of `@code`. + +#### Wiki changes + + - [Pull 6324](https://github.com/ReactiveX/RxJava/pull/6324): Java 8 version for [Problem-Solving-Examples-in-RxJava](https://github.com/ReactiveX/RxJava/wiki/Problem-Solving-Examples-in-RxJava). + - [Pull 6343](https://github.com/ReactiveX/RxJava/pull/6343): Update [Filtering Observables](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) docs. + - [Pull 6351](https://github.com/ReactiveX/RxJava/pull/6351): Updated java example in [How-To-Use-RxJava.md](https://github.com/ReactiveX/RxJava/wiki/How-To-Use-RxJava) file with java 8 version. + +#### Other changes + + - [Pull 6313](https://github.com/ReactiveX/RxJava/pull/6313): Adding `@NonNull` annotation factory methods. + - [Pull 6335](https://github.com/ReactiveX/RxJava/pull/6335): Replace indexed loop with for-each java5 syntax. + ### Version 2.2.4 - November 23, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.4%7C)) #### API changes From 2e0c8b585e467f94a0cc47d5792b6eb8e7f51262 Mon Sep 17 00:00:00 2001 From: lorenzpahl <l.pahl@outlook.com> Date: Wed, 2 Jan 2019 18:00:44 +0100 Subject: [PATCH 329/417] docs(README): Use 'ignoreElement' to convert Single to Completable (#6353) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3fcaf292d2..c29d6d3fc0 100644 --- a/README.md +++ b/README.md @@ -369,7 +369,7 @@ Each reactive base class features operators that can perform such conversions, i |----------|----------|------------|--------|-------|-------------| |**Flowable** | | `toObservable` | `first`, `firstOrError`, `single`, `singleOrError`, `last`, `lastOrError`<sup>1</sup> | `firstElement`, `singleElement`, `lastElement` | `ignoreElements` | |**Observable**| `toFlowable`<sup>2</sup> | | `first`, `firstOrError`, `single`, `singleOrError`, `last`, `lastOrError`<sup>1</sup> | `firstElement`, `singleElement`, `lastElement` | `ignoreElements` | -|**Single** | `toFlowable`<sup>3</sup> | `toObservable` | | `toMaybe` | `toCompletable` | +|**Single** | `toFlowable`<sup>3</sup> | `toObservable` | | `toMaybe` | `ignoreElement` | |**Maybe** | `toFlowable`<sup>3</sup> | `toObservable` | `toSingle` | | `ignoreElement` | |**Completable** | `toFlowable` | `toObservable` | `toSingle` | `toMaybe` | | From 090f99e13534c0e0e9e4665f1187c1c42637c7b0 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sat, 5 Jan 2019 00:39:20 +0100 Subject: [PATCH 330/417] 2.x: Fix the error/race in Obs.repeatWhen due to flooding repeat signal (#6359) --- .../observable/ObservableRepeatWhen.java | 2 +- .../flowable/FlowableRepeatTest.java | 53 ++++++++++++++++ .../operators/flowable/FlowableRetryTest.java | 61 +++++++++++++++++++ .../observable/ObservableRepeatTest.java | 53 ++++++++++++++++ .../observable/ObservableRetryTest.java | 61 +++++++++++++++++++ 5 files changed, 229 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java index af27f2f6d0..24725997d1 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRepeatWhen.java @@ -108,8 +108,8 @@ public void onError(Throwable e) { @Override public void onComplete() { - active = false; DisposableHelper.replace(upstream, null); + active = false; signaller.onNext(0); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java index 51376bc594..fd5061d9ed 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java @@ -29,6 +29,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; @@ -441,4 +442,56 @@ public boolean test(Object v) throws Exception { assertEquals(0, counter.get()); } + + @Test + public void repeatFloodNoSubscriptionError() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + + try { + final PublishProcessor<Integer> source = PublishProcessor.create(); + final PublishProcessor<Integer> signaller = PublishProcessor.create(); + + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + TestSubscriber<Integer> ts = source.take(1) + .repeatWhen(new Function<Flowable<Object>, Flowable<Integer>>() { + @Override + public Flowable<Integer> apply(Flowable<Object> v) + throws Exception { + return signaller; + } + }).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + source.onNext(1); + } + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + signaller.offer(1); + } + } + }; + + TestHelper.race(r1, r2); + + ts.dispose(); + } + + if (!errors.isEmpty()) { + for (Throwable e : errors) { + e.printStackTrace(); + } + fail(errors + ""); + } + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java index a5dd4918ab..a47a5d6eca 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java @@ -32,6 +32,7 @@ import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.*; @@ -1221,4 +1222,64 @@ public boolean test(Object v) throws Exception { assertEquals(0, counter.get()); } + + @Test + public void repeatFloodNoSubscriptionError() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + + final TestException error = new TestException(); + + try { + final PublishProcessor<Integer> source = PublishProcessor.create(); + final PublishProcessor<Integer> signaller = PublishProcessor.create(); + + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + TestSubscriber<Integer> ts = source.take(1) + .map(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer v) throws Exception { + throw error; + } + }) + .retryWhen(new Function<Flowable<Throwable>, Flowable<Integer>>() { + @Override + public Flowable<Integer> apply(Flowable<Throwable> v) + throws Exception { + return signaller; + } + }).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + source.onNext(1); + } + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + signaller.offer(1); + } + } + }; + + TestHelper.race(r1, r2); + + ts.dispose(); + } + + if (!errors.isEmpty()) { + for (Throwable e : errors) { + e.printStackTrace(); + } + fail(errors + ""); + } + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java index 3afc1f1cc7..dbb72e21ef 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java @@ -30,6 +30,7 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; @@ -397,4 +398,56 @@ public boolean test(Object v) throws Exception { assertEquals(0, counter.get()); } + + @Test + public void repeatFloodNoSubscriptionError() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + + try { + final PublishSubject<Integer> source = PublishSubject.create(); + final PublishSubject<Integer> signaller = PublishSubject.create(); + + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + TestObserver<Integer> to = source.take(1) + .repeatWhen(new Function<Observable<Object>, ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> apply(Observable<Object> v) + throws Exception { + return signaller; + } + }).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + source.onNext(1); + } + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + signaller.onNext(1); + } + } + }; + + TestHelper.race(r1, r2); + + to.dispose(); + } + + if (!errors.isEmpty()) { + for (Throwable e : errors) { + e.printStackTrace(); + } + fail(errors + ""); + } + } finally { + RxJavaPlugins.reset(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java index e576479921..0055449ef5 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java @@ -34,6 +34,7 @@ import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.observables.GroupedObservable; import io.reactivex.observers.*; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; @@ -1131,4 +1132,64 @@ public boolean test(Object v) throws Exception { assertEquals(0, counter.get()); } + + @Test + public void repeatFloodNoSubscriptionError() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + + final TestException error = new TestException(); + + try { + final PublishSubject<Integer> source = PublishSubject.create(); + final PublishSubject<Integer> signaller = PublishSubject.create(); + + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + TestObserver<Integer> to = source.take(1) + .map(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer v) throws Exception { + throw error; + } + }) + .retryWhen(new Function<Observable<Throwable>, ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> apply(Observable<Throwable> v) + throws Exception { + return signaller; + } + }).test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + source.onNext(1); + } + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + signaller.onNext(1); + } + } + }; + + TestHelper.race(r1, r2); + + to.dispose(); + } + + if (!errors.isEmpty()) { + for (Throwable e : errors) { + e.printStackTrace(); + } + fail(errors + ""); + } + } finally { + RxJavaPlugins.reset(); + } + } } From d7d0a33e04e4b409789fc67ec94883bf0e828c64 Mon Sep 17 00:00:00 2001 From: pjastrz <pjastrz@gmail.com> Date: Sat, 12 Jan 2019 19:06:23 +0100 Subject: [PATCH 331/417] 2.x: Fix Completable.andThen(Completable) not running on observeOn scheduler. (#6362) * 2.x: Fix Completable.andThen(Completable) not running on scheduler defined with observeOn. * 2.x: Fix Completable.andThen(Completable) not running on scheduler defined with observeOn. * 2.x: Fix Completable.andThen(Completable) not running on scheduler defined with observeOn. --- src/main/java/io/reactivex/Completable.java | 5 +- .../CompletableAndThenCompletable.java | 107 ++++++++++ .../CompletableAndThenCompletableabTest.java | 185 ++++++++++++++++++ .../completable/CompletableAndThenTest.java | 45 +---- 4 files changed, 297 insertions(+), 45 deletions(-) create mode 100644 src/main/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletable.java create mode 100644 src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletableabTest.java diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 9d8325e3b6..7ac7ead344 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -1171,7 +1171,8 @@ public final <T> Maybe<T> andThen(MaybeSource<T> next) { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Completable andThen(CompletableSource next) { - return concatWith(next); + ObjectHelper.requireNonNull(next, "next is null"); + return RxJavaPlugins.onAssembly(new CompletableAndThenCompletable(this, next)); } /** @@ -1357,7 +1358,7 @@ public final Completable compose(CompletableTransformer transformer) { @SchedulerSupport(SchedulerSupport.NONE) public final Completable concatWith(CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); - return concatArray(this, other); + return RxJavaPlugins.onAssembly(new CompletableAndThenCompletable(this, other)); } /** diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletable.java new file mode 100644 index 0000000000..20d2332214 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletable.java @@ -0,0 +1,107 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import java.util.concurrent.atomic.AtomicReference; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.DisposableHelper; + +public final class CompletableAndThenCompletable extends Completable { + + final CompletableSource source; + + final CompletableSource next; + + public CompletableAndThenCompletable(CompletableSource source, CompletableSource next) { + this.source = source; + this.next = next; + } + + @Override + protected void subscribeActual(CompletableObserver observer) { + source.subscribe(new SourceObserver(observer, next)); + } + + static final class SourceObserver + extends AtomicReference<Disposable> + implements CompletableObserver, Disposable { + + private static final long serialVersionUID = -4101678820158072998L; + + final CompletableObserver actualObserver; + + final CompletableSource next; + + SourceObserver(CompletableObserver actualObserver, CompletableSource next) { + this.actualObserver = actualObserver; + this.next = next; + } + + @Override + public void onSubscribe(Disposable d) { + if (DisposableHelper.setOnce(this, d)) { + actualObserver.onSubscribe(this); + } + } + + @Override + public void onError(Throwable e) { + actualObserver.onError(e); + } + + @Override + public void onComplete() { + next.subscribe(new NextObserver(this, actualObserver)); + } + + @Override + public void dispose() { + DisposableHelper.dispose(this); + } + + @Override + public boolean isDisposed() { + return DisposableHelper.isDisposed(get()); + } + } + + static final class NextObserver implements CompletableObserver { + + final AtomicReference<Disposable> parent; + + final CompletableObserver downstream; + + public NextObserver(AtomicReference<Disposable> parent, CompletableObserver downstream) { + this.parent = parent; + this.downstream = downstream; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.replace(parent, d); + } + + @Override + public void onComplete() { + downstream.onComplete(); + } + + @Override + public void onError(Throwable e) { + downstream.onError(e); + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletableabTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletableabTest.java new file mode 100644 index 0000000000..34b9c82436 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletableabTest.java @@ -0,0 +1,185 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.completable; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.observers.TestObserver; +import io.reactivex.schedulers.Schedulers; + +import static org.junit.Assert.*; + +public class CompletableAndThenCompletableabTest { + @Test(expected = NullPointerException.class) + public void andThenCompletableCompleteNull() { + Completable.complete() + .andThen((Completable) null); + } + + @Test + public void andThenCompletableCompleteComplete() { + Completable.complete() + .andThen(Completable.complete()) + .test() + .assertComplete(); + } + + @Test + public void andThenCompletableCompleteError() { + Completable.complete() + .andThen(Completable.error(new TestException("test"))) + .test() + .assertNotComplete() + .assertNoValues() + .assertError(TestException.class) + .assertErrorMessage("test"); + } + + @Test + public void andThenCompletableCompleteNever() { + Completable.complete() + .andThen(Completable.never()) + .test() + .assertNoValues() + .assertNoErrors() + .assertNotComplete(); + } + + @Test + public void andThenCompletableErrorComplete() { + Completable.error(new TestException("bla")) + .andThen(Completable.complete()) + .test() + .assertNotComplete() + .assertNoValues() + .assertError(TestException.class) + .assertErrorMessage("bla"); + } + + @Test + public void andThenCompletableErrorNever() { + Completable.error(new TestException("bla")) + .andThen(Completable.never()) + .test() + .assertNotComplete() + .assertNoValues() + .assertError(TestException.class) + .assertErrorMessage("bla"); + } + + @Test + public void andThenCompletableErrorError() { + Completable.error(new TestException("error1")) + .andThen(Completable.error(new TestException("error2"))) + .test() + .assertNotComplete() + .assertNoValues() + .assertError(TestException.class) + .assertErrorMessage("error1"); + } + + @Test + public void andThenCanceled() { + final AtomicInteger completableRunCount = new AtomicInteger(); + Completable.fromRunnable(new Runnable() { + @Override + public void run() { + completableRunCount.incrementAndGet(); + } + }) + .andThen(Completable.complete()) + .test(true) + .assertEmpty(); + assertEquals(1, completableRunCount.get()); + } + + @Test + public void andThenFirstCancels() { + final TestObserver<Void> to = new TestObserver<Void>(); + Completable.fromRunnable(new Runnable() { + @Override + public void run() { + to.cancel(); + } + }) + .andThen(Completable.complete()) + .subscribe(to); + to + .assertNotComplete() + .assertNoErrors(); + } + + @Test + public void andThenSecondCancels() { + final TestObserver<Void> to = new TestObserver<Void>(); + Completable.complete() + .andThen(Completable.fromRunnable(new Runnable() { + @Override + public void run() { + to.cancel(); + } + })) + .subscribe(to); + to + .assertNotComplete() + .assertNoErrors(); + } + + @Test + public void andThenDisposed() { + TestHelper.checkDisposed(Completable.complete() + .andThen(Completable.complete())); + } + + @Test + public void andThenNoInterrupt() throws InterruptedException { + for (int k = 0; k < 100; k++) { + final int count = 10; + final CountDownLatch latch = new CountDownLatch(count); + final boolean[] interrupted = {false}; + + for (int i = 0; i < count; i++) { + Completable.complete() + .subscribeOn(Schedulers.io()) + .observeOn(Schedulers.io()) + .andThen(Completable.fromAction(new Action() { + @Override + public void run() throws Exception { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + System.out.println("Interrupted! " + Thread.currentThread()); + interrupted[0] = true; + } + } + })) + .subscribe(new Action() { + @Override + public void run() throws Exception { + latch.countDown(); + } + }); + } + + latch.await(); + assertFalse("The second Completable was interrupted!", interrupted[0]); + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenTest.java index a5d9b3a279..c873d5472d 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableAndThenTest.java @@ -13,15 +13,9 @@ package io.reactivex.internal.operators.completable; -import io.reactivex.Completable; -import io.reactivex.Maybe; -import io.reactivex.functions.Action; -import io.reactivex.schedulers.Schedulers; - -import java.util.concurrent.CountDownLatch; - import org.junit.Test; -import static org.junit.Assert.*; + +import io.reactivex.*; public class CompletableAndThenTest { @Test(expected = NullPointerException.class) @@ -69,39 +63,4 @@ public void andThenMaybeError() { .assertError(RuntimeException.class) .assertErrorMessage("bla"); } - - @Test - public void andThenNoInterrupt() throws InterruptedException { - for (int k = 0; k < 100; k++) { - final int count = 10; - final CountDownLatch latch = new CountDownLatch(count); - final boolean[] interrupted = { false }; - - for (int i = 0; i < count; i++) { - Completable.complete() - .subscribeOn(Schedulers.io()) - .observeOn(Schedulers.io()) - .andThen(Completable.fromAction(new Action() { - @Override - public void run() throws Exception { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - System.out.println("Interrupted! " + Thread.currentThread()); - interrupted[0] = true; - } - } - })) - .subscribe(new Action() { - @Override - public void run() throws Exception { - latch.countDown(); - } - }); - } - - latch.await(); - assertFalse("The second Completable was interrupted!", interrupted[0]); - } - } } From 2eda9d82f41cef934da4e22a52899b1eed85d729 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 15 Jan 2019 11:37:22 +0100 Subject: [PATCH 332/417] 2.x: Fix publish not requesting upon client change (#6364) * 2.x: Fix publish not requesting upon client change * Add fused test, rename test method --- .../operators/flowable/FlowablePublish.java | 10 +- .../flowable/FlowablePublishTest.java | 130 ++++++++++++++++++ 2 files changed, 139 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java index 0e08551495..7ab84a568b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java @@ -557,12 +557,20 @@ void dispatch() { InnerSubscriber<T>[] freshArray = subscribers.get(); if (subscribersChanged || freshArray != ps) { ps = freshArray; + + // if we did emit at least one element, request more to replenish the queue + if (d != 0) { + if (sourceMode != QueueSubscription.SYNC) { + upstream.get().request(d); + } + } + continue outer; } } // if we did emit at least one element, request more to replenish the queue - if (d > 0) { + if (d != 0) { if (sourceMode != QueueSubscription.SYNC) { upstream.get().request(d); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java index c7c9865f24..eac12749f5 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java @@ -1368,4 +1368,134 @@ public String apply(Integer t) throws Exception { public void badRequest() { TestHelper.assertBadRequestReported(Flowable.range(1, 5).publish()); } + + @Test + @SuppressWarnings("unchecked") + public void splitCombineSubscriberChangeAfterOnNext() { + Flowable<Integer> source = Flowable.range(0, 20) + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription v) throws Exception { + System.out.println("Subscribed"); + } + }) + .publish(10) + .refCount() + ; + + Flowable<Integer> evenNumbers = source.filter(new Predicate<Integer>() { + @Override + public boolean test(Integer v) throws Exception { + return v % 2 == 0; + } + }); + + Flowable<Integer> oddNumbers = source.filter(new Predicate<Integer>() { + @Override + public boolean test(Integer v) throws Exception { + return v % 2 != 0; + } + }); + + final Single<Integer> getNextOdd = oddNumbers.first(0); + + TestSubscriber<List<Integer>> ts = evenNumbers.concatMap(new Function<Integer, Publisher<List<Integer>>>() { + @Override + public Publisher<List<Integer>> apply(Integer v) throws Exception { + return Single.zip( + Single.just(v), getNextOdd, + new BiFunction<Integer, Integer, List<Integer>>() { + @Override + public List<Integer> apply(Integer a, Integer b) throws Exception { + return Arrays.asList( a, b ); + } + } + ) + .toFlowable(); + } + }) + .takeWhile(new Predicate<List<Integer>>() { + @Override + public boolean test(List<Integer> v) throws Exception { + return v.get(0) < 20; + } + }) + .test(); + + ts + .assertResult( + Arrays.asList(0, 1), + Arrays.asList(2, 3), + Arrays.asList(4, 5), + Arrays.asList(6, 7), + Arrays.asList(8, 9), + Arrays.asList(10, 11), + Arrays.asList(12, 13), + Arrays.asList(14, 15), + Arrays.asList(16, 17), + Arrays.asList(18, 19) + ); + } + + @Test + @SuppressWarnings("unchecked") + public void splitCombineSubscriberChangeAfterOnNextFused() { + Flowable<Integer> source = Flowable.range(0, 20) + .publish(10) + .refCount() + ; + + Flowable<Integer> evenNumbers = source.filter(new Predicate<Integer>() { + @Override + public boolean test(Integer v) throws Exception { + return v % 2 == 0; + } + }); + + Flowable<Integer> oddNumbers = source.filter(new Predicate<Integer>() { + @Override + public boolean test(Integer v) throws Exception { + return v % 2 != 0; + } + }); + + final Single<Integer> getNextOdd = oddNumbers.first(0); + + TestSubscriber<List<Integer>> ts = evenNumbers.concatMap(new Function<Integer, Publisher<List<Integer>>>() { + @Override + public Publisher<List<Integer>> apply(Integer v) throws Exception { + return Single.zip( + Single.just(v), getNextOdd, + new BiFunction<Integer, Integer, List<Integer>>() { + @Override + public List<Integer> apply(Integer a, Integer b) throws Exception { + return Arrays.asList( a, b ); + } + } + ) + .toFlowable(); + } + }) + .takeWhile(new Predicate<List<Integer>>() { + @Override + public boolean test(List<Integer> v) throws Exception { + return v.get(0) < 20; + } + }) + .test(); + + ts + .assertResult( + Arrays.asList(0, 1), + Arrays.asList(2, 3), + Arrays.asList(4, 5), + Arrays.asList(6, 7), + Arrays.asList(8, 9), + Arrays.asList(10, 11), + Arrays.asList(12, 13), + Arrays.asList(14, 15), + Arrays.asList(16, 17), + Arrays.asList(18, 19) + ); + } } From e1b383840d26ebdfbf298ee7f64ac26f697f9495 Mon Sep 17 00:00:00 2001 From: "Artem Zinnatullin :slowpoke" <ceo@artemzin.com> Date: Tue, 15 Jan 2019 03:27:26 -0800 Subject: [PATCH 333/417] Indicate source disposal in timeout(fallback) (#6365) --- src/main/java/io/reactivex/Flowable.java | 5 +++-- src/main/java/io/reactivex/Maybe.java | 5 +++-- src/main/java/io/reactivex/Observable.java | 6 ++++-- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index aea0ed9951..cba4b69210 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -16442,7 +16442,7 @@ public final Flowable<T> timeout(long timeout, TimeUnit timeUnit) { /** * Returns a Flowable that mirrors the source Publisher but applies a timeout policy for each emitted * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, - * the resulting Publisher begins instead to mirror a fallback Publisher. + * the source Publisher is disposed and resulting Publisher begins instead to mirror a fallback Publisher. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.2.png" alt=""> * <dl> @@ -16476,7 +16476,8 @@ public final Flowable<T> timeout(long timeout, TimeUnit timeUnit, Publisher<? ex /** * Returns a Flowable that mirrors the source Publisher but applies a timeout policy for each emitted * item using a specified Scheduler. If the next item isn't emitted within the specified timeout duration - * starting from its predecessor, the resulting Publisher begins instead to mirror a fallback Publisher. + * starting from its predecessor, the source Publisher is disposed and resulting Publisher begins + * instead to mirror a fallback Publisher. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.2s.png" alt=""> * <dl> diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 773021a028..147b3f3125 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -4463,7 +4463,7 @@ public final Maybe<T> timeout(long timeout, TimeUnit timeUnit) { /** * Returns a Maybe that mirrors the source Maybe but applies a timeout policy for each emitted * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, - * the resulting Maybe begins instead to mirror a fallback MaybeSource. + * the source MaybeSource is disposed and resulting Maybe begins instead to mirror a fallback MaybeSource. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.2.png" alt=""> * <dl> @@ -4491,7 +4491,8 @@ public final Maybe<T> timeout(long timeout, TimeUnit timeUnit, MaybeSource<? ext /** * Returns a Maybe that mirrors the source Maybe but applies a timeout policy for each emitted * item using a specified Scheduler. If the next item isn't emitted within the specified timeout duration - * starting from its predecessor, the resulting Maybe begins instead to mirror a fallback MaybeSource. + * starting from its predecessor, the source MaybeSource is disposed and resulting Maybe begins instead + * to mirror a fallback MaybeSource. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.2s.png" alt=""> * <dl> diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 50060d353d..90b96c38fd 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -13617,7 +13617,8 @@ public final Observable<T> timeout(long timeout, TimeUnit timeUnit) { /** * Returns an Observable that mirrors the source ObservableSource but applies a timeout policy for each emitted * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, - * the resulting ObservableSource begins instead to mirror a fallback ObservableSource. + * the source ObservableSource is disposed and resulting ObservableSource begins instead + * to mirror a fallback ObservableSource. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.2.png" alt=""> * <dl> @@ -13644,7 +13645,8 @@ public final Observable<T> timeout(long timeout, TimeUnit timeUnit, ObservableSo /** * Returns an Observable that mirrors the source ObservableSource but applies a timeout policy for each emitted * item using a specified Scheduler. If the next item isn't emitted within the specified timeout duration - * starting from its predecessor, the resulting ObservableSource begins instead to mirror a fallback ObservableSource. + * starting from its predecessor, the source ObservableSource is disposed and resulting ObservableSource + * begins instead to mirror a fallback ObservableSource. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.2s.png" alt=""> * <dl> From a85ddd154087f634c2834851acff87a02d39a061 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 17 Jan 2019 14:41:02 +0100 Subject: [PATCH 334/417] 2.x: Add interruptible mode to Schedulers.from (#6370) --- .../schedulers/ExecutorScheduler.java | 139 +++- .../io/reactivex/schedulers/Schedulers.java | 73 +- .../ExecutorSchedulerInterruptibleTest.java | 664 ++++++++++++++++++ 3 files changed, 861 insertions(+), 15 deletions(-) create mode 100644 src/test/java/io/reactivex/schedulers/ExecutorSchedulerInterruptibleTest.java diff --git a/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java b/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java index 45e3c1850e..75322a8de8 100644 --- a/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java @@ -22,7 +22,7 @@ import io.reactivex.internal.disposables.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.queue.MpscLinkedQueue; -import io.reactivex.internal.schedulers.ExecutorScheduler.ExecutorWorker.BooleanRunnable; +import io.reactivex.internal.schedulers.ExecutorScheduler.ExecutorWorker.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; @@ -31,19 +31,22 @@ */ public final class ExecutorScheduler extends Scheduler { + final boolean interruptibleWorker; + @NonNull final Executor executor; static final Scheduler HELPER = Schedulers.single(); - public ExecutorScheduler(@NonNull Executor executor) { + public ExecutorScheduler(@NonNull Executor executor, boolean interruptibleWorker) { this.executor = executor; + this.interruptibleWorker = interruptibleWorker; } @NonNull @Override public Worker createWorker() { - return new ExecutorWorker(executor); + return new ExecutorWorker(executor, interruptibleWorker); } @NonNull @@ -58,9 +61,15 @@ public Disposable scheduleDirect(@NonNull Runnable run) { return task; } - BooleanRunnable br = new BooleanRunnable(decoratedRun); - executor.execute(br); - return br; + if (interruptibleWorker) { + InterruptibleRunnable interruptibleTask = new InterruptibleRunnable(decoratedRun, null); + executor.execute(interruptibleTask); + return interruptibleTask; + } else { + BooleanRunnable br = new BooleanRunnable(decoratedRun); + executor.execute(br); + return br; + } } catch (RejectedExecutionException ex) { RxJavaPlugins.onError(ex); return EmptyDisposable.INSTANCE; @@ -111,6 +120,9 @@ public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initial } /* public: test support. */ public static final class ExecutorWorker extends Scheduler.Worker implements Runnable { + + final boolean interruptibleWorker; + final Executor executor; final MpscLinkedQueue<Runnable> queue; @@ -121,9 +133,10 @@ public static final class ExecutorWorker extends Scheduler.Worker implements Run final CompositeDisposable tasks = new CompositeDisposable(); - public ExecutorWorker(Executor executor) { + public ExecutorWorker(Executor executor, boolean interruptibleWorker) { this.executor = executor; this.queue = new MpscLinkedQueue<Runnable>(); + this.interruptibleWorker = interruptibleWorker; } @NonNull @@ -134,9 +147,24 @@ public Disposable schedule(@NonNull Runnable run) { } Runnable decoratedRun = RxJavaPlugins.onSchedule(run); - BooleanRunnable br = new BooleanRunnable(decoratedRun); - queue.offer(br); + Runnable task; + Disposable disposable; + + if (interruptibleWorker) { + InterruptibleRunnable interruptibleTask = new InterruptibleRunnable(decoratedRun, tasks); + tasks.add(interruptibleTask); + + task = interruptibleTask; + disposable = interruptibleTask; + } else { + BooleanRunnable runnableTask = new BooleanRunnable(decoratedRun); + + task = runnableTask; + disposable = runnableTask; + } + + queue.offer(task); if (wip.getAndIncrement() == 0) { try { @@ -149,7 +177,7 @@ public Disposable schedule(@NonNull Runnable run) { } } - return br; + return disposable; } @NonNull @@ -288,6 +316,97 @@ public void run() { mar.replace(schedule(decoratedRun)); } } + + /** + * Wrapper for a {@link Runnable} with additional logic for handling interruption on + * a shared thread, similar to how Java Executors do it. + */ + static final class InterruptibleRunnable extends AtomicInteger implements Runnable, Disposable { + + private static final long serialVersionUID = -3603436687413320876L; + + final Runnable run; + + final DisposableContainer tasks; + + volatile Thread thread; + + static final int READY = 0; + + static final int RUNNING = 1; + + static final int FINISHED = 2; + + static final int INTERRUPTING = 3; + + static final int INTERRUPTED = 4; + + InterruptibleRunnable(Runnable run, DisposableContainer tasks) { + this.run = run; + this.tasks = tasks; + } + + @Override + public void run() { + if (get() == READY) { + thread = Thread.currentThread(); + if (compareAndSet(READY, RUNNING)) { + try { + run.run(); + } finally { + thread = null; + if (compareAndSet(RUNNING, FINISHED)) { + cleanup(); + } else { + while (get() == INTERRUPTING) { + Thread.yield(); + } + Thread.interrupted(); + } + } + } else { + thread = null; + } + } + } + + @Override + public void dispose() { + for (;;) { + int state = get(); + if (state >= FINISHED) { + break; + } else if (state == READY) { + if (compareAndSet(READY, INTERRUPTED)) { + cleanup(); + break; + } + } else { + if (compareAndSet(RUNNING, INTERRUPTING)) { + Thread t = thread; + if (t != null) { + t.interrupt(); + thread = null; + } + set(INTERRUPTED); + cleanup(); + break; + } + } + } + } + + void cleanup() { + if (tasks != null) { + tasks.delete(this); + } + } + + @Override + public boolean isDisposed() { + return get() >= FINISHED; + } + } } static final class DelayedRunnable extends AtomicReference<Runnable> diff --git a/src/main/java/io/reactivex/schedulers/Schedulers.java b/src/main/java/io/reactivex/schedulers/Schedulers.java index d3febba3ac..4edaf65b1a 100644 --- a/src/main/java/io/reactivex/schedulers/Schedulers.java +++ b/src/main/java/io/reactivex/schedulers/Schedulers.java @@ -13,13 +13,13 @@ package io.reactivex.schedulers; +import java.util.concurrent.*; + import io.reactivex.Scheduler; -import io.reactivex.annotations.NonNull; +import io.reactivex.annotations.*; import io.reactivex.internal.schedulers.*; import io.reactivex.plugins.RxJavaPlugins; -import java.util.concurrent.*; - /** * Static factory methods for returning standard Scheduler instances. * <p> @@ -299,6 +299,9 @@ public static Scheduler single() { * a time delay or periodically will use the {@link #single()} scheduler for the timed waiting * before posting the actual task to the given executor. * <p> + * Tasks submitted to the {@link Scheduler.Worker} of this {@code Scheduler} are also not interruptible. Use the + * {@link #from(Executor, boolean)} overload to enable task interruption via this wrapper. + * <p> * If the provided executor supports the standard Java {@link ExecutorService} API, * cancelling tasks scheduled by this scheduler can be cancelled/interrupted by calling * {@link io.reactivex.disposables.Disposable#dispose()}. In addition, tasks scheduled with @@ -329,7 +332,7 @@ public static Scheduler single() { * } * </code></pre> * <p> - * This type of scheduler is less sensitive to leaking {@link io.reactivex.Scheduler.Worker} instances, although + * This type of scheduler is less sensitive to leaking {@link Scheduler.Worker} instances, although * not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or * execute those tasks "unexpectedly". * <p> @@ -340,7 +343,67 @@ public static Scheduler single() { */ @NonNull public static Scheduler from(@NonNull Executor executor) { - return new ExecutorScheduler(executor); + return new ExecutorScheduler(executor, false); + } + + /** + * Wraps an {@link Executor} into a new Scheduler instance and delegates {@code schedule()} + * calls to it. + * <p> + * The tasks scheduled by the returned {@link Scheduler} and its {@link Scheduler.Worker} + * can be optionally interrupted. + * <p> + * If the provided executor doesn't support any of the more specific standard Java executor + * APIs, tasks scheduled with a time delay or periodically will use the + * {@link #single()} scheduler for the timed waiting + * before posting the actual task to the given executor. + * <p> + * If the provided executor supports the standard Java {@link ExecutorService} API, + * canceling tasks scheduled by this scheduler can be cancelled/interrupted by calling + * {@link io.reactivex.disposables.Disposable#dispose()}. In addition, tasks scheduled with + * a time delay or periodically will use the {@link #single()} scheduler for the timed waiting + * before posting the actual task to the given executor. + * <p> + * If the provided executor supports the standard Java {@link ScheduledExecutorService} API, + * canceling tasks scheduled by this scheduler can be cancelled/interrupted by calling + * {@link io.reactivex.disposables.Disposable#dispose()}. In addition, tasks scheduled with + * a time delay or periodically will use the provided executor. Note, however, if the provided + * {@code ScheduledExecutorService} instance is not single threaded, tasks scheduled + * with a time delay close to each other may end up executing in different order than + * the original schedule() call was issued. This limitation may be lifted in a future patch. + * <p> + * Starting, stopping and restarting this scheduler is not supported (no-op) and the provided + * executor's lifecycle must be managed externally: + * <pre><code> + * ExecutorService exec = Executors.newSingleThreadedExecutor(); + * try { + * Scheduler scheduler = Schedulers.from(exec, true); + * Flowable.just(1) + * .subscribeOn(scheduler) + * .map(v -> v + 1) + * .observeOn(scheduler) + * .blockingSubscribe(System.out::println); + * } finally { + * exec.shutdown(); + * } + * </code></pre> + * <p> + * This type of scheduler is less sensitive to leaking {@link Scheduler.Worker} instances, although + * not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or + * execute those tasks "unexpectedly". + * <p> + * Note that this method returns a new {@link Scheduler} instance, even for the same {@link Executor} instance. + * @param executor + * the executor to wrap + * @param interruptibleWorker if {@code true} the tasks submitted to the {@link Scheduler.Worker} will + * be interrupted when the task is disposed. + * @return the new Scheduler wrapping the Executor + * @since 2.2.6 - experimental + */ + @NonNull + @Experimental + public static Scheduler from(@NonNull Executor executor, boolean interruptibleWorker) { + return new ExecutorScheduler(executor, interruptibleWorker); } /** diff --git a/src/test/java/io/reactivex/schedulers/ExecutorSchedulerInterruptibleTest.java b/src/test/java/io/reactivex/schedulers/ExecutorSchedulerInterruptibleTest.java new file mode 100644 index 0000000000..bccca7524e --- /dev/null +++ b/src/test/java/io/reactivex/schedulers/ExecutorSchedulerInterruptibleTest.java @@ -0,0 +1,664 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.schedulers; + +import static org.junit.Assert.*; + +import java.lang.management.*; +import java.util.List; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; + +import org.junit.*; + +import io.reactivex.*; +import io.reactivex.Scheduler.Worker; +import io.reactivex.disposables.Disposable; +import io.reactivex.internal.disposables.EmptyDisposable; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.schedulers.*; +import io.reactivex.plugins.RxJavaPlugins; + +public class ExecutorSchedulerInterruptibleTest extends AbstractSchedulerConcurrencyTests { + + static final Executor executor = Executors.newFixedThreadPool(2, new RxThreadFactory("TestCustomPool")); + + @Override + protected Scheduler getScheduler() { + return Schedulers.from(executor, true); + } + + @Test + @Ignore("Unhandled errors are no longer thrown") + public final void testUnhandledErrorIsDeliveredToThreadHandler() throws InterruptedException { + SchedulerTestHelper.testUnhandledErrorIsDeliveredToThreadHandler(getScheduler()); + } + + @Test + public final void testHandledErrorIsNotDeliveredToThreadHandler() throws InterruptedException { + SchedulerTestHelper.testHandledErrorIsNotDeliveredToThreadHandler(getScheduler()); + } + + public static void testCancelledRetention(Scheduler.Worker w, boolean periodic) throws InterruptedException { + System.out.println("Wait before GC"); + Thread.sleep(1000); + + System.out.println("GC"); + System.gc(); + + Thread.sleep(1000); + + MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); + MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); + long initial = memHeap.getUsed(); + + System.out.printf("Starting: %.3f MB%n", initial / 1024.0 / 1024.0); + + int n = 100 * 1000; + if (periodic) { + final CountDownLatch cdl = new CountDownLatch(n); + final Runnable action = new Runnable() { + @Override + public void run() { + cdl.countDown(); + } + }; + for (int i = 0; i < n; i++) { + if (i % 50000 == 0) { + System.out.println(" -> still scheduling: " + i); + } + w.schedulePeriodically(action, 0, 1, TimeUnit.DAYS); + } + + System.out.println("Waiting for the first round to finish..."); + cdl.await(); + } else { + for (int i = 0; i < n; i++) { + if (i % 50000 == 0) { + System.out.println(" -> still scheduling: " + i); + } + w.schedule(Functions.EMPTY_RUNNABLE, 1, TimeUnit.DAYS); + } + } + + memHeap = memoryMXBean.getHeapMemoryUsage(); + long after = memHeap.getUsed(); + System.out.printf("Peak: %.3f MB%n", after / 1024.0 / 1024.0); + + w.dispose(); + + System.out.println("Wait before second GC"); + System.out.println("JDK 6 purge is N log N because it removes and shifts one by one"); + int t = (int)(n * Math.log(n) / 100) + SchedulerPoolFactory.PURGE_PERIOD_SECONDS * 1000; + while (t > 0) { + System.out.printf(" >> Waiting for purge: %.2f s remaining%n", t / 1000d); + + System.gc(); + + Thread.sleep(1000); + + t -= 1000; + memHeap = memoryMXBean.getHeapMemoryUsage(); + long finish = memHeap.getUsed(); + System.out.printf("After: %.3f MB%n", finish / 1024.0 / 1024.0); + if (finish <= initial * 5) { + break; + } + } + + System.out.println("Second GC"); + System.gc(); + + Thread.sleep(1000); + + memHeap = memoryMXBean.getHeapMemoryUsage(); + long finish = memHeap.getUsed(); + System.out.printf("After: %.3f MB%n", finish / 1024.0 / 1024.0); + + if (finish > initial * 5) { + fail(String.format("Tasks retained: %.3f -> %.3f -> %.3f", initial / 1024 / 1024.0, after / 1024 / 1024.0, finish / 1024 / 1024d)); + } + } + + @Test(timeout = 60000) + public void testCancelledTaskRetention() throws InterruptedException { + ExecutorService exec = Executors.newSingleThreadExecutor(); + Scheduler s = Schedulers.from(exec, true); + try { + Scheduler.Worker w = s.createWorker(); + try { + testCancelledRetention(w, false); + } finally { + w.dispose(); + } + + w = s.createWorker(); + try { + testCancelledRetention(w, true); + } finally { + w.dispose(); + } + } finally { + exec.shutdownNow(); + } + } + + /** A simple executor which queues tasks and executes them one-by-one if executeOne() is called. */ + static final class TestExecutor implements Executor { + final ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<Runnable>(); + @Override + public void execute(Runnable command) { + queue.offer(command); + } + public void executeOne() { + Runnable r = queue.poll(); + if (r != null) { + r.run(); + } + } + public void executeAll() { + Runnable r; + while ((r = queue.poll()) != null) { + r.run(); + } + } + } + + @Test + public void testCancelledTasksDontRun() { + final AtomicInteger calls = new AtomicInteger(); + Runnable task = new Runnable() { + @Override + public void run() { + calls.getAndIncrement(); + } + }; + TestExecutor exec = new TestExecutor(); + Scheduler custom = Schedulers.from(exec, true); + Worker w = custom.createWorker(); + try { + Disposable d1 = w.schedule(task); + Disposable d2 = w.schedule(task); + Disposable d3 = w.schedule(task); + + d1.dispose(); + d2.dispose(); + d3.dispose(); + + exec.executeAll(); + + assertEquals(0, calls.get()); + } finally { + w.dispose(); + } + } + + @Test + public void testCancelledWorkerDoesntRunTasks() { + final AtomicInteger calls = new AtomicInteger(); + Runnable task = new Runnable() { + @Override + public void run() { + calls.getAndIncrement(); + } + }; + TestExecutor exec = new TestExecutor(); + Scheduler custom = Schedulers.from(exec, true); + Worker w = custom.createWorker(); + try { + w.schedule(task); + w.schedule(task); + w.schedule(task); + } finally { + w.dispose(); + } + exec.executeAll(); + assertEquals(0, calls.get()); + } + + // FIXME the internal structure changed and these can't be tested +// +// @Test +// public void testNoTimedTaskAfterScheduleRetention() throws InterruptedException { +// Executor e = new Executor() { +// @Override +// public void execute(Runnable command) { +// command.run(); +// } +// }; +// ExecutorWorker w = (ExecutorWorker)Schedulers.from(e, true).createWorker(); +// +// w.schedule(Functions.emptyRunnable(), 50, TimeUnit.MILLISECONDS); +// +// assertTrue(w.tasks.hasSubscriptions()); +// +// Thread.sleep(150); +// +// assertFalse(w.tasks.hasSubscriptions()); +// } +// +// @Test +// public void testNoTimedTaskPartRetention() { +// Executor e = new Executor() { +// @Override +// public void execute(Runnable command) { +// +// } +// }; +// ExecutorWorker w = (ExecutorWorker)Schedulers.from(e, true).createWorker(); +// +// Disposable task = w.schedule(Functions.emptyRunnable(), 1, TimeUnit.DAYS); +// +// assertTrue(w.tasks.hasSubscriptions()); +// +// task.dispose(); +// +// assertFalse(w.tasks.hasSubscriptions()); +// } +// +// @Test +// public void testNoPeriodicTimedTaskPartRetention() throws InterruptedException { +// Executor e = new Executor() { +// @Override +// public void execute(Runnable command) { +// command.run(); +// } +// }; +// ExecutorWorker w = (ExecutorWorker)Schedulers.from(e, true).createWorker(); +// +// final CountDownLatch cdl = new CountDownLatch(1); +// final Runnable action = new Runnable() { +// @Override +// public void run() { +// cdl.countDown(); +// } +// }; +// +// Disposable task = w.schedulePeriodically(action, 0, 1, TimeUnit.DAYS); +// +// assertTrue(w.tasks.hasSubscriptions()); +// +// cdl.await(); +// +// task.dispose(); +// +// assertFalse(w.tasks.hasSubscriptions()); +// } + + @Test + public void plainExecutor() throws Exception { + Scheduler s = Schedulers.from(new Executor() { + @Override + public void execute(Runnable r) { + r.run(); + } + }, true); + + final CountDownLatch cdl = new CountDownLatch(5); + + Runnable r = new Runnable() { + @Override + public void run() { + cdl.countDown(); + } + }; + + s.scheduleDirect(r); + + s.scheduleDirect(r, 50, TimeUnit.MILLISECONDS); + + Disposable d = s.schedulePeriodicallyDirect(r, 10, 10, TimeUnit.MILLISECONDS); + + try { + assertTrue(cdl.await(5, TimeUnit.SECONDS)); + } finally { + d.dispose(); + } + + assertTrue(d.isDisposed()); + } + + @Test + public void rejectingExecutor() { + ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); + exec.shutdown(); + + Scheduler s = Schedulers.from(exec, true); + + List<Throwable> errors = TestHelper.trackPluginErrors(); + + try { + assertSame(EmptyDisposable.INSTANCE, s.scheduleDirect(Functions.EMPTY_RUNNABLE)); + + assertSame(EmptyDisposable.INSTANCE, s.scheduleDirect(Functions.EMPTY_RUNNABLE, 10, TimeUnit.MILLISECONDS)); + + assertSame(EmptyDisposable.INSTANCE, s.schedulePeriodicallyDirect(Functions.EMPTY_RUNNABLE, 10, 10, TimeUnit.MILLISECONDS)); + + TestHelper.assertUndeliverable(errors, 0, RejectedExecutionException.class); + TestHelper.assertUndeliverable(errors, 1, RejectedExecutionException.class); + TestHelper.assertUndeliverable(errors, 2, RejectedExecutionException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void rejectingExecutorWorker() { + ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); + exec.shutdown(); + + List<Throwable> errors = TestHelper.trackPluginErrors(); + + try { + Worker s = Schedulers.from(exec, true).createWorker(); + assertSame(EmptyDisposable.INSTANCE, s.schedule(Functions.EMPTY_RUNNABLE)); + + s = Schedulers.from(exec, true).createWorker(); + assertSame(EmptyDisposable.INSTANCE, s.schedule(Functions.EMPTY_RUNNABLE, 10, TimeUnit.MILLISECONDS)); + + s = Schedulers.from(exec, true).createWorker(); + assertSame(EmptyDisposable.INSTANCE, s.schedulePeriodically(Functions.EMPTY_RUNNABLE, 10, 10, TimeUnit.MILLISECONDS)); + + TestHelper.assertUndeliverable(errors, 0, RejectedExecutionException.class); + TestHelper.assertUndeliverable(errors, 1, RejectedExecutionException.class); + TestHelper.assertUndeliverable(errors, 2, RejectedExecutionException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void reuseScheduledExecutor() throws Exception { + ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); + + try { + Scheduler s = Schedulers.from(exec, true); + + final CountDownLatch cdl = new CountDownLatch(8); + + Runnable r = new Runnable() { + @Override + public void run() { + cdl.countDown(); + } + }; + + s.scheduleDirect(r); + + s.scheduleDirect(r, 10, TimeUnit.MILLISECONDS); + + Disposable d = s.schedulePeriodicallyDirect(r, 10, 10, TimeUnit.MILLISECONDS); + + try { + assertTrue(cdl.await(5, TimeUnit.SECONDS)); + } finally { + d.dispose(); + } + } finally { + exec.shutdown(); + } + } + + @Test + public void reuseScheduledExecutorAsWorker() throws Exception { + ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); + + Worker s = Schedulers.from(exec, true).createWorker(); + + assertFalse(s.isDisposed()); + try { + + final CountDownLatch cdl = new CountDownLatch(8); + + Runnable r = new Runnable() { + @Override + public void run() { + cdl.countDown(); + } + }; + + s.schedule(r); + + s.schedule(r, 10, TimeUnit.MILLISECONDS); + + Disposable d = s.schedulePeriodically(r, 10, 10, TimeUnit.MILLISECONDS); + + try { + assertTrue(cdl.await(5, TimeUnit.SECONDS)); + } finally { + d.dispose(); + } + } finally { + s.dispose(); + exec.shutdown(); + } + + assertTrue(s.isDisposed()); + } + + @Test + public void disposeRace() { + ExecutorService exec = Executors.newSingleThreadExecutor(); + final Scheduler s = Schedulers.from(exec, true); + try { + for (int i = 0; i < 500; i++) { + final Worker w = s.createWorker(); + + final AtomicInteger c = new AtomicInteger(2); + + w.schedule(new Runnable() { + @Override + public void run() { + c.decrementAndGet(); + while (c.get() != 0) { } + } + }); + + c.decrementAndGet(); + while (c.get() != 0) { } + w.dispose(); + } + } finally { + exec.shutdownNow(); + } + } + + @Test + public void runnableDisposed() { + final Scheduler s = Schedulers.from(new Executor() { + @Override + public void execute(Runnable r) { + r.run(); + } + }, true); + Disposable d = s.scheduleDirect(Functions.EMPTY_RUNNABLE); + + assertTrue(d.isDisposed()); + } + + @Test(timeout = 1000) + public void runnableDisposedAsync() throws Exception { + final Scheduler s = Schedulers.from(new Executor() { + @Override + public void execute(Runnable r) { + new Thread(r).start(); + } + }, true); + Disposable d = s.scheduleDirect(Functions.EMPTY_RUNNABLE); + + while (!d.isDisposed()) { + Thread.sleep(1); + } + } + + @Test(timeout = 1000) + public void runnableDisposedAsync2() throws Exception { + final Scheduler s = Schedulers.from(executor, true); + Disposable d = s.scheduleDirect(Functions.EMPTY_RUNNABLE); + + while (!d.isDisposed()) { + Thread.sleep(1); + } + } + + @Test(timeout = 1000) + public void runnableDisposedAsyncCrash() throws Exception { + final Scheduler s = Schedulers.from(new Executor() { + @Override + public void execute(Runnable r) { + new Thread(r).start(); + } + }, true); + Disposable d = s.scheduleDirect(new Runnable() { + @Override + public void run() { + throw new IllegalStateException(); + } + }); + + while (!d.isDisposed()) { + Thread.sleep(1); + } + } + + @Test(timeout = 1000) + public void runnableDisposedAsyncTimed() throws Exception { + final Scheduler s = Schedulers.from(new Executor() { + @Override + public void execute(Runnable r) { + new Thread(r).start(); + } + }, true); + Disposable d = s.scheduleDirect(Functions.EMPTY_RUNNABLE, 1, TimeUnit.MILLISECONDS); + + while (!d.isDisposed()) { + Thread.sleep(1); + } + } + + @Test(timeout = 1000) + public void runnableDisposedAsyncTimed2() throws Exception { + ExecutorService executorScheduler = Executors.newScheduledThreadPool(1, new RxThreadFactory("TestCustomPoolTimed")); + try { + final Scheduler s = Schedulers.from(executorScheduler, true); + Disposable d = s.scheduleDirect(Functions.EMPTY_RUNNABLE, 1, TimeUnit.MILLISECONDS); + + while (!d.isDisposed()) { + Thread.sleep(1); + } + } finally { + executorScheduler.shutdownNow(); + } + } + + @Test + public void unwrapScheduleDirectTaskAfterDispose() { + Scheduler scheduler = getScheduler(); + final CountDownLatch cdl = new CountDownLatch(1); + Runnable countDownRunnable = new Runnable() { + @Override + public void run() { + cdl.countDown(); + } + }; + Disposable disposable = scheduler.scheduleDirect(countDownRunnable, 100, TimeUnit.MILLISECONDS); + SchedulerRunnableIntrospection wrapper = (SchedulerRunnableIntrospection) disposable; + assertSame(countDownRunnable, wrapper.getWrappedRunnable()); + disposable.dispose(); + + assertSame(Functions.EMPTY_RUNNABLE, wrapper.getWrappedRunnable()); + } + + @Test(timeout = 10000) + public void interruptibleDirectTask() throws Exception { + Scheduler scheduler = getScheduler(); + + final AtomicInteger sync = new AtomicInteger(2); + + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + Disposable d = scheduler.scheduleDirect(new Runnable() { + @Override + public void run() { + if (sync.decrementAndGet() != 0) { + while (sync.get() != 0) { } + } + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + } + }); + + if (sync.decrementAndGet() != 0) { + while (sync.get() != 0) { } + } + + Thread.sleep(500); + + d.dispose(); + + int i = 20; + while (i-- > 0 && !isInterrupted.get()) { + Thread.sleep(50); + } + + assertTrue("Interruption did not propagate", isInterrupted.get()); + } + + @Test(timeout = 10000) + public void interruptibleWorkerTask() throws Exception { + Scheduler scheduler = getScheduler(); + + Worker worker = scheduler.createWorker(); + + try { + final AtomicInteger sync = new AtomicInteger(2); + + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + Disposable d = worker.schedule(new Runnable() { + @Override + public void run() { + if (sync.decrementAndGet() != 0) { + while (sync.get() != 0) { } + } + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + } + }); + + if (sync.decrementAndGet() != 0) { + while (sync.get() != 0) { } + } + + Thread.sleep(500); + + d.dispose(); + + int i = 20; + while (i-- > 0 && !isInterrupted.get()) { + Thread.sleep(50); + } + + assertTrue("Interruption did not propagate", isInterrupted.get()); + } finally { + worker.dispose(); + } + } +} From 5106a20e0a2aa45763ac5c6726d6ff86a125d665 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 17 Jan 2019 15:02:36 +0100 Subject: [PATCH 335/417] 2.x: Fix bounded replay() memory leak due to bad node retention (#6371) --- .../operators/flowable/FlowableReplay.java | 4 ++ .../observable/ObservableReplay.java | 3 + .../flowable/FlowableReplayTest.java | 64 ++++++++++++++++++ .../observable/ObservableReplayTest.java | 67 ++++++++++++++++++- .../processors/ReplayProcessorTest.java | 65 +++++++++++++++++- .../reactivex/subjects/ReplaySubjectTest.java | 65 +++++++++++++++++- 6 files changed, 260 insertions(+), 8 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java index 21b1b1d39c..7a02482b4b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java @@ -566,6 +566,8 @@ public void dispose() { // the others had non-zero. By removing this 'blocking' child, the others // are now free to receive events parent.manageRequests(); + // make sure the last known node is not retained + index = null; } } /** @@ -824,6 +826,7 @@ public final void replay(InnerSubscription<T> output) { } for (;;) { if (output.isDisposed()) { + output.index = null; return; } @@ -864,6 +867,7 @@ public final void replay(InnerSubscription<T> output) { break; } if (output.isDisposed()) { + output.index = null; return; } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java index 89db184d6b..197ada9706 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java @@ -453,6 +453,8 @@ public void dispose() { cancelled = true; // remove this from the parent parent.remove(this); + // make sure the last known node is not retained + index = null; } } /** @@ -686,6 +688,7 @@ public final void replay(InnerDisposable<T> output) { for (;;) { if (output.isDisposed()) { + output.index = null; return; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index dcf7eea347..b3bea718bd 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -17,6 +17,7 @@ import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; +import java.lang.management.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; @@ -1976,4 +1977,67 @@ public void currentDisposedWhenConnecting() { assertFalse(fr.current.get().isDisposed()); } + + @Test + public void noBoundedRetentionViaThreadLocal() throws Exception { + Flowable<byte[]> source = Flowable.range(1, 200) + .map(new Function<Integer, byte[]>() { + @Override + public byte[] apply(Integer v) throws Exception { + return new byte[1024 * 1024]; + } + }) + .replay(new Function<Flowable<byte[]>, Publisher<byte[]>>() { + @Override + public Publisher<byte[]> apply(final Flowable<byte[]> f) throws Exception { + return f.take(1) + .concatMap(new Function<byte[], Publisher<byte[]>>() { + @Override + public Publisher<byte[]> apply(byte[] v) throws Exception { + return f; + } + }); + } + }, 1) + .takeLast(1) + ; + + System.out.println("Bounded Replay Leak check: Wait before GC"); + Thread.sleep(1000); + + System.out.println("Bounded Replay Leak check: GC"); + System.gc(); + + Thread.sleep(500); + + final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); + MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); + long initial = memHeap.getUsed(); + + System.out.printf("Bounded Replay Leak check: Starting: %.3f MB%n", initial / 1024.0 / 1024.0); + + final AtomicLong after = new AtomicLong(); + + source.subscribe(new Consumer<byte[]>() { + @Override + public void accept(byte[] v) throws Exception { + System.out.println("Bounded Replay Leak check: Wait before GC 2"); + Thread.sleep(1000); + + System.out.println("Bounded Replay Leak check: GC 2"); + System.gc(); + + Thread.sleep(500); + + after.set(memoryMXBean.getHeapMemoryUsage().getUsed()); + } + }); + + System.out.printf("Bounded Replay Leak check: After: %.3f MB%n", after.get() / 1024.0 / 1024.0); + + if (initial + 100 * 1024 * 1024 < after.get()) { + Assert.fail("Bounded Replay Leak check: Memory leak detected: " + (initial / 1024.0 / 1024.0) + + " -> " + after.get() / 1024.0 / 1024.0); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java index 2592361cd6..40d09f4f33 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java @@ -17,9 +17,10 @@ import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; +import java.lang.management.*; import java.util.*; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.*; import org.junit.*; import org.mockito.InOrder; @@ -1713,4 +1714,66 @@ public void noHeadRetentionTime() { assertSame(o, buf.get()); } -} + + @Test + public void noBoundedRetentionViaThreadLocal() throws Exception { + Observable<byte[]> source = Observable.range(1, 200) + .map(new Function<Integer, byte[]>() { + @Override + public byte[] apply(Integer v) throws Exception { + return new byte[1024 * 1024]; + } + }) + .replay(new Function<Observable<byte[]>, Observable<byte[]>>() { + @Override + public Observable<byte[]> apply(final Observable<byte[]> o) throws Exception { + return o.take(1) + .concatMap(new Function<byte[], Observable<byte[]>>() { + @Override + public Observable<byte[]> apply(byte[] v) throws Exception { + return o; + } + }); + } + }, 1) + .takeLast(1) + ; + + System.out.println("Bounded Replay Leak check: Wait before GC"); + Thread.sleep(1000); + + System.out.println("Bounded Replay Leak check: GC"); + System.gc(); + + Thread.sleep(500); + + final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); + MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); + long initial = memHeap.getUsed(); + + System.out.printf("Bounded Replay Leak check: Starting: %.3f MB%n", initial / 1024.0 / 1024.0); + + final AtomicLong after = new AtomicLong(); + + source.subscribe(new Consumer<byte[]>() { + @Override + public void accept(byte[] v) throws Exception { + System.out.println("Bounded Replay Leak check: Wait before GC 2"); + Thread.sleep(1000); + + System.out.println("Bounded Replay Leak check: GC 2"); + System.gc(); + + Thread.sleep(500); + + after.set(memoryMXBean.getHeapMemoryUsage().getUsed()); + } + }); + + System.out.printf("Bounded Replay Leak check: After: %.3f MB%n", after.get() / 1024.0 / 1024.0); + + if (initial + 100 * 1024 * 1024 < after.get()) { + Assert.fail("Bounded Replay Leak check: Memory leak detected: " + (initial / 1024.0 / 1024.0) + + " -> " + after.get() / 1024.0 / 1024.0); + } + }} diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index 810e80d9e5..cf930b062a 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -17,18 +17,19 @@ import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; +import java.lang.management.*; import java.util.Arrays; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.*; -import org.junit.Test; +import org.junit.*; import org.mockito.*; import org.reactivestreams.*; import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.TestException; -import io.reactivex.functions.Function; +import io.reactivex.functions.*; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.processors.ReplayProcessor.*; import io.reactivex.schedulers.*; @@ -1692,4 +1693,62 @@ public void noHeadRetentionTime() { public void invalidRequest() { TestHelper.assertBadRequestReported(ReplayProcessor.create()); } + + @Test + public void noBoundedRetentionViaThreadLocal() throws Exception { + final ReplayProcessor<byte[]> rp = ReplayProcessor.createWithSize(1); + + Flowable<byte[]> source = rp.take(1) + .concatMap(new Function<byte[], Publisher<byte[]>>() { + @Override + public Publisher<byte[]> apply(byte[] v) throws Exception { + return rp; + } + }) + .takeLast(1) + ; + + System.out.println("Bounded Replay Leak check: Wait before GC"); + Thread.sleep(1000); + + System.out.println("Bounded Replay Leak check: GC"); + System.gc(); + + Thread.sleep(500); + + final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); + MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); + long initial = memHeap.getUsed(); + + System.out.printf("Bounded Replay Leak check: Starting: %.3f MB%n", initial / 1024.0 / 1024.0); + + final AtomicLong after = new AtomicLong(); + + source.subscribe(new Consumer<byte[]>() { + @Override + public void accept(byte[] v) throws Exception { + System.out.println("Bounded Replay Leak check: Wait before GC 2"); + Thread.sleep(1000); + + System.out.println("Bounded Replay Leak check: GC 2"); + System.gc(); + + Thread.sleep(500); + + after.set(memoryMXBean.getHeapMemoryUsage().getUsed()); + } + }); + + for (int i = 0; i < 200; i++) { + rp.onNext(new byte[1024 * 1024]); + } + rp.onComplete(); + + System.out.printf("Bounded Replay Leak check: After: %.3f MB%n", after.get() / 1024.0 / 1024.0); + + if (initial + 100 * 1024 * 1024 < after.get()) { + Assert.fail("Bounded Replay Leak check: Memory leak detected: " + (initial / 1024.0 / 1024.0) + + " -> " + after.get() / 1024.0 / 1024.0); + } + } } diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java index 2326241cfd..aa91270226 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java @@ -17,17 +17,18 @@ import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; +import java.lang.management.*; import java.util.Arrays; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.*; -import org.junit.Test; +import org.junit.*; import org.mockito.*; import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; -import io.reactivex.functions.Function; +import io.reactivex.functions.*; import io.reactivex.observers.*; import io.reactivex.schedulers.*; import io.reactivex.subjects.ReplaySubject.*; @@ -1284,4 +1285,62 @@ public void noHeadRetentionTime() { assertSame(o, buf.head); } + + @Test + public void noBoundedRetentionViaThreadLocal() throws Exception { + final ReplaySubject<byte[]> rs = ReplaySubject.createWithSize(1); + + Observable<byte[]> source = rs.take(1) + .concatMap(new Function<byte[], Observable<byte[]>>() { + @Override + public Observable<byte[]> apply(byte[] v) throws Exception { + return rs; + } + }) + .takeLast(1) + ; + + System.out.println("Bounded Replay Leak check: Wait before GC"); + Thread.sleep(1000); + + System.out.println("Bounded Replay Leak check: GC"); + System.gc(); + + Thread.sleep(500); + + final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); + MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); + long initial = memHeap.getUsed(); + + System.out.printf("Bounded Replay Leak check: Starting: %.3f MB%n", initial / 1024.0 / 1024.0); + + final AtomicLong after = new AtomicLong(); + + source.subscribe(new Consumer<byte[]>() { + @Override + public void accept(byte[] v) throws Exception { + System.out.println("Bounded Replay Leak check: Wait before GC 2"); + Thread.sleep(1000); + + System.out.println("Bounded Replay Leak check: GC 2"); + System.gc(); + + Thread.sleep(500); + + after.set(memoryMXBean.getHeapMemoryUsage().getUsed()); + } + }); + + for (int i = 0; i < 200; i++) { + rs.onNext(new byte[1024 * 1024]); + } + rs.onComplete(); + + System.out.printf("Bounded Replay Leak check: After: %.3f MB%n", after.get() / 1024.0 / 1024.0); + + if (initial + 100 * 1024 * 1024 < after.get()) { + Assert.fail("Bounded Replay Leak check: Memory leak detected: " + (initial / 1024.0 / 1024.0) + + " -> " + after.get() / 1024.0 / 1024.0); + } + } } From d40f923efe6b867d71412858b11f4344c1f0883a Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 17 Jan 2019 15:28:30 +0100 Subject: [PATCH 336/417] 2.x: Don't dispose the winner of {Single|Maybe|Completable}.amb() (#6375) * 2.x: Don't dispose the winner of {Single|Maybe|Completable}.amb() * Add null-source test to MaybeAmbTest --- .../operators/completable/CompletableAmb.java | 19 ++- .../internal/operators/maybe/MaybeAmb.java | 56 ++++---- .../internal/operators/single/SingleAmb.java | 26 ++-- .../completable/CompletableAmbTest.java | 55 ++++++++ .../operators/flowable/FlowableAmbTest.java | 84 +++++++++++- .../operators/maybe/MaybeAmbTest.java | 124 ++++++++++++++++++ .../observable/ObservableAmbTest.java | 87 +++++++++++- .../operators/single/SingleAmbTest.java | 61 +++++++++ 8 files changed, 462 insertions(+), 50 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableAmb.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableAmb.java index cc603acbdc..7de1c648e4 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableAmb.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableAmb.java @@ -63,8 +63,6 @@ public void subscribeActual(final CompletableObserver observer) { final AtomicBoolean once = new AtomicBoolean(); - CompletableObserver inner = new Amb(once, set, observer); - for (int i = 0; i < count; i++) { CompletableSource c = sources[i]; if (set.isDisposed()) { @@ -82,7 +80,7 @@ public void subscribeActual(final CompletableObserver observer) { } // no need to have separate subscribers because inner is stateless - c.subscribe(inner); + c.subscribe(new Amb(once, set, observer)); } if (count == 0) { @@ -91,9 +89,14 @@ public void subscribeActual(final CompletableObserver observer) { } static final class Amb implements CompletableObserver { - private final AtomicBoolean once; - private final CompositeDisposable set; - private final CompletableObserver downstream; + + final AtomicBoolean once; + + final CompositeDisposable set; + + final CompletableObserver downstream; + + Disposable upstream; Amb(AtomicBoolean once, CompositeDisposable set, CompletableObserver observer) { this.once = once; @@ -104,6 +107,7 @@ static final class Amb implements CompletableObserver { @Override public void onComplete() { if (once.compareAndSet(false, true)) { + set.delete(upstream); set.dispose(); downstream.onComplete(); } @@ -112,6 +116,7 @@ public void onComplete() { @Override public void onError(Throwable e) { if (once.compareAndSet(false, true)) { + set.delete(upstream); set.dispose(); downstream.onError(e); } else { @@ -121,8 +126,8 @@ public void onError(Throwable e) { @Override public void onSubscribe(Disposable d) { + upstream = d; set.add(d); } - } } diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java index d9c1c6963c..8efc69b24b 100644 --- a/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeAmb.java @@ -64,64 +64,63 @@ protected void subscribeActual(MaybeObserver<? super T> observer) { count = sources.length; } - AmbMaybeObserver<T> parent = new AmbMaybeObserver<T>(observer); - observer.onSubscribe(parent); + CompositeDisposable set = new CompositeDisposable(); + observer.onSubscribe(set); + + AtomicBoolean winner = new AtomicBoolean(); for (int i = 0; i < count; i++) { MaybeSource<? extends T> s = sources[i]; - if (parent.isDisposed()) { + if (set.isDisposed()) { return; } if (s == null) { - parent.onError(new NullPointerException("One of the MaybeSources is null")); + set.dispose(); + NullPointerException ex = new NullPointerException("One of the MaybeSources is null"); + if (winner.compareAndSet(false, true)) { + observer.onError(ex); + } else { + RxJavaPlugins.onError(ex); + } return; } - s.subscribe(parent); + s.subscribe(new AmbMaybeObserver<T>(observer, set, winner)); } if (count == 0) { observer.onComplete(); } - } static final class AmbMaybeObserver<T> - extends AtomicBoolean - implements MaybeObserver<T>, Disposable { - - private static final long serialVersionUID = -7044685185359438206L; + implements MaybeObserver<T> { final MaybeObserver<? super T> downstream; - final CompositeDisposable set; + final AtomicBoolean winner; - AmbMaybeObserver(MaybeObserver<? super T> downstream) { - this.downstream = downstream; - this.set = new CompositeDisposable(); - } + final CompositeDisposable set; - @Override - public void dispose() { - if (compareAndSet(false, true)) { - set.dispose(); - } - } + Disposable upstream; - @Override - public boolean isDisposed() { - return get(); + AmbMaybeObserver(MaybeObserver<? super T> downstream, CompositeDisposable set, AtomicBoolean winner) { + this.downstream = downstream; + this.set = set; + this.winner = winner; } @Override public void onSubscribe(Disposable d) { + upstream = d; set.add(d); } @Override public void onSuccess(T value) { - if (compareAndSet(false, true)) { + if (winner.compareAndSet(false, true)) { + set.delete(upstream); set.dispose(); downstream.onSuccess(value); @@ -130,7 +129,8 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - if (compareAndSet(false, true)) { + if (winner.compareAndSet(false, true)) { + set.delete(upstream); set.dispose(); downstream.onError(e); @@ -141,12 +141,12 @@ public void onError(Throwable e) { @Override public void onComplete() { - if (compareAndSet(false, true)) { + if (winner.compareAndSet(false, true)) { + set.delete(upstream); set.dispose(); downstream.onComplete(); } } - } } diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleAmb.java b/src/main/java/io/reactivex/internal/operators/single/SingleAmb.java index d7508c3a72..2584506b59 100644 --- a/src/main/java/io/reactivex/internal/operators/single/SingleAmb.java +++ b/src/main/java/io/reactivex/internal/operators/single/SingleAmb.java @@ -59,21 +59,21 @@ protected void subscribeActual(final SingleObserver<? super T> observer) { count = sources.length; } + final AtomicBoolean winner = new AtomicBoolean(); final CompositeDisposable set = new CompositeDisposable(); - AmbSingleObserver<T> shared = new AmbSingleObserver<T>(observer, set); observer.onSubscribe(set); for (int i = 0; i < count; i++) { SingleSource<? extends T> s1 = sources[i]; - if (shared.get()) { + if (set.isDisposed()) { return; } if (s1 == null) { set.dispose(); Throwable e = new NullPointerException("One of the sources is null"); - if (shared.compareAndSet(false, true)) { + if (winner.compareAndSet(false, true)) { observer.onError(e); } else { RxJavaPlugins.onError(e); @@ -81,31 +81,36 @@ protected void subscribeActual(final SingleObserver<? super T> observer) { return; } - s1.subscribe(shared); + s1.subscribe(new AmbSingleObserver<T>(observer, set, winner)); } } - static final class AmbSingleObserver<T> extends AtomicBoolean implements SingleObserver<T> { - - private static final long serialVersionUID = -1944085461036028108L; + static final class AmbSingleObserver<T> implements SingleObserver<T> { final CompositeDisposable set; final SingleObserver<? super T> downstream; - AmbSingleObserver(SingleObserver<? super T> observer, CompositeDisposable set) { + final AtomicBoolean winner; + + Disposable upstream; + + AmbSingleObserver(SingleObserver<? super T> observer, CompositeDisposable set, AtomicBoolean winner) { this.downstream = observer; this.set = set; + this.winner = winner; } @Override public void onSubscribe(Disposable d) { + this.upstream = d; set.add(d); } @Override public void onSuccess(T value) { - if (compareAndSet(false, true)) { + if (winner.compareAndSet(false, true)) { + set.delete(upstream); set.dispose(); downstream.onSuccess(value); } @@ -113,7 +118,8 @@ public void onSuccess(T value) { @Override public void onError(Throwable e) { - if (compareAndSet(false, true)) { + if (winner.compareAndSet(false, true)) { + set.delete(upstream); set.dispose(); downstream.onError(e); } else { diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java index 0e45cd1c1b..f4a8a084b8 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java @@ -16,6 +16,7 @@ import static org.junit.Assert.*; import java.util.*; +import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; @@ -23,10 +24,13 @@ import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.internal.operators.completable.CompletableAmb.Amb; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; +import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.*; public class CompletableAmbTest { @@ -173,6 +177,7 @@ public void ambRace() { CompositeDisposable cd = new CompositeDisposable(); AtomicBoolean once = new AtomicBoolean(); Amb a = new Amb(once, cd, to); + a.onSubscribe(Disposables.empty()); a.onComplete(); a.onComplete(); @@ -259,4 +264,54 @@ public void untilCompletableOtherError() { to.assertFailure(TestException.class); } + @Test + public void noWinnerErrorDispose() throws Exception { + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Completable.ambArray( + Completable.error(ex) + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Completable.never() + ) + .subscribe(Functions.EMPTY_ACTION, new Consumer<Throwable>() { + @Override + public void accept(Throwable e) throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } + + @Test + public void noWinnerCompleteDispose() throws Exception { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Completable.ambArray( + Completable.complete() + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Completable.never() + ) + .subscribe(new Action() { + @Override + public void run() throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java index a4b03c633c..5b5941fbf4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java @@ -19,8 +19,8 @@ import java.io.IOException; import java.lang.reflect.Method; import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; import org.junit.*; import org.mockito.InOrder; @@ -30,6 +30,7 @@ import io.reactivex.disposables.CompositeDisposable; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.internal.util.CrashingMappedIterable; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; @@ -713,4 +714,83 @@ public void ambArrayOrder() { Flowable<Integer> error = Flowable.error(new RuntimeException()); Flowable.ambArray(Flowable.just(1), error).test().assertValue(1).assertComplete(); } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerSuccessDispose() throws Exception { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Flowable.ambArray( + Flowable.just(1) + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Flowable.never() + ) + .subscribe(new Consumer<Object>() { + @Override + public void accept(Object v) throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerErrorDispose() throws Exception { + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Flowable.ambArray( + Flowable.error(ex) + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Flowable.never() + ) + .subscribe(Functions.emptyConsumer(), new Consumer<Throwable>() { + @Override + public void accept(Throwable e) throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerCompleteDispose() throws Exception { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Flowable.ambArray( + Flowable.empty() + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Flowable.never() + ) + .subscribe(Functions.emptyConsumer(), Functions.emptyConsumer(), new Action() { + @Override + public void run() throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java index a50c685233..a701a279ab 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java @@ -16,15 +16,21 @@ import static org.junit.Assert.*; import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import io.reactivex.*; import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.subjects.*; public class MaybeAmbTest { @@ -129,4 +135,122 @@ protected void subscribeActual( to.assertResult(1); } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerSuccessDispose() throws Exception { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Maybe.ambArray( + Maybe.just(1) + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Maybe.never() + ) + .subscribe(new Consumer<Object>() { + @Override + public void accept(Object v) throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerErrorDispose() throws Exception { + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Maybe.ambArray( + Maybe.error(ex) + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Maybe.never() + ) + .subscribe(Functions.emptyConsumer(), new Consumer<Throwable>() { + @Override + public void accept(Throwable e) throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerCompleteDispose() throws Exception { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Maybe.ambArray( + Maybe.empty() + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Maybe.never() + ) + .subscribe(Functions.emptyConsumer(), Functions.emptyConsumer(), new Action() { + @Override + public void run() throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } + + @Test + public void nullSourceSuccessRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + List<Throwable> errors = TestHelper.trackPluginErrors(); + + try { + + final Subject<Integer> ps = ReplaySubject.create(); + ps.onNext(1); + + @SuppressWarnings("unchecked") + final Maybe<Integer> source = Maybe.ambArray(ps.singleElement(), + Maybe.<Integer>never(), Maybe.<Integer>never(), null); + + Runnable r1 = new Runnable() { + @Override + public void run() { + source.test(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ps.onComplete(); + } + }; + + TestHelper.race(r1, r2); + + if (!errors.isEmpty()) { + TestHelper.assertError(errors, 0, NullPointerException.class); + } + } finally { + RxJavaPlugins.reset(); + } + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java index ee4d58adf5..6e2c737f75 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java @@ -18,8 +18,8 @@ import java.io.IOException; import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; import org.junit.*; import org.mockito.InOrder; @@ -29,7 +29,8 @@ import io.reactivex.Observer; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; -import io.reactivex.functions.Consumer; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; @@ -383,4 +384,84 @@ public void ambArrayOrder() { Observable<Integer> error = Observable.error(new RuntimeException()); Observable.ambArray(Observable.just(1), error).test().assertValue(1).assertComplete(); } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerSuccessDispose() throws Exception { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Observable.ambArray( + Observable.just(1) + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Observable.never() + ) + .subscribe(new Consumer<Object>() { + @Override + public void accept(Object v) throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerErrorDispose() throws Exception { + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Observable.ambArray( + Observable.error(ex) + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Observable.never() + ) + .subscribe(Functions.emptyConsumer(), new Consumer<Throwable>() { + @Override + public void accept(Throwable e) throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerCompleteDispose() throws Exception { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Observable.ambArray( + Observable.empty() + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Observable.never() + ) + .subscribe(Functions.emptyConsumer(), Functions.emptyConsumer(), new Action() { + @Override + public void run() throws Exception { + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } + } diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java index 1bc00dedd6..18f4f3be65 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleAmbTest.java @@ -16,14 +16,18 @@ import static org.junit.Assert.*; import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import io.reactivex.*; import io.reactivex.exceptions.TestException; +import io.reactivex.functions.BiConsumer; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; +import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.*; public class SingleAmbTest { @@ -280,4 +284,61 @@ public void ambArrayOrder() { Single<Integer> error = Single.error(new RuntimeException()); Single.ambArray(Single.just(1), error).test().assertValue(1); } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerSuccessDispose() throws Exception { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Single.ambArray( + Single.just(1) + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Single.never() + ) + .subscribe(new BiConsumer<Object, Throwable>() { + @Override + public void accept(Object v, Throwable e) throws Exception { + assertNotNull(v); + assertNull(e); + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } + + @SuppressWarnings("unchecked") + @Test + public void noWinnerErrorDispose() throws Exception { + final TestException ex = new TestException(); + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final AtomicBoolean interrupted = new AtomicBoolean(); + final CountDownLatch cdl = new CountDownLatch(1); + + Single.ambArray( + Single.error(ex) + .subscribeOn(Schedulers.single()) + .observeOn(Schedulers.computation()), + Single.never() + ) + .subscribe(new BiConsumer<Object, Throwable>() { + @Override + public void accept(Object v, Throwable e) throws Exception { + assertNull(v); + assertNotNull(e); + interrupted.set(Thread.currentThread().isInterrupted()); + cdl.countDown(); + } + }); + + assertTrue(cdl.await(500, TimeUnit.SECONDS)); + assertFalse("Interrupted!", interrupted.get()); + } + } } From 621b8cda977605f91b8620a6e4e34f6c1cc89455 Mon Sep 17 00:00:00 2001 From: Guillermo Calvo <guillermocalvo@yahoo.com> Date: Mon, 21 Jan 2019 18:16:34 +0900 Subject: [PATCH 337/417] Fix bug in CompositeException.getRootCause (#6380) * Fix bug in CompositeException.getRootCause The original code use to be `if (root == null || root == e)`, but apparently after some refactoring it ended up as `if (root == null || cause == root)`, which I believe is a bug. This method should probably be `static` (that would have prevented the bug). * Update unit tests for CompositeException.getRootCause --- .../exceptions/CompositeException.java | 2 +- .../exceptions/CompositeExceptionTest.java | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/exceptions/CompositeException.java b/src/main/java/io/reactivex/exceptions/CompositeException.java index 748b964cf7..4915688379 100644 --- a/src/main/java/io/reactivex/exceptions/CompositeException.java +++ b/src/main/java/io/reactivex/exceptions/CompositeException.java @@ -280,7 +280,7 @@ public int size() { */ /*private */Throwable getRootCause(Throwable e) { Throwable root = e.getCause(); - if (root == null || cause == root) { + if (root == null || e == root) { return e; } while (true) { diff --git a/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java b/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java index 3625aa099a..2737b90712 100644 --- a/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java +++ b/src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java @@ -364,7 +364,22 @@ public synchronized Throwable getCause() { } }; CompositeException ex = new CompositeException(throwable); - assertSame(ex, ex.getRootCause(ex)); + assertSame(ex0, ex.getRootCause(ex)); + } + + @Test + public void rootCauseSelf() { + Throwable throwable = new Throwable() { + + private static final long serialVersionUID = -4398003222998914415L; + + @Override + public synchronized Throwable getCause() { + return this; + } + }; + CompositeException tmp = new CompositeException(new TestException()); + assertSame(throwable, tmp.getRootCause(throwable)); } } From 1484106b1889fe981a2bb62862d9c353373f9851 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 23 Jan 2019 10:53:39 +0100 Subject: [PATCH 338/417] Release 2.2.6 --- CHANGES.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 57b421fc21..2dabb3be28 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,29 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.6 - January 23, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.6%7C)) + +#### API enhancements + + - [Pull 6370](https://github.com/ReactiveX/RxJava/pull/6370): Add interruptible mode via the new `Schedulers.from(Executor, boolean)` overload. + +#### Bugfixes + + - [Pull 6359](https://github.com/ReactiveX/RxJava/pull/6359): Fix the error/race in `Observable.repeatWhen` due to flooding repeat signal. + - [Pull 6362 ](https://github.com/ReactiveX/RxJava/pull/6362 ): Fix `Completable.andThen(Completable)` not running on `observeOn`'s `Scheduler`. + - [Pull 6364](https://github.com/ReactiveX/RxJava/pull/6364): Fix `Flowable.publish` not requesting upon client change. + - [Pull 6371](https://github.com/ReactiveX/RxJava/pull/6371): Fix bounded `replay()` memory leak due to bad node retention. + - [Pull 6375](https://github.com/ReactiveX/RxJava/pull/6375): Don't dispose the winner of `{Single|Maybe|Completable}.amb()`. + - [Pull 6380](https://github.com/ReactiveX/RxJava/pull/6380): Fix `CompositeException.getRootCause()` detecting loops in the cause graph. + +#### Documentation changes + + - [Pull 6365](https://github.com/ReactiveX/RxJava/pull/6365): Indicate source disposal in `timeout(fallback)`. + +#### Other changes + + - [Pull 6353](https://github.com/ReactiveX/RxJava/pull/6353): Use `ignoreElement` to convert `Single` to `Completable` in the `README.md`. + ### Version 2.2.5 - December 31, 2018 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.5%7C)) #### Documentation changes From 3fbfcc9c648dc02a064158c3ddb262f95949cbc5 Mon Sep 17 00:00:00 2001 From: Roman Wuattier <roman.wuattier@gmail.com> Date: Wed, 23 Jan 2019 13:33:30 +0100 Subject: [PATCH 339/417] Expand `Observable#debounce` and `Flowable#debounce` javadoc (#6377) Mention that if the processing of a task takes too long and a newer item arrives then the previous task will get disposed interrupting a long running work. Fixes: #6288 --- src/main/java/io/reactivex/Flowable.java | 22 ++++++++++++++++++++++ src/main/java/io/reactivex/Observable.java | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index cba4b69210..79f4251ddd 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -8189,6 +8189,14 @@ public final Single<Long> count() { * source Publisher that are followed by another item within a computed debounce duration. * <p> * <img width="640" height="425" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.f.png" alt=""> + * <p> + * The delivery of the item happens on the thread of the first {@code onNext} or {@code onComplete} + * signal of the generated {@code Publisher} sequence, + * which if takes too long, a newer item may arrive from the upstream, causing the + * generated sequence to get cancelled, which may also interrupt any downstream blocking operation + * (yielding an {@code InterruptedException}). It is recommended processing items + * that may take long time to be moved to another thread via {@link #observeOn} applied after + * {@code debounce} itself. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator does not support backpressure as it uses the {@code debounceSelector} to mark @@ -8224,6 +8232,13 @@ public final <U> Flowable<T> debounce(Function<? super T, ? extends Publisher<U> * will be emitted by the resulting Publisher. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.png" alt=""> + * <p> + * Delivery of the item after the grace period happens on the {@code computation} {@code Scheduler}'s + * {@code Worker} which if takes too long, a newer item may arrive from the upstream, causing the + * {@code Worker}'s task to get disposed, which may also interrupt any downstream blocking operation + * (yielding an {@code InterruptedException}). It is recommended processing items + * that may take long time to be moved to another thread via {@link #observeOn} applied after + * {@code debounce} itself. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> @@ -8259,6 +8274,13 @@ public final Flowable<T> debounce(long timeout, TimeUnit unit) { * will be emitted by the resulting Publisher. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.s.png" alt=""> + * <p> + * Delivery of the item after the grace period happens on the given {@code Scheduler}'s + * {@code Worker} which if takes too long, a newer item may arrive from the upstream, causing the + * {@code Worker}'s task to get disposed, which may also interrupt any downstream blocking operation + * (yielding an {@code InterruptedException}). It is recommended processing items + * that may take long time to be moved to another thread via {@link #observeOn} applied after + * {@code debounce} itself. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 90b96c38fd..fe2989bae4 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7297,6 +7297,14 @@ public final Single<Long> count() { * source ObservableSource that are followed by another item within a computed debounce duration. * <p> * <img width="640" height="425" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.f.png" alt=""> + * <p> + * The delivery of the item happens on the thread of the first {@code onNext} or {@code onComplete} + * signal of the generated {@code ObservableSource} sequence, + * which if takes too long, a newer item may arrive from the upstream, causing the + * generated sequence to get disposed, which may also interrupt any downstream blocking operation + * (yielding an {@code InterruptedException}). It is recommended processing items + * that may take long time to be moved to another thread via {@link #observeOn} applied after + * {@code debounce} itself. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code debounce} does not operate by default on a particular {@link Scheduler}.</dd> @@ -7326,6 +7334,13 @@ public final <U> Observable<T> debounce(Function<? super T, ? extends Observable * will be emitted by the resulting ObservableSource. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.png" alt=""> + * <p> + * Delivery of the item after the grace period happens on the {@code computation} {@code Scheduler}'s + * {@code Worker} which if takes too long, a newer item may arrive from the upstream, causing the + * {@code Worker}'s task to get disposed, which may also interrupt any downstream blocking operation + * (yielding an {@code InterruptedException}). It is recommended processing items + * that may take long time to be moved to another thread via {@link #observeOn} applied after + * {@code debounce} itself. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code debounce} operates by default on the {@code computation} {@link Scheduler}.</dd> @@ -7357,6 +7372,13 @@ public final Observable<T> debounce(long timeout, TimeUnit unit) { * will be emitted by the resulting ObservableSource. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.s.png" alt=""> + * <p> + * Delivery of the item after the grace period happens on the given {@code Scheduler}'s + * {@code Worker} which if takes too long, a newer item may arrive from the upstream, causing the + * {@code Worker}'s task to get disposed, which may also interrupt any downstream blocking operation + * (yielding an {@code InterruptedException}). It is recommended processing items + * that may take long time to be moved to another thread via {@link #observeOn} applied after + * {@code debounce} itself. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> From 6e266af1000083f25dcae9defdcfe41e4ea2b97b Mon Sep 17 00:00:00 2001 From: Sergey Kryvets <10011693+skryvets@users.noreply.github.com> Date: Tue, 29 Jan 2019 06:45:37 -0600 Subject: [PATCH 340/417] Add doOnTerminate to Single/Maybe for consistency (#6379) (#6386) --- src/main/java/io/reactivex/Maybe.java | 27 ++++ src/main/java/io/reactivex/Single.java | 27 ++++ .../operators/maybe/MaybeDoOnTerminate.java | 90 +++++++++++++ .../operators/single/SingleDoOnTerminate.java | 78 +++++++++++ .../maybe/MaybeDoOnTerminateTest.java | 124 ++++++++++++++++++ .../single/SingleDoOnTerminateTest.java | 96 ++++++++++++++ 6 files changed, 442 insertions(+) create mode 100644 src/main/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminate.java create mode 100644 src/main/java/io/reactivex/internal/operators/single/SingleDoOnTerminate.java create mode 100644 src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminateTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/single/SingleDoOnTerminateTest.java diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 147b3f3125..d978d4a9dd 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -2892,6 +2892,33 @@ public final Maybe<T> doOnSubscribe(Consumer<? super Disposable> onSubscribe) { )); } + /** + * Returns a Maybe instance that calls the given onTerminate callback + * just before this Maybe completes normally or with an exception. + * <p> + * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnTerminate.png" alt=""> + * <p> + * This differs from {@code doAfterTerminate} in that this happens <em>before</em> the {@code onComplete} or + * {@code onError} notification. + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code doOnTerminate} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * @param onTerminate the action to invoke when the consumer calls {@code onComplete} or {@code onError} + * @return the new Maybe instance + * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> + * @see #doOnTerminate(Action) + * @since 2.2.7 - experimental + */ + @Experimental + @CheckReturnValue + @NonNull + @SchedulerSupport(SchedulerSupport.NONE) + public final Maybe<T> doOnTerminate(final Action onTerminate) { + ObjectHelper.requireNonNull(onTerminate, "onTerminate is null"); + return RxJavaPlugins.onAssembly(new MaybeDoOnTerminate<T>(this, onTerminate)); + } + /** * Calls the shared consumer with the success value sent via onSuccess for each * MaybeObserver that subscribes to the current Maybe. diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index f41d69a80c..1071fa836b 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2495,6 +2495,33 @@ public final Single<T> doOnSubscribe(final Consumer<? super Disposable> onSubscr return RxJavaPlugins.onAssembly(new SingleDoOnSubscribe<T>(this, onSubscribe)); } + /** + * Returns a Single instance that calls the given onTerminate callback + * just before this Single completes normally or with an exception. + * <p> + * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnTerminate.png" alt=""> + * <p> + * This differs from {@code doAfterTerminate} in that this happens <em>before</em> the {@code onComplete} or + * {@code onError} notification. + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code doOnTerminate} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * @param onTerminate the action to invoke when the consumer calls {@code onComplete} or {@code onError} + * @return the new Single instance + * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> + * @see #doOnTerminate(Action) + * @since 2.2.7 - experimental + */ + @Experimental + @CheckReturnValue + @NonNull + @SchedulerSupport(SchedulerSupport.NONE) + public final Single<T> doOnTerminate(final Action onTerminate) { + ObjectHelper.requireNonNull(onTerminate, "onTerminate is null"); + return RxJavaPlugins.onAssembly(new SingleDoOnTerminate<T>(this, onTerminate)); + } + /** * Calls the shared consumer with the success value sent via onSuccess for each * SingleObserver that subscribes to the current Single. diff --git a/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminate.java b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminate.java new file mode 100644 index 0000000000..81d0d8af34 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminate.java @@ -0,0 +1,90 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.maybe; + +import io.reactivex.Maybe; +import io.reactivex.MaybeObserver; +import io.reactivex.MaybeSource; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.CompositeException; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Action; + +public final class MaybeDoOnTerminate<T> extends Maybe<T> { + + final MaybeSource<T> source; + + final Action onTerminate; + + public MaybeDoOnTerminate(MaybeSource<T> source, Action onTerminate) { + this.source = source; + this.onTerminate = onTerminate; + } + + @Override + protected void subscribeActual(MaybeObserver<? super T> observer) { + source.subscribe(new DoOnTerminate(observer)); + } + + final class DoOnTerminate implements MaybeObserver<T> { + final MaybeObserver<? super T> downstream; + + DoOnTerminate(MaybeObserver<? super T> observer) { + this.downstream = observer; + } + + @Override + public void onSubscribe(Disposable d) { + downstream.onSubscribe(d); + } + + @Override + public void onSuccess(T value) { + try { + onTerminate.run(); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + downstream.onError(ex); + return; + } + + downstream.onSuccess(value); + } + + @Override + public void onError(Throwable e) { + try { + onTerminate.run(); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + e = new CompositeException(e, ex); + } + + downstream.onError(e); + } + + @Override + public void onComplete() { + try { + onTerminate.run(); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + downstream.onError(ex); + return; + } + + downstream.onComplete(); + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/single/SingleDoOnTerminate.java b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnTerminate.java new file mode 100644 index 0000000000..7497aff902 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/single/SingleDoOnTerminate.java @@ -0,0 +1,78 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.single; + +import io.reactivex.Single; +import io.reactivex.SingleObserver; +import io.reactivex.SingleSource; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.CompositeException; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Action; + +public final class SingleDoOnTerminate<T> extends Single<T> { + + final SingleSource<T> source; + + final Action onTerminate; + + public SingleDoOnTerminate(SingleSource<T> source, Action onTerminate) { + this.source = source; + this.onTerminate = onTerminate; + } + + @Override + protected void subscribeActual(final SingleObserver<? super T> observer) { + source.subscribe(new DoOnTerminate(observer)); + } + + final class DoOnTerminate implements SingleObserver<T> { + + final SingleObserver<? super T> downstream; + + DoOnTerminate(SingleObserver<? super T> observer) { + this.downstream = observer; + } + + @Override + public void onSubscribe(Disposable d) { + downstream.onSubscribe(d); + } + + @Override + public void onSuccess(T value) { + try { + onTerminate.run(); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + downstream.onError(ex); + return; + } + + downstream.onSuccess(value); + } + + @Override + public void onError(Throwable e) { + try { + onTerminate.run(); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + e = new CompositeException(e, ex); + } + + downstream.onError(e); + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminateTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminateTest.java new file mode 100644 index 0000000000..d442fcc135 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminateTest.java @@ -0,0 +1,124 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.maybe; + +import io.reactivex.Maybe; +import io.reactivex.TestHelper; +import io.reactivex.exceptions.CompositeException; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.subjects.PublishSubject; +import org.junit.Test; + +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.Assert.assertTrue; + +public class MaybeDoOnTerminateTest { + + @Test(expected = NullPointerException.class) + public void doOnTerminate() { + Maybe.just(1).doOnTerminate(null); + } + + @Test + public void doOnTerminateSuccess() { + final AtomicBoolean atomicBoolean = new AtomicBoolean(); + Maybe.just(1).doOnTerminate(new Action() { + @Override + public void run() { + atomicBoolean.set(true); + } + }) + .test() + .assertResult(1); + + assertTrue(atomicBoolean.get()); + } + + @Test + public void doOnTerminateError() { + final AtomicBoolean atomicBoolean = new AtomicBoolean(); + Maybe.error(new TestException()).doOnTerminate(new Action() { + @Override + public void run() { + atomicBoolean.set(true); + } + }) + .test() + .assertFailure(TestException.class); + + assertTrue(atomicBoolean.get()); + } + + @Test + public void doOnTerminateComplete() { + final AtomicBoolean atomicBoolean = new AtomicBoolean(); + Maybe.empty().doOnTerminate(new Action() { + @Override + public void run() { + atomicBoolean.set(true); + } + }) + .test() + .assertResult(); + + assertTrue(atomicBoolean.get()); + } + + @Test + public void doOnTerminateSuccessCrash() { + Maybe.just(1).doOnTerminate(new Action() { + @Override + public void run() { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void doOnTerminateErrorCrash() { + TestObserver<Object> to = Maybe.error(new TestException("Outer")) + .doOnTerminate(new Action() { + @Override + public void run() { + throw new TestException("Inner"); + } + }) + .test() + .assertFailure(CompositeException.class); + + List<Throwable> errors = TestHelper.compositeList(to.errors().get(0)); + TestHelper.assertError(errors, 0, TestException.class, "Outer"); + TestHelper.assertError(errors, 1, TestException.class, "Inner"); + } + + @Test + public void doOnTerminateCompleteCrash() { + Maybe.empty() + .doOnTerminate(new Action() { + @Override + public void run() { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTerminateTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTerminateTest.java new file mode 100644 index 0000000000..ba15f9f71b --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTerminateTest.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.single; + +import io.reactivex.Single; +import io.reactivex.TestHelper; +import io.reactivex.exceptions.CompositeException; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.Action; +import io.reactivex.observers.TestObserver; +import org.junit.Assert; +import org.junit.Test; + +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.Assert.assertTrue; + +public class SingleDoOnTerminateTest { + + @Test(expected = NullPointerException.class) + public void doOnTerminate() { + Single.just(1).doOnTerminate(null); + } + + @Test + public void doOnTerminateSuccess() { + final AtomicBoolean atomicBoolean = new AtomicBoolean(); + + Single.just(1).doOnTerminate(new Action() { + @Override + public void run() throws Exception { + atomicBoolean.set(true); + } + }) + .test() + .assertResult(1); + + assertTrue(atomicBoolean.get()); + } + + @Test + public void doOnTerminateError() { + final AtomicBoolean atomicBoolean = new AtomicBoolean(); + Single.error(new TestException()).doOnTerminate(new Action() { + @Override + public void run() { + atomicBoolean.set(true); + } + }) + .test() + .assertFailure(TestException.class); + + assertTrue(atomicBoolean.get()); + } + + @Test + public void doOnTerminateSuccessCrash() { + Single.just(1).doOnTerminate(new Action() { + @Override + public void run() throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void doOnTerminateErrorCrash() { + TestObserver<Object> to = Single.error(new TestException("Outer")).doOnTerminate(new Action() { + @Override + public void run() { + throw new TestException("Inner"); + } + }) + .test() + .assertFailure(CompositeException.class); + + List<Throwable> errors = TestHelper.compositeList(to.errors().get(0)); + + TestHelper.assertError(errors, 0, TestException.class, "Outer"); + TestHelper.assertError(errors, 1, TestException.class, "Inner"); + } +} From 7fffa00e3139e7c59e2e26e80f084f29d32a5688 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 12 Feb 2019 23:24:46 +0100 Subject: [PATCH 341/417] 2.x: Fix concatEager to dispose sources & clean up properly. (#6405) --- .../flowable/FlowableConcatMapEager.java | 7 +++- .../observable/ObservableConcatMapEager.java | 15 +++++++-- .../flowable/FlowableConcatMapEagerTest.java | 33 +++++++++++++++++++ .../ObservableConcatMapEagerTest.java | 33 +++++++++++++++++++ 4 files changed, 85 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java index 87ee235704..8acad8ac69 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java @@ -176,7 +176,12 @@ void drainAndCancel() { } void cancelAll() { - InnerQueuedSubscriber<R> inner; + InnerQueuedSubscriber<R> inner = current; + current = null; + + if (inner != null) { + inner.cancel(); + } while ((inner = subscribers.poll()) != null) { inner.cancel(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapEager.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapEager.java index cb15b10f65..7028fdcf62 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapEager.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapEager.java @@ -162,10 +162,21 @@ public void onComplete() { @Override public void dispose() { + if (cancelled) { + return; + } cancelled = true; + upstream.dispose(); + + drainAndDispose(); + } + + void drainAndDispose() { if (getAndIncrement() == 0) { - queue.clear(); - disposeAll(); + do { + queue.clear(); + disposeAll(); + } while (decrementAndGet() != 0); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java index 1e34d2937b..11f12fb4a3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java @@ -1333,4 +1333,37 @@ public void arrayDelayErrorMaxConcurrencyErrorDelayed() { ts.assertFailure(TestException.class, 1, 2); } + + @Test + public void cancelActive() { + PublishProcessor<Integer> pp1 = PublishProcessor.create(); + PublishProcessor<Integer> pp2 = PublishProcessor.create(); + + TestSubscriber<Integer> ts = Flowable + .concatEager(Flowable.just(pp1, pp2)) + .test(); + + assertTrue(pp1.hasSubscribers()); + assertTrue(pp2.hasSubscribers()); + + ts.cancel(); + + assertFalse(pp1.hasSubscribers()); + assertFalse(pp2.hasSubscribers()); + } + + @Test + public void cancelNoInnerYet() { + PublishProcessor<Flowable<Integer>> pp1 = PublishProcessor.create(); + + TestSubscriber<Integer> ts = Flowable + .concatEager(pp1) + .test(); + + assertTrue(pp1.hasSubscribers()); + + ts.cancel(); + + assertFalse(pp1.hasSubscribers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java index 3959fab45e..17e418bab7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableConcatMapEagerTest.java @@ -1141,4 +1141,37 @@ public void arrayDelayErrorMaxConcurrencyErrorDelayed() { to.assertFailure(TestException.class, 1, 2); } + + @Test + public void cancelActive() { + PublishSubject<Integer> ps1 = PublishSubject.create(); + PublishSubject<Integer> ps2 = PublishSubject.create(); + + TestObserver<Integer> to = Observable + .concatEager(Observable.just(ps1, ps2)) + .test(); + + assertTrue(ps1.hasObservers()); + assertTrue(ps2.hasObservers()); + + to.dispose(); + + assertFalse(ps1.hasObservers()); + assertFalse(ps2.hasObservers()); + } + + @Test + public void cancelNoInnerYet() { + PublishSubject<Observable<Integer>> ps1 = PublishSubject.create(); + + TestObserver<Integer> to = Observable + .concatEager(ps1) + .test(); + + assertTrue(ps1.hasObservers()); + + to.dispose(); + + assertFalse(ps1.hasObservers()); + } } From 184a17b7da82683e4c17d5c70392e8c5df50017f Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 13 Feb 2019 09:51:08 +0100 Subject: [PATCH 342/417] 2.x: Fix window() with start/end selector not disposing/cancelling properly (#6398) * 2.x: Fix window() with s/e selector not disposing/cancelling properly * Fix cancellation upon backpressure problem/handler crash --- .../FlowableWindowBoundarySelector.java | 18 ++++-- .../ObservableWindowBoundarySelector.java | 18 ++++-- ...lowableWindowWithStartEndFlowableTest.java | 61 ++++++++++++++++++- ...vableWindowWithStartEndObservableTest.java | 39 +++++++++++- 4 files changed, 119 insertions(+), 17 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java index 0e3fe58b83..d9d6ffa517 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java @@ -71,6 +71,8 @@ static final class WindowBoundaryMainSubscriber<T, B, V> final AtomicLong windows = new AtomicLong(); + final AtomicBoolean stopWindows = new AtomicBoolean(); + WindowBoundaryMainSubscriber(Subscriber<? super Flowable<T>> actual, Publisher<B> open, Function<? super B, ? extends Publisher<V>> close, int bufferSize) { super(actual, new MpscLinkedQueue<Object>()); @@ -89,14 +91,13 @@ public void onSubscribe(Subscription s) { downstream.onSubscribe(this); - if (cancelled) { + if (stopWindows.get()) { return; } OperatorWindowBoundaryOpenSubscriber<T, B> os = new OperatorWindowBoundaryOpenSubscriber<T, B>(this); if (boundary.compareAndSet(null, os)) { - windows.getAndIncrement(); s.request(Long.MAX_VALUE); open.subscribe(os); } @@ -177,7 +178,12 @@ public void request(long n) { @Override public void cancel() { - cancelled = true; + if (stopWindows.compareAndSet(false, true)) { + DisposableHelper.dispose(boundary); + if (windows.decrementAndGet() == 0) { + upstream.cancel(); + } + } } void dispose() { @@ -236,7 +242,7 @@ void drainLoop() { continue; } - if (cancelled) { + if (stopWindows.get()) { continue; } @@ -250,7 +256,7 @@ void drainLoop() { produced(1); } } else { - cancelled = true; + cancel(); a.onError(new MissingBackpressureException("Could not deliver new window due to lack of requests")); continue; } @@ -260,7 +266,7 @@ void drainLoop() { try { p = ObjectHelper.requireNonNull(close.apply(wo.open), "The publisher supplied is null"); } catch (Throwable e) { - cancelled = true; + cancel(); a.onError(e); continue; } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java index 1e2a2ea052..d8e745e213 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java @@ -69,6 +69,8 @@ static final class WindowBoundaryMainObserver<T, B, V> final AtomicLong windows = new AtomicLong(); + final AtomicBoolean stopWindows = new AtomicBoolean(); + WindowBoundaryMainObserver(Observer<? super Observable<T>> actual, ObservableSource<B> open, Function<? super B, ? extends ObservableSource<V>> close, int bufferSize) { super(actual, new MpscLinkedQueue<Object>()); @@ -87,14 +89,13 @@ public void onSubscribe(Disposable d) { downstream.onSubscribe(this); - if (cancelled) { + if (stopWindows.get()) { return; } OperatorWindowBoundaryOpenObserver<T, B> os = new OperatorWindowBoundaryOpenObserver<T, B>(this); if (boundary.compareAndSet(null, os)) { - windows.getAndIncrement(); open.subscribe(os); } } @@ -164,12 +165,17 @@ void error(Throwable t) { @Override public void dispose() { - cancelled = true; + if (stopWindows.compareAndSet(false, true)) { + DisposableHelper.dispose(boundary); + if (windows.decrementAndGet() == 0) { + upstream.dispose(); + } + } } @Override public boolean isDisposed() { - return cancelled; + return stopWindows.get(); } void disposeBoundary() { @@ -229,7 +235,7 @@ void drainLoop() { continue; } - if (cancelled) { + if (stopWindows.get()) { continue; } @@ -244,7 +250,7 @@ void drainLoop() { p = ObjectHelper.requireNonNull(close.apply(wo.open), "The ObservableSource supplied is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); - cancelled = true; + stopWindows.set(true); a.onError(e); continue; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java index c1d825afed..1d27381129 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithStartEndFlowableTest.java @@ -17,12 +17,13 @@ import java.util.*; import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.*; import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.exceptions.TestException; +import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; @@ -254,8 +255,8 @@ public Flowable<Integer> apply(Integer t) { ts.dispose(); - // FIXME subject has subscribers because of the open window - assertTrue(open.hasSubscribers()); + // Disposing the outer sequence stops the opening of new windows + assertFalse(open.hasSubscribers()); // FIXME subject has subscribers because of the open window assertTrue(close.hasSubscribers()); } @@ -430,4 +431,58 @@ protected void subscribeActual( RxJavaPlugins.reset(); } } + + static Flowable<Integer> flowableDisposed(final AtomicBoolean ref) { + return Flowable.just(1).concatWith(Flowable.<Integer>never()) + .doOnCancel(new Action() { + @Override + public void run() throws Exception { + ref.set(true); + } + }); + } + + @Test + public void mainAndBoundaryDisposeOnNoWindows() { + AtomicBoolean mainDisposed = new AtomicBoolean(); + AtomicBoolean openDisposed = new AtomicBoolean(); + final AtomicBoolean closeDisposed = new AtomicBoolean(); + + flowableDisposed(mainDisposed) + .window(flowableDisposed(openDisposed), new Function<Integer, Flowable<Integer>>() { + @Override + public Flowable<Integer> apply(Integer v) throws Exception { + return flowableDisposed(closeDisposed); + } + }) + .test() + .assertSubscribed() + .assertNoErrors() + .assertNotComplete() + .dispose(); + + assertTrue(mainDisposed.get()); + assertTrue(openDisposed.get()); + assertTrue(closeDisposed.get()); + } + + @Test + @SuppressWarnings("unchecked") + public void mainWindowMissingBackpressure() { + PublishProcessor<Integer> source = PublishProcessor.create(); + PublishProcessor<Integer> boundary = PublishProcessor.create(); + + TestSubscriber<Flowable<Integer>> ts = source.window(boundary, Functions.justFunction(Flowable.never())) + .test(0L) + ; + + ts.assertEmpty(); + + boundary.onNext(1); + + ts.assertFailure(MissingBackpressureException.class); + + assertFalse(source.hasSubscribers()); + assertFalse(boundary.hasSubscribers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java index d1426a5a61..c4f7fa6409 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithStartEndObservableTest.java @@ -17,6 +17,7 @@ import java.util.*; import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.*; @@ -256,8 +257,8 @@ public Observable<Integer> apply(Integer t) { to.dispose(); - // FIXME subject has subscribers because of the open window - assertTrue(open.hasObservers()); + // Disposing the outer sequence stops the opening of new windows + assertFalse(open.hasObservers()); // FIXME subject has subscribers because of the open window assertTrue(close.hasObservers()); } @@ -423,4 +424,38 @@ protected void subscribeActual( RxJavaPlugins.reset(); } } + + static Observable<Integer> observableDisposed(final AtomicBoolean ref) { + return Observable.just(1).concatWith(Observable.<Integer>never()) + .doOnDispose(new Action() { + @Override + public void run() throws Exception { + ref.set(true); + } + }); + } + + @Test + public void mainAndBoundaryDisposeOnNoWindows() { + AtomicBoolean mainDisposed = new AtomicBoolean(); + AtomicBoolean openDisposed = new AtomicBoolean(); + final AtomicBoolean closeDisposed = new AtomicBoolean(); + + observableDisposed(mainDisposed) + .window(observableDisposed(openDisposed), new Function<Integer, ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> apply(Integer v) throws Exception { + return observableDisposed(closeDisposed); + } + }) + .test() + .assertSubscribed() + .assertNoErrors() + .assertNotComplete() + .dispose(); + + assertTrue(mainDisposed.get()); + assertTrue(openDisposed.get()); + assertTrue(closeDisposed.get()); + } } From add2812a20bda65bb7326c3845f7714b7218a505 Mon Sep 17 00:00:00 2001 From: Thiyagarajan <38608518+thiyagu-7@users.noreply.github.com> Date: Sun, 17 Feb 2019 00:32:31 +0530 Subject: [PATCH 343/417] Improving Javadoc of flattenAsFlowable and flattenAsObservable methods (#6276) (#6408) --- src/main/java/io/reactivex/Maybe.java | 7 ++++--- src/main/java/io/reactivex/Single.java | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index d978d4a9dd..ab221724eb 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3062,8 +3062,8 @@ public final <U, R> Maybe<R> flatMap(Function<? super T, ? extends MaybeSource<? } /** - * Returns a Flowable that merges each item emitted by the source Maybe with the values in an - * Iterable corresponding to that item that is generated by a selector. + * Maps the success value of the upstream {@link Maybe} into an {@link Iterable} and emits its items as a + * {@link Flowable} sequence. * <p> * <img width="640" height="373" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flattenAsFlowable.png" alt=""> * <dl> @@ -3091,7 +3091,8 @@ public final <U> Flowable<U> flattenAsFlowable(final Function<? super T, ? exten } /** - * Returns an Observable that maps a success value into an Iterable and emits its items. + * Maps the success value of the upstream {@link Maybe} into an {@link Iterable} and emits its items as an + * {@link Observable} sequence. * <p> * <img width="640" height="373" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flattenAsObservable.png" alt=""> * <dl> diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 1071fa836b..d4b5f7aaf4 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2711,8 +2711,8 @@ public final <R> Flowable<R> flatMapPublisher(Function<? super T, ? extends Publ } /** - * Returns a Flowable that merges each item emitted by the source Single with the values in an - * Iterable corresponding to that item that is generated by a selector. + * Maps the success value of the upstream {@link Single} into an {@link Iterable} and emits its items as a + * {@link Flowable} sequence. * <p> * <img width="640" height="373" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flattenAsFlowable.png" alt=""> * <dl> @@ -2740,7 +2740,8 @@ public final <U> Flowable<U> flattenAsFlowable(final Function<? super T, ? exten } /** - * Returns an Observable that maps a success value into an Iterable and emits its items. + * Maps the success value of the upstream {@link Single} into an {@link Iterable} and emits its items as an + * {@link Observable} sequence. * <p> * <img width="640" height="373" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flattenAsObservable.png" alt=""> * <dl> From 9a74adf5f85ebfe5063e8191665956d547d515e0 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sat, 23 Feb 2019 09:37:49 +0100 Subject: [PATCH 344/417] Release 2.2.7 --- CHANGES.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 2dabb3be28..16757d46b4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,22 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.7 - February 23, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.7%7C)) + +#### API enhancements + + - [Pull 6386](https://github.com/ReactiveX/RxJava/pull/6386): Add `doOnTerminate` to `Single`/`Maybe` for consistency. + +#### Bugfixes + + - [Pull 6405](https://github.com/ReactiveX/RxJava/pull/6405): Fix concatEager to dispose sources & clean up properly. + - [Pull 6398](https://github.com/ReactiveX/RxJava/pull/6398): Fix `window()` with start/end selector not disposing/cancelling properly. + +#### Documentation changes + + - [Pull 6377](https://github.com/ReactiveX/RxJava/pull/6377): Expand `Observable#debounce` and `Flowable#debounce` javadoc. + - [Pull 6408](https://github.com/ReactiveX/RxJava/pull/6408): Improving Javadoc of `flattenAsFlowable` and `flattenAsObservable` methods. + ### Version 2.2.6 - January 23, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.6%7C)) #### API enhancements From 0bb7b4db47e5af8d7e37b48545b00f70f69a34f1 Mon Sep 17 00:00:00 2001 From: chronvas <chron.vas@outlook.com> Date: Fri, 15 Mar 2019 18:21:25 +0000 Subject: [PATCH 345/417] 2.x composite disposable docs (#6432) * 2.x: Improving NPE message in CompositeDisposable add(..) when param is null * 2.x: Improving NPE message in CompositeDisposable addAll(..) when item in vararg param is null * 2.x: Improved in CompositeDisposable: NPE error messages, parameter naming at methods, added @throws javadoc where applicable * 2.x: Applied PR suggestions in javadoc and messages for CompositeDisposable --- .../disposables/CompositeDisposable.java | 67 ++++++++++--------- 1 file changed, 36 insertions(+), 31 deletions(-) diff --git a/src/main/java/io/reactivex/disposables/CompositeDisposable.java b/src/main/java/io/reactivex/disposables/CompositeDisposable.java index 5bed43ec77..f7a1bf4a36 100644 --- a/src/main/java/io/reactivex/disposables/CompositeDisposable.java +++ b/src/main/java/io/reactivex/disposables/CompositeDisposable.java @@ -38,26 +38,28 @@ public CompositeDisposable() { /** * Creates a CompositeDisposables with the given array of initial elements. - * @param resources the array of Disposables to start with + * @param disposables the array of Disposables to start with + * @throws NullPointerException if {@code disposables} or any of its array items is null */ - public CompositeDisposable(@NonNull Disposable... resources) { - ObjectHelper.requireNonNull(resources, "resources is null"); - this.resources = new OpenHashSet<Disposable>(resources.length + 1); - for (Disposable d : resources) { - ObjectHelper.requireNonNull(d, "Disposable item is null"); + public CompositeDisposable(@NonNull Disposable... disposables) { + ObjectHelper.requireNonNull(disposables, "disposables is null"); + this.resources = new OpenHashSet<Disposable>(disposables.length + 1); + for (Disposable d : disposables) { + ObjectHelper.requireNonNull(d, "A Disposable in the disposables array is null"); this.resources.add(d); } } /** * Creates a CompositeDisposables with the given Iterable sequence of initial elements. - * @param resources the Iterable sequence of Disposables to start with + * @param disposables the Iterable sequence of Disposables to start with + * @throws NullPointerException if {@code disposables} or any of its items is null */ - public CompositeDisposable(@NonNull Iterable<? extends Disposable> resources) { - ObjectHelper.requireNonNull(resources, "resources is null"); + public CompositeDisposable(@NonNull Iterable<? extends Disposable> disposables) { + ObjectHelper.requireNonNull(disposables, "disposables is null"); this.resources = new OpenHashSet<Disposable>(); - for (Disposable d : resources) { - ObjectHelper.requireNonNull(d, "Disposable item is null"); + for (Disposable d : disposables) { + ObjectHelper.requireNonNull(d, "A Disposable item in the disposables sequence is null"); this.resources.add(d); } } @@ -88,12 +90,13 @@ public boolean isDisposed() { /** * Adds a disposable to this container or disposes it if the * container has been disposed. - * @param d the disposable to add, not null + * @param disposable the disposable to add, not null * @return true if successful, false if this container has been disposed + * @throws NullPointerException if {@code disposable} is null */ @Override - public boolean add(@NonNull Disposable d) { - ObjectHelper.requireNonNull(d, "d is null"); + public boolean add(@NonNull Disposable disposable) { + ObjectHelper.requireNonNull(disposable, "disposable is null"); if (!disposed) { synchronized (this) { if (!disposed) { @@ -102,40 +105,41 @@ public boolean add(@NonNull Disposable d) { set = new OpenHashSet<Disposable>(); resources = set; } - set.add(d); + set.add(disposable); return true; } } } - d.dispose(); + disposable.dispose(); return false; } /** * Atomically adds the given array of Disposables to the container or * disposes them all if the container has been disposed. - * @param ds the array of Disposables + * @param disposables the array of Disposables * @return true if the operation was successful, false if the container has been disposed + * @throws NullPointerException if {@code disposables} or any of its array items is null */ - public boolean addAll(@NonNull Disposable... ds) { - ObjectHelper.requireNonNull(ds, "ds is null"); + public boolean addAll(@NonNull Disposable... disposables) { + ObjectHelper.requireNonNull(disposables, "disposables is null"); if (!disposed) { synchronized (this) { if (!disposed) { OpenHashSet<Disposable> set = resources; if (set == null) { - set = new OpenHashSet<Disposable>(ds.length + 1); + set = new OpenHashSet<Disposable>(disposables.length + 1); resources = set; } - for (Disposable d : ds) { - ObjectHelper.requireNonNull(d, "d is null"); + for (Disposable d : disposables) { + ObjectHelper.requireNonNull(d, "A Disposable in the disposables array is null"); set.add(d); } return true; } } } - for (Disposable d : ds) { + for (Disposable d : disposables) { d.dispose(); } return false; @@ -144,13 +148,13 @@ public boolean addAll(@NonNull Disposable... ds) { /** * Removes and disposes the given disposable if it is part of this * container. - * @param d the disposable to remove and dispose, not null + * @param disposable the disposable to remove and dispose, not null * @return true if the operation was successful */ @Override - public boolean remove(@NonNull Disposable d) { - if (delete(d)) { - d.dispose(); + public boolean remove(@NonNull Disposable disposable) { + if (delete(disposable)) { + disposable.dispose(); return true; } return false; @@ -159,12 +163,13 @@ public boolean remove(@NonNull Disposable d) { /** * Removes (but does not dispose) the given disposable if it is part of this * container. - * @param d the disposable to remove, not null + * @param disposable the disposable to remove, not null * @return true if the operation was successful + * @throws NullPointerException if {@code disposable} is null */ @Override - public boolean delete(@NonNull Disposable d) { - ObjectHelper.requireNonNull(d, "Disposable item is null"); + public boolean delete(@NonNull Disposable disposable) { + ObjectHelper.requireNonNull(disposable, "disposables is null"); if (disposed) { return false; } @@ -174,7 +179,7 @@ public boolean delete(@NonNull Disposable d) { } OpenHashSet<Disposable> set = resources; - if (set == null || !set.remove(d)) { + if (set == null || !set.remove(disposable)) { return false; } } From 0c4f5c11bfe0774888294dbdac75c98829b13374 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 18 Mar 2019 12:33:14 +0100 Subject: [PATCH 346/417] 2.x: Improve subjects and processors package doc (#6434) --- .../io/reactivex/processors/package-info.java | 22 +++++++++++++++++-- .../io/reactivex/subjects/package-info.java | 2 +- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/processors/package-info.java b/src/main/java/io/reactivex/processors/package-info.java index 64caf9a4c4..1266a74ee1 100644 --- a/src/main/java/io/reactivex/processors/package-info.java +++ b/src/main/java/io/reactivex/processors/package-info.java @@ -15,7 +15,25 @@ */ /** - * Classes extending the Flowable base reactive class and implementing - * the Subscriber interface at the same time (aka hot Flowables). + * Classes representing so-called hot backpressure-aware sources, aka <strong>processors</strong>, + * that implement the {@link FlowableProcessor} class, + * the Reactive Streams {@link org.reactivestreams.Processor Processor} interface + * to allow forms of multicasting events to one or more subscribers as well as consuming another + * Reactive Streams {@link org.reactivestreams.Publisher Publisher}. + * <p> + * Available processor implementations: + * <br> + * <ul> + * <li>{@link io.reactivex.processors.AsyncProcessor AsyncProcessor} - replays the very last item</li> + * <li>{@link io.reactivex.processors.BehaviorProcessor BehaviorProcessor} - remembers the latest item</li> + * <li>{@link io.reactivex.processors.MulticastProcessor MulticastProcessor} - coordinates its source with its consumers</li> + * <li>{@link io.reactivex.processors.PublishProcessor PublishProcessor} - dispatches items to current consumers</li> + * <li>{@link io.reactivex.processors.ReplayProcessor ReplayProcessor} - remembers some or all items and replays them to consumers</li> + * <li>{@link io.reactivex.processors.UnicastProcessor UnicastProcessor} - remembers or relays items to a single consumer</li> + * </ul> + * <p> + * The non-backpressured variants of the {@code FlowableProcessor} class are called + * {@link io.reactivex.Subject}s and reside in the {@code io.reactivex.subjects} package. + * @see io.reactivex.subjects */ package io.reactivex.processors; diff --git a/src/main/java/io/reactivex/subjects/package-info.java b/src/main/java/io/reactivex/subjects/package-info.java index 8bd3b06ac2..091c223445 100644 --- a/src/main/java/io/reactivex/subjects/package-info.java +++ b/src/main/java/io/reactivex/subjects/package-info.java @@ -29,7 +29,7 @@ * <br>   {@link io.reactivex.subjects.BehaviorSubject BehaviorSubject} * <br>   {@link io.reactivex.subjects.PublishSubject PublishSubject} * <br>   {@link io.reactivex.subjects.ReplaySubject ReplaySubject} - * <br>   {@link io.reactivex.subjects.UnicastSubject UnicastSubjectSubject} + * <br>   {@link io.reactivex.subjects.UnicastSubject UnicastSubject} * </td> * <td>{@link io.reactivex.Observable Observable}</td> * <td>{@link io.reactivex.Observer Observer}</td> From b3d7f5f2ac25344143ebdf22f4ae23677e41cc8f Mon Sep 17 00:00:00 2001 From: Lorenz Pahl <l.pahl@outlook.com> Date: Thu, 21 Mar 2019 14:00:27 +0100 Subject: [PATCH 347/417] Make error messages of parameter checks consistent (#6433) --- src/main/java/io/reactivex/Completable.java | 2 +- src/main/java/io/reactivex/Flowable.java | 126 +++++++++---------- src/main/java/io/reactivex/Maybe.java | 10 +- src/main/java/io/reactivex/Observable.java | 131 ++++++++++---------- src/main/java/io/reactivex/Single.java | 10 +- 5 files changed, 139 insertions(+), 140 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 7ac7ead344..13364dc1a6 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -2292,7 +2292,7 @@ public final Disposable subscribe() { @SchedulerSupport(SchedulerSupport.NONE) @Override public final void subscribe(CompletableObserver observer) { - ObjectHelper.requireNonNull(observer, "s is null"); + ObjectHelper.requireNonNull(observer, "observer is null"); try { observer = RxJavaPlugins.onSubscribe(this, observer); diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 79f4251ddd..ff85859f99 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -1900,7 +1900,7 @@ public static <T> Flowable<T> empty() { @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> error(Callable<? extends Throwable> supplier) { - ObjectHelper.requireNonNull(supplier, "errorSupplier is null"); + ObjectHelper.requireNonNull(supplier, "supplier is null"); return RxJavaPlugins.onAssembly(new FlowableError<T>(supplier)); } @@ -2235,7 +2235,7 @@ public static <T> Flowable<T> fromPublisher(final Publisher<? extends T> source) if (source instanceof Flowable) { return RxJavaPlugins.onAssembly((Flowable<T>)source); } - ObjectHelper.requireNonNull(source, "publisher is null"); + ObjectHelper.requireNonNull(source, "source is null"); return RxJavaPlugins.onAssembly(new FlowableFromPublisher<T>(source)); } @@ -2662,8 +2662,8 @@ public static <T> Flowable<T> just(T item) { @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); return fromArray(item1, item2); } @@ -2696,9 +2696,9 @@ public static <T> Flowable<T> just(T item1, T item2) { @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); return fromArray(item1, item2, item3); } @@ -2733,10 +2733,10 @@ public static <T> Flowable<T> just(T item1, T item2, T item3) { @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); return fromArray(item1, item2, item3, item4); } @@ -2773,11 +2773,11 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4) { @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); return fromArray(item1, item2, item3, item4, item5); } @@ -2816,12 +2816,12 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5) @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, T item6) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); - ObjectHelper.requireNonNull(item6, "The sixth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); + ObjectHelper.requireNonNull(item6, "item6 is null"); return fromArray(item1, item2, item3, item4, item5, item6); } @@ -2862,13 +2862,13 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); - ObjectHelper.requireNonNull(item6, "The sixth item is null"); - ObjectHelper.requireNonNull(item7, "The seventh item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); + ObjectHelper.requireNonNull(item6, "item6 is null"); + ObjectHelper.requireNonNull(item7, "item7 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7); } @@ -2911,14 +2911,14 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); - ObjectHelper.requireNonNull(item6, "The sixth item is null"); - ObjectHelper.requireNonNull(item7, "The seventh item is null"); - ObjectHelper.requireNonNull(item8, "The eighth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); + ObjectHelper.requireNonNull(item6, "item6 is null"); + ObjectHelper.requireNonNull(item7, "item7 is null"); + ObjectHelper.requireNonNull(item8, "item8 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7, item8); } @@ -2963,15 +2963,15 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8, T item9) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); - ObjectHelper.requireNonNull(item6, "The sixth item is null"); - ObjectHelper.requireNonNull(item7, "The seventh item is null"); - ObjectHelper.requireNonNull(item8, "The eighth item is null"); - ObjectHelper.requireNonNull(item9, "The ninth is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); + ObjectHelper.requireNonNull(item6, "item6 is null"); + ObjectHelper.requireNonNull(item7, "item7 is null"); + ObjectHelper.requireNonNull(item8, "item8 is null"); + ObjectHelper.requireNonNull(item9, "item9 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7, item8, item9); } @@ -3018,16 +3018,16 @@ public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static <T> Flowable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8, T item9, T item10) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); - ObjectHelper.requireNonNull(item6, "The sixth item is null"); - ObjectHelper.requireNonNull(item7, "The seventh item is null"); - ObjectHelper.requireNonNull(item8, "The eighth item is null"); - ObjectHelper.requireNonNull(item9, "The ninth item is null"); - ObjectHelper.requireNonNull(item10, "The tenth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); + ObjectHelper.requireNonNull(item6, "item6 is null"); + ObjectHelper.requireNonNull(item7, "item7 is null"); + ObjectHelper.requireNonNull(item8, "item8 is null"); + ObjectHelper.requireNonNull(item9, "item9 is null"); + ObjectHelper.requireNonNull(item10, "item10 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10); } @@ -4485,7 +4485,7 @@ public static <T, D> Flowable<T> using(Callable<? extends D> resourceSupplier, Consumer<? super D> resourceDisposer, boolean eager) { ObjectHelper.requireNonNull(resourceSupplier, "resourceSupplier is null"); ObjectHelper.requireNonNull(sourceSupplier, "sourceSupplier is null"); - ObjectHelper.requireNonNull(resourceDisposer, "disposer is null"); + ObjectHelper.requireNonNull(resourceDisposer, "resourceDisposer is null"); return RxJavaPlugins.onAssembly(new FlowableUsing<T, D>(resourceSupplier, sourceSupplier, resourceDisposer, eager)); } @@ -8338,7 +8338,7 @@ public final Flowable<T> debounce(long timeout, TimeUnit unit, Scheduler schedul @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> defaultIfEmpty(T defaultItem) { - ObjectHelper.requireNonNull(defaultItem, "item is null"); + ObjectHelper.requireNonNull(defaultItem, "defaultItem is null"); return switchIfEmpty(just(defaultItem)); } @@ -9167,7 +9167,7 @@ private Flowable<T> doOnEach(Consumer<? super T> onNext, Consumer<? super Throwa @BackpressureSupport(BackpressureKind.PASS_THROUGH) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> doOnEach(final Consumer<? super Notification<T>> onNotification) { - ObjectHelper.requireNonNull(onNotification, "consumer is null"); + ObjectHelper.requireNonNull(onNotification, "onNotification is null"); return doOnEach( Functions.notificationOnNext(onNotification), Functions.notificationOnError(onNotification), @@ -11769,7 +11769,7 @@ public final Flowable<T> onBackpressureBuffer(int capacity, boolean delayError) @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> onBackpressureBuffer(int capacity, boolean delayError, boolean unbounded) { - ObjectHelper.verifyPositive(capacity, "bufferSize"); + ObjectHelper.verifyPositive(capacity, "capacity"); return RxJavaPlugins.onAssembly(new FlowableOnBackpressureBuffer<T>(this, capacity, unbounded, delayError, Functions.EMPTY_ACTION)); } @@ -11877,7 +11877,7 @@ public final Flowable<T> onBackpressureBuffer(int capacity, Action onOverflow) { @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> onBackpressureBuffer(long capacity, Action onOverflow, BackpressureOverflowStrategy overflowStrategy) { - ObjectHelper.requireNonNull(overflowStrategy, "strategy is null"); + ObjectHelper.requireNonNull(overflowStrategy, "overflowStrategy is null"); ObjectHelper.verifyPositive(capacity, "capacity"); return RxJavaPlugins.onAssembly(new FlowableOnBackpressureBufferStrategy<T>(this, capacity, onOverflow, overflowStrategy)); } @@ -13882,7 +13882,7 @@ public final Flowable<T> scan(BiFunction<T, T, T> accumulator) { @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> Flowable<R> scan(final R initialValue, BiFunction<R, ? super T, R> accumulator) { - ObjectHelper.requireNonNull(initialValue, "seed is null"); + ObjectHelper.requireNonNull(initialValue, "initialValue is null"); return scanWith(Functions.justCallable(initialValue), accumulator); } @@ -14562,7 +14562,7 @@ public final Flowable<T> startWith(Publisher<? extends T> other) { @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> startWith(T value) { - ObjectHelper.requireNonNull(value, "item is null"); + ObjectHelper.requireNonNull(value, "value is null"); return concatArray(just(value), this); } diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index ab221724eb..9fd5f6c810 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -2533,7 +2533,7 @@ public final Single<Long> count() { @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> defaultIfEmpty(T defaultItem) { - ObjectHelper.requireNonNull(defaultItem, "item is null"); + ObjectHelper.requireNonNull(defaultItem, "defaultItem is null"); return switchIfEmpty(just(defaultItem)); } @@ -2709,7 +2709,7 @@ public final Maybe<T> delaySubscription(long delay, TimeUnit unit, Scheduler sch @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Maybe<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) { - ObjectHelper.requireNonNull(onAfterSuccess, "doAfterSuccess is null"); + ObjectHelper.requireNonNull(onAfterSuccess, "onAfterSuccess is null"); return RxJavaPlugins.onAssembly(new MaybeDoAfterSuccess<T>(this, onAfterSuccess)); } @@ -2937,7 +2937,7 @@ public final Maybe<T> doOnTerminate(final Action onTerminate) { public final Maybe<T> doOnSuccess(Consumer<? super T> onSuccess) { return RxJavaPlugins.onAssembly(new MaybePeek<T>(this, Functions.emptyConsumer(), // onSubscribe - ObjectHelper.requireNonNull(onSuccess, "onSubscribe is null"), + ObjectHelper.requireNonNull(onSuccess, "onSuccess is null"), Functions.emptyConsumer(), // onError Functions.EMPTY_ACTION, // onComplete Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete) @@ -3452,7 +3452,7 @@ public final Single<Boolean> isEmpty() { @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Maybe<R> lift(final MaybeOperator<? extends R, ? super T> lift) { - ObjectHelper.requireNonNull(lift, "onLift is null"); + ObjectHelper.requireNonNull(lift, "lift is null"); return RxJavaPlugins.onAssembly(new MaybeLift<T, R>(this, lift)); } @@ -4512,7 +4512,7 @@ public final Maybe<T> timeout(long timeout, TimeUnit timeUnit) { @NonNull @SchedulerSupport(SchedulerSupport.COMPUTATION) public final Maybe<T> timeout(long timeout, TimeUnit timeUnit, MaybeSource<? extends T> fallback) { - ObjectHelper.requireNonNull(fallback, "other is null"); + ObjectHelper.requireNonNull(fallback, "fallback is null"); return timeout(timeout, timeUnit, Schedulers.computation(), fallback); } diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index fe2989bae4..148f96c87b 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -1738,7 +1738,7 @@ public static <T> Observable<T> error(Callable<? extends Throwable> errorSupplie @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> error(final Throwable exception) { - ObjectHelper.requireNonNull(exception, "e is null"); + ObjectHelper.requireNonNull(exception, "exception is null"); return error(Functions.justCallable(exception)); } @@ -2046,7 +2046,7 @@ public static <T> Observable<T> fromPublisher(Publisher<? extends T> publisher) @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> generate(final Consumer<Emitter<T>> generator) { - ObjectHelper.requireNonNull(generator, "generator is null"); + ObjectHelper.requireNonNull(generator, "generator is null"); return generate(Functions.<Object>nullSupplier(), ObservableInternalHelper.simpleGenerator(generator), Functions.<Object>emptyConsumer()); } @@ -2078,7 +2078,7 @@ public static <T> Observable<T> generate(final Consumer<Emitter<T>> generator) { @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T, S> Observable<T> generate(Callable<S> initialState, final BiConsumer<S, Emitter<T>> generator) { - ObjectHelper.requireNonNull(generator, "generator is null"); + ObjectHelper.requireNonNull(generator, "generator is null"); return generate(initialState, ObservableInternalHelper.simpleBiGenerator(generator), Functions.emptyConsumer()); } @@ -2114,7 +2114,7 @@ public static <T, S> Observable<T> generate( final Callable<S> initialState, final BiConsumer<S, Emitter<T>> generator, Consumer<? super S> disposeState) { - ObjectHelper.requireNonNull(generator, "generator is null"); + ObjectHelper.requireNonNull(generator, "generator is null"); return generate(initialState, ObservableInternalHelper.simpleBiGenerator(generator), disposeState); } @@ -2180,7 +2180,7 @@ public static <T, S> Observable<T> generate(Callable<S> initialState, BiFunction public static <T, S> Observable<T> generate(Callable<S> initialState, BiFunction<S, Emitter<T>, S> generator, Consumer<? super S> disposeState) { ObjectHelper.requireNonNull(initialState, "initialState is null"); - ObjectHelper.requireNonNull(generator, "generator is null"); + ObjectHelper.requireNonNull(generator, "generator is null"); ObjectHelper.requireNonNull(disposeState, "disposeState is null"); return RxJavaPlugins.onAssembly(new ObservableGenerate<T, S>(initialState, generator, disposeState)); } @@ -2386,7 +2386,7 @@ public static Observable<Long> intervalRange(long start, long count, long initia @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item) { - ObjectHelper.requireNonNull(item, "The item is null"); + ObjectHelper.requireNonNull(item, "item is null"); return RxJavaPlugins.onAssembly(new ObservableJust<T>(item)); } @@ -2413,8 +2413,8 @@ public static <T> Observable<T> just(T item) { @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); return fromArray(item1, item2); } @@ -2444,9 +2444,9 @@ public static <T> Observable<T> just(T item1, T item2) { @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); return fromArray(item1, item2, item3); } @@ -2478,10 +2478,10 @@ public static <T> Observable<T> just(T item1, T item2, T item3) { @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); return fromArray(item1, item2, item3, item4); } @@ -2515,11 +2515,11 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4) { @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); return fromArray(item1, item2, item3, item4, item5); } @@ -2555,12 +2555,12 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5, T item6) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); - ObjectHelper.requireNonNull(item6, "The sixth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); + ObjectHelper.requireNonNull(item6, "item6 is null"); return fromArray(item1, item2, item3, item4, item5, item6); } @@ -2598,13 +2598,13 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); - ObjectHelper.requireNonNull(item6, "The sixth item is null"); - ObjectHelper.requireNonNull(item7, "The seventh item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); + ObjectHelper.requireNonNull(item6, "item6 is null"); + ObjectHelper.requireNonNull(item7, "item7 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7); } @@ -2644,14 +2644,14 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); - ObjectHelper.requireNonNull(item6, "The sixth item is null"); - ObjectHelper.requireNonNull(item7, "The seventh item is null"); - ObjectHelper.requireNonNull(item8, "The eighth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); + ObjectHelper.requireNonNull(item6, "item6 is null"); + ObjectHelper.requireNonNull(item7, "item7 is null"); + ObjectHelper.requireNonNull(item8, "item8 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7, item8); } @@ -2693,15 +2693,15 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8, T item9) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); - ObjectHelper.requireNonNull(item6, "The sixth item is null"); - ObjectHelper.requireNonNull(item7, "The seventh item is null"); - ObjectHelper.requireNonNull(item8, "The eighth item is null"); - ObjectHelper.requireNonNull(item9, "The ninth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); + ObjectHelper.requireNonNull(item6, "item6 is null"); + ObjectHelper.requireNonNull(item7, "item7 is null"); + ObjectHelper.requireNonNull(item8, "item8 is null"); + ObjectHelper.requireNonNull(item9, "item9 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7, item8, item9); } @@ -2745,16 +2745,16 @@ public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5 @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> just(T item1, T item2, T item3, T item4, T item5, T item6, T item7, T item8, T item9, T item10) { - ObjectHelper.requireNonNull(item1, "The first item is null"); - ObjectHelper.requireNonNull(item2, "The second item is null"); - ObjectHelper.requireNonNull(item3, "The third item is null"); - ObjectHelper.requireNonNull(item4, "The fourth item is null"); - ObjectHelper.requireNonNull(item5, "The fifth item is null"); - ObjectHelper.requireNonNull(item6, "The sixth item is null"); - ObjectHelper.requireNonNull(item7, "The seventh item is null"); - ObjectHelper.requireNonNull(item8, "The eighth item is null"); - ObjectHelper.requireNonNull(item9, "The ninth item is null"); - ObjectHelper.requireNonNull(item10, "The tenth item is null"); + ObjectHelper.requireNonNull(item1, "item1 is null"); + ObjectHelper.requireNonNull(item2, "item2 is null"); + ObjectHelper.requireNonNull(item3, "item3 is null"); + ObjectHelper.requireNonNull(item4, "item4 is null"); + ObjectHelper.requireNonNull(item5, "item5 is null"); + ObjectHelper.requireNonNull(item6, "item6 is null"); + ObjectHelper.requireNonNull(item7, "item7 is null"); + ObjectHelper.requireNonNull(item8, "item8 is null"); + ObjectHelper.requireNonNull(item9, "item9 is null"); + ObjectHelper.requireNonNull(item10, "item10 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10); } @@ -3995,7 +3995,6 @@ public static Observable<Long> timer(long delay, TimeUnit unit, Scheduler schedu @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> unsafeCreate(ObservableSource<T> onSubscribe) { - ObjectHelper.requireNonNull(onSubscribe, "source is null"); ObjectHelper.requireNonNull(onSubscribe, "onSubscribe is null"); if (onSubscribe instanceof Observable) { throw new IllegalArgumentException("unsafeCreate(Observable) should be upgraded"); @@ -8157,7 +8156,7 @@ private Observable<T> doOnEach(Consumer<? super T> onNext, Consumer<? super Thro @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Observable<T> doOnEach(final Consumer<? super Notification<T>> onNotification) { - ObjectHelper.requireNonNull(onNotification, "consumer is null"); + ObjectHelper.requireNonNull(onNotification, "onNotification is null"); return doOnEach( Functions.notificationOnNext(onNotification), Functions.notificationOnError(onNotification), @@ -9754,7 +9753,7 @@ public final Single<T> lastOrError() { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final <R> Observable<R> lift(ObservableOperator<? extends R, ? super T> lifter) { - ObjectHelper.requireNonNull(lifter, "onLift is null"); + ObjectHelper.requireNonNull(lifter, "lifter is null"); return RxJavaPlugins.onAssembly(new ObservableLift<R, T>(this, lifter)); } @@ -11240,7 +11239,7 @@ public final Observable<T> retryWhen( */ @SchedulerSupport(SchedulerSupport.NONE) public final void safeSubscribe(Observer<? super T> observer) { - ObjectHelper.requireNonNull(observer, "s is null"); + ObjectHelper.requireNonNull(observer, "observer is null"); if (observer instanceof SafeObserver) { subscribe(observer); } else { @@ -11499,7 +11498,7 @@ public final Observable<T> scan(BiFunction<T, T, T> accumulator) { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final <R> Observable<R> scan(final R initialValue, BiFunction<R, ? super T, R> accumulator) { - ObjectHelper.requireNonNull(initialValue, "seed is null"); + ObjectHelper.requireNonNull(initialValue, "initialValue is null"); return scanWith(Functions.justCallable(initialValue), accumulator); } @@ -13122,7 +13121,7 @@ public final <U> Observable<T> takeUntil(ObservableSource<U> other) { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Observable<T> takeUntil(Predicate<? super T> stopPredicate) { - ObjectHelper.requireNonNull(stopPredicate, "predicate is null"); + ObjectHelper.requireNonNull(stopPredicate, "stopPredicate is null"); return RxJavaPlugins.onAssembly(new ObservableTakeUntilPredicate<T>(this, stopPredicate)); } diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index d4b5f7aaf4..f7d02b7a99 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -584,7 +584,7 @@ public static <T> Single<T> error(final Callable<? extends Throwable> errorSuppl @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <T> Single<T> error(final Throwable exception) { - ObjectHelper.requireNonNull(exception, "error is null"); + ObjectHelper.requireNonNull(exception, "exception is null"); return error(Functions.justCallable(exception)); } @@ -834,7 +834,7 @@ public static <T> Single<T> fromObservable(ObservableSource<? extends T> observa @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <T> Single<T> just(final T item) { - ObjectHelper.requireNonNull(item, "value is null"); + ObjectHelper.requireNonNull(item, "item is null"); return RxJavaPlugins.onAssembly(new SingleJust<T>(item)); } @@ -2413,7 +2413,7 @@ public final <R> Maybe<R> dematerialize(Function<? super T, Notification<R>> sel @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) { - ObjectHelper.requireNonNull(onAfterSuccess, "doAfterSuccess is null"); + ObjectHelper.requireNonNull(onAfterSuccess, "onAfterSuccess is null"); return RxJavaPlugins.onAssembly(new SingleDoAfterSuccess<T>(this, onAfterSuccess)); } @@ -2980,7 +2980,7 @@ public final T blockingGet() { @NonNull @SchedulerSupport(SchedulerSupport.NONE) public final <R> Single<R> lift(final SingleOperator<? extends R, ? super T> lift) { - ObjectHelper.requireNonNull(lift, "onLift is null"); + ObjectHelper.requireNonNull(lift, "lift is null"); return RxJavaPlugins.onAssembly(new SingleLift<T, R>(this, lift)); } @@ -3593,7 +3593,7 @@ public final Disposable subscribe(final Consumer<? super T> onSuccess, final Con @SchedulerSupport(SchedulerSupport.NONE) @Override public final void subscribe(SingleObserver<? super T> observer) { - ObjectHelper.requireNonNull(observer, "subscriber is null"); + ObjectHelper.requireNonNull(observer, "observer is null"); observer = RxJavaPlugins.onSubscribe(this, observer); From b0cb174db6088d231f1385606f1907f2fc5f4afc Mon Sep 17 00:00:00 2001 From: vikas kumar <vkbookworm@gmail.com> Date: Thu, 21 Mar 2019 19:15:52 +0530 Subject: [PATCH 348/417] refactor: improves Creating-Observables wiki doc (#6436) --- docs/Creating-Observables.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/Creating-Observables.md b/docs/Creating-Observables.md index 8e31a56528..360e03ab09 100644 --- a/docs/Creating-Observables.md +++ b/docs/Creating-Observables.md @@ -37,8 +37,8 @@ There exist overloads with 2 to 9 arguments for convenience, which objects (with ```java Observable<Object> observable = Observable.just("1", "A", "3.2", "def"); -observable.subscribe(item -> System.out.print(item), error -> error.printStackTrace, - () -> System.out.println()); + observable.subscribe(item -> System.out.print(item), error -> error.printStackTrace(), + () -> System.out.println()); ``` ## From @@ -80,7 +80,7 @@ for (int i = 0; i < array.length; i++) { array[i] = i; } -Observable<Integer> observable = Observable.fromIterable(array); +Observable<Integer> observable = Observable.fromArray(array); observable.subscribe(item -> System.out.println(item), error -> error.printStackTrace(), () -> System.out.println("Done")); @@ -155,7 +155,7 @@ Given a pre-existing, already running or already completed `java.util.concurrent #### fromFuture example: ```java -ScheduledExecutorService executor = Executors.newSingleThreadedScheduledExecutor(); +ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); Future<String> future = executor.schedule(() -> "Hello world!", 1, TimeUnit.SECONDS); @@ -298,10 +298,10 @@ String greeting = "Hello World!"; Observable<Integer> indexes = Observable.range(0, greeting.length()); -Observable<Char> characters = indexes +Observable<Character> characters = indexes .map(index -> greeting.charAt(index)); -characters.subscribe(character -> System.out.print(character), erro -> error.printStackTrace(), +characters.subscribe(character -> System.out.print(character), error -> error.printStackTrace(), () -> System.out.println()); ``` @@ -396,7 +396,7 @@ Observable<String> error = Observable.error(new IOException()); error.subscribe( v -> System.out.println("This should never be printed!"), - error -> error.printStackTrace(), + e -> e.printStackTrace(), () -> System.out.println("This neither!")); ``` @@ -423,4 +423,4 @@ for (int i = 0; i < 10; i++) { error -> error.printStackTrace(), () -> System.out.println("Done")); } -``` +``` \ No newline at end of file From 0b3558dbf026411b665c581bc39034e27803e5e0 Mon Sep 17 00:00:00 2001 From: mgb <bmgbharath@gmail.com> Date: Tue, 26 Mar 2019 20:36:21 +0530 Subject: [PATCH 349/417] Undeliverable error handling logic for Completable operators (#6442) * Error handle on Completable.fromAction with RxJavaPlugins * Error handle on Completable.fromRunnable with RxJavaPlugins * Added error handling java docs section to Completable.fromRunnable --- src/main/java/io/reactivex/Completable.java | 7 +++++++ .../operators/completable/CompletableFromAction.java | 3 +++ .../operators/completable/CompletableFromRunnable.java | 3 +++ 3 files changed, 13 insertions(+) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 13364dc1a6..fe4d886dcd 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -508,6 +508,13 @@ public static <T> Completable fromMaybe(final MaybeSource<T> maybe) { * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromRunnable} does not operate by default on a particular {@link Scheduler}.</dd> + * <dt><b>Error handling:</b></dt> + * <dd> If the {@link Runnable} throws an exception, the respective {@link Throwable} is + * delivered to the downstream via {@link CompletableObserver#onError(Throwable)}, + * except when the downstream has disposed this {@code Completable} source. + * In this latter case, the {@code Throwable} is delivered to the global error handler via + * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}. + * </dd> * </dl> * @param run the runnable to run for each subscriber * @return the new Completable instance diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromAction.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromAction.java index 3e49bf0ec6..6722722390 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromAction.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromAction.java @@ -17,6 +17,7 @@ import io.reactivex.disposables.*; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Action; +import io.reactivex.plugins.RxJavaPlugins; public final class CompletableFromAction extends Completable { @@ -36,6 +37,8 @@ protected void subscribeActual(CompletableObserver observer) { Exceptions.throwIfFatal(e); if (!d.isDisposed()) { observer.onError(e); + } else { + RxJavaPlugins.onError(e); } return; } diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromRunnable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromRunnable.java index 981e6d1f1f..3ce78a167f 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableFromRunnable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableFromRunnable.java @@ -18,6 +18,7 @@ import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.Exceptions; +import io.reactivex.plugins.RxJavaPlugins; public final class CompletableFromRunnable extends Completable { @@ -37,6 +38,8 @@ protected void subscribeActual(CompletableObserver observer) { Exceptions.throwIfFatal(e); if (!d.isDisposed()) { observer.onError(e); + } else { + RxJavaPlugins.onError(e); } return; } From 4a78cfcbf2f0d7008042c15ea8bb6797fcd2b06e Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 26 Mar 2019 16:08:13 +0100 Subject: [PATCH 350/417] Release 2.2.8 --- CHANGES.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 16757d46b4..8b4d70b96b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,23 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.8 - March 26, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.8%7C)) + +#### Bugfixes + + - [Pull 6442](https://github.com/ReactiveX/RxJava/pull/6442): Add missing undeliverable error handling logic for `Completable.fromRunnable` & `fromAction` operators. + +#### Documentation changes + + - [Pull 6432](https://github.com/ReactiveX/RxJava/pull/6432): Improve the docs of `CompositeDisposable`. + - [Pull 6434](https://github.com/ReactiveX/RxJava/pull/6434): Improve subjects and processors package doc. + - [Pull 6436](https://github.com/ReactiveX/RxJava/pull/6436): Improve `Creating-Observables` wiki doc. + + +#### Other + + - [Pull 6433](https://github.com/ReactiveX/RxJava/pull/6433): Make error messages of parameter checks consistent. + ### Version 2.2.7 - February 23, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.7%7C)) #### API enhancements From 0f565f21eb041540358cf9f5bcd375069bcde188 Mon Sep 17 00:00:00 2001 From: Kuan-Yu Tseng <mycallmax@gmail.com> Date: Thu, 4 Apr 2019 11:37:16 -0700 Subject: [PATCH 351/417] Remove dependency of Schedulers from ObservableRefCount (#6452) In the constructor of `ObservableRefCount` that takes `ConnectableObservable<T> source` as the argument, we set `timeout` to `0L`. In that specific use case of `ObservableRefCount`, `scheduler` is never needed. It's only referenced in `cancel()` method but if timeout is 0, it won't be triggered at all because there is early return. This commit removes the need to depend on `Schedulers.trampoline()` and instead passes null to be scheduler when the ref count is not time-based. The reasons for this change are the following: 1. In projects that don't depend on `Schedulers` class, if there is no reference to `Schedulers`, the whole `Schedulers` can be stripped out of the library after optimizations (e.g., proguard). With constructor that references `Schedulers`, the optimizer can't properly strip it out. In our quick test of our Android app, we were able to reduce the RxJava library size dependency from 51KB to 37KB (after optimization but before compression) by simply avoiding access to `Schedulers` in `ObservableRefCount`. 2. In terms of modularity, `ObservableRefCount` is just an operator so it by itself should probably not have dependency on what available pool of schedulers (`Schedulers`) there are. It should just know that there is some `Scheduler` that could be passed to `ObservableRefCount` when `ObservableRefCount` needs it. --- .../internal/operators/flowable/FlowableRefCount.java | 3 +-- .../internal/operators/observable/ObservableRefCount.java | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java index bc11aa5425..02ed97b462 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java @@ -25,7 +25,6 @@ import io.reactivex.internal.disposables.*; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; /** * Returns an observable sequence that stays connected to the source as long as @@ -49,7 +48,7 @@ public final class FlowableRefCount<T> extends Flowable<T> { RefConnection connection; public FlowableRefCount(ConnectableFlowable<T> source) { - this(source, 1, 0L, TimeUnit.NANOSECONDS, Schedulers.trampoline()); + this(source, 1, 0L, TimeUnit.NANOSECONDS, null); } public FlowableRefCount(ConnectableFlowable<T> source, int n, long timeout, TimeUnit unit, diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java index 5abc174350..5306f4481d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java @@ -22,7 +22,6 @@ import io.reactivex.internal.disposables.*; import io.reactivex.observables.ConnectableObservable; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; /** * Returns an observable sequence that stays connected to the source as long as @@ -46,7 +45,7 @@ public final class ObservableRefCount<T> extends Observable<T> { RefConnection connection; public ObservableRefCount(ConnectableObservable<T> source) { - this(source, 1, 0L, TimeUnit.NANOSECONDS, Schedulers.trampoline()); + this(source, 1, 0L, TimeUnit.NANOSECONDS, null); } public ObservableRefCount(ConnectableObservable<T> source, int n, long timeout, TimeUnit unit, From 3958d1bd56e49947cf6253a51f982b300b56a145 Mon Sep 17 00:00:00 2001 From: Alexis Munsayac <alexis.munsayac@gmail.com> Date: Fri, 5 Apr 2019 02:56:17 +0800 Subject: [PATCH 352/417] Fixed typos for comments (#6453) * Update Maybe.java * Update Single.java --- src/main/java/io/reactivex/Maybe.java | 8 ++++---- src/main/java/io/reactivex/Single.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index 9fd5f6c810..e2266c6b50 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -3685,7 +3685,7 @@ public final Single<T> toSingle() { * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorComplete} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * @return the new Completable instance + * @return the new Maybe instance */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -3702,7 +3702,7 @@ public final Maybe<T> onErrorComplete() { * </dl> * @param predicate the predicate to call when an Throwable is emitted which should return true * if the Throwable should be swallowed and replaced with an onComplete. - * @return the new Completable instance + * @return the new Maybe instance */ @CheckReturnValue @NonNull @@ -3984,7 +3984,7 @@ public final Flowable<T> repeatWhen(final Function<? super Flowable<Object>, ? e * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * - * @return the nww Maybe instance + * @return the new Maybe instance * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ @CheckReturnValue @@ -4006,7 +4006,7 @@ public final Maybe<T> retry() { * @param predicate * the predicate that determines if a resubscription may happen in case of a specific exception * and retry count - * @return the nww Maybe instance + * @return the new Maybe instance * @see #retry() * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index f7d02b7a99..f97f4d22b7 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -476,7 +476,7 @@ public static <T> Flowable<T> concatEager(Iterable<? extends SingleSource<? exte } /** - * Provides an API (via a cold Completable) that bridges the reactive world with the callback-style world. + * Provides an API (via a cold Single) that bridges the reactive world with the callback-style world. * <p> * <img width="640" height="454" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.create.png" alt=""> * <p> From c04cfb8366534560e045f86201c05991763e1643 Mon Sep 17 00:00:00 2001 From: Roman Wuattier <roman.wuattier@gmail.com> Date: Fri, 12 Apr 2019 14:03:32 +0200 Subject: [PATCH 353/417] Update the Javadoc of the `retry` operator (#6458) Specify that the `times` function parameter describes "the number of times to resubscribe if the current *operator* fails". Also, this commit updates some unit tests to illustrate the Javadoc wording. Solves: #6402 --- src/main/java/io/reactivex/Completable.java | 4 ++-- src/main/java/io/reactivex/Flowable.java | 4 ++-- src/main/java/io/reactivex/Maybe.java | 4 ++-- src/main/java/io/reactivex/Observable.java | 4 ++-- .../io/reactivex/completable/CompletableTest.java | 6 ++++-- .../internal/operators/single/SingleMiscTest.java | 10 ++++++++-- src/test/java/io/reactivex/maybe/MaybeTest.java | 13 +++++++++++++ 7 files changed, 33 insertions(+), 12 deletions(-) diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index fe4d886dcd..79fcc9b432 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -2090,7 +2090,7 @@ public final Completable retry(BiPredicate<? super Integer, ? super Throwable> p * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * @param times the number of times the returned Completable should retry this Completable + * @param times the number of times to resubscribe if the current Completable fails * @return the new Completable instance * @throws IllegalArgumentException if times is negative */ @@ -2110,7 +2110,7 @@ public final Completable retry(long times) { * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p>History: 2.1.8 - experimental - * @param times the number of times the returned Completable should retry this Completable + * @param times the number of times to resubscribe if the current Completable fails * @param predicate the predicate that is called with the latest throwable and should return * true to indicate the returned Completable should resubscribe to this Completable. * @return the new Completable instance diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index ff85859f99..550b2958ce 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -13399,7 +13399,7 @@ public final Flowable<T> retry(BiPredicate<? super Integer, ? super Throwable> p * </dl> * * @param count - * number of retry attempts before failing + * the number of times to resubscribe if the current Flowable fails * @return the source Publisher modified with retry logic * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ @@ -13420,7 +13420,7 @@ public final Flowable<T> retry(long count) { * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * @param times the number of times to repeat + * @param times the number of times to resubscribe if the current Flowable fails * @param predicate the predicate called with the failure Throwable and should return true to trigger a retry. * @return the new Flowable instance */ diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index e2266c6b50..c123aa2316 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -4031,7 +4031,7 @@ public final Maybe<T> retry(BiPredicate<? super Integer, ? super Throwable> pred * </dl> * * @param count - * number of retry attempts before failing + * the number of times to resubscribe if the current Maybe fails * @return the new Maybe instance * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ @@ -4048,7 +4048,7 @@ public final Maybe<T> retry(long count) { * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * @param times the number of times to repeat + * @param times the number of times to resubscribe if the current Maybe fails * @param predicate the predicate called with the failure Throwable and should return true to trigger a retry. * @return the new Maybe instance */ diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 148f96c87b..15b453cd45 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -11075,7 +11075,7 @@ public final Observable<T> retry(BiPredicate<? super Integer, ? super Throwable> * </dl> * * @param times - * number of retry attempts before failing + * the number of times to resubscribe if the current Observable fails * @return the source ObservableSource modified with retry logic * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ @@ -11093,7 +11093,7 @@ public final Observable<T> retry(long times) { * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * @param times the number of times to repeat + * @param times the number of times to resubscribe if the current Observable fails * @param predicate the predicate called with the failure Throwable and should return true to trigger a retry. * @return the new Observable instance */ diff --git a/src/test/java/io/reactivex/completable/CompletableTest.java b/src/test/java/io/reactivex/completable/CompletableTest.java index 4798973835..80f4b49d5a 100644 --- a/src/test/java/io/reactivex/completable/CompletableTest.java +++ b/src/test/java/io/reactivex/completable/CompletableTest.java @@ -2398,18 +2398,20 @@ public void retryTimes5Error() { @Test(timeout = 5000) public void retryTimes5Normal() { - final AtomicInteger calls = new AtomicInteger(5); + final AtomicInteger calls = new AtomicInteger(); Completable c = Completable.fromAction(new Action() { @Override public void run() { - if (calls.decrementAndGet() != 0) { + if (calls.incrementAndGet() != 6) { throw new TestException(); } } }).retry(5); c.blockingAwait(); + + assertEquals(6, calls.get()); } @Test(expected = IllegalArgumentException.class) diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java index c811291851..7b3a891680 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleMiscTest.java @@ -27,7 +27,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; @@ -199,11 +201,13 @@ public boolean test(Integer i, Throwable e) throws Exception { @Test public void retryTimes() { + final AtomicInteger calls = new AtomicInteger(); + Single.fromCallable(new Callable<Object>() { - int c; + @Override public Object call() throws Exception { - if (++c != 5) { + if (calls.incrementAndGet() != 6) { throw new TestException(); } return 1; @@ -212,6 +216,8 @@ public Object call() throws Exception { .retry(5) .test() .assertResult(1); + + assertEquals(6, calls.get()); } @Test diff --git a/src/test/java/io/reactivex/maybe/MaybeTest.java b/src/test/java/io/reactivex/maybe/MaybeTest.java index 41225a47cc..45b31b0a8a 100644 --- a/src/test/java/io/reactivex/maybe/MaybeTest.java +++ b/src/test/java/io/reactivex/maybe/MaybeTest.java @@ -3185,6 +3185,19 @@ public Publisher<Object> apply(Flowable<? extends Throwable> v) throws Exception return (Publisher)v; } }).test().assertResult(1); + + final AtomicInteger calls = new AtomicInteger(); + try { + Maybe.error(new Callable<Throwable>() { + @Override + public Throwable call() { + calls.incrementAndGet(); + return new TestException(); + } + }).retry(5).test(); + } finally { + assertEquals(6, calls.get()); + } } @Test From deeb14150ac21ad8c7b38c1ac692be487375faf5 Mon Sep 17 00:00:00 2001 From: IRuizM <13287486+IRuizM@users.noreply.github.com> Date: Sat, 13 Apr 2019 14:59:19 +0200 Subject: [PATCH 354/417] Change error message in ObservableFromArray (#6461) * Change error message in ObservableFromArray Changed error message from "The $i th element is null" to "The element at index $i is null". Solves #6460 * Change error messages in FlowableFromArray Changed error messages from "array element is null" to "The element at index $i is null". Solves #6460 --- .../internal/operators/flowable/FlowableFromArray.java | 8 ++++---- .../operators/observable/ObservableFromArray.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java index c8c6201daa..d54fb15a21 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java @@ -126,7 +126,7 @@ void fastPath() { } T t = arr[i]; if (t == null) { - a.onError(new NullPointerException("array element is null")); + a.onError(new NullPointerException("The element at index " + i + " is null")); return; } else { a.onNext(t); @@ -156,7 +156,7 @@ void slowPath(long r) { T t = arr[i]; if (t == null) { - a.onError(new NullPointerException("array element is null")); + a.onError(new NullPointerException("The element at index " + i + " is null")); return; } else { a.onNext(t); @@ -209,7 +209,7 @@ void fastPath() { } T t = arr[i]; if (t == null) { - a.onError(new NullPointerException("array element is null")); + a.onError(new NullPointerException("The element at index " + i + " is null")); return; } else { a.tryOnNext(t); @@ -239,7 +239,7 @@ void slowPath(long r) { T t = arr[i]; if (t == null) { - a.onError(new NullPointerException("array element is null")); + a.onError(new NullPointerException("The element at index " + i + " is null")); return; } else { if (a.tryOnNext(t)) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java index 11b871ee46..9a04a4fcc3 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java @@ -102,7 +102,7 @@ void run() { for (int i = 0; i < n && !isDisposed(); i++) { T value = a[i]; if (value == null) { - downstream.onError(new NullPointerException("The " + i + "th element is null")); + downstream.onError(new NullPointerException("The element at index " + i + " is null")); return; } downstream.onNext(value); From b570c912a507485c5fd8afee1dbd442836db0629 Mon Sep 17 00:00:00 2001 From: Alexis Munsayac <alexis.munsayac@gmail.com> Date: Fri, 26 Apr 2019 18:49:27 +0800 Subject: [PATCH 355/417] Remove redundant methods from Sample(Observable) (#6469) * Update Maybe.java * Update Single.java * Update ObservableSampleWithObservable.java * Update FlowableSamplePublisher.java * Update FlowableSamplePublisher.java --- .../flowable/FlowableSamplePublisher.java | 26 ++++--------------- .../ObservableSampleWithObservable.java | 26 ++++--------------- 2 files changed, 10 insertions(+), 42 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java index 55439eee69..66b9c48ec3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java @@ -90,7 +90,7 @@ public void onError(Throwable t) { @Override public void onComplete() { SubscriptionHelper.cancel(other); - completeMain(); + completion(); } void setOther(Subscription o) { @@ -117,7 +117,7 @@ public void error(Throwable e) { public void complete() { upstream.cancel(); - completeOther(); + completion(); } void emit() { @@ -134,9 +134,7 @@ void emit() { } } - abstract void completeMain(); - - abstract void completeOther(); + abstract void completion(); abstract void run(); } @@ -178,12 +176,7 @@ static final class SampleMainNoLast<T> extends SamplePublisherSubscriber<T> { } @Override - void completeMain() { - downstream.onComplete(); - } - - @Override - void completeOther() { + void completion() { downstream.onComplete(); } @@ -207,16 +200,7 @@ static final class SampleMainEmitLast<T> extends SamplePublisherSubscriber<T> { } @Override - void completeMain() { - done = true; - if (wip.getAndIncrement() == 0) { - emit(); - downstream.onComplete(); - } - } - - @Override - void completeOther() { + void completion() { done = true; if (wip.getAndIncrement() == 0) { emit(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleWithObservable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleWithObservable.java index fcb0f33a00..1d5f8a5fe1 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleWithObservable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSampleWithObservable.java @@ -84,7 +84,7 @@ public void onError(Throwable t) { @Override public void onComplete() { DisposableHelper.dispose(other); - completeMain(); + completion(); } boolean setOther(Disposable o) { @@ -109,7 +109,7 @@ public void error(Throwable e) { public void complete() { upstream.dispose(); - completeOther(); + completion(); } void emit() { @@ -119,9 +119,7 @@ void emit() { } } - abstract void completeMain(); - - abstract void completeOther(); + abstract void completion(); abstract void run(); } @@ -163,12 +161,7 @@ static final class SampleMainNoLast<T> extends SampleMainObserver<T> { } @Override - void completeMain() { - downstream.onComplete(); - } - - @Override - void completeOther() { + void completion() { downstream.onComplete(); } @@ -192,16 +185,7 @@ static final class SampleMainEmitLast<T> extends SampleMainObserver<T> { } @Override - void completeMain() { - done = true; - if (wip.getAndIncrement() == 0) { - emit(); - downstream.onComplete(); - } - } - - @Override - void completeOther() { + void completion() { done = true; if (wip.getAndIncrement() == 0) { emit(); From ac84182aa2bd866b53e01c8e3fe99683b882c60e Mon Sep 17 00:00:00 2001 From: OH JAE HWAN <ojh102@gmail.com> Date: Mon, 29 Apr 2019 04:46:09 +0900 Subject: [PATCH 356/417] remove unused import in Flowable.java (#6470) --- src/main/java/io/reactivex/Flowable.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 550b2958ce..fe27b9bfd3 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -17,7 +17,6 @@ import org.reactivestreams.*; -import io.reactivex.Observable; import io.reactivex.annotations.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.Exceptions; From 1830453000ff04b099074bde1a17fa594b5468aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cristiano=20Gavi=C3=A3o?= <cvgaviao@users.noreply.github.com> Date: Sat, 18 May 2019 14:14:17 -0300 Subject: [PATCH 357/417] Update README.md (#6480) fix issue #6479 --- README.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c29d6d3fc0..982f0c393d 100644 --- a/README.md +++ b/README.md @@ -258,12 +258,10 @@ Flowable.range(1, 10) ```java Flowable<Inventory> inventorySource = warehouse.getInventoryAsync(); -inventorySource.flatMap(inventoryItem -> - erp.getDemandAsync(inventoryItem.getId()) - .map(demand - -> System.out.println("Item " + inventoryItem.getName() + " has demand " + demand)); - ) - .subscribe(); +inventorySource + .flatMap(inventoryItem -> erp.getDemandAsync(inventoryItem.getId()) + .map(demand -> "Item " + inventoryItem.getName() + " has demand " + demand)) + .subscribe(System.out::println); ``` ### Continuations From 8f51d2df7dfa4cfbf735a68085e6673aaa4a2856 Mon Sep 17 00:00:00 2001 From: Alexis Munsayac <alexis.munsayac@gmail.com> Date: Mon, 20 May 2019 17:01:03 +0800 Subject: [PATCH 358/417] Correction for Maybe.count doc typo (#6483) Resolves #6481 --- src/main/java/io/reactivex/Maybe.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/Maybe.java b/src/main/java/io/reactivex/Maybe.java index c123aa2316..aecb501348 100644 --- a/src/main/java/io/reactivex/Maybe.java +++ b/src/main/java/io/reactivex/Maybe.java @@ -2489,7 +2489,7 @@ public final Single<Boolean> contains(final Object item) { } /** - * Returns a Maybe that counts the total number of items emitted (0 or 1) by the source Maybe and emits + * Returns a Single that counts the total number of items emitted (0 or 1) by the source Maybe and emits * this count as a 64-bit Long. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/longCount.png" alt=""> From 4ca7a9b91df673801ed6d09a7d79cfeff7699f79 Mon Sep 17 00:00:00 2001 From: Volodymyr <vovochkastelmashchuk@gmail.com> Date: Thu, 23 May 2019 20:17:32 +0300 Subject: [PATCH 359/417] remove unused else from the Observable (#6485) * remove unused else from the Observable * fixed MR comments --- src/main/java/io/reactivex/Observable.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 15b453cd45..5bdd940909 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -84,12 +84,12 @@ * System.out.println("Done!"); * } * }); - * + * * Thread.sleep(500); * // the sequence can now be disposed via dispose() * d.dispose(); * </code></pre> - * + * * @param <T> * the type of the items emitted by the Observable * @see Flowable @@ -1278,7 +1278,7 @@ public static <T> Observable<T> concat( public static <T> Observable<T> concatArray(ObservableSource<? extends T>... sources) { if (sources.length == 0) { return empty(); - } else + } if (sources.length == 1) { return wrap((ObservableSource<T>)sources[0]); } @@ -1305,7 +1305,7 @@ public static <T> Observable<T> concatArray(ObservableSource<? extends T>... sou public static <T> Observable<T> concatArrayDelayError(ObservableSource<? extends T>... sources) { if (sources.length == 0) { return empty(); - } else + } if (sources.length == 1) { return (Observable<T>)wrap(sources[0]); } @@ -1765,7 +1765,7 @@ public static <T> Observable<T> fromArray(T... items) { ObjectHelper.requireNonNull(items, "items is null"); if (items.length == 0) { return empty(); - } else + } if (items.length == 1) { return just(items[0]); } @@ -9626,7 +9626,7 @@ public final Single<T> lastOrError() { * Example: * <pre><code> * // Step 1: Create the consumer type that will be returned by the ObservableOperator.apply(): - * + * * public final class CustomObserver<T> implements Observer<T>, Disposable { * * // The downstream's Observer that will receive the onXXX events @@ -12816,10 +12816,10 @@ public final Observable<T> take(long time, TimeUnit unit, Scheduler scheduler) { public final Observable<T> takeLast(int count) { if (count < 0) { throw new IndexOutOfBoundsException("count >= 0 required but it was " + count); - } else + } if (count == 0) { return RxJavaPlugins.onAssembly(new ObservableIgnoreElements<T>(this)); - } else + } if (count == 1) { return RxJavaPlugins.onAssembly(new ObservableTakeLastOne<T>(this)); } From c415b322614aedddd6a5d6d7e5b838e49f3fde4c Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 27 May 2019 10:23:32 +0200 Subject: [PATCH 360/417] 2.x: Fix zip not stopping the subscription upon eager error (#6488) --- .../operators/observable/ObservableZip.java | 4 +++ .../operators/flowable/FlowableZipTest.java | 30 +++++++++++++++++++ .../observable/ObservableZipTest.java | 30 +++++++++++++++++++ 3 files changed, 64 insertions(+) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java index a259cd6d56..af465c43c6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java @@ -179,6 +179,7 @@ public void drain() { if (z.done && !delayError) { Throwable ex = z.error; if (ex != null) { + cancelled = true; cancel(); a.onError(ex); return; @@ -224,6 +225,7 @@ boolean checkTerminated(boolean d, boolean empty, Observer<? super R> a, boolean if (delayError) { if (empty) { Throwable e = source.error; + cancelled = true; cancel(); if (e != null) { a.onError(e); @@ -235,11 +237,13 @@ boolean checkTerminated(boolean d, boolean empty, Observer<? super R> a, boolean } else { Throwable e = source.error; if (e != null) { + cancelled = true; cancel(); a.onError(e); return true; } else if (empty) { + cancelled = true; cancel(); a.onComplete(); return true; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java index ef1223d66a..12f81c33e0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java @@ -1895,4 +1895,34 @@ public Integer apply(Integer a, Integer b) throws Exception { ts.assertResult(4); } + + @Test + public void firstErrorPreventsSecondSubscription() { + final AtomicInteger counter = new AtomicInteger(); + + List<Flowable<?>> flowableList = new ArrayList<Flowable<?>>(); + flowableList.add(Flowable.create(new FlowableOnSubscribe<Object>() { + @Override + public void subscribe(FlowableEmitter<Object> e) + throws Exception { throw new TestException(); } + }, BackpressureStrategy.MISSING)); + flowableList.add(Flowable.create(new FlowableOnSubscribe<Object>() { + @Override + public void subscribe(FlowableEmitter<Object> e) + throws Exception { counter.getAndIncrement(); } + }, BackpressureStrategy.MISSING)); + + Flowable.zip(flowableList, + new Function<Object[], Object>() { + @Override + public Object apply(Object[] a) throws Exception { + return a; + } + }) + .test() + .assertFailure(TestException.class) + ; + + assertEquals(0, counter.get()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java index 2fc7d7cb52..ba86f16175 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java @@ -1428,4 +1428,34 @@ public Integer apply(Integer t1, Integer t2) throws Exception { ps2.onNext(2); to.assertResult(3); } + + @Test + public void firstErrorPreventsSecondSubscription() { + final AtomicInteger counter = new AtomicInteger(); + + List<Observable<?>> observableList = new ArrayList<Observable<?>>(); + observableList.add(Observable.create(new ObservableOnSubscribe<Object>() { + @Override + public void subscribe(ObservableEmitter<Object> e) + throws Exception { throw new TestException(); } + })); + observableList.add(Observable.create(new ObservableOnSubscribe<Object>() { + @Override + public void subscribe(ObservableEmitter<Object> e) + throws Exception { counter.getAndIncrement(); } + })); + + Observable.zip(observableList, + new Function<Object[], Object>() { + @Override + public Object apply(Object[] a) throws Exception { + return a; + } + }) + .test() + .assertFailure(TestException.class) + ; + + assertEquals(0, counter.get()); + } } From 86048e18479daff55aca132098dcfa0f123cc29f Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 30 May 2019 09:08:32 +0200 Subject: [PATCH 361/417] Release 2.2.9 --- CHANGES.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 8b4d70b96b..7a5a441cea 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,25 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.9 - May 30, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.9%7C)) + +#### Bugfixes + + - [Pull 6488](https://github.com/ReactiveX/RxJava/pull/6488): Fix `zip` not stopping the subscription upon eager error. + +#### Documentation changes + + - [Pull 6453](https://github.com/ReactiveX/RxJava/pull/6453): Fixed wrong type referenced in `Maybe` and `Single` JavaDocs. + - [Pull 6458](https://github.com/ReactiveX/RxJava/pull/6458): Update the Javadoc of the `retry` operator. + +#### Other + + - [Pull 6452](https://github.com/ReactiveX/RxJava/pull/6452): Remove dependency of `Schedulers` from `ObservableRefCount`. + - [Pull 6461](https://github.com/ReactiveX/RxJava/pull/6461): Change error message in `ObservableFromArray`. + - [Pull 6469](https://github.com/ReactiveX/RxJava/pull/6469): Remove redundant methods from `sample(Observable)`. + - [Pull 6470](https://github.com/ReactiveX/RxJava/pull/6470): Remove unused import from `Flowable.java`. + - [Pull 6485](https://github.com/ReactiveX/RxJava/pull/6485): Remove unused `else` from the `Observable`. + ### Version 2.2.8 - March 26, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.8%7C)) #### Bugfixes From 368e0b422cee3848078e2d15c720d87ab571b8b5 Mon Sep 17 00:00:00 2001 From: kongngng <51318004+kongngng@users.noreply.github.com> Date: Tue, 4 Jun 2019 19:44:42 +0900 Subject: [PATCH 362/417] Update Additional-Reading.md (#6496) * Update Additional-Reading.md #6132 - 'What is Reactive Programming?' was wrong link, so deleted. - First line was edited. * Update Additional-Reading.md - add 'What is Reactive Programming?' link. --- docs/Additional-Reading.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/Additional-Reading.md b/docs/Additional-Reading.md index b5a4a2604a..d634e956a6 100644 --- a/docs/Additional-Reading.md +++ b/docs/Additional-Reading.md @@ -1,4 +1,4 @@ -(A more complete and up-to-date list of resources can be found at the reactivex.io site: [[http://reactivex.io/tutorials.html]]) +A more complete and up-to-date list of resources can be found at the [reactivex.io site](http://reactivex.io/tutorials.html) # Introducing Reactive Programming * [Introduction to Rx](http://www.introtorx.com/): a free, on-line book by Lee Campbell **(1.x)** @@ -10,7 +10,7 @@ * [Your Mouse is a Database](http://queue.acm.org/detail.cfm?id=2169076) by Erik Meijer * [A Playful Introduction to Rx](https://www.youtube.com/watch?v=WKore-AkisY) a video lecture by Erik Meijer * Wikipedia: [Reactive Programming](http://en.wikipedia.org/wiki/Reactive_programming) and [Functional Reactive Programming](http://en.wikipedia.org/wiki/Functional_reactive_programming) -* [What is Reactive Programming?](http://blog.hackhands.com/overview-of-reactive-programming/) a video presentation by Jafar Husain. +* [What is Reactive Programming?](https://www.youtube.com/watch?v=-8Y1-lE6NSA) a video presentation by Jafar Husain. * [2 minute introduction to Rx](https://medium.com/@andrestaltz/2-minute-introduction-to-rx-24c8ca793877) by André Staltz * StackOverflow: [What is (functional) reactive programming?](http://stackoverflow.com/a/1030631/1946802) * [The Reactive Manifesto](http://www.reactivemanifesto.org/) From 68ad8e24ad2ecf13285b3044cbb31c302653a3c0 Mon Sep 17 00:00:00 2001 From: Kyeonghwan Kong <51318004+khkong@users.noreply.github.com> Date: Tue, 4 Jun 2019 23:09:54 +0900 Subject: [PATCH 363/417] Update Alphabetical-List-of-Observable-Operators.md (#6497) #6132 * Invalid link edited. --- ...phabetical-List-of-Observable-Operators.md | 496 +++++++++--------- 1 file changed, 248 insertions(+), 248 deletions(-) diff --git a/docs/Alphabetical-List-of-Observable-Operators.md b/docs/Alphabetical-List-of-Observable-Operators.md index 86495638c0..e5728356bc 100644 --- a/docs/Alphabetical-List-of-Observable-Operators.md +++ b/docs/Alphabetical-List-of-Observable-Operators.md @@ -1,250 +1,250 @@ -* **`aggregate( )`** — _see [**`reduce( )`**](Mathematical-and-Aggregate-Operators#reduce)_ -* [**`all( )`**](Conditional-and-Boolean-Operators#all) — determine whether all items emitted by an Observable meet some criteria -* [**`amb( )`**](Conditional-and-Boolean-Operators#amb) — given two or more source Observables, emits all of the items from the first of these Observables to emit an item -* **`ambWith( )`** — _instance version of [**`amb( )`**](Conditional-and-Boolean-Operators#amb)_ -* [**`and( )`**](Combining-Observables#and-then-and-when) — combine the emissions from two or more source Observables into a `Pattern` (`rxjava-joins`) -* **`apply( )`** (scala) — _see [**`create( )`**](Creating-Observables#create)_ -* **`asObservable( )`** (kotlin) — _see [**`from( )`**](Creating-Observables#from) (et al.)_ -* [**`asyncAction( )`**](Async-Operators#toasync-or-asyncaction-or-asyncfunc) — convert an Action into an Observable that executes the Action and emits its return value (`rxjava-async`) -* [**`asyncFunc( )`**](Async-Operators#toasync-or-asyncaction-or-asyncfunc) — convert a function into an Observable that executes the function and emits its return value (`rxjava-async`) -* [**`averageDouble( )`**](Mathematical-and-Aggregate-Operators#averageinteger-averagelong-averagefloat-and-averagedouble) — calculates the average of Doubles emitted by an Observable and emits this average (`rxjava-math`) -* [**`averageFloat( )`**](Mathematical-and-Aggregate-Operators#averageinteger-averagelong-averagefloat-and-averagedouble) — calculates the average of Floats emitted by an Observable and emits this average (`rxjava-math`) -* [**`averageInteger( )`**](Mathematical-and-Aggregate-Operators#averageinteger-averagelong-averagefloat-and-averagedouble) — calculates the average of Integers emitted by an Observable and emits this average (`rxjava-math`) -* [**`averageLong( )`**](Mathematical-and-Aggregate-Operators#averageinteger-averagelong-averagefloat-and-averagedouble) — calculates the average of Longs emitted by an Observable and emits this average (`rxjava-math`) -* **`blocking( )`** (clojure) — _see [**`toBlocking( )`**](Blocking-Observable-Operators)_ -* [**`buffer( )`**](Transforming-Observables#buffer) — periodically gather items from an Observable into bundles and emit these bundles rather than emitting the items one at a time -* [**`byLine( )`**](String-Observables#byline) (`StringObservable`) — converts an Observable of Strings into an Observable of Lines by treating the source sequence as a stream and splitting it on line-endings -* [**`cache( )`**](Observable-Utility-Operators#cache) — remember the sequence of items emitted by the Observable and emit the same sequence to future Subscribers -* [**`cast( )`**](Transforming-Observables#cast) — cast all items from the source Observable into a particular type before reemitting them -* **`catch( )`** (clojure) — _see [**`onErrorResumeNext( )`**](Error-Handling-Operators#onerrorresumenext)_ -* [**`chunkify( )`**](Phantom-Operators#chunkify) — returns an iterable that periodically returns a list of items emitted by the source Observable since the last list (⁇) -* [**`collect( )`**](Mathematical-and-Aggregate-Operators#collect) — collects items emitted by the source Observable into a single mutable data structure and returns an Observable that emits this structure -* [**`combineLatest( )`**](Combining-Observables#combinelatest) — when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function -* **`combineLatestWith( )`** (scala) — _instance version of [**`combineLatest( )`**](Combining-Observables#combinelatest)_ -* [**`concat( )`**](Mathematical-and-Aggregate-Operators#concat) — concatenate two or more Observables sequentially -* [**`concatMap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable) — transform the items emitted by an Observable into Observables, then flatten this into a single Observable, without interleaving -* **`concatWith( )`** — _instance version of [**`concat( )`**](Mathematical-and-Aggregate-Operators#concat)_ -* [**`connect( )`**](Connectable-Observable-Operators#connectableobservableconnect) — instructs a Connectable Observable to begin emitting items -* **`cons( )`** (clojure) — _see [**`concat( )`**](Mathematical-and-Aggregate-Operators#concat)_ -* [**`contains( )`**](Conditional-and-Boolean-Operators#contains) — determine whether an Observable emits a particular item or not -* [**`count( )`**](Mathematical-and-Aggregate-Operators#count-and-countlong) — counts the number of items emitted by an Observable and emits this count -* [**`countLong( )`**](Mathematical-and-Aggregate-Operators#count-and-countlong) — counts the number of items emitted by an Observable and emits this count -* [**`create( )`**](Creating-Observables#create) — create an Observable from scratch by means of a function -* **`cycle( )`** (clojure) — _see [**`repeat( )`**](Creating-Observables#repeat)_ -* [**`debounce( )`**](Filtering-Observables#throttlewithtimeout-or-debounce) — only emit an item from the source Observable after a particular timespan has passed without the Observable emitting any other items -* [**`decode( )`**](String-Observables#decode) (`StringObservable`) — convert a stream of multibyte characters into an Observable that emits byte arrays that respect character boundaries -* [**`defaultIfEmpty( )`**](Conditional-and-Boolean-Operators#defaultifempty) — emit items from the source Observable, or emit a default item if the source Observable completes after emitting no items -* [**`defer( )`**](Creating-Observables#defer) — do not create the Observable until a Subscriber subscribes; create a fresh Observable on each subscription -* [**`deferFuture( )`**](Async-Operators#deferfuture) — convert a Future that returns an Observable into an Observable, but do not attempt to get the Observable that the Future returns until a Subscriber subscribes (`rxjava-async`) -* [**`deferCancellableFuture( )`**](Phantom-Operators#fromcancellablefuture-startcancellablefuture-and-defercancellablefuture-) — convert a Future that returns an Observable into an Observable in a way that monitors the subscription status of the Observable to determine whether to halt work on the Future, but do not attempt to get the returned Observable until a Subscriber subscribes (⁇)(`rxjava-async`) -* [**`delay( )`**](Observable-Utility-Operators#delay) — shift the emissions from an Observable forward in time by a specified amount -* [**`dematerialize( )`**](Observable-Utility-Operators#dematerialize) — convert a materialized Observable back into its non-materialized form -* [**`distinct( )`**](Filtering-Observables#distinct) — suppress duplicate items emitted by the source Observable -* [**`distinctUntilChanged( )`**](Filtering-Observables#distinctuntilchanged) — suppress duplicate consecutive items emitted by the source Observable -* **`do( )`** (clojure) — _see [**`doOnEach( )`**](Observable-Utility-Operators#dooneach)_ -* [**`doOnCompleted( )`**](Observable-Utility-Operators#dooncompleted) — register an action to take when an Observable completes successfully -* [**`doOnEach( )`**](Observable-Utility-Operators#dooneach) — register an action to take whenever an Observable emits an item -* [**`doOnError( )`**](Observable-Utility-Operators#doonerror) — register an action to take when an Observable completes with an error -* **`doOnNext( )`** — _see [**`doOnEach( )`**](Observable-Utility-Operators#dooneach)_ +* **`aggregate( )`** — _see [**`reduce( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#reduce)_ +* [**`all( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#boolean-operators) — determine whether all items emitted by an Observable meet some criteria +* [**`amb( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators) — given two or more source Observables, emits all of the items from the first of these Observables to emit an item +* **`ambWith( )`** — _instance version of [**`amb( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators)_ +* [**`and( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#and-then-and-when) — combine the emissions from two or more source Observables into a `Pattern` (`rxjava-joins`) +* **`apply( )`** (scala) — _see [**`create( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#create)_ +* **`asObservable( )`** (kotlin) — _see [**`from( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#from) (et al.)_ +* [**`asyncAction( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators#toasync-or-asyncaction-or-asyncfunc) — convert an Action into an Observable that executes the Action and emits its return value (`rxjava-async`) +* [**`asyncFunc( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators#toasync-or-asyncaction-or-asyncfunc) — convert a function into an Observable that executes the function and emits its return value (`rxjava-async`) +* [**`averageDouble( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#averagedouble) — calculates the average of Doubles emitted by an Observable and emits this average (`rxjava-math`) +* [**`averageFloat( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#averagefloat) — calculates the average of Floats emitted by an Observable and emits this average (`rxjava-math`) +* [**`averageInteger( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators) — calculates the average of Integers emitted by an Observable and emits this average (`rxjava-math`) +* [**`averageLong( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators) — calculates the average of Longs emitted by an Observable and emits this average (`rxjava-math`) +* **`blocking( )`** (clojure) — _see [**`toBlocking( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators)_ +* [**`buffer( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#buffer) — periodically gather items from an Observable into bundles and emit these bundles rather than emitting the items one at a time +* [**`byLine( )`**](https://github.com/ReactiveX/RxJava/wiki/String-Observables) (`StringObservable`) — converts an Observable of Strings into an Observable of Lines by treating the source sequence as a stream and splitting it on line-endings +* [**`cache( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — remember the sequence of items emitted by the Observable and emit the same sequence to future Subscribers +* [**`cast( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#cast) — cast all items from the source Observable into a particular type before reemitting them +* **`catch( )`** (clojure) — _see [**`onErrorResumeNext( )`**](https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators#onerrorresumenext)_ +* [**`chunkify( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#chunkify) — returns an iterable that periodically returns a list of items emitted by the source Observable since the last list (⁇) +* [**`collect( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#collect) — collects items emitted by the source Observable into a single mutable data structure and returns an Observable that emits this structure +* [**`combineLatest( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#combinelatest) — when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function +* **`combineLatestWith( )`** (scala) — _instance version of [**`combineLatest( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#combinelatest)_ +* [**`concat( )`**](http://reactivex.io/documentation/operators/concat.html) — concatenate two or more Observables sequentially +* [**`concatMap( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#concatmap) — transform the items emitted by an Observable into Observables, then flatten this into a single Observable, without interleaving +* **`concatWith( )`** — _instance version of [**`concat( )`**](http://reactivex.io/documentation/operators/concat.html)_ +* [**`connect( )`**](https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators) — instructs a Connectable Observable to begin emitting items +* **`cons( )`** (clojure) — _see [**`concat( )`**](http://reactivex.io/documentation/operators/concat.html)_ +* [**`contains( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#boolean-operators) — determine whether an Observable emits a particular item or not +* [**`count( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#count) — counts the number of items emitted by an Observable and emits this count +* [**`countLong( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#count) — counts the number of items emitted by an Observable and emits this count +* [**`create( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#create) — create an Observable from scratch by means of a function +* **`cycle( )`** (clojure) — _see [**`repeat( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables)_ +* [**`debounce( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#debounce) — only emit an item from the source Observable after a particular timespan has passed without the Observable emitting any other items +* [**`decode( )`**](https://github.com/ReactiveX/RxJava/wiki/String-Observables) (`StringObservable`) — convert a stream of multibyte characters into an Observable that emits byte arrays that respect character boundaries +* [**`defaultIfEmpty( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators) — emit items from the source Observable, or emit a default item if the source Observable completes after emitting no items +* [**`defer( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#defer) — do not create the Observable until a Subscriber subscribes; create a fresh Observable on each subscription +* [**`deferFuture( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) — convert a Future that returns an Observable into an Observable, but do not attempt to get the Observable that the Future returns until a Subscriber subscribes (`rxjava-async`) +* [**`deferCancellableFuture( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#fromcancellablefuture-startcancellablefuture-and-defercancellablefuture) — convert a Future that returns an Observable into an Observable in a way that monitors the subscription status of the Observable to determine whether to halt work on the Future, but do not attempt to get the returned Observable until a Subscriber subscribes (⁇)(`rxjava-async`) +* [**`delay( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — shift the emissions from an Observable forward in time by a specified amount +* [**`dematerialize( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — convert a materialized Observable back into its non-materialized form +* [**`distinct( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#distinct) — suppress duplicate items emitted by the source Observable +* [**`distinctUntilChanged( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#distinctuntilchanged) — suppress duplicate consecutive items emitted by the source Observable +* **`do( )`** (clojure) — _see [**`doOnEach( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators)_ +* [**`doOnCompleted( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — register an action to take when an Observable completes successfully +* [**`doOnEach( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — register an action to take whenever an Observable emits an item +* [**`doOnError( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — register an action to take when an Observable completes with an error +* **`doOnNext( )`** — _see [**`doOnEach( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators)_ * **`doOnRequest( )`** — register an action to take when items are requested from an Observable via reactive-pull backpressure (⁇) -* [**`doOnSubscribe( )`**](Observable-Utility-Operators#doonsubscribe) — register an action to take when an observer subscribes to an Observable -* [**`doOnTerminate( )`**](Observable-Utility-Operators#doonterminate) — register an action to take when an Observable completes, either successfully or with an error -* [**`doOnUnsubscribe( )`**](Observable-Utility-Operators#doonunsubscribe) — register an action to take when an observer unsubscribes from an Observable -* [**`doWhile( )`**](Conditional-and-Boolean-Operators#dowhile) — emit the source Observable's sequence, and then repeat the sequence as long as a condition remains true (`contrib-computation-expressions`) -* **`drop( )`** (scala/clojure) — _see [**`skip( )`**](Filtering-Observables#skip)_ -* **`dropRight( )`** (scala) — _see [**`skipLast( )`**](Filtering-Observables#skiplast)_ -* **`dropUntil( )`** (scala) — _see [**`skipUntil( )`**](Conditional-and-Boolean-Operators#skipuntil)_ -* **`dropWhile( )`** (scala) — _see [**`skipWhile( )`**](Conditional-and-Boolean-Operators#skipwhile)_ -* **`drop-while( )`** (clojure) — _see [**`skipWhile( )`**](Conditional-and-Boolean-Operators#skipwhile)_ -* [**`elementAt( )`**](Filtering-Observables#elementat) — emit item _n_ emitted by the source Observable -* [**`elementAtOrDefault( )`**](Filtering-Observables#elementatordefault) — emit item _n_ emitted by the source Observable, or a default item if the source Observable emits fewer than _n_ items -* [**`empty( )`**](Creating-Observables#empty-error-and-never) — create an Observable that emits nothing and then completes -* [**`encode( )`**](String-Observables#encode) (`StringObservable`) — transform an Observable that emits strings into an Observable that emits byte arrays that respect character boundaries of multibyte characters in the original strings -* [**`error( )`**](Creating-Observables#empty-error-and-never) — create an Observable that emits nothing and then signals an error -* **`every( )`** (clojure) — _see [**`all( )`**](Conditional-and-Boolean-Operators#all)_ -* [**`exists( )`**](Conditional-and-Boolean-Operators#exists-and-isempty) — determine whether an Observable emits any items or not -* [**`filter( )`**](Filtering-Observables#filter) — filter items emitted by an Observable -* **`finally( )`** (clojure) — _see [**`finallyDo( )`**](Observable-Utility-Operators#finallydo)_ -* **`filterNot( )`** (scala) — _see [**`filter( )`**](Filtering-Observables#filter)_ -* [**`finallyDo( )`**](Observable-Utility-Operators#finallydo) — register an action to take when an Observable completes -* [**`first( )`**](Filtering-Observables#first-and-takefirst) (`Observable`) — emit only the first item emitted by an Observable, or the first item that meets some condition -* [**`first( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`) — emit only the first item emitted by an Observable, or the first item that meets some condition -* [**`firstOrDefault( )`**](Filtering-Observables#firstordefault) (`Observable`) — emit only the first item emitted by an Observable, or the first item that meets some condition, or a default value if the source Observable is empty -* [**`firstOrDefault( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`) — emit only the first item emitted by an Observable, or the first item that meets some condition, or a default value if the source Observable is empty -* **`firstOrElse( )`** (scala) — _see [**`firstOrDefault( )`**](Filtering-Observables#firstordefault) or [**`firstOrDefault( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`)_ -* [**`flatMap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable) — transform the items emitted by an Observable into Observables, then flatten this into a single Observable -* [**`flatMapIterable( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable) — create Iterables corresponding to each emission from a source Observable and merge the results into a single Observable -* **`flatMapIterableWith( )`** (scala) — _instance version of [**`flatMapIterable( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ -* **`flatMapWith( )`** (scala) — _instance version of [**`flatmap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ -* **`flatten( )`** (scala) — _see [**`merge( )`**](Combining-Observables#merge)_ -* **`flattenDelayError( )`** (scala) — _see [**`mergeDelayError( )`**](Combining-Observables#mergedelayerror)_ -* **`foldLeft( )`** (scala) — _see [**`reduce( )`**](Mathematical-and-Aggregate-Operators#reduce)_ -* **`forall( )`** (scala) — _see [**`all( )`**](Conditional-and-Boolean-Operators#all)_ -* **`forEach( )`** (`Observable`) — _see [**`subscribe( )`**](Observable#onnext-oncompleted-and-onerror)_ -* [**`forEach( )`**](Blocking-Observable-Operators#foreach) (`BlockingObservable`) — invoke a function on each item emitted by the Observable; block until the Observable completes -* [**`forEachFuture( )`**](Async-Operators#foreachfuture) (`Async`) — pass Subscriber methods to an Observable but also have it behave like a Future that blocks until it completes (`rxjava-async`) -* [**`forEachFuture( )`**](Phantom-Operators#foreachfuture) (`BlockingObservable`)— create a futureTask that will invoke a specified function on each item emitted by an Observable (⁇) -* [**`forIterable( )`**](Phantom-Operators#foriterable) — apply a function to the elements of an Iterable to create Observables which are then concatenated (⁇) -* [**`from( )`**](Creating-Observables#from) — convert an Iterable, a Future, or an Array into an Observable -* [**`from( )`**](String-Observables#from) (`StringObservable`) — convert a stream of characters or a Reader into an Observable that emits byte arrays or Strings -* [**`fromAction( )`**](Async-Operators#fromaction) — convert an Action into an Observable that invokes the action and emits its result when a Subscriber subscribes (`rxjava-async`) -* [**`fromCallable( )`**](Async-Operators#fromcallable) — convert a Callable into an Observable that invokes the callable and emits its result or exception when a Subscriber subscribes (`rxjava-async`) -* [**`fromCancellableFuture( )`**](Phantom-Operators#fromcancellablefuture-startcancellablefuture-and-defercancellablefuture-) — convert a Future into an Observable in a way that monitors the subscription status of the Observable to determine whether to halt work on the Future, but do not attempt to get the Future's value until a Subscriber subscribes (⁇)(`rxjava-async`) -* **`fromFunc0( )`** — _see [**`fromCallable( )`**](Async-Operators#fromcallable) (`rxjava-async`)_ -* [**`fromFuture( )`**](Phantom-Operators#fromfuture) — convert a Future into an Observable, but do not attempt to get the Future's value until a Subscriber subscribes (⁇) -* [**`fromRunnable( )`**](Async-Operators#fromrunnable) — convert a Runnable into an Observable that invokes the runable and emits its result when a Subscriber subscribes (`rxjava-async`) -* [**`generate( )`**](Phantom-Operators#generate-and-generateabsolutetime) — create an Observable that emits a sequence of items as generated by a function of your choosing (⁇) -* [**`generateAbsoluteTime( )`**](Phantom-Operators#generate-and-generateabsolutetime) — create an Observable that emits a sequence of items as generated by a function of your choosing, with each item emitted at an item-specific time (⁇) -* **`generator( )`** (clojure) — _see [**`generate( )`**](Phantom-Operators#generate-and-generateabsolutetime)_ -* [**`getIterator( )`**](Blocking-Observable-Operators#transformations-tofuture-toiterable-and-getiterator) — convert the sequence emitted by the Observable into an Iterator -* [**`groupBy( )`**](Transforming-Observables#groupby) — divide an Observable into a set of Observables that emit groups of items from the original Observable, organized by key -* **`group-by( )`** (clojure) — _see [**`groupBy( )`**](Transforming-Observables#groupby)_ -* [**`groupByUntil( )`**](Phantom-Operators#groupbyuntil) — a variant of the [`groupBy( )`](Transforming-Observables#groupby) operator that closes any open GroupedObservable upon a signal from another Observable (⁇) -* [**`groupJoin( )`**](Combining-Observables#join-and-groupjoin) — combine the items emitted by two Observables whenever one item from one Observable falls within a window of duration specified by an item emitted by the other Observable -* **`head( )`** (scala) — _see [**`first( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`)_ -* **`headOption( )`** (scala) — _see [**`firstOrDefault( )`**](Filtering-Observables#firstordefault) or [**`firstOrDefault( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`)_ -* **`headOrElse( )`** (scala) — _see [**`firstOrDefault( )`**](Filtering-Observables#firstordefault) or [**`firstOrDefault( )`**](Blocking-Observable-Operators#first-and-firstordefault) (`BlockingObservable`)_ -* [**`ifThen( )`**](Conditional-and-Boolean-Operators#ifthen) — only emit the source Observable's sequence if a condition is true, otherwise emit an empty or default sequence (`contrib-computation-expressions`) -* [**`ignoreElements( )`**](Filtering-Observables#ignoreelements) — discard the items emitted by the source Observable and only pass through the error or completed notification -* [**`interval( )`**](Creating-Observables#interval) — create an Observable that emits a sequence of integers spaced by a given time interval -* **`into( )`** (clojure) — _see [**`reduce( )`**](Mathematical-and-Aggregate-Operators#reduce)_ -* [**`isEmpty( )`**](Conditional-and-Boolean-Operators#exists-and-isempty) — determine whether an Observable emits any items or not -* **`items( )`** (scala) — _see [**`just( )`**](Creating-Observables#just)_ -* [**`join( )`**](Combining-Observables#join-and-groupjoin) — combine the items emitted by two Observables whenever one item from one Observable falls within a window of duration specified by an item emitted by the other Observable -* [**`join( )`**](String-Observables#join) (`StringObservable`) — converts an Observable that emits a sequence of strings into an Observable that emits a single string that concatenates them all, separating them by a specified string -* [**`just( )`**](Creating-Observables#just) — convert an object into an Observable that emits that object -* [**`last( )`**](Blocking-Observable-Operators#last-and-lastordefault) (`BlockingObservable`) — block until the Observable completes, then return the last item emitted by the Observable -* [**`last( )`**](Filtering-Observables#last) (`Observable`) — emit only the last item emitted by the source Observable -* **`lastOption( )`** (scala) — _see [**`lastOrDefault( )`**](Filtering-Observables#lastOrDefault) or [**`lastOrDefault( )`**](Blocking-Observable-Operators#last-and-lastordefault) (`BlockingObservable`)_ -* [**`lastOrDefault( )`**](Blocking-Observable-Operators#last-and-lastordefault) (`BlockingObservable`) — block until the Observable completes, then return the last item emitted by the Observable or a default item if there is no last item -* [**`lastOrDefault( )`**](Filtering-Observables#lastOrDefault) (`Observable`) — emit only the last item emitted by an Observable, or a default value if the source Observable is empty -* **`lastOrElse( )`** (scala) — _see [**`lastOrDefault( )`**](Filtering-Observables#lastOrDefault) or [**`lastOrDefault( )`**](Blocking-Observable-Operators#last-and-lastordefault) (`BlockingObservable`)_ -* [**`latest( )`**](Blocking-Observable-Operators#latest) — returns an iterable that blocks until or unless the Observable emits an item that has not been returned by the iterable, then returns the latest such item -* **`length( )`** (scala) — _see [**`count( )`**](Mathematical-and-Aggregate-Operators#count-and-countlong)_ -* **`limit( )`** — _see [**`take( )`**](Filtering-Observables#take)_ -* **`longCount( )`** (scala) — _see [**`countLong( )`**](Mathematical-and-Aggregate-Operators#count-and-countlong)_ -* [**`map( )`**](Transforming-Observables#map) — transform the items emitted by an Observable by applying a function to each of them -* **`mapcat( )`** (clojure) — _see [**`concatMap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ -* **`mapMany( )`** — _see: [**`flatMap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ -* [**`materialize( )`**](Observable-Utility-Operators#materialize) — convert an Observable into a list of Notifications -* [**`max( )`**](Mathematical-and-Aggregate-Operators#max) — emits the maximum value emitted by a source Observable (`rxjava-math`) -* [**`maxBy( )`**](Mathematical-and-Aggregate-Operators#maxby) — emits the item emitted by the source Observable that has the maximum key value (`rxjava-math`) -* [**`merge( )`**](Combining-Observables#merge) — combine multiple Observables into one -* [**`mergeDelayError( )`**](Combining-Observables#mergedelayerror) — combine multiple Observables into one, allowing error-free Observables to continue before propagating errors -* **`merge-delay-error( )`** (clojure) — _see [**`mergeDelayError( )`**](Combining-Observables#mergedelayerror)_ -* **`mergeMap( )`** * — _see: [**`flatMap( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ -* **`mergeMapIterable( )`** — _see: [**`flatMapIterable( )`**](Transforming-Observables#flatmap-concatmap-and-flatmapiterable)_ -* **`mergeWith( )`** — _instance version of [**`merge( )`**](Combining-Observables#merge)_ -* [**`min( )`**](Mathematical-and-Aggregate-Operators#min) — emits the minimum value emitted by a source Observable (`rxjava-math`) -* [**`minBy( )`**](Mathematical-and-Aggregate-Operators#minby) — emits the item emitted by the source Observable that has the minimum key value (`rxjava-math`) -* [**`mostRecent( )`**](Blocking-Observable-Operators#mostrecent) — returns an iterable that always returns the item most recently emitted by the Observable -* [**`multicast( )`**](Phantom-Operators#multicast) — represents an Observable as a Connectable Observable -* [**`never( )`**](Creating-Observables#empty-error-and-never) — create an Observable that emits nothing at all -* [**`next( )`**](Blocking-Observable-Operators#next) — returns an iterable that blocks until the Observable emits another item, then returns that item -* **`nonEmpty( )`** (scala) — _see [**`isEmpty( )`**](Conditional-and-Boolean-Operators#exists-and-isempty)_ -* **`nth( )`** (clojure) — _see [**`elementAt( )`**](Filtering-Observables#elementat) and [**`elementAtOrDefault( )`**](Filtering-Observables#elementatordefault)_ -* [**`observeOn( )`**](Observable-Utility-Operators#observeon) — specify on which Scheduler a Subscriber should observe the Observable -* [**`ofType( )`**](Filtering-Observables#oftype) — emit only those items from the source Observable that are of a particular class -* [**`onBackpressureBlock( )`**](Backpressure) — block the Observable's thread until the Observer is ready to accept more items from the Observable (⁇) -* [**`onBackpressureBuffer( )`**](Backpressure) — maintain a buffer of all emissions from the source Observable and emit them to downstream Subscribers according to the requests they generate -* [**`onBackpressureDrop( )`**](Backpressure) — drop emissions from the source Observable unless there is a pending request from a downstream Subscriber, in which case emit enough items to fulfill the request -* [**`onErrorFlatMap( )`**](Phantom-Operators#onerrorflatmap) — instructs an Observable to emit a sequence of items whenever it encounters an error (⁇) -* [**`onErrorResumeNext( )`**](Error-Handling-Operators#onerrorresumenext) — instructs an Observable to emit a sequence of items if it encounters an error -* [**`onErrorReturn( )`**](Error-Handling-Operators#onerrorreturn) — instructs an Observable to emit a particular item when it encounters an error -* [**`onExceptionResumeNext( )`**](Error-Handling-Operators#onexceptionresumenext) — instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable) -* **`orElse( )`** (scala) — _see [**`defaultIfEmpty( )`**](Conditional-and-Boolean-Operators#defaultifempty)_ -* [**`parallel( )`**](Phantom-Operators#parallel) — split the work done on the emissions from an Observable into multiple Observables each operating on its own parallel thread (⁇) -* [**`parallelMerge( )`**](Phantom-Operators#parallelmerge) — combine multiple Observables into smaller number of Observables (⁇) -* [**`pivot( )`**](Phantom-Operators#pivot) — combine multiple sets of grouped observables so that they are arranged primarily by group rather than by set (⁇) -* [**`publish( )`**](Connectable-Observable-Operators#observablepublish) — represents an Observable as a Connectable Observable -* [**`publishLast( )`**](Phantom-Operators#publishlast) — represent an Observable as a Connectable Observable that emits only the last item emitted by the source Observable (⁇) -* [**`range( )`**](Creating-Observables#range) — create an Observable that emits a range of sequential integers -* [**`reduce( )`**](Mathematical-and-Aggregate-Operators#reduce) — apply a function to each emitted item, sequentially, and emit only the final accumulated value -* **`reductions( )`** (clojure) — _see [**`scan( )`**](Transforming-Observables#scan)_ -* [**`refCount( )`**](Connectable-Observable-Operators#connectableobservablerefcount) — makes a Connectable Observable behave like an ordinary Observable -* [**`repeat( )`**](Creating-Observables#repeat) — create an Observable that emits a particular item or sequence of items repeatedly -* [**`repeatWhen( )`**](Creating-Observables#repeatwhen) — create an Observable that emits a particular item or sequence of items repeatedly, depending on the emissions of a second Observable -* [**`replay( )`**](Connectable-Observable-Operators#observablereplay) — ensures that all Subscribers see the same sequence of emitted items, even if they subscribe after the Observable begins emitting the items -* **`rest( )`** (clojure) — _see [**`next( )`**](Blocking-Observable-Operators#next)_ -* **`return( )`** (clojure) — _see [**`just( )`**](Creating-Observables#just)_ -* [**`retry( )`**](Error-Handling-Operators#retry) — if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error -* [**`retrywhen( )`**](Error-Handling-Operators#retrywhen) — if a source Observable emits an error, pass that error to another Observable to determine whether to resubscribe to the source -* [**`runAsync( )`**](Async-Operators#runasync) — returns a `StoppableObservable` that emits multiple actions as generated by a specified Action on a Scheduler (`rxjava-async`) -* [**`sample( )`**](Filtering-Observables#sample-or-throttlelast) — emit the most recent items emitted by an Observable within periodic time intervals -* [**`scan( )`**](Transforming-Observables#scan) — apply a function to each item emitted by an Observable, sequentially, and emit each successive value -* **`seq( )`** (clojure) — _see [**`getIterator( )`**](Blocking-Observable-Operators#transformations-tofuture-toiterable-and-getiterator)_ -* [**`sequenceEqual( )`**](Conditional-and-Boolean-Operators#sequenceequal) — test the equality of sequences emitted by two Observables -* **`sequenceEqualWith( )`** (scala) — _instance version of [**`sequenceEqual( )`**](Conditional-and-Boolean-Operators#sequenceequal)_ -* [**`serialize( )`**](Observable-Utility-Operators#serialize) — force an Observable to make serialized calls and to be well-behaved -* **`share( )`** — _see [**`refCount( )`**](Connectable-Observable-Operators#connectableobservablerefcount)_ -* [**`single( )`**](Blocking-Observable-Operators#single-and-singleordefault) (`BlockingObservable`) — if the source Observable completes after emitting a single item, return that item, otherwise throw an exception -* [**`single( )`**](Observable-Utility-Operators#single-and-singleordefault) (`Observable`) — if the source Observable completes after emitting a single item, emit that item, otherwise notify of an exception -* **`singleOption( )`** (scala) — _see [**`singleOrDefault( )`**](Blocking-Observable-Operators#single-and-singleordefault) (`BlockingObservable`)_ -* [**`singleOrDefault( )`**](Blocking-Observable-Operators#single-and-singleordefault) (`BlockingObservable`) — if the source Observable completes after emitting a single item, return that item, otherwise return a default item -* [**`singleOrDefault( )`**](Observable-Utility-Operators#single-and-singleordefault) (`Observable`) — if the source Observable completes after emitting a single item, emit that item, otherwise emit a default item -* **`singleOrElse( )`** (scala) — _see [**`singleOrDefault( )`**](Observable-Utility-Operators#single-and-singleordefault)_ -* **`size( )`** (scala) — _see [**`count( )`**](Mathematical-and-Aggregate-Operators#count-and-countlong)_ -* [**`skip( )`**](Filtering-Observables#skip) — ignore the first _n_ items emitted by an Observable -* [**`skipLast( )`**](Filtering-Observables#skiplast) — ignore the last _n_ items emitted by an Observable -* [**`skipUntil( )`**](Conditional-and-Boolean-Operators#skipuntil) — discard items emitted by a source Observable until a second Observable emits an item, then emit the remainder of the source Observable's items -* [**`skipWhile( )`**](Conditional-and-Boolean-Operators#skipwhile) — discard items emitted by an Observable until a specified condition is false, then emit the remainder -* **`sliding( )`** (scala) — _see [**`window( )`**](Transforming-Observables#window)_ -* **`slidingBuffer( )`** (scala) — _see [**`buffer( )`**](Transforming-Observables#buffer)_ -* [**`split( )`**](String-Observables#split) (`StringObservable`) — converts an Observable of Strings into an Observable of Strings that treats the source sequence as a stream and splits it on a specified regex boundary -* [**`start( )`**](Async-Operators#start) — create an Observable that emits the return value of a function (`rxjava-async`) -* [**`startCancellableFuture( )`**](Phantom-Operators#fromcancellablefuture-startcancellablefuture-and-defercancellablefuture-) — convert a function that returns Future into an Observable that emits that Future's return value in a way that monitors the subscription status of the Observable to determine whether to halt work on the Future (⁇)(`rxjava-async`) -* [**`startFuture( )`**](Async-Operators#startfuture) — convert a function that returns Future into an Observable that emits that Future's return value (`rxjava-async`) -* [**`startWith( )`**](Combining-Observables#startwith) — emit a specified sequence of items before beginning to emit the items from the Observable -* [**`stringConcat( )`**](String-Observables#stringconcat) (`StringObservable`) — converts an Observable that emits a sequence of strings into an Observable that emits a single string that concatenates them all -* [**`subscribeOn( )`**](Observable-Utility-Operators#subscribeon) — specify which Scheduler an Observable should use when its subscription is invoked -* [**`sumDouble( )`**](Mathematical-and-Aggregate-Operators#suminteger-sumlong-sumfloat-and-sumdouble) — adds the Doubles emitted by an Observable and emits this sum (`rxjava-math`) -* [**`sumFloat( )`**](Mathematical-and-Aggregate-Operators#suminteger-sumlong-sumfloat-and-sumdouble) — adds the Floats emitted by an Observable and emits this sum (`rxjava-math`) -* [**`sumInteger( )`**](Mathematical-and-Aggregate-Operators#suminteger-sumlong-sumfloat-and-sumdouble) — adds the Integers emitted by an Observable and emits this sum (`rxjava-math`) -* [**`sumLong( )`**](Mathematical-and-Aggregate-Operators#suminteger-sumlong-sumfloat-and-sumdouble) — adds the Longs emitted by an Observable and emits this sum (`rxjava-math`) -* **`switch( )`** (scala) — _see [**`switchOnNext( )`**](Combining-Observables#switchonnext)_ -* [**`switchCase( )`**](Conditional-and-Boolean-Operators#switchcase) — emit the sequence from a particular Observable based on the results of an evaluation (`contrib-computation-expressions`) -* [**`switchMap( )`**](Transforming-Observables#switchmap) — transform the items emitted by an Observable into Observables, and mirror those items emitted by the most-recently transformed Observable -* [**`switchOnNext( )`**](Combining-Observables#switchonnext) — convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently emitted of those Observables -* **`synchronize( )`** — _see [**`serialize( )`**](Observable-Utility-Operators#serialize)_ -* [**`take( )`**](Filtering-Observables#take) — emit only the first _n_ items emitted by an Observable -* [**`takeFirst( )`**](Filtering-Observables#first-and-takefirst) — emit only the first item emitted by an Observable, or the first item that meets some condition -* [**`takeLast( )`**](Filtering-Observables#takelast) — only emit the last _n_ items emitted by an Observable -* [**`takeLastBuffer( )`**](Filtering-Observables#takelastbuffer) — emit the last _n_ items emitted by an Observable, as a single list item -* **`takeRight( )`** (scala) — _see [**`last( )`**](Filtering-Observables#last) (`Observable`) or [**`takeLast( )`**](Filtering-Observables#takelast)_ -* [**`takeUntil( )`**](Conditional-and-Boolean-Operators#takeuntil) — emits the items from the source Observable until a second Observable emits an item -* [**`takeWhile( )`**](Conditional-and-Boolean-Operators#takewhile) — emit items emitted by an Observable as long as a specified condition is true, then skip the remainder -* **`take-while( )`** (clojure) — _see [**`takeWhile( )`**](Conditional-and-Boolean-Operators#takewhile)_ -* [**`then( )`**](Combining-Observables#and-then-and-when) — transform a series of `Pattern` objects via a `Plan` template (`rxjava-joins`) -* [**`throttleFirst( )`**](Filtering-Observables#throttlefirst) — emit the first items emitted by an Observable within periodic time intervals -* [**`throttleLast( )`**](Filtering-Observables#sample-or-throttlelast) — emit the most recent items emitted by an Observable within periodic time intervals -* [**`throttleWithTimeout( )`**](Filtering-Observables#throttlewithtimeout-or-debounce) — only emit an item from the source Observable after a particular timespan has passed without the Observable emitting any other items -* **`throw( )`** (clojure) — _see [**`error( )`**](Creating-Observables#empty-error-and-never)_ -* [**`timeInterval( )`**](Observable-Utility-Operators#timeinterval) — emit the time lapsed between consecutive emissions of a source Observable -* [**`timeout( )`**](Filtering-Observables#timeout) — emit items from a source Observable, but issue an exception if no item is emitted in a specified timespan -* [**`timer( )`**](Creating-Observables#timer) — create an Observable that emits a single item after a given delay -* [**`timestamp( )`**](Observable-Utility-Operators#timestamp) — attach a timestamp to every item emitted by an Observable -* [**`toAsync( )`**](Async-Operators#toasync-or-asyncaction-or-asyncfunc) — convert a function or Action into an Observable that executes the function and emits its return value (`rxjava-async`) -* [**`toBlocking( )`**](Blocking-Observable-Operators) — transform an Observable into a BlockingObservable -* **`toBlockingObservable( )`** - _see [**`toBlocking( )`**](Blocking-Observable-Operators)_ -* [**`toFuture( )`**](Blocking-Observable-Operators#transformations-tofuture-toiterable-and-getiterator) — convert the Observable into a Future -* [**`toIterable( )`**](Blocking-Observable-Operators#transformations-tofuture-toiterable-and-getiterator) — convert the sequence emitted by the Observable into an Iterable -* **`toIterator( )`** — _see [**`getIterator( )`**](Blocking-Observable-Operators#transformations-tofuture-toiterable-and-getiterator)_ -* [**`toList( )`**](Mathematical-and-Aggregate-Operators#tolist) — collect all items from an Observable and emit them as a single List -* [**`toMap( )`**](Mathematical-and-Aggregate-Operators#tomap-and-tomultimap) — convert the sequence of items emitted by an Observable into a map keyed by a specified key function -* [**`toMultimap( )`**](Mathematical-and-Aggregate-Operators#tomap-and-tomultimap) — convert the sequence of items emitted by an Observable into an ArrayList that is also a map keyed by a specified key function -* **`toSeq( )`** (scala) — _see [**`toList( )`**](Mathematical-and-Aggregate-Operators#tolist)_ -* [**`toSortedList( )`**](Mathematical-and-Aggregate-Operators#tosortedlist) — collect all items from an Observable and emit them as a single, sorted List -* **`tumbling( )`** (scala) — _see [**`window( )`**](Transforming-Observables#window)_ -* **`tumblingBuffer( )`** (scala) — _see [**`buffer( )`**](Transforming-Observables#buffer)_ -* [**`using( )`**](Observable-Utility-Operators#using) — create a disposable resource that has the same lifespan as an Observable -* [**`when( )`**](Combining-Observables#and-then-and-when) — convert a series of `Plan` objects into an Observable (`rxjava-joins`) -* **`where( )`** — _see: [**`filter( )`**](Filtering-Observables#filter)_ -* [**`whileDo( )`**](Conditional-and-Boolean-Operators#whiledo) — if a condition is true, emit the source Observable's sequence and then repeat the sequence as long as the condition remains true (`contrib-computation-expressions`) -* [**`window( )`**](Transforming-Observables#window) — periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time -* [**`zip( )`**](Combining-Observables#zip) — combine sets of items emitted by two or more Observables together via a specified function and emit items based on the results of this function -* **`zipWith( )`** — _instance version of [**`zip( )`**](Combining-Observables#zip)_ -* **`zipWithIndex( )`** (scala) — _see [**`zip( )`**](Combining-Observables#zip)_ -* **`++`** (scala) — _see [**`concat( )`**](Mathematical-and-Aggregate-Operators#concat)_ -* **`+:`** (scala) — _see [**`startWith( )`**](Combining-Observables#startwith)_ +* [**`doOnSubscribe( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — register an action to take when an observer subscribes to an Observable +* [**`doOnTerminate( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — register an action to take when an Observable completes, either successfully or with an error +* [**`doOnUnsubscribe( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — register an action to take when an observer unsubscribes from an Observable +* [**`doWhile( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators) — emit the source Observable's sequence, and then repeat the sequence as long as a condition remains true (`contrib-computation-expressions`) +* **`drop( )`** (scala/clojure) — _see [**`skip( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#skip)_ +* **`dropRight( )`** (scala) — _see [**`skipLast( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#skiplast)_ +* **`dropUntil( )`** (scala) — _see [**`skipUntil( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators)_ +* **`dropWhile( )`** (scala) — _see [**`skipWhile( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators)_ +* **`drop-while( )`** (clojure) — _see [**`skipWhile( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#skipwhile)_ +* [**`elementAt( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#elementat) — emit item _n_ emitted by the source Observable +* [**`elementAtOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) — emit item _n_ emitted by the source Observable, or a default item if the source Observable emits fewer than _n_ items +* [**`empty( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#empty) — create an Observable that emits nothing and then completes +* [**`encode( )`**](https://github.com/ReactiveX/RxJava/wiki/String-Observables) (`StringObservable`) — transform an Observable that emits strings into an Observable that emits byte arrays that respect character boundaries of multibyte characters in the original strings +* [**`error( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#error) — create an Observable that emits nothing and then signals an error +* **`every( )`** (clojure) — _see [**`all( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#boolean-operators)_ +* [**`exists( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#boolean-operators) — determine whether an Observable emits any items or not +* [**`filter( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#filter) — filter items emitted by an Observable +* **`finally( )`** (clojure) — _see [**`finallyDo( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators)_ +* **`filterNot( )`** (scala) — _see [**`filter( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#filter)_ +* [**`finallyDo( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — register an action to take when an Observable completes +* [**`first( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#first) (`Observable`) — emit only the first item emitted by an Observable, or the first item that meets some condition +* [**`first( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`) — emit only the first item emitted by an Observable, or the first item that meets some condition +* [**`firstOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) (`Observable`) — emit only the first item emitted by an Observable, or the first item that meets some condition, or a default value if the source Observable is empty +* [**`firstOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`) — emit only the first item emitted by an Observable, or the first item that meets some condition, or a default value if the source Observable is empty +* **`firstOrElse( )`** (scala) — _see [**`firstOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) or [**`firstOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`)_ +* [**`flatMap( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#flatmap) — transform the items emitted by an Observable into Observables, then flatten this into a single Observable +* [**`flatMapIterable( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#flatmapiterable) — create Iterables corresponding to each emission from a source Observable and merge the results into a single Observable +* **`flatMapIterableWith( )`** (scala) — _instance version of [**`flatMapIterable( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#flatmapiterable)_ +* **`flatMapWith( )`** (scala) — _instance version of [**`flatmap( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#flatmap)_ +* **`flatten( )`** (scala) — _see [**`merge( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#merge)_ +* **`flattenDelayError( )`** (scala) — _see [**`mergeDelayError( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#mergedelayerror)_ +* **`foldLeft( )`** (scala) — _see [**`reduce( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#reduce)_ +* **`forall( )`** (scala) — _see [**`all( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#boolean-operators)_ +* **`forEach( )`** (`Observable`) — _see [**`subscribe( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable)_ +* [**`forEach( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`) — invoke a function on each item emitted by the Observable; block until the Observable completes +* [**`forEachFuture( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) (`Async`) — pass Subscriber methods to an Observable but also have it behave like a Future that blocks until it completes (`rxjava-async`) +* [**`forEachFuture( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#foreachfuture) (`BlockingObservable`)— create a futureTask that will invoke a specified function on each item emitted by an Observable (⁇) +* [**`forIterable( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#foriterable) — apply a function to the elements of an Iterable to create Observables which are then concatenated (⁇) +* [**`from( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#from) — convert an Iterable, a Future, or an Array into an Observable +* [**`from( )`**](https://github.com/ReactiveX/RxJava/wiki/String-Observables) (`StringObservable`) — convert a stream of characters or a Reader into an Observable that emits byte arrays or Strings +* [**`fromAction( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) — convert an Action into an Observable that invokes the action and emits its result when a Subscriber subscribes (`rxjava-async`) +* [**`fromCallable( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) — convert a Callable into an Observable that invokes the callable and emits its result or exception when a Subscriber subscribes (`rxjava-async`) +* [**`fromCancellableFuture( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#fromcancellablefuture-startcancellablefuture-and-defercancellablefuture) — convert a Future into an Observable in a way that monitors the subscription status of the Observable to determine whether to halt work on the Future, but do not attempt to get the Future's value until a Subscriber subscribes (⁇)(`rxjava-async`) +* **`fromFunc0( )`** — _see [**`fromCallable( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) (`rxjava-async`)_ +* [**`fromFuture( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#fromfuture) — convert a Future into an Observable, but do not attempt to get the Future's value until a Subscriber subscribes (⁇) +* [**`fromRunnable( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators#fromrunnable) — convert a Runnable into an Observable that invokes the runable and emits its result when a Subscriber subscribes (`rxjava-async`) +* [**`generate( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#generate-and-generateabsolutetime) — create an Observable that emits a sequence of items as generated by a function of your choosing (⁇) +* [**`generateAbsoluteTime( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#generate-and-generateabsolutetime) — create an Observable that emits a sequence of items as generated by a function of your choosing, with each item emitted at an item-specific time (⁇) +* **`generator( )`** (clojure) — _see [**`generate( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#generate-and-generateabsolutetime)_ +* [**`getIterator( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) — convert the sequence emitted by the Observable into an Iterator +* [**`groupBy( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#groupby) — divide an Observable into a set of Observables that emit groups of items from the original Observable, organized by key +* **`group-by( )`** (clojure) — _see [**`groupBy( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#groupby)_ +* [**`groupByUntil( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators) — a variant of the [`groupBy( )`](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#groupby) operator that closes any open GroupedObservable upon a signal from another Observable (⁇) +* [**`groupJoin( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#joins) — combine the items emitted by two Observables whenever one item from one Observable falls within a window of duration specified by an item emitted by the other Observable +* **`head( )`** (scala) — _see [**`first( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`)_ +* **`headOption( )`** (scala) — _see [**`firstOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) or [**`firstOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`)_ +* **`headOrElse( )`** (scala) — _see [**`firstOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) or [**`firstOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`)_ +* [**`ifThen( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators) — only emit the source Observable's sequence if a condition is true, otherwise emit an empty or default sequence (`contrib-computation-expressions`) +* [**`ignoreElements( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#ignoreelements) — discard the items emitted by the source Observable and only pass through the error or completed notification +* [**`interval( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#interval) — create an Observable that emits a sequence of integers spaced by a given time interval +* **`into( )`** (clojure) — _see [**`reduce( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#reduce)_ +* [**`isEmpty( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#boolean-operators) — determine whether an Observable emits any items or not +* **`items( )`** (scala) — _see [**`just( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#just)_ +* [**`join( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#joins) — combine the items emitted by two Observables whenever one item from one Observable falls within a window of duration specified by an item emitted by the other Observable +* [**`join( )`**](https://github.com/ReactiveX/RxJava/wiki/String-Observables) (`StringObservable`) — converts an Observable that emits a sequence of strings into an Observable that emits a single string that concatenates them all, separating them by a specified string +* [**`just( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#just) — convert an object into an Observable that emits that object +* [**`last( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`) — block until the Observable completes, then return the last item emitted by the Observable +* [**`last( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#last) (`Observable`) — emit only the last item emitted by the source Observable +* **`lastOption( )`** (scala) — _see [**`lastOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) or [**`lastOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`)_ +* [**`lastOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`) — block until the Observable completes, then return the last item emitted by the Observable or a default item if there is no last item +* [**`lastOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) (`Observable`) — emit only the last item emitted by an Observable, or a default value if the source Observable is empty +* **`lastOrElse( )`** (scala) — _see [**`lastOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) or [**`lastOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`)_ +* [**`latest( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) — returns an iterable that blocks until or unless the Observable emits an item that has not been returned by the iterable, then returns the latest such item +* **`length( )`** (scala) — _see [**`count( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#count)_ +* **`limit( )`** — _see [**`take( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#take)_ +* **`longCount( )`** (scala) — _see [**`countLong( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators)_ +* [**`map( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#map) — transform the items emitted by an Observable by applying a function to each of them +* **`mapcat( )`** (clojure) — _see [**`concatMap( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#concatmap)_ +* **`mapMany( )`** — _see: [**`flatMap( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#flatmap)_ +* [**`materialize( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — convert an Observable into a list of Notifications +* [**`max( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#max) — emits the maximum value emitted by a source Observable (`rxjava-math`) +* [**`maxBy( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators) — emits the item emitted by the source Observable that has the maximum key value (`rxjava-math`) +* [**`merge( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#merge) — combine multiple Observables into one +* [**`mergeDelayError( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#mergedelayerror) — combine multiple Observables into one, allowing error-free Observables to continue before propagating errors +* **`merge-delay-error( )`** (clojure) — _see [**`mergeDelayError( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#mergedelayerror)_ +* **`mergeMap( )`** * — _see: [**`flatMap( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#flatmap)_ +* **`mergeMapIterable( )`** — _see: [**`flatMapIterable( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#flatmapiterable)_ +* **`mergeWith( )`** — _instance version of [**`merge( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#merge)_ +* [**`min( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#min) — emits the minimum value emitted by a source Observable (`rxjava-math`) +* [**`minBy( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators) — emits the item emitted by the source Observable that has the minimum key value (`rxjava-math`) +* [**`mostRecent( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) — returns an iterable that always returns the item most recently emitted by the Observable +* [**`multicast( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#multicast) — represents an Observable as a Connectable Observable +* [**`never( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#never) — create an Observable that emits nothing at all +* [**`next( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) — returns an iterable that blocks until the Observable emits another item, then returns that item +* **`nonEmpty( )`** (scala) — _see [**`isEmpty( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#boolean-operators)_ +* **`nth( )`** (clojure) — _see [**`elementAt( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#elementat) and [**`elementAtOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables)_ +* [**`observeOn( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — specify on which Scheduler a Subscriber should observe the Observable +* [**`ofType( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#oftype) — emit only those items from the source Observable that are of a particular class +* [**`onBackpressureBlock( )`**](https://github.com/ReactiveX/RxJava/wiki/Backpressure#reactive-pull-backpressure-isnt-magic) — block the Observable's thread until the Observer is ready to accept more items from the Observable (⁇) +* [**`onBackpressureBuffer( )`**](https://github.com/ReactiveX/RxJava/wiki/Backpressure#reactive-pull-backpressure-isnt-magic) — maintain a buffer of all emissions from the source Observable and emit them to downstream Subscribers according to the requests they generate +* [**`onBackpressureDrop( )`**](https://github.com/ReactiveX/RxJava/wiki/Backpressure#reactive-pull-backpressure-isnt-magic) — drop emissions from the source Observable unless there is a pending request from a downstream Subscriber, in which case emit enough items to fulfill the request +* [**`onErrorFlatMap( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#onerrorflatmap) — instructs an Observable to emit a sequence of items whenever it encounters an error (⁇) +* [**`onErrorResumeNext( )`**](https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators#onerrorresumenext) — instructs an Observable to emit a sequence of items if it encounters an error +* [**`onErrorReturn( )`**](https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators#onerrorreturn) — instructs an Observable to emit a particular item when it encounters an error +* [**`onExceptionResumeNext( )`**](https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators#onexceptionresumenext) — instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable) +* **`orElse( )`** (scala) — _see [**`defaultIfEmpty( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators)_ +* [**`parallel( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#parallel) — split the work done on the emissions from an Observable into multiple Observables each operating on its own parallel thread (⁇) +* [**`parallelMerge( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#parallelmerge) — combine multiple Observables into smaller number of Observables (⁇) +* [**`pivot( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#pivot) — combine multiple sets of grouped observables so that they are arranged primarily by group rather than by set (⁇) +* [**`publish( )`**](https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators) — represents an Observable as a Connectable Observable +* [**`publishLast( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#publishlast) — represent an Observable as a Connectable Observable that emits only the last item emitted by the source Observable (⁇) +* [**`range( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#range) — create an Observable that emits a range of sequential integers +* [**`reduce( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#reduce) — apply a function to each emitted item, sequentially, and emit only the final accumulated value +* **`reductions( )`** (clojure) — _see [**`scan( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#scan)_ +* [**`refCount( )`**](https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators) — makes a Connectable Observable behave like an ordinary Observable +* [**`repeat( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables) — create an Observable that emits a particular item or sequence of items repeatedly +* [**`repeatWhen( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#repeatwhen) — create an Observable that emits a particular item or sequence of items repeatedly, depending on the emissions of a second Observable +* [**`replay( )`**](https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators#observablereplay) — ensures that all Subscribers see the same sequence of emitted items, even if they subscribe after the Observable begins emitting the items +* **`rest( )`** (clojure) — _see [**`next( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators#next)_ +* **`return( )`** (clojure) — _see [**`just( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#just)_ +* [**`retry( )`**](https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators#retry) — if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error +* [**`retrywhen( )`**](https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators#retrywhen) — if a source Observable emits an error, pass that error to another Observable to determine whether to resubscribe to the source +* [**`runAsync( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) — returns a `StoppableObservable` that emits multiple actions as generated by a specified Action on a Scheduler (`rxjava-async`) +* [**`sample( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#sample) — emit the most recent items emitted by an Observable within periodic time intervals +* [**`scan( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#scan) — apply a function to each item emitted by an Observable, sequentially, and emit each successive value +* **`seq( )`** (clojure) — _see [**`getIterator( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators)_ +* [**`sequenceEqual( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators) — test the equality of sequences emitted by two Observables +* **`sequenceEqualWith( )`** (scala) — _instance version of [**`sequenceEqual( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators)_ +* [**`serialize( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators#serialize) — force an Observable to make serialized calls and to be well-behaved +* **`share( )`** — _see [**`refCount( )`**](https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators)_ +* [**`single( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`) — if the source Observable completes after emitting a single item, return that item, otherwise throw an exception +* [**`single( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) (`Observable`) — if the source Observable completes after emitting a single item, emit that item, otherwise notify of an exception +* **`singleOption( )`** (scala) — _see [**`singleOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators#single-and-singleordefault) (`BlockingObservable`)_ +* [**`singleOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) (`BlockingObservable`) — if the source Observable completes after emitting a single item, return that item, otherwise return a default item +* [**`singleOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) (`Observable`) — if the source Observable completes after emitting a single item, emit that item, otherwise emit a default item +* **`singleOrElse( )`** (scala) — _see [**`singleOrDefault( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators)_ +* **`size( )`** (scala) — _see [**`count( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#count)_ +* [**`skip( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#skip) — ignore the first _n_ items emitted by an Observable +* [**`skipLast( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#skiplast) — ignore the last _n_ items emitted by an Observable +* [**`skipUntil( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators) — discard items emitted by a source Observable until a second Observable emits an item, then emit the remainder of the source Observable's items +* [**`skipWhile( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators) — discard items emitted by an Observable until a specified condition is false, then emit the remainder +* **`sliding( )`** (scala) — _see [**`window( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#window)_ +* **`slidingBuffer( )`** (scala) — _see [**`buffer( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#buffer)_ +* [**`split( )`**](https://github.com/ReactiveX/RxJava/wiki/String-Observables) (`StringObservable`) — converts an Observable of Strings into an Observable of Strings that treats the source sequence as a stream and splits it on a specified regex boundary +* [**`start( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) — create an Observable that emits the return value of a function (`rxjava-async`) +* [**`startCancellableFuture( )`**](https://github.com/ReactiveX/RxJava/wiki/Phantom-Operators#fromcancellablefuture-startcancellablefuture-and-defercancellablefuture) — convert a function that returns Future into an Observable that emits that Future's return value in a way that monitors the subscription status of the Observable to determine whether to halt work on the Future (⁇)(`rxjava-async`) +* [**`startFuture( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) — convert a function that returns Future into an Observable that emits that Future's return value (`rxjava-async`) +* [**`startWith( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#startwith) — emit a specified sequence of items before beginning to emit the items from the Observable +* [**`stringConcat( )`**](https://github.com/ReactiveX/RxJava/wiki/String-Observables) (`StringObservable`) — converts an Observable that emits a sequence of strings into an Observable that emits a single string that concatenates them all +* [**`subscribeOn( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — specify which Scheduler an Observable should use when its subscription is invoked +* [**`sumDouble( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#sumdouble) — adds the Doubles emitted by an Observable and emits this sum (`rxjava-math`) +* [**`sumFloat( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#sumfloat) — adds the Floats emitted by an Observable and emits this sum (`rxjava-math`) +* [**`sumInt( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#sumint) — adds the Integers emitted by an Observable and emits this sum (`rxjava-math`) +* [**`sumLong( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#sumlong) — adds the Longs emitted by an Observable and emits this sum (`rxjava-math`) +* **`switch( )`** (scala) — _see [**`switchOnNext( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#switchonnext)_ +* [**`switchCase( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators) — emit the sequence from a particular Observable based on the results of an evaluation (`contrib-computation-expressions`) +* [**`switchMap( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#switchmap) — transform the items emitted by an Observable into Observables, and mirror those items emitted by the most-recently transformed Observable +* [**`switchOnNext( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#switchonnext) — convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently emitted of those Observables +* **`synchronize( )`** — _see [**`serialize( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators)_ +* [**`take( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#take) — emit only the first _n_ items emitted by an Observable +* [**`takeFirst( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) — emit only the first item emitted by an Observable, or the first item that meets some condition +* [**`takeLast( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#takelast) — only emit the last _n_ items emitted by an Observable +* [**`takeLastBuffer( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables) — emit the last _n_ items emitted by an Observable, as a single list item +* **`takeRight( )`** (scala) — _see [**`last( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#last) (`Observable`) or [**`takeLast( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#takelast)_ +* [**`takeUntil( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators) — emits the items from the source Observable until a second Observable emits an item +* [**`takeWhile( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators) — emit items emitted by an Observable as long as a specified condition is true, then skip the remainder +* **`take-while( )`** (clojure) — _see [**`takeWhile( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators)_ +* [**`then( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#rxjava-joins) — transform a series of `Pattern` objects via a `Plan` template (`rxjava-joins`) +* [**`throttleFirst( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#throttlefirst) — emit the first items emitted by an Observable within periodic time intervals +* [**`throttleLast( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#throttlelast) — emit the most recent items emitted by an Observable within periodic time intervals +* [**`throttleWithTimeout( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#throttlewithtimeout) — only emit an item from the source Observable after a particular timespan has passed without the Observable emitting any other items +* **`throw( )`** (clojure) — _see [**`error( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#error)_ +* [**`timeInterval( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — emit the time lapsed between consecutive emissions of a source Observable +* [**`timeout( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#timeout) — emit items from a source Observable, but issue an exception if no item is emitted in a specified timespan +* [**`timer( )`**](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#timer) — create an Observable that emits a single item after a given delay +* [**`timestamp( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — attach a timestamp to every item emitted by an Observable +* [**`toAsync( )`**](https://github.com/ReactiveX/RxJava/wiki/Async-Operators) — convert a function or Action into an Observable that executes the function and emits its return value (`rxjava-async`) +* [**`toBlocking( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) — transform an Observable into a BlockingObservable +* **`toBlockingObservable( )`** - _see [**`toBlocking( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators)_ +* [**`toFuture( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) — convert the Observable into a Future +* [**`toIterable( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators) — convert the sequence emitted by the Observable into an Iterable +* **`toIterator( )`** — _see [**`getIterator( )`**](https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators)_ +* [**`toList( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#tolist) — collect all items from an Observable and emit them as a single List +* [**`toMap( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#tomap) — convert the sequence of items emitted by an Observable into a map keyed by a specified key function +* [**`toMultimap( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#tomultimap) — convert the sequence of items emitted by an Observable into an ArrayList that is also a map keyed by a specified key function +* **`toSeq( )`** (scala) — _see [**`toList( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#tolist)_ +* [**`toSortedList( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#tosortedlist) — collect all items from an Observable and emit them as a single, sorted List +* **`tumbling( )`** (scala) — _see [**`window( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#window)_ +* **`tumblingBuffer( )`** (scala) — _see [**`buffer( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#buffer)_ +* [**`using( )`**](https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators) — create a disposable resource that has the same lifespan as an Observable +* [**`when( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#rxjava-joins) — convert a series of `Plan` objects into an Observable (`rxjava-joins`) +* **`where( )`** — _see: [**`filter( )`**](https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#filter)_ +* [**`whileDo( )`**](https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators#conditional-operators) — if a condition is true, emit the source Observable's sequence and then repeat the sequence as long as the condition remains true (`contrib-computation-expressions`) +* [**`window( )`**](https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables#window) — periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time +* [**`zip( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#zip) — combine sets of items emitted by two or more Observables together via a specified function and emit items based on the results of this function +* **`zipWith( )`** — _instance version of [**`zip( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#zip)_ +* **`zipWithIndex( )`** (scala) — _see [**`zip( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#zip)_ +* **`++`** (scala) — _see [**`concat( )`**](https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators)_ +* **`+:`** (scala) — _see [**`startWith( )`**](https://github.com/ReactiveX/RxJava/wiki/Combining-Observables#startwith)_ -(⁇) — this proposed operator is not part of RxJava 1.0 \ No newline at end of file +(⁇) — this proposed operator is not part of RxJava 1.0 From 15e52bbf7221498f37cf563fba1abf38ebbf5b90 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 7 Jun 2019 11:51:05 +0200 Subject: [PATCH 364/417] Create What's-different-in-3.0.md --- docs/What's-different-in-3.0.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 docs/What's-different-in-3.0.md diff --git a/docs/What's-different-in-3.0.md b/docs/What's-different-in-3.0.md new file mode 100644 index 0000000000..e936692c06 --- /dev/null +++ b/docs/What's-different-in-3.0.md @@ -0,0 +1,33 @@ +Table of contents + +# Introduction +TBD. + +### API signature changes + +TBD. + +- as() merged into to() +- some operators returning a more appropriate Single or Maybe +- functional interfaces throws widening to Throwable +- standard methods removed +- standard methods signature changes + +### Standardized operators + +(former experimental and beta operators from 2.x) + +TBD. + +### Operator behavior changes + +TBD. + +- connectable sources lifecycle-fixes + + +### Test support changes + +TBD. + +- methods removed from the test consumers From 89d506d587a9fc0614a45a599f2e45f04e08eac5 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sat, 15 Jun 2019 21:30:30 +0200 Subject: [PATCH 365/417] 2.x: Fix javadocs & imports (#6504) --- gradle/javadoc_cleanup.gradle | 2 ++ .../java/io/reactivex/processors/package-info.java | 4 ++-- src/main/java/io/reactivex/schedulers/Schedulers.java | 10 +++++----- .../operators/maybe/MaybeDoOnTerminateTest.java | 2 -- .../operators/single/SingleDoOnTerminateTest.java | 1 - 5 files changed, 9 insertions(+), 10 deletions(-) diff --git a/gradle/javadoc_cleanup.gradle b/gradle/javadoc_cleanup.gradle index 79f4d5411a..518d7a1d51 100644 --- a/gradle/javadoc_cleanup.gradle +++ b/gradle/javadoc_cleanup.gradle @@ -12,6 +12,8 @@ task javadocCleanup(dependsOn: "javadoc") doLast { fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/subjects/ReplaySubject.html')); fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/processors/ReplayProcessor.html')); fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/plugins/RxJavaPlugins.html')); + + fixJavadocFile(rootProject.file('build/docs/javadoc/io/reactivex/parallel/ParallelFlowable.html')); } def fixJavadocFile(file) { diff --git a/src/main/java/io/reactivex/processors/package-info.java b/src/main/java/io/reactivex/processors/package-info.java index 1266a74ee1..b6a619372f 100644 --- a/src/main/java/io/reactivex/processors/package-info.java +++ b/src/main/java/io/reactivex/processors/package-info.java @@ -16,7 +16,7 @@ /** * Classes representing so-called hot backpressure-aware sources, aka <strong>processors</strong>, - * that implement the {@link FlowableProcessor} class, + * that implement the {@link io.reactivex.processors.FlowableProcessor FlowableProcessor} class, * the Reactive Streams {@link org.reactivestreams.Processor Processor} interface * to allow forms of multicasting events to one or more subscribers as well as consuming another * Reactive Streams {@link org.reactivestreams.Publisher Publisher}. @@ -33,7 +33,7 @@ * </ul> * <p> * The non-backpressured variants of the {@code FlowableProcessor} class are called - * {@link io.reactivex.Subject}s and reside in the {@code io.reactivex.subjects} package. + * {@link io.reactivex.subjects.Subject}s and reside in the {@code io.reactivex.subjects} package. * @see io.reactivex.subjects */ package io.reactivex.processors; diff --git a/src/main/java/io/reactivex/schedulers/Schedulers.java b/src/main/java/io/reactivex/schedulers/Schedulers.java index 4edaf65b1a..9e070690b8 100644 --- a/src/main/java/io/reactivex/schedulers/Schedulers.java +++ b/src/main/java/io/reactivex/schedulers/Schedulers.java @@ -299,7 +299,7 @@ public static Scheduler single() { * a time delay or periodically will use the {@link #single()} scheduler for the timed waiting * before posting the actual task to the given executor. * <p> - * Tasks submitted to the {@link Scheduler.Worker} of this {@code Scheduler} are also not interruptible. Use the + * Tasks submitted to the {@link io.reactivex.Scheduler.Worker Scheduler.Worker} of this {@code Scheduler} are also not interruptible. Use the * {@link #from(Executor, boolean)} overload to enable task interruption via this wrapper. * <p> * If the provided executor supports the standard Java {@link ExecutorService} API, @@ -332,7 +332,7 @@ public static Scheduler single() { * } * </code></pre> * <p> - * This type of scheduler is less sensitive to leaking {@link Scheduler.Worker} instances, although + * This type of scheduler is less sensitive to leaking {@link io.reactivex.Scheduler.Worker Scheduler.Worker} instances, although * not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or * execute those tasks "unexpectedly". * <p> @@ -350,7 +350,7 @@ public static Scheduler from(@NonNull Executor executor) { * Wraps an {@link Executor} into a new Scheduler instance and delegates {@code schedule()} * calls to it. * <p> - * The tasks scheduled by the returned {@link Scheduler} and its {@link Scheduler.Worker} + * The tasks scheduled by the returned {@link Scheduler} and its {@link io.reactivex.Scheduler.Worker Scheduler.Worker} * can be optionally interrupted. * <p> * If the provided executor doesn't support any of the more specific standard Java executor @@ -388,14 +388,14 @@ public static Scheduler from(@NonNull Executor executor) { * } * </code></pre> * <p> - * This type of scheduler is less sensitive to leaking {@link Scheduler.Worker} instances, although + * This type of scheduler is less sensitive to leaking {@link io.reactivex.Scheduler.Worker Scheduler.Worker} instances, although * not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or * execute those tasks "unexpectedly". * <p> * Note that this method returns a new {@link Scheduler} instance, even for the same {@link Executor} instance. * @param executor * the executor to wrap - * @param interruptibleWorker if {@code true} the tasks submitted to the {@link Scheduler.Worker} will + * @param interruptibleWorker if {@code true} the tasks submitted to the {@link io.reactivex.Scheduler.Worker Scheduler.Worker} will * be interrupted when the task is disposed. * @return the new Scheduler wrapping the Executor * @since 2.2.6 - experimental diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminateTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminateTest.java index d442fcc135..0e90e57731 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminateTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminateTest.java @@ -19,8 +19,6 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.Action; import io.reactivex.observers.TestObserver; -import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.subjects.PublishSubject; import org.junit.Test; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTerminateTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTerminateTest.java index ba15f9f71b..425ee84205 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTerminateTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleDoOnTerminateTest.java @@ -19,7 +19,6 @@ import io.reactivex.exceptions.TestException; import io.reactivex.functions.Action; import io.reactivex.observers.TestObserver; -import org.junit.Assert; import org.junit.Test; import java.util.List; From c5e1b3a29b916341bfe5ab8ea58f94053e79b497 Mon Sep 17 00:00:00 2001 From: Jan Knotek <jan.knotek@gmail.com> Date: Mon, 17 Jun 2019 13:43:35 +0100 Subject: [PATCH 366/417] Null check for BufferExactBoundedObserver (#6499) * Null check for BufferExactBoundedObserver Other variants contain this Null check already, e.g. BufferExactUnboundedObserver It is causing 0.1% crashes in our production app. * ObservableBufferTimed.BufferExactBoundedObserver - failing supplier unit test FlowableBufferTimed.BufferExactBoundedSubscriber - failing supplier fix + unit test * Better Unit tests for FlowableBufferTimed and BufferExactBoundedSubscriber NPE issue Reverted --- .../operators/flowable/FlowableBufferTimed.java | 13 +++++++------ .../observable/ObservableBufferTimed.java | 10 ++++++---- .../operators/flowable/FlowableBufferTest.java | 15 +++++++++++++++ .../observable/ObservableBufferTest.java | 15 +++++++++++++++ 4 files changed, 43 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java index 4e3be8a9e5..06736603f1 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java @@ -501,13 +501,14 @@ public void onComplete() { buffer = null; } - queue.offer(b); - done = true; - if (enter()) { - QueueDrainHelper.drainMaxLoop(queue, downstream, false, this, this); + if (b != null) { + queue.offer(b); + done = true; + if (enter()) { + QueueDrainHelper.drainMaxLoop(queue, downstream, false, this, this); + } + w.dispose(); } - - w.dispose(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java index 8a6fafea6e..b9f692db9d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java @@ -504,10 +504,12 @@ public void onComplete() { buffer = null; } - queue.offer(b); - done = true; - if (enter()) { - QueueDrainHelper.drainLoop(queue, downstream, false, this, this); + if (b != null) { + queue.offer(b); + done = true; + if (enter()) { + QueueDrainHelper.drainLoop(queue, downstream, false, this, this); + } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index 5060c58253..e79130ff41 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -2769,4 +2769,19 @@ public void timedSizeBufferAlreadyCleared() { sub.run(); } + + @Test + public void bufferExactFailingSupplier() { + Flowable.empty() + .buffer(1, TimeUnit.SECONDS, Schedulers.computation(), 10, new Callable<List<Object>>() { + @Override + public List<Object> call() throws Exception { + throw new TestException(); + } + }, false) + .test() + .awaitDone(1, TimeUnit.SECONDS) + .assertFailure(TestException.class) + ; + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 43612b228d..66a4e24dc0 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -2136,4 +2136,19 @@ public ObservableSource<List<Object>> apply(Observable<Object> o) } }); } + + @Test + public void bufferExactFailingSupplier() { + Observable.empty() + .buffer(1, TimeUnit.SECONDS, Schedulers.computation(), 10, new Callable<List<Object>>() { + @Override + public List<Object> call() throws Exception { + throw new TestException(); + } + }, false) + .test() + .awaitDone(1, TimeUnit.SECONDS) + .assertFailure(TestException.class) + ; + } } From ed29fac873fb44d8ab3fab08c65f483fe52e05ab Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 17 Jun 2019 14:51:04 +0200 Subject: [PATCH 367/417] 2.x: Expand the Javadoc of Flowable (#6506) --- src/main/java/io/reactivex/Flowable.java | 108 +++++++++++++++++++-- src/main/java/io/reactivex/Observable.java | 2 +- 2 files changed, 101 insertions(+), 9 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index fe27b9bfd3..7dc6d77716 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -36,12 +36,12 @@ import io.reactivex.subscribers.*; /** - * The Flowable class that implements the Reactive-Streams Pattern and offers factory methods, - * intermediate operators and the ability to consume reactive dataflows. + * The Flowable class that implements the <a href="https://github.com/reactive-streams/reactive-streams-jvm">Reactive Streams</a> + * Pattern and offers factory methods, intermediate operators and the ability to consume reactive dataflows. * <p> - * Reactive-Streams operates with {@code Publisher}s which {@code Flowable} extends. Many operators + * Reactive Streams operates with {@link Publisher}s which {@code Flowable} extends. Many operators * therefore accept general {@code Publisher}s directly and allow direct interoperation with other - * Reactive-Streams implementations. + * Reactive Streams implementations. * <p> * The Flowable hosts the default buffer size of 128 elements for operators, accessible via {@link #bufferSize()}, * that can be overridden globally via the system parameter {@code rx2.buffer-size}. Most operators, however, have @@ -51,11 +51,103 @@ * <p> * <img width="640" height="317" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/legend.png" alt=""> * <p> + * The {@code Flowable} follows the protocol + * <pre><code> + * onSubscribe onNext* (onError | onComplete)? + * </code></pre> + * where the stream can be disposed through the {@link Subscription} instance provided to consumers through + * {@link Subscriber#onSubscribe(Subscription)}. + * Unlike the {@code Observable.subscribe()} of version 1.x, {@link #subscribe(Subscriber)} does not allow external cancellation + * of a subscription and the {@link Subscriber} instance is expected to expose such capability if needed. + * <p> + * Flowables support backpressure and require {@link Subscriber}s to signal demand via {@link Subscription#request(long)}. + * <p> + * Example: + * <pre><code> + * Disposable d = Flowable.just("Hello world!") + * .delay(1, TimeUnit.SECONDS) + * .subscribeWith(new DisposableSubscriber<String>() { + * @Override public void onStart() { + * System.out.println("Start!"); + * request(1); + * } + * @Override public void onNext(String t) { + * System.out.println(t); + * request(1); + * } + * @Override public void onError(Throwable t) { + * t.printStackTrace(); + * } + * @Override public void onComplete() { + * System.out.println("Done!"); + * } + * }); + * + * Thread.sleep(500); + * // the sequence can now be cancelled via dispose() + * d.dispose(); + * </code></pre> + * <p> + * The Reactive Streams specification is relatively strict when defining interactions between {@code Publisher}s and {@code Subscriber}s, so much so + * that there is a significant performance penalty due certain timing requirements and the need to prepare for invalid + * request amounts via {@link Subscription#request(long)}. + * Therefore, RxJava has introduced the {@link FlowableSubscriber} interface that indicates the consumer can be driven with relaxed rules. + * All RxJava operators are implemented with these relaxed rules in mind. + * If the subscribing {@code Subscriber} does not implement this interface, for example, due to it being from another Reactive Streams compliant + * library, the Flowable will automatically apply a compliance wrapper around it. + * <p> + * {@code Flowable} is an abstract class, but it is not advised to implement sources and custom operators by extending the class directly due + * to the large amounts of <a href="https://github.com/reactive-streams/reactive-streams-jvm#specification">Reactive Streams</a> + * rules to be followed to the letter. See <a href="https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0">the wiki</a> for + * some guidance if such custom implementations are necessary. + * <p> + * The recommended way of creating custom {@code Flowable}s is by using the {@link #create(FlowableOnSubscribe, BackpressureStrategy)} factory method: + * <pre><code> + * Flowable<String> source = Flowable.create(new FlowableOnSubscribe<String>() { + * @Override + * public void subscribe(FlowableEmitter<String> emitter) throws Exception { + * + * // signal an item + * emitter.onNext("Hello"); + * + * // could be some blocking operation + * Thread.sleep(1000); + * + * // the consumer might have cancelled the flow + * if (emitter.isCancelled() { + * return; + * } + * + * emitter.onNext("World"); + * + * Thread.sleep(1000); + * + * // the end-of-sequence has to be signaled, otherwise the + * // consumers may never finish + * emitter.onComplete(); + * } + * }, BackpressureStrategy.BUFFER); + * + * System.out.println("Subscribe!"); + * + * source.subscribe(System.out::println); + * + * System.out.println("Done!"); + * </code></pre> + * <p> + * RxJava reactive sources, such as {@code Flowable}, are generally synchronous and sequential in nature. In the ReactiveX design, the location (thread) + * where operators run is <i>orthogonal</i> to when the operators can work with data. This means that asynchrony and parallelism + * has to be explicitly expressed via operators such as {@link #subscribeOn(Scheduler)}, {@link #observeOn(Scheduler)} and {@link #parallel()}. In general, + * operators featuring a {@link Scheduler} parameter are introducing this type of asynchrony into the flow. + * <p> * For more information see the <a href="http://reactivex.io/documentation/Publisher.html">ReactiveX * documentation</a>. * * @param <T> * the type of the items emitted by the Flowable + * @see Observable + * @see ParallelFlowable + * @see io.reactivex.subscribers.DisposableSubscriber */ public abstract class Flowable<T> implements Publisher<T> { /** The default buffer size. */ @@ -2199,7 +2291,7 @@ public static <T> Flowable<T> fromIterable(Iterable<? extends T> source) { } /** - * Converts an arbitrary Reactive-Streams Publisher into a Flowable if not already a + * Converts an arbitrary Reactive Streams Publisher into a Flowable if not already a * Flowable. * <p> * The {@link Publisher} must follow the @@ -4385,7 +4477,7 @@ public static Flowable<Long> timer(long delay, TimeUnit unit, Scheduler schedule /** * Create a Flowable by wrapping a Publisher <em>which has to be implemented according - * to the Reactive-Streams specification by handling backpressure and + * to the Reactive Streams specification by handling backpressure and * cancellation correctly; no safeguards are provided by the Flowable itself</em>. * <dl> * <dt><b>Backpressure:</b></dt> @@ -13569,7 +13661,7 @@ public final Flowable<T> retryWhen( * Subscribes to the current Flowable and wraps the given Subscriber into a SafeSubscriber * (if not already a SafeSubscriber) that * deals with exceptions thrown by a misbehaving Subscriber (that doesn't follow the - * Reactive-Streams specification). + * Reactive Streams specification). * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator leaves the reactive world and the backpressure behavior depends on the Subscriber's behavior.</dd> @@ -14792,7 +14884,7 @@ public final void subscribe(Subscriber<? super T> s) { * If the {@link Flowable} rejects the subscription attempt or otherwise fails it will signal * the error via {@link FlowableSubscriber#onError(Throwable)}. * <p> - * This subscribe method relaxes the following Reactive-Streams rules: + * This subscribe method relaxes the following Reactive Streams rules: * <ul> * <li>§1.3: onNext should not be called concurrently until onSubscribe returns. * <b>FlowableSubscriber.onSubscribe should make sure a sync or async call triggered by request() is safe.</b></li> diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 5bdd940909..20b829ad2e 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -42,7 +42,7 @@ * Many operators in the class accept {@code ObservableSource}(s), the base reactive interface * for such non-backpressured flows, which {@code Observable} itself implements as well. * <p> - * The Observable's operators, by default, run with a buffer size of 128 elements (see {@link Flowable#bufferSize()}, + * The Observable's operators, by default, run with a buffer size of 128 elements (see {@link Flowable#bufferSize()}), * that can be overridden globally via the system parameter {@code rx2.buffer-size}. Most operators, however, have * overloads that allow setting their internal buffer size explicitly. * <p> From 31e8d48a53c42c46a01f1db3d09ab4cafe5133f6 Mon Sep 17 00:00:00 2001 From: Jonathan Sawyer <JonathanSawyer@users.noreply.github.com> Date: Mon, 17 Jun 2019 22:49:56 +0900 Subject: [PATCH 368/417] 2.x: Correct Reactive-Streams to Reactive Streams in Documentation (#6510) --- DESIGN.md | 4 +- README.md | 4 +- docs/What's-different-in-2.0.md | 38 +++++++++---------- docs/Writing-operators-for-2.0.md | 26 ++++++------- src/main/java/io/reactivex/Completable.java | 2 +- src/main/java/io/reactivex/Flowable.java | 2 +- .../java/io/reactivex/FlowableSubscriber.java | 2 +- src/main/java/io/reactivex/Observable.java | 10 ++--- src/main/java/io/reactivex/Single.java | 2 +- .../ProtocolViolationException.java | 2 +- .../subscribers/StrictSubscriber.java | 2 +- src/main/java/io/reactivex/package-info.java | 2 +- 12 files changed, 48 insertions(+), 48 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 53f828186a..5480b39948 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -528,13 +528,13 @@ interface ScalarCallable<T> extends java.util.Callable<T> { `ScalarCallable` is also `Callable` and thus its value can be extracted practically anytime. For convenience (and for sense), `ScalarCallable` overrides and hides the superclass' `throws Exception` clause - throwing during assembly time is likely unreasonable for scalars. -Since Reactive-Streams doesn't allow `null`s in the value flow, we have the opportunity to define `ScalarCallable`s and `Callable`s returning `null` should be considered as an empty source - allowing operators to dispatch on the type `Callable` first then branch on the nullness of `call()`. +Since Reactive Streams doesn't allow `null`s in the value flow, we have the opportunity to define `ScalarCallable`s and `Callable`s returning `null` should be considered as an empty source - allowing operators to dispatch on the type `Callable` first then branch on the nullness of `call()`. Interoperating with other libraries, at this level is possible. Reactor-Core uses the same pattern and the two libraries can work with each other's `Publisher+Callable` types. Unfortunately, this means subscription-time only fusion as `ScalarCallable`s live locally in each library. ##### Micro-fusion -Micro-fusion goes a step deeper and tries to reuse internal structures, mostly queues, in operator pairs, saving on allocation and sometimes on atomic operations. It's property is that, in a way, subverts the standard Reactive-Streams protocol between subsequent operators that both support fusion. However, from the outside world's view, they still work according to the RS protocol. +Micro-fusion goes a step deeper and tries to reuse internal structures, mostly queues, in operator pairs, saving on allocation and sometimes on atomic operations. It's property is that, in a way, subverts the standard Reactive Streams protocol between subsequent operators that both support fusion. However, from the outside world's view, they still work according to the RS protocol. Currently, two main kinds of micro-fusion opportunities are available. diff --git a/README.md b/README.md index 982f0c393d..fd53e02083 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ It extends the [observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) #### Version 2.x ([Javadoc](http://reactivex.io/RxJava/2.x/javadoc/)) -- single dependency: [Reactive-Streams](https://github.com/reactive-streams/reactive-streams-jvm) +- single dependency: [Reactive Streams](https://github.com/reactive-streams/reactive-streams-jvm) - continued support for Java 6+ & [Android](https://github.com/ReactiveX/RxAndroid) 2.3+ - performance gains through design changes learned through the 1.x cycle and through [Reactive-Streams-Commons](https://github.com/reactor/reactive-streams-commons) research project. - Java 8 lambda-friendly API @@ -72,7 +72,7 @@ Flowable.just("Hello world") RxJava 2 features several base classes you can discover operators on: - - [`io.reactivex.Flowable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html): 0..N flows, supporting Reactive-Streams and backpressure + - [`io.reactivex.Flowable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html): 0..N flows, supporting Reactive Streams and backpressure - [`io.reactivex.Observable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html): 0..N flows, no backpressure, - [`io.reactivex.Single`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Single.html): a flow of exactly 1 item or an error, - [`io.reactivex.Completable`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Completable.html): a flow without items but only a completion or error signal, diff --git a/docs/What's-different-in-2.0.md b/docs/What's-different-in-2.0.md index fac50df56d..30f9a4ccba 100644 --- a/docs/What's-different-in-2.0.md +++ b/docs/What's-different-in-2.0.md @@ -1,6 +1,6 @@ -RxJava 2.0 has been completely rewritten from scratch on top of the Reactive-Streams specification. The specification itself has evolved out of RxJava 1.x and provides a common baseline for reactive systems and libraries. +RxJava 2.0 has been completely rewritten from scratch on top of the Reactive Streams specification. The specification itself has evolved out of RxJava 1.x and provides a common baseline for reactive systems and libraries. -Because Reactive-Streams has a different architecture, it mandates changes to some well known RxJava types. This wiki page attempts to summarize what has changed and describes how to rewrite 1.x code into 2.x code. +Because Reactive Streams has a different architecture, it mandates changes to some well known RxJava types. This wiki page attempts to summarize what has changed and describes how to rewrite 1.x code into 2.x code. For technical details on how to write operators for 2.x, please visit the [Writing Operators](https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0) wiki page. @@ -20,7 +20,7 @@ For technical details on how to write operators for 2.x, please visit the [Writi - [Subscriber](#subscriber) - [Subscription](#subscription) - [Backpressure](#backpressure) - - [Reactive-Streams compliance](#reactive-streams-compliance) + - [Reactive Streams compliance](#reactive-streams-compliance) - [Runtime hooks](#runtime-hooks) - [Error handling](#error-handling) - [Scheduler](#schedulers) @@ -105,7 +105,7 @@ When architecting dataflows (as an end-consumer of RxJava) or deciding upon what # Single -The 2.x `Single` reactive base type, which can emit a single `onSuccess` or `onError` has been redesigned from scratch. Its architecture now derives from the Reactive-Streams design. Its consumer type (`rx.Single.SingleSubscriber<T>`) has been changed from being a class that accepts `rx.Subscription` resources to be an interface `io.reactivex.SingleObserver<T>` that has only 3 methods: +The 2.x `Single` reactive base type, which can emit a single `onSuccess` or `onError` has been redesigned from scratch. Its architecture now derives from the Reactive Streams design. Its consumer type (`rx.Single.SingleSubscriber<T>`) has been changed from being a class that accepts `rx.Subscription` resources to be an interface `io.reactivex.SingleObserver<T>` that has only 3 methods: ```java interface SingleObserver<T> { @@ -119,7 +119,7 @@ and follows the protocol `onSubscribe (onSuccess | onError)?`. # Completable -The `Completable` type remains largely the same. It was already designed along the Reactive-Streams style for 1.x so no user-level changes there. +The `Completable` type remains largely the same. It was already designed along the Reactive Streams style for 1.x so no user-level changes there. Similar to the naming changes, `rx.Completable.CompletableSubscriber` has become `io.reactivex.CompletableObserver` with `onSubscribe(Disposable)`: @@ -154,7 +154,7 @@ Maybe.just(1) # Base reactive interfaces -Following the style of extending the Reactive-Streams `Publisher<T>` in `Flowable`, the other base reactive classes now extend similar base interfaces (in package `io.reactivex`): +Following the style of extending the Reactive Streams `Publisher<T>` in `Flowable`, the other base reactive classes now extend similar base interfaces (in package `io.reactivex`): ```java interface ObservableSource<T> { @@ -182,7 +182,7 @@ Flowable<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapper Observable<R> flatMap(Function<? super T, ? extends ObservableSource<? extends R>> mapper); ``` -By having `Publisher` as input this way, you can compose with other Reactive-Streams compliant libraries without the need to wrap them or convert them into `Flowable` first. +By having `Publisher` as input this way, you can compose with other Reactive Streams compliant libraries without the need to wrap them or convert them into `Flowable` first. If an operator has to offer a reactive base type, however, the user will receive the full reactive class (as giving out an `XSource` is practically useless as it doesn't have operators on it): @@ -197,7 +197,7 @@ source.compose((Flowable<T> flowable) -> # Subjects and Processors -In the Reactive-Streams specification, the `Subject`-like behavior, namely being a consumer and supplier of events at the same time, is done by the `org.reactivestreams.Processor` interface. As with the `Observable`/`Flowable` split, the backpressure-aware, Reactive-Streams compliant implementations are based on the `FlowableProcessor<T>` class (which extends `Flowable` to give a rich set of instance operators). An important change regarding `Subject`s (and by extension, `FlowableProcessor`) that they no longer support `T -> R` like conversion (that is, input is of type `T` and the output is of type `R`). (We never had a use for it in 1.x and the original `Subject<T, R>` came from .NET where there is a `Subject<T>` overload because .NET allows the same class name with a different number of type arguments.) +In the Reactive Streams specification, the `Subject`-like behavior, namely being a consumer and supplier of events at the same time, is done by the `org.reactivestreams.Processor` interface. As with the `Observable`/`Flowable` split, the backpressure-aware, Reactive Streams compliant implementations are based on the `FlowableProcessor<T>` class (which extends `Flowable` to give a rich set of instance operators). An important change regarding `Subject`s (and by extension, `FlowableProcessor`) that they no longer support `T -> R` like conversion (that is, input is of type `T` and the output is of type `R`). (We never had a use for it in 1.x and the original `Subject<T, R>` came from .NET where there is a `Subject<T>` overload because .NET allows the same class name with a different number of type arguments.) The `io.reactivex.subjects.AsyncSubject`, `io.reactivex.subjects.BehaviorSubject`, `io.reactivex.subjects.PublishSubject`, `io.reactivex.subjects.ReplaySubject` and `io.reactivex.subjects.UnicastSubject` in 2.x don't support backpressure (as part of the 2.x `Observable` family). @@ -296,7 +296,7 @@ In addition, operators requiring a predicate no longer use `Func1<T, Boolean>` b # Subscriber -The Reactive-Streams specification has its own Subscriber as an interface. This interface is lightweight and combines request management with cancellation into a single interface `org.reactivestreams.Subscription` instead of having `rx.Producer` and `rx.Subscription` separately. This allows creating stream consumers with less internal state than the quite heavy `rx.Subscriber` of 1.x. +The Reactive Streams specification has its own Subscriber as an interface. This interface is lightweight and combines request management with cancellation into a single interface `org.reactivestreams.Subscription` instead of having `rx.Producer` and `rx.Subscription` separately. This allows creating stream consumers with less internal state than the quite heavy `rx.Subscriber` of 1.x. ```java Flowable.range(1, 10).subscribe(new Subscriber<Integer>() { @@ -354,7 +354,7 @@ Flowable.range(1, 10).delay(1, TimeUnit.SECONDS).subscribe(subscriber); subscriber.dispose(); ``` -Note also that due to Reactive-Streams compatibility, the method `onCompleted` has been renamed to `onComplete` without the trailing `d`. +Note also that due to Reactive Streams compatibility, the method `onCompleted` has been renamed to `onComplete` without the trailing `d`. Since 1.x `Observable.subscribe(Subscriber)` returned `Subscription`, users often added the `Subscription` to a `CompositeSubscription` for example: @@ -364,7 +364,7 @@ CompositeSubscription composite = new CompositeSubscription(); composite.add(Observable.range(1, 5).subscribe(new TestSubscriber<Integer>())); ``` -Due to the Reactive-Streams specification, `Publisher.subscribe` returns void and the pattern by itself no longer works in 2.0. To remedy this, the method `E subscribeWith(E subscriber)` has been added to each base reactive class which returns its input subscriber/observer as is. With the two examples before, the 2.x code can now look like this since `ResourceSubscriber` implements `Disposable` directly: +Due to the Reactive Streams specification, `Publisher.subscribe` returns void and the pattern by itself no longer works in 2.0. To remedy this, the method `E subscribeWith(E subscriber)` has been added to each base reactive class which returns its input subscriber/observer as is. With the two examples before, the 2.x code can now look like this since `ResourceSubscriber` implements `Disposable` directly: ```java CompositeDisposable composite2 = new CompositeDisposable(); @@ -420,11 +420,11 @@ This behavior differs from 1.x where a `request` call went through a deferred lo # Subscription -In RxJava 1.x, the interface `rx.Subscription` was responsible for stream and resource lifecycle management, namely unsubscribing a sequence and releasing general resources such as scheduled tasks. The Reactive-Streams specification took this name for specifying an interaction point between a source and a consumer: `org.reactivestreams.Subscription` allows requesting a positive amount from the upstream and allows cancelling the sequence. +In RxJava 1.x, the interface `rx.Subscription` was responsible for stream and resource lifecycle management, namely unsubscribing a sequence and releasing general resources such as scheduled tasks. The Reactive Streams specification took this name for specifying an interaction point between a source and a consumer: `org.reactivestreams.Subscription` allows requesting a positive amount from the upstream and allows cancelling the sequence. To avoid the name clash, the 1.x `rx.Subscription` has been renamed into `io.reactivex.Disposable` (somewhat resembling .NET's own IDisposable). -Because Reactive-Streams base interface, `org.reactivestreams.Publisher` defines the `subscribe()` method as `void`, `Flowable.subscribe(Subscriber)` no longer returns any `Subscription` (or `Disposable`). The other base reactive types also follow this signature with their respective subscriber types. +Because Reactive Streams base interface, `org.reactivestreams.Publisher` defines the `subscribe()` method as `void`, `Flowable.subscribe(Subscriber)` no longer returns any `Subscription` (or `Disposable`). The other base reactive types also follow this signature with their respective subscriber types. The other overloads of `subscribe` now return `Disposable` in 2.x. @@ -436,19 +436,19 @@ The original `Subscription` container types have been renamed and updated # Backpressure -The Reactive-Streams specification mandates operators supporting backpressure, specifically via the guarantee that they don't overflow their consumers when those don't request. Operators of the new `Flowable` base reactive type now consider downstream request amounts properly, however, this doesn't mean `MissingBackpressureException` is gone. The exception is still there but this time, the operator that can't signal more `onNext` will signal this exception instead (allowing better identification of who is not properly backpressured). +The Reactive Streams specification mandates operators supporting backpressure, specifically via the guarantee that they don't overflow their consumers when those don't request. Operators of the new `Flowable` base reactive type now consider downstream request amounts properly, however, this doesn't mean `MissingBackpressureException` is gone. The exception is still there but this time, the operator that can't signal more `onNext` will signal this exception instead (allowing better identification of who is not properly backpressured). As an alternative, the 2.x `Observable` doesn't do backpressure at all and is available as a choice to switch over. -# Reactive-Streams compliance +# Reactive Streams compliance **updated in 2.0.7** -**The `Flowable`-based sources and operators are, as of 2.0.7, fully Reactive-Streams version 1.0.0 specification compliant.** +**The `Flowable`-based sources and operators are, as of 2.0.7, fully Reactive Streams version 1.0.0 specification compliant.** Before 2.0.7, the operator `strict()` had to be applied in order to achieve the same level of compliance. In 2.0.7, the operator `strict()` returns `this`, is deprecated and will be removed completely in 2.1.0. -As one of the primary goals of RxJava 2, the design focuses on performance and in order enable it, RxJava 2.0.7 adds a custom `io.reactivex.FlowableSubscriber` interface (extends `org.reactivestreams.Subscriber`) but adds no new methods to it. The new interface is **constrained to RxJava 2** and represents a consumer to `Flowable` that is able to work in a mode that relaxes the Reactive-Streams version 1.0.0 specification in rules §1.3, §2.3, §2.12 and §3.9: +As one of the primary goals of RxJava 2, the design focuses on performance and in order enable it, RxJava 2.0.7 adds a custom `io.reactivex.FlowableSubscriber` interface (extends `org.reactivestreams.Subscriber`) but adds no new methods to it. The new interface is **constrained to RxJava 2** and represents a consumer to `Flowable` that is able to work in a mode that relaxes the Reactive Streams version 1.0.0 specification in rules §1.3, §2.3, §2.12 and §3.9: - §1.3 relaxation: `onSubscribe` may run concurrently with `onNext` in case the `FlowableSubscriber` calls `request()` from inside `onSubscribe` and it is the resposibility of `FlowableSubscriber` to ensure thread-safety between the remaining instructions in `onSubscribe` and `onNext`. - §2.3 relaxation: calling `Subscription.cancel` and `Subscription.request` from `FlowableSubscriber.onComplete()` or `FlowableSubscriber.onError()` is considered a no-operation. @@ -603,7 +603,7 @@ Integer i = Flowable.range(100, 100).blockingLast(); (The reason for this is twofold: performance and ease of use of the library as a synchronous Java 8 Streams-like processor.) -Another significant difference between `rx.Subscriber` (and co) and `org.reactivestreams.Subscriber` (and co) is that in 2.x, your `Subscriber`s and `Observer`s are not allowed to throw anything but fatal exceptions (see `Exceptions.throwIfFatal()`). (The Reactive-Streams specification allows throwing `NullPointerException` if the `onSubscribe`, `onNext` or `onError` receives a `null` value, but RxJava doesn't let `null`s in any way.) This means the following code is no longer legal: +Another significant difference between `rx.Subscriber` (and co) and `org.reactivestreams.Subscriber` (and co) is that in 2.x, your `Subscriber`s and `Observer`s are not allowed to throw anything but fatal exceptions (see `Exceptions.throwIfFatal()`). (The Reactive Streams specification allows throwing `NullPointerException` if the `onSubscribe`, `onNext` or `onError` receives a `null` value, but RxJava doesn't let `null`s in any way.) This means the following code is no longer legal: ```java Subscriber<Integer> subscriber = new Subscriber<Integer>() { @@ -933,7 +933,7 @@ To make sure the final API of 2.0 is clean as possible, we remove methods and ot ## doOnCancel/doOnDispose/unsubscribeOn -In 1.x, the `doOnUnsubscribe` was always executed on a terminal event because 1.x' `SafeSubscriber` called `unsubscribe` on itself. This was practically unnecessary and the Reactive-Streams specification states that when a terminal event arrives at a `Subscriber`, the upstream `Subscription` should be considered cancelled and thus calling `cancel()` is a no-op. +In 1.x, the `doOnUnsubscribe` was always executed on a terminal event because 1.x' `SafeSubscriber` called `unsubscribe` on itself. This was practically unnecessary and the Reactive Streams specification states that when a terminal event arrives at a `Subscriber`, the upstream `Subscription` should be considered cancelled and thus calling `cancel()` is a no-op. For the same reason, `unsubscribeOn` is not called on the regular termination path but only when there is an actual `cancel` (or `dispose`) call on the chain. diff --git a/docs/Writing-operators-for-2.0.md b/docs/Writing-operators-for-2.0.md index 7b6e57666e..9649c02be7 100644 --- a/docs/Writing-operators-for-2.0.md +++ b/docs/Writing-operators-for-2.0.md @@ -40,7 +40,7 @@ Writing operators, source-like (`fromEmitter`) or intermediate-like (`flatMap`) *(If you have been following [my blog](http://akarnokd.blogspot.hu/) about RxJava internals, writing operators is maybe only 2 times harder than 1.x; some things have moved around, some tools popped up while others have been dropped but there is a relatively straight mapping from 1.x concepts and approaches to 2.x concepts and approaches.)* -In this article, I'll describe the how-to's from the perspective of a developer who skipped the 1.x knowledge base and basically wants to write operators that conforms the Reactive-Streams specification as well as RxJava 2.x's own extensions and additional expectations/requirements. +In this article, I'll describe the how-to's from the perspective of a developer who skipped the 1.x knowledge base and basically wants to write operators that conforms the Reactive Streams specification as well as RxJava 2.x's own extensions and additional expectations/requirements. Since **Reactor 3** has the same architecture as **RxJava 2** (no accident, I architected and contributed 80% of **Reactor 3** as well) the same principles outlined in this page applies to writing operators for **Reactor 3**. Note however that they chose different naming and locations for their utility and support classes so you may have to search for the equivalent components. @@ -66,7 +66,7 @@ When dealing with backpressure in `Flowable` operators, one needs a way to accou The naive approach for accounting would be to simply call `AtomicLong.getAndAdd()` with new requests and `AtomicLong.addAndGet()` for decrementing based on how many elements were emitted. -The problem with this is that the Reactive-Streams specification declares `Long.MAX_VALUE` as the upper bound for outstanding requests (interprets it as the unbounded mode) but adding two large longs may overflow the `long` into a negative value. In addition, if for some reason, there are more values emitted than were requested, the subtraction may yield a negative current request value, causing crashes or hangs. +The problem with this is that the Reactive Streams specification declares `Long.MAX_VALUE` as the upper bound for outstanding requests (interprets it as the unbounded mode) but adding two large longs may overflow the `long` into a negative value. In addition, if for some reason, there are more values emitted than were requested, the subtraction may yield a negative current request value, causing crashes or hangs. Therefore, both addition and subtraction have to be capped at `Long.MAX_VALUE` and `0` respectively. Since there is no dedicated `AtomicLong` method for it, we have to use a Compare-And-Set loop. (Usually, requesting happens relatively rarely compared to emission amounts thus the lack of dedicated machine code instruction is not a performance bottleneck.) @@ -225,7 +225,7 @@ This simplified queue API gets rid of the unused parts (iterator, collections AP ## Deferred actions -The Reactive-Streams has a strict requirement that calling `onSubscribe()` must happen before any calls to the rest of the `onXXX` methods and by nature, any calls to `Subscription.request()` and `Subscription.cancel()`. The same logic applies to the design of `Observable`, `Single`, `Completable` and `Maybe` with their connection type of `Disposable`. +The Reactive Streams has a strict requirement that calling `onSubscribe()` must happen before any calls to the rest of the `onXXX` methods and by nature, any calls to `Subscription.request()` and `Subscription.cancel()`. The same logic applies to the design of `Observable`, `Single`, `Completable` and `Maybe` with their connection type of `Disposable`. Often though, such call to `onSubscribe` may happen later than the respective `cancel()` needs to happen. For example, the user may want to call `cancel()` before the respective `Subscription` actually becomes available in `subscribeOn`. Other operators may need to call `onSubscribe` before they connect to other sources but at that time, there is no direct way for relaying a `cancel` call to an unavailable upstream `Subscription`. @@ -286,7 +286,7 @@ The same pattern applies to `Subscription` with its `cancel()` method and with h ### Deferred requesting -With `Flowable`s (and Reactive-Streams `Publisher`s) the `request()` calls need to be deferred as well. In one form (the simpler one), the respective late `Subscription` will eventually arrive and we need to relay all previous and all subsequent request amount to its `request()` method. +With `Flowable`s (and Reactive Streams `Publisher`s) the `request()` calls need to be deferred as well. In one form (the simpler one), the respective late `Subscription` will eventually arrive and we need to relay all previous and all subsequent request amount to its `request()` method. In 1.x, this behavior was implicitly provided by `rx.Subscriber` but at a high cost that had to be payed by all instances whether or not they needed this feature. @@ -561,7 +561,7 @@ On the fast path, when we try to leave it, it is possible a concurrent call to ` ## FlowableSubscriber -Version 2.0.7 introduced a new interface, `FlowableSubscriber` that extends `Subscriber` from Reactive-Streams. It has the same methods with the same parameter types but different textual rules attached to it, a set of relaxations to the Reactive-Streams specification to enable better performing RxJava internals while still honoring the specification to the letter for non-RxJava consumers of `Flowable`s. +Version 2.0.7 introduced a new interface, `FlowableSubscriber` that extends `Subscriber` from Reactive Streams. It has the same methods with the same parameter types but different textual rules attached to it, a set of relaxations to the Reactive Streams specification to enable better performing RxJava internals while still honoring the specification to the letter for non-RxJava consumers of `Flowable`s. The rule relaxations are as follows: @@ -588,7 +588,7 @@ The other base reactive consumers, `Observer`, `SingleObserver`, `MaybeObserver` # Backpressure and cancellation -Backpressure (or flow control) in Reactive-Streams is the means to tell the upstream how many elements to produce or to tell it to stop producing elements altogether. Unlike the name suggest, there is no physical pressure preventing the upstream from calling `onNext` but the protocol to honor the request amount. +Backpressure (or flow control) in Reactive Streams is the means to tell the upstream how many elements to produce or to tell it to stop producing elements altogether. Unlike the name suggest, there is no physical pressure preventing the upstream from calling `onNext` but the protocol to honor the request amount. ## Replenishing @@ -1425,7 +1425,7 @@ public final class FlowableMyOperator extends Flowable<Integer> { } ``` -When taking other reactive types as inputs in these operators, it is recommended one defines the base reactive interfaces instead of the abstract classes, allowing better interoperability between libraries (especially with `Flowable` operators and other Reactive-Streams `Publisher`s). To recap, these are the class-interface pairs: +When taking other reactive types as inputs in these operators, it is recommended one defines the base reactive interfaces instead of the abstract classes, allowing better interoperability between libraries (especially with `Flowable` operators and other Reactive Streams `Publisher`s). To recap, these are the class-interface pairs: - `Flowable` - `Publisher` - `FlowableSubscriber`/`Subscriber` - `Observable` - `ObservableSource` - `Observer` @@ -1433,7 +1433,7 @@ When taking other reactive types as inputs in these operators, it is recommended - `Completable` - `CompletableSource` - `CompletableObserver` - `Maybe` - `MaybeSource` - `MaybeObserver` -RxJava 2.x locks down `Flowable.subscribe` (and the same methods in the other types) in order to provide runtime hooks into the various flows, therefore, implementors are given the `subscribeActual()` to be overridden. When it is invoked, all relevant hooks and wrappers have been applied. Implementors should avoid throwing unchecked exceptions as the library generally can't deliver it to the respective `Subscriber` due to lifecycle restrictions of the Reactive-Streams specification and sends it to the global error consumer via `RxJavaPlugins.onError`. +RxJava 2.x locks down `Flowable.subscribe` (and the same methods in the other types) in order to provide runtime hooks into the various flows, therefore, implementors are given the `subscribeActual()` to be overridden. When it is invoked, all relevant hooks and wrappers have been applied. Implementors should avoid throwing unchecked exceptions as the library generally can't deliver it to the respective `Subscriber` due to lifecycle restrictions of the Reactive Streams specification and sends it to the global error consumer via `RxJavaPlugins.onError`. Unlike in 1.x, In the example above, the incoming `Subscriber` is simply used directly for subscribing again (but still at most once) without any kind of wrapping. In 1.x, one needs to call `Subscribers.wrap` to avoid double calls to `onStart` and cause unexpected double initialization or double-requesting. @@ -1516,7 +1516,7 @@ public final class MyOperator implements FlowableOperator<Integer, Integer> { You may recognize that implementing operators via extension or lifting looks quite similar. In both cases, one usually implements a `FlowableSubscriber` (`Observer`, etc) that takes a downstream `Subscriber`, implements the business logic in the `onXXX` methods and somehow (manually or as part of `lift()`'s lifecycle) gets subscribed to an upstream source. -The benefit of applying the Reactive-Streams design to all base reactive types is that each consumer type is now an interface and can be applied to operators that have to extend some class. This was a pain in 1.x because `Subscriber` and `SingleSubscriber` are classes themselves, plus `Subscriber.request()` is a protected-final method and an operator's `Subscriber` can't implement the `Producer` interface at the same time. In 2.x there is no such problem and one can have both `Subscriber`, `Subscription` or even `Observer` together in the same consumer type. +The benefit of applying the Reactive Streams design to all base reactive types is that each consumer type is now an interface and can be applied to operators that have to extend some class. This was a pain in 1.x because `Subscriber` and `SingleSubscriber` are classes themselves, plus `Subscriber.request()` is a protected-final method and an operator's `Subscriber` can't implement the `Producer` interface at the same time. In 2.x there is no such problem and one can have both `Subscriber`, `Subscription` or even `Observer` together in the same consumer type. # Operator fusion @@ -1569,12 +1569,12 @@ This is the level of the **Rx.NET** library (even up to 3.x) that supports compo This is what **RxJava 1.x** is categorized, it supports composition, backpressure and synchronous cancellation along with the ability to lift an operator into a sequence. #### Generation 3 -This is the level of the Reactive-Streams based libraries such as **Reactor 2** and **Akka-Stream**. They are based upon a specification that evolved out of RxJava but left behind its drawbacks (such as the need to return anything from `subscribe()`). This is incompatible with RxJava 1.x and thus 2.x had to be rewritten from scratch. +This is the level of the Reactive Streams based libraries such as **Reactor 2** and **Akka-Stream**. They are based upon a specification that evolved out of RxJava but left behind its drawbacks (such as the need to return anything from `subscribe()`). This is incompatible with RxJava 1.x and thus 2.x had to be rewritten from scratch. #### Generation 4 -This level expands upon the Reactive-Streams interfaces with operator-fusion (in a compatible fashion, that is, op-fusion is optional between two stages and works without them). **Reactor 3** and **RxJava 2** are at this level. The material around **Akka-Stream** mentions operator-fusion as well, however, **Akka-Stream** is not a native Reactive-Streams implementation (requires a materializer to get a `Publisher` out) and as such it is only Gen 3. +This level expands upon the Reactive Streams interfaces with operator-fusion (in a compatible fashion, that is, op-fusion is optional between two stages and works without them). **Reactor 3** and **RxJava 2** are at this level. The material around **Akka-Stream** mentions operator-fusion as well, however, **Akka-Stream** is not a native Reactive Streams implementation (requires a materializer to get a `Publisher` out) and as such it is only Gen 3. -There are discussions among the 4th generation library providers to have the elements of operator-fusion standardized in Reactive-Streams 2.0 specification (or in a neighboring extension) and have **RxJava 3** and **Reactor 4** work together on that aspect as well. +There are discussions among the 4th generation library providers to have the elements of operator-fusion standardized in Reactive Streams 2.0 specification (or in a neighboring extension) and have **RxJava 3** and **Reactor 4** work together on that aspect as well. ## Components @@ -1629,7 +1629,7 @@ The reason for the two separate interfaces is that if a source is constant, like `Callable` denotes sources, such as `fromCallable` that indicates the single value has to be calculated at runtime of the flow. By this logic, you can see that `ScalarCallable` is a `Callable` on its own right because the constant can be "calculated" as late as the runtime phase of the flow. -Since Reactive-Streams forbids using `null`s as emission values, we can use `null` in `(Scalar)Callable` marked sources to indicate there is no value to be emitted, thus one can't mistake an user's `null` with the empty indicator `null`. For example, this is how `empty()` is implemented: +Since Reactive Streams forbids using `null`s as emission values, we can use `null` in `(Scalar)Callable` marked sources to indicate there is no value to be emitted, thus one can't mistake an user's `null` with the empty indicator `null`. For example, this is how `empty()` is implemented: ```java final class FlowableEmpty extends Flowable<Object> implements ScalarCallable<Object> { diff --git a/src/main/java/io/reactivex/Completable.java b/src/main/java/io/reactivex/Completable.java index 79fcc9b432..1994632307 100644 --- a/src/main/java/io/reactivex/Completable.java +++ b/src/main/java/io/reactivex/Completable.java @@ -557,7 +557,7 @@ public static <T> Completable fromObservable(final ObservableSource<T> observabl * <img width="640" height="422" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromPublisher.png" alt=""> * <p> * The {@link Publisher} must follow the - * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive-Streams specification</a>. + * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive Streams specification</a>. * Violating the specification may result in undefined behavior. * <p> * If possible, use {@link #create(CompletableOnSubscribe)} to create a diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 7dc6d77716..4fe78199fe 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -2295,7 +2295,7 @@ public static <T> Flowable<T> fromIterable(Iterable<? extends T> source) { * Flowable. * <p> * The {@link Publisher} must follow the - * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive-Streams specification</a>. + * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive Streams specification</a>. * Violating the specification may result in undefined behavior. * <p> * If possible, use {@link #create(FlowableOnSubscribe, BackpressureStrategy)} to create a diff --git a/src/main/java/io/reactivex/FlowableSubscriber.java b/src/main/java/io/reactivex/FlowableSubscriber.java index 2ef1019acf..e2636406e1 100644 --- a/src/main/java/io/reactivex/FlowableSubscriber.java +++ b/src/main/java/io/reactivex/FlowableSubscriber.java @@ -17,7 +17,7 @@ import org.reactivestreams.*; /** - * Represents a Reactive-Streams inspired Subscriber that is RxJava 2 only + * Represents a Reactive Streams inspired Subscriber that is RxJava 2 only * and weakens rules §1.3 and §3.9 of the specification for gaining performance. * * <p>History: 2.0.7 - experimental; 2.1 - beta diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 20b829ad2e..d2f11d2b5b 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -51,7 +51,7 @@ * <img width="640" height="317" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/legend.png" alt=""> * <p> * The design of this class was derived from the - * <a href="https://github.com/reactive-streams/reactive-streams-jvm">Reactive-Streams design and specification</a> + * <a href="https://github.com/reactive-streams/reactive-streams-jvm">Reactive Streams design and specification</a> * by removing any backpressure-related infrastructure and implementation detail, replacing the * {@code org.reactivestreams.Subscription} with {@link Disposable} as the primary means to dispose of * a flow. @@ -1985,12 +1985,12 @@ public static <T> Observable<T> fromIterable(Iterable<? extends T> source) { } /** - * Converts an arbitrary Reactive-Streams Publisher into an Observable. + * Converts an arbitrary Reactive Streams Publisher into an Observable. * <p> * <img width="640" height="344" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromPublisher.o.png" alt=""> * <p> * The {@link Publisher} must follow the - * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive-Streams specification</a>. + * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive Streams specification</a>. * Violating the specification may result in undefined behavior. * <p> * If possible, use {@link #create(ObservableOnSubscribe)} to create a @@ -3982,7 +3982,7 @@ public static Observable<Long> timer(long delay, TimeUnit unit, Scheduler schedu /** * Create an Observable by wrapping an ObservableSource <em>which has to be implemented according - * to the Reactive-Streams-based Observable specification by handling + * to the Reactive Streams based Observable specification by handling * disposal correctly; no safeguards are provided by the Observable itself</em>. * <dl> * <dt><b>Scheduler:</b></dt> @@ -11229,7 +11229,7 @@ public final Observable<T> retryWhen( * Subscribes to the current Observable and wraps the given Observer into a SafeObserver * (if not already a SafeObserver) that * deals with exceptions thrown by a misbehaving Observer (that doesn't follow the - * Reactive-Streams specification). + * Reactive Streams specification). * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code safeSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index f97f4d22b7..3dd0776e11 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -755,7 +755,7 @@ public static <T> Single<T> fromFuture(Future<? extends T> future, Scheduler sch * the source has more than one element, an IndexOutOfBoundsException is signalled. * <p> * The {@link Publisher} must follow the - * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive-Streams specification</a>. + * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive Streams specification</a>. * Violating the specification may result in undefined behavior. * <p> * If possible, use {@link #create(SingleOnSubscribe)} to create a diff --git a/src/main/java/io/reactivex/exceptions/ProtocolViolationException.java b/src/main/java/io/reactivex/exceptions/ProtocolViolationException.java index 09c0361108..ff36ce1cf3 100644 --- a/src/main/java/io/reactivex/exceptions/ProtocolViolationException.java +++ b/src/main/java/io/reactivex/exceptions/ProtocolViolationException.java @@ -14,7 +14,7 @@ package io.reactivex.exceptions; /** - * Explicitly named exception to indicate a Reactive-Streams + * Explicitly named exception to indicate a Reactive Streams * protocol violation. * <p>History: 2.0.6 - experimental; 2.1 - beta * @since 2.2 diff --git a/src/main/java/io/reactivex/internal/subscribers/StrictSubscriber.java b/src/main/java/io/reactivex/internal/subscribers/StrictSubscriber.java index 0fb9d5666c..c7770bf163 100644 --- a/src/main/java/io/reactivex/internal/subscribers/StrictSubscriber.java +++ b/src/main/java/io/reactivex/internal/subscribers/StrictSubscriber.java @@ -23,7 +23,7 @@ /** * Ensures that the event flow between the upstream and downstream follow - * the Reactive-Streams 1.0 specification by honoring the 3 additional rules + * the Reactive Streams 1.0 specification by honoring the 3 additional rules * (which are omitted in standard operators due to performance reasons). * <ul> * <li>§1.3: onNext should not be called concurrently until onSubscribe returns</li> diff --git a/src/main/java/io/reactivex/package-info.java b/src/main/java/io/reactivex/package-info.java index 7d78294b6d..75ceb6cd7b 100644 --- a/src/main/java/io/reactivex/package-info.java +++ b/src/main/java/io/reactivex/package-info.java @@ -25,7 +25,7 @@ * Completable/CompletableObserver interfaces and associated operators (in * the {@code io.reactivex.internal.operators} package) are inspired by the * Reactive Rx library in Microsoft .NET but designed and implemented on - * the more advanced Reactive-Streams ( http://www.reactivestreams.org ) principles.</p> + * the more advanced Reactive Streams ( http://www.reactivestreams.org ) principles.</p> * <p> * More information can be found at <a * href="http://msdn.microsoft.com/en-us/data/gg577609">http://msdn.microsoft.com/en-us/data/gg577609</a>. From b763ffadb4c9aefb0b168d8684ac0b3a7f8d42d0 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 20 Jun 2019 14:34:47 +0200 Subject: [PATCH 369/417] 2.x: Fix concatMapDelayError not continuing on fused inner source crash (#6522) --- .../operators/flowable/FlowableConcatMap.java | 9 ++-- .../flowable/FlowableConcatMapTest.java | 42 ++++++++++++++++++- 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java index 2dc316d1e9..f3dc0c58b8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java @@ -520,10 +520,13 @@ void drain() { vr = supplier.call(); } catch (Throwable e) { Exceptions.throwIfFatal(e); - upstream.cancel(); errors.addThrowable(e); - downstream.onError(errors.terminate()); - return; + if (!veryEnd) { + upstream.cancel(); + downstream.onError(errors.terminate()); + return; + } + vr = null; } if (vr == null) { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java index eba09e564f..d9fe79977f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java @@ -15,14 +15,14 @@ import static org.junit.Assert.assertEquals; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.reactivestreams.Publisher; import io.reactivex.*; -import io.reactivex.exceptions.TestException; +import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.operators.flowable.FlowableConcatMap.WeakScalarSubscription; import io.reactivex.schedulers.Schedulers; @@ -168,4 +168,42 @@ public void run() throws Exception { assertEquals(0, counter.get()); } + + @Test + public void delayErrorCallableTillTheEnd() { + Flowable.just(1, 2, 3, 101, 102, 23, 890, 120, 32) + .concatMapDelayError(new Function<Integer, Flowable<Integer>>() { + @Override public Flowable<Integer> apply(final Integer integer) throws Exception { + return Flowable.fromCallable(new Callable<Integer>() { + @Override public Integer call() throws Exception { + if (integer >= 100) { + throw new NullPointerException("test null exp"); + } + return integer; + } + }); + } + }) + .test() + .assertFailure(CompositeException.class, 1, 2, 3, 23, 32); + } + + @Test + public void delayErrorCallableEager() { + Flowable.just(1, 2, 3, 101, 102, 23, 890, 120, 32) + .concatMapDelayError(new Function<Integer, Flowable<Integer>>() { + @Override public Flowable<Integer> apply(final Integer integer) throws Exception { + return Flowable.fromCallable(new Callable<Integer>() { + @Override public Integer call() throws Exception { + if (integer >= 100) { + throw new NullPointerException("test null exp"); + } + return integer; + } + }); + } + }, 2, false) + .test() + .assertFailure(NullPointerException.class, 1, 2, 3); + } } From 19c09592801e8ae84bc11c23837f824292b7da86 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 20 Jun 2019 21:30:04 +0200 Subject: [PATCH 370/417] 2.x: Fix publish().refCount() hang due to race (#6505) * 2.x: Fix publish().refCount() hang due to race * Add more time to GC when detecting leaks. * Fix subscriber swap mistake in the Alt implementation --- .../flowables/ConnectableFlowable.java | 22 +- .../operators/flowable/FlowablePublish.java | 16 +- .../flowable/FlowablePublishAlt.java | 483 +++++ .../flowable/FlowablePublishClassic.java | 41 + .../observable/ObservablePublish.java | 8 +- .../observable/ObservablePublishAlt.java | 282 +++ .../observable/ObservablePublishClassic.java | 36 + .../observables/ConnectableObservable.java | 21 +- .../flowable/FlowablePublishAltTest.java | 1629 +++++++++++++++++ .../flowable/FlowablePublishTest.java | 22 + .../flowable/FlowableRefCountAltTest.java | 1447 +++++++++++++++ .../flowable/FlowableRefCountTest.java | 30 +- .../observable/ObservablePublishAltTest.java | 794 ++++++++ .../observable/ObservablePublishTest.java | 23 +- .../observable/ObservableRefCountAltTest.java | 1394 ++++++++++++++ .../observable/ObservableRefCountTest.java | 23 +- 16 files changed, 6262 insertions(+), 9 deletions(-) create mode 100644 src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishAlt.java create mode 100644 src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishClassic.java create mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservablePublishAlt.java create mode 100644 src/main/java/io/reactivex/internal/operators/observable/ObservablePublishClassic.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishAltTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservablePublishAltTest.java create mode 100644 src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java diff --git a/src/main/java/io/reactivex/flowables/ConnectableFlowable.java b/src/main/java/io/reactivex/flowables/ConnectableFlowable.java index 21636e67da..ef5b667bac 100644 --- a/src/main/java/io/reactivex/flowables/ConnectableFlowable.java +++ b/src/main/java/io/reactivex/flowables/ConnectableFlowable.java @@ -68,6 +68,24 @@ public final Disposable connect() { return cc.disposable; } + /** + * Apply a workaround for a race condition with the regular publish().refCount() + * so that racing subscribers and refCount won't hang. + * + * @return the ConnectableFlowable to work with + * @since 2.2.10 + */ + private ConnectableFlowable<T> onRefCount() { + if (this instanceof FlowablePublishClassic) { + @SuppressWarnings("unchecked") + FlowablePublishClassic<T> fp = (FlowablePublishClassic<T>) this; + return RxJavaPlugins.onAssembly( + new FlowablePublishAlt<T>(fp.publishSource(), fp.publishBufferSize()) + ); + } + return this; + } + /** * Returns a {@code Flowable} that stays connected to this {@code ConnectableFlowable} as long as there * is at least one subscription to this {@code ConnectableFlowable}. @@ -89,7 +107,7 @@ public final Disposable connect() { @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.PASS_THROUGH) public Flowable<T> refCount() { - return RxJavaPlugins.onAssembly(new FlowableRefCount<T>(this)); + return RxJavaPlugins.onAssembly(new FlowableRefCount<T>(onRefCount())); } /** @@ -216,7 +234,7 @@ public final Flowable<T> refCount(int subscriberCount, long timeout, TimeUnit un ObjectHelper.verifyPositive(subscriberCount, "subscriberCount"); ObjectHelper.requireNonNull(unit, "unit is null"); ObjectHelper.requireNonNull(scheduler, "scheduler is null"); - return RxJavaPlugins.onAssembly(new FlowableRefCount<T>(this, subscriberCount, timeout, unit, scheduler)); + return RxJavaPlugins.onAssembly(new FlowableRefCount<T>(onRefCount(), subscriberCount, timeout, unit, scheduler)); } /** diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java index 7ab84a568b..e573f3daf3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java @@ -33,7 +33,8 @@ * manner. * @param <T> the value type */ -public final class FlowablePublish<T> extends ConnectableFlowable<T> implements HasUpstreamPublisher<T> { +public final class FlowablePublish<T> extends ConnectableFlowable<T> +implements HasUpstreamPublisher<T>, FlowablePublishClassic<T> { /** * Indicates this child has been cancelled: the state is swapped in atomically and * will prevent the dispatch() to emit (too many) values to a terminated child subscriber. @@ -77,6 +78,19 @@ public Publisher<T> source() { return source; } + /** + * @return The internal buffer size of this FloawblePublish operator. + */ + @Override + public int publishBufferSize() { + return bufferSize; + } + + @Override + public Publisher<T> publishSource() { + return source; + } + @Override protected void subscribeActual(Subscriber<? super T> s) { onSubscribe.subscribe(s); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishAlt.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishAlt.java new file mode 100644 index 0000000000..d58ba84503 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishAlt.java @@ -0,0 +1,483 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import java.util.concurrent.atomic.*; + +import org.reactivestreams.*; + +import io.reactivex.FlowableSubscriber; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.*; +import io.reactivex.flowables.ConnectableFlowable; +import io.reactivex.functions.Consumer; +import io.reactivex.internal.disposables.ResettableConnectable; +import io.reactivex.internal.fuseable.*; +import io.reactivex.internal.queue.SpscArrayQueue; +import io.reactivex.internal.subscriptions.SubscriptionHelper; +import io.reactivex.internal.util.*; +import io.reactivex.plugins.RxJavaPlugins; + +/** + * Shares a single underlying connection to the upstream Publisher + * and multicasts events to all subscribed subscribers until the upstream + * completes or the connection is disposed. + * <p> + * The difference to FlowablePublish is that when the upstream terminates, + * late subscriberss will receive that terminal event until the connection is + * disposed and the ConnectableFlowable is reset to its fresh state. + * + * @param <T> the element type + * @since 2.2.10 + */ +public final class FlowablePublishAlt<T> extends ConnectableFlowable<T> +implements HasUpstreamPublisher<T>, ResettableConnectable { + + final Publisher<T> source; + + final int bufferSize; + + final AtomicReference<PublishConnection<T>> current; + + public FlowablePublishAlt(Publisher<T> source, int bufferSize) { + this.source = source; + this.bufferSize = bufferSize; + this.current = new AtomicReference<PublishConnection<T>>(); + } + + @Override + public Publisher<T> source() { + return source; + } + + /** + * @return The internal buffer size of this FloawblePublishAlt operator. + */ + public int publishBufferSize() { + return bufferSize; + } + + @Override + public void connect(Consumer<? super Disposable> connection) { + PublishConnection<T> conn; + boolean doConnect = false; + + for (;;) { + conn = current.get(); + + if (conn == null || conn.isDisposed()) { + PublishConnection<T> fresh = new PublishConnection<T>(current, bufferSize); + if (!current.compareAndSet(conn, fresh)) { + continue; + } + conn = fresh; + } + + doConnect = !conn.connect.get() && conn.connect.compareAndSet(false, true); + break; + } + + try { + connection.accept(conn); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + throw ExceptionHelper.wrapOrThrow(ex); + } + + if (doConnect) { + source.subscribe(conn); + } + } + + @Override + protected void subscribeActual(Subscriber<? super T> s) { + PublishConnection<T> conn; + + for (;;) { + conn = current.get(); + + // don't create a fresh connection if the current is disposed + if (conn == null) { + PublishConnection<T> fresh = new PublishConnection<T>(current, bufferSize); + if (!current.compareAndSet(conn, fresh)) { + continue; + } + conn = fresh; + } + + break; + } + + InnerSubscription<T> inner = new InnerSubscription<T>(s, conn); + s.onSubscribe(inner); + + if (conn.add(inner)) { + if (inner.isCancelled()) { + conn.remove(inner); + } else { + conn.drain(); + } + return; + } + + Throwable ex = conn.error; + if (ex != null) { + s.onError(ex); + } else { + s.onComplete(); + } + } + + @SuppressWarnings("unchecked") + @Override + public void resetIf(Disposable connection) { + current.compareAndSet((PublishConnection<T>)connection, null); + } + + static final class PublishConnection<T> + extends AtomicInteger + implements FlowableSubscriber<T>, Disposable { + + private static final long serialVersionUID = -1672047311619175801L; + + final AtomicReference<PublishConnection<T>> current; + + final AtomicReference<Subscription> upstream; + + final AtomicBoolean connect; + + final AtomicReference<InnerSubscription<T>[]> subscribers; + + final int bufferSize; + + volatile SimpleQueue<T> queue; + + int sourceMode; + + volatile boolean done; + Throwable error; + + int consumed; + + @SuppressWarnings("rawtypes") + static final InnerSubscription[] EMPTY = new InnerSubscription[0]; + @SuppressWarnings("rawtypes") + static final InnerSubscription[] TERMINATED = new InnerSubscription[0]; + + @SuppressWarnings("unchecked") + PublishConnection(AtomicReference<PublishConnection<T>> current, int bufferSize) { + this.current = current; + this.upstream = new AtomicReference<Subscription>(); + this.connect = new AtomicBoolean(); + this.bufferSize = bufferSize; + this.subscribers = new AtomicReference<InnerSubscription<T>[]>(EMPTY); + } + + @SuppressWarnings("unchecked") + @Override + public void dispose() { + subscribers.getAndSet(TERMINATED); + current.compareAndSet(this, null); + SubscriptionHelper.cancel(upstream); + } + + @Override + public boolean isDisposed() { + return subscribers.get() == TERMINATED; + } + + @Override + public void onSubscribe(Subscription s) { + if (SubscriptionHelper.setOnce(this.upstream, s)) { + if (s instanceof QueueSubscription) { + @SuppressWarnings("unchecked") + QueueSubscription<T> qs = (QueueSubscription<T>) s; + + int m = qs.requestFusion(QueueSubscription.ANY | QueueSubscription.BOUNDARY); + if (m == QueueSubscription.SYNC) { + sourceMode = m; + queue = qs; + done = true; + drain(); + return; + } + if (m == QueueSubscription.ASYNC) { + sourceMode = m; + queue = qs; + s.request(bufferSize); + return; + } + } + + queue = new SpscArrayQueue<T>(bufferSize); + + s.request(bufferSize); + } + } + + @Override + public void onNext(T t) { + // we expect upstream to honor backpressure requests + if (sourceMode == QueueSubscription.NONE && !queue.offer(t)) { + onError(new MissingBackpressureException("Prefetch queue is full?!")); + return; + } + // since many things can happen concurrently, we have a common dispatch + // loop to act on the current state serially + drain(); + } + + @Override + public void onError(Throwable t) { + if (done) { + RxJavaPlugins.onError(t); + } else { + error = t; + done = true; + drain(); + } + } + + @Override + public void onComplete() { + done = true; + drain(); + } + + void drain() { + if (getAndIncrement() != 0) { + return; + } + + int missed = 1; + SimpleQueue<T> queue = this.queue; + int consumed = this.consumed; + int limit = this.bufferSize - (this.bufferSize >> 2); + boolean async = this.sourceMode != QueueSubscription.SYNC; + + outer: + for (;;) { + if (queue != null) { + long minDemand = Long.MAX_VALUE; + boolean hasDemand = false; + + InnerSubscription<T>[] innerSubscriptions = subscribers.get(); + + for (InnerSubscription<T> inner : innerSubscriptions) { + long request = inner.get(); + if (request != Long.MIN_VALUE) { + hasDemand = true; + minDemand = Math.min(request - inner.emitted, minDemand); + } + } + + if (!hasDemand) { + minDemand = 0L; + } + + while (minDemand != 0L) { + boolean d = done; + T v; + + try { + v = queue.poll(); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + upstream.get().cancel(); + queue.clear(); + done = true; + signalError(ex); + return; + } + + boolean empty = v == null; + + if (checkTerminated(d, empty)) { + return; + } + + if (empty) { + break; + } + + for (InnerSubscription<T> inner : innerSubscriptions) { + if (!inner.isCancelled()) { + inner.downstream.onNext(v); + inner.emitted++; + } + } + + if (async && ++consumed == limit) { + consumed = 0; + upstream.get().request(limit); + } + minDemand--; + + if (innerSubscriptions != subscribers.get()) { + continue outer; + } + } + + if (checkTerminated(done, queue.isEmpty())) { + return; + } + } + + this.consumed = consumed; + missed = addAndGet(-missed); + if (missed == 0) { + break; + } + if (queue == null) { + queue = this.queue; + } + } + } + + @SuppressWarnings("unchecked") + boolean checkTerminated(boolean isDone, boolean isEmpty) { + if (isDone && isEmpty) { + Throwable ex = error; + + if (ex != null) { + signalError(ex); + } else { + for (InnerSubscription<T> inner : subscribers.getAndSet(TERMINATED)) { + if (!inner.isCancelled()) { + inner.downstream.onComplete(); + } + } + } + return true; + } + return false; + } + + @SuppressWarnings("unchecked") + void signalError(Throwable ex) { + for (InnerSubscription<T> inner : subscribers.getAndSet(TERMINATED)) { + if (!inner.isCancelled()) { + inner.downstream.onError(ex); + } + } + } + + boolean add(InnerSubscription<T> inner) { + // the state can change so we do a CAS loop to achieve atomicity + for (;;) { + // get the current producer array + InnerSubscription<T>[] c = subscribers.get(); + // if this subscriber-to-source reached a terminal state by receiving + // an onError or onComplete, just refuse to add the new producer + if (c == TERMINATED) { + return false; + } + // we perform a copy-on-write logic + int len = c.length; + @SuppressWarnings("unchecked") + InnerSubscription<T>[] u = new InnerSubscription[len + 1]; + System.arraycopy(c, 0, u, 0, len); + u[len] = inner; + // try setting the subscribers array + if (subscribers.compareAndSet(c, u)) { + return true; + } + // if failed, some other operation succeeded (another add, remove or termination) + // so retry + } + } + + @SuppressWarnings("unchecked") + void remove(InnerSubscription<T> inner) { + // the state can change so we do a CAS loop to achieve atomicity + for (;;) { + // let's read the current subscribers array + InnerSubscription<T>[] c = subscribers.get(); + int len = c.length; + // if it is either empty or terminated, there is nothing to remove so we quit + if (len == 0) { + break; + } + // let's find the supplied producer in the array + // although this is O(n), we don't expect too many child subscribers in general + int j = -1; + for (int i = 0; i < len; i++) { + if (c[i] == inner) { + j = i; + break; + } + } + // we didn't find it so just quit + if (j < 0) { + return; + } + // we do copy-on-write logic here + InnerSubscription<T>[] u; + // we don't create a new empty array if producer was the single inhabitant + // but rather reuse an empty array + if (len == 1) { + u = EMPTY; + } else { + // otherwise, create a new array one less in size + u = new InnerSubscription[len - 1]; + // copy elements being before the given producer + System.arraycopy(c, 0, u, 0, j); + // copy elements being after the given producer + System.arraycopy(c, j + 1, u, j, len - j - 1); + } + // try setting this new array as + if (subscribers.compareAndSet(c, u)) { + break; + } + // if we failed, it means something else happened + // (a concurrent add/remove or termination), we need to retry + } + } + } + + static final class InnerSubscription<T> extends AtomicLong + implements Subscription { + + private static final long serialVersionUID = 2845000326761540265L; + + final Subscriber<? super T> downstream; + + final PublishConnection<T> parent; + + long emitted; + + InnerSubscription(Subscriber<? super T> downstream, PublishConnection<T> parent) { + this.downstream = downstream; + this.parent = parent; + } + + @Override + public void request(long n) { + BackpressureHelper.addCancel(this, n); + parent.drain(); + } + + @Override + public void cancel() { + if (getAndSet(Long.MIN_VALUE) != Long.MIN_VALUE) { + parent.remove(this); + parent.drain(); + } + } + + public boolean isCancelled() { + return get() == Long.MIN_VALUE; + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishClassic.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishClassic.java new file mode 100644 index 0000000000..0cbf70efad --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishClassic.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import org.reactivestreams.Publisher; + +/** + * Interface to mark classic publish() operators to + * indicate refCount() should replace them with the Alt + * implementation. + * <p> + * Without this, hooking the connectables with an intercept + * implementation would result in the unintended lack + * or presense of the replacement by refCount(). + * + * @param <T> the element type of the sequence + * @since 2.2.10 + */ +public interface FlowablePublishClassic<T> { + + /** + * @return the upstream source of this publish operator + */ + Publisher<T> publishSource(); + + /** + * @return the internal buffer size of this publish operator + */ + int publishBufferSize(); +} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java index debc37875b..04b90506c3 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java @@ -30,7 +30,8 @@ * manner. * @param <T> the value type */ -public final class ObservablePublish<T> extends ConnectableObservable<T> implements HasUpstreamObservableSource<T> { +public final class ObservablePublish<T> extends ConnectableObservable<T> +implements HasUpstreamObservableSource<T>, ObservablePublishClassic<T> { /** The source observable. */ final ObservableSource<T> source; /** Holds the current subscriber that is, will be or just was subscribed to the source observable. */ @@ -63,6 +64,11 @@ public ObservableSource<T> source() { return source; } + @Override + public ObservableSource<T> publishSource() { + return source; + } + @Override protected void subscribeActual(Observer<? super T> observer) { onSubscribe.subscribe(observer); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishAlt.java b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishAlt.java new file mode 100644 index 0000000000..771e58dda8 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishAlt.java @@ -0,0 +1,282 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import java.util.concurrent.atomic.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.Exceptions; +import io.reactivex.functions.Consumer; +import io.reactivex.internal.disposables.*; +import io.reactivex.internal.fuseable.HasUpstreamObservableSource; +import io.reactivex.internal.util.ExceptionHelper; +import io.reactivex.observables.ConnectableObservable; + +/** + * Shares a single underlying connection to the upstream ObservableSource + * and multicasts events to all subscribed observers until the upstream + * completes or the connection is disposed. + * <p> + * The difference to ObservablePublish is that when the upstream terminates, + * late observers will receive that terminal event until the connection is + * disposed and the ConnectableObservable is reset to its fresh state. + * + * @param <T> the element type + * @since 2.2.10 + */ +public final class ObservablePublishAlt<T> extends ConnectableObservable<T> +implements HasUpstreamObservableSource<T>, ResettableConnectable { + + final ObservableSource<T> source; + + final AtomicReference<PublishConnection<T>> current; + + public ObservablePublishAlt(ObservableSource<T> source) { + this.source = source; + this.current = new AtomicReference<PublishConnection<T>>(); + } + + @Override + public void connect(Consumer<? super Disposable> connection) { + boolean doConnect = false; + PublishConnection<T> conn; + + for (;;) { + conn = current.get(); + + if (conn == null || conn.isDisposed()) { + PublishConnection<T> fresh = new PublishConnection<T>(current); + if (!current.compareAndSet(conn, fresh)) { + continue; + } + conn = fresh; + } + + doConnect = !conn.connect.get() && conn.connect.compareAndSet(false, true); + break; + } + + try { + connection.accept(conn); + } catch (Throwable ex) { + Exceptions.throwIfFatal(ex); + throw ExceptionHelper.wrapOrThrow(ex); + } + + if (doConnect) { + source.subscribe(conn); + } + } + + @Override + protected void subscribeActual(Observer<? super T> observer) { + PublishConnection<T> conn; + + for (;;) { + conn = current.get(); + // we don't create a fresh connection if the current is terminated + if (conn == null) { + PublishConnection<T> fresh = new PublishConnection<T>(current); + if (!current.compareAndSet(conn, fresh)) { + continue; + } + conn = fresh; + } + break; + } + + InnerDisposable<T> inner = new InnerDisposable<T>(observer, conn); + observer.onSubscribe(inner); + if (conn.add(inner)) { + if (inner.isDisposed()) { + conn.remove(inner); + } + return; + } + // Late observers will be simply terminated + Throwable error = conn.error; + if (error != null) { + observer.onError(error); + } else { + observer.onComplete(); + } + } + + @Override + @SuppressWarnings("unchecked") + public void resetIf(Disposable connection) { + current.compareAndSet((PublishConnection<T>)connection, null); + } + + @Override + public ObservableSource<T> source() { + return source; + } + + static final class PublishConnection<T> + extends AtomicReference<InnerDisposable<T>[]> + implements Observer<T>, Disposable { + + private static final long serialVersionUID = -3251430252873581268L; + + final AtomicBoolean connect; + + final AtomicReference<PublishConnection<T>> current; + + final AtomicReference<Disposable> upstream; + + @SuppressWarnings("rawtypes") + static final InnerDisposable[] EMPTY = new InnerDisposable[0]; + + @SuppressWarnings("rawtypes") + static final InnerDisposable[] TERMINATED = new InnerDisposable[0]; + + Throwable error; + + @SuppressWarnings("unchecked") + public PublishConnection(AtomicReference<PublishConnection<T>> current) { + this.connect = new AtomicBoolean(); + this.current = current; + this.upstream = new AtomicReference<Disposable>(); + lazySet(EMPTY); + } + + @SuppressWarnings("unchecked") + @Override + public void dispose() { + getAndSet(TERMINATED); + current.compareAndSet(this, null); + DisposableHelper.dispose(upstream); + } + + @Override + public boolean isDisposed() { + return get() == TERMINATED; + } + + @Override + public void onSubscribe(Disposable d) { + DisposableHelper.setOnce(upstream, d); + } + + @Override + public void onNext(T t) { + for (InnerDisposable<T> inner : get()) { + inner.downstream.onNext(t); + } + } + + @Override + @SuppressWarnings("unchecked") + public void onError(Throwable e) { + error = e; + upstream.lazySet(DisposableHelper.DISPOSED); + for (InnerDisposable<T> inner : getAndSet(TERMINATED)) { + inner.downstream.onError(e); + } + } + + @Override + @SuppressWarnings("unchecked") + public void onComplete() { + upstream.lazySet(DisposableHelper.DISPOSED); + for (InnerDisposable<T> inner : getAndSet(TERMINATED)) { + inner.downstream.onComplete(); + } + } + + public boolean add(InnerDisposable<T> inner) { + for (;;) { + InnerDisposable<T>[] a = get(); + if (a == TERMINATED) { + return false; + } + int n = a.length; + @SuppressWarnings("unchecked") + InnerDisposable<T>[] b = new InnerDisposable[n + 1]; + System.arraycopy(a, 0, b, 0, n); + b[n] = inner; + if (compareAndSet(a, b)) { + return true; + } + } + } + + @SuppressWarnings("unchecked") + public void remove(InnerDisposable<T> inner) { + for (;;) { + InnerDisposable<T>[] a = get(); + int n = a.length; + if (n == 0) { + return; + } + + int j = -1; + for (int i = 0; i < n; i++) { + if (a[i] == inner) { + j = i; + break; + } + } + + if (j < 0) { + return; + } + InnerDisposable<T>[] b = EMPTY; + if (n != 1) { + b = new InnerDisposable[n - 1]; + System.arraycopy(a, 0, b, 0, j); + System.arraycopy(a, j + 1, b, j, n - j - 1); + } + if (compareAndSet(a, b)) { + return; + } + } + } + } + + /** + * Intercepts the dispose signal from the downstream and + * removes itself from the connection's observers array + * at most once. + * @param <T> the element type + */ + static final class InnerDisposable<T> + extends AtomicReference<PublishConnection<T>> + implements Disposable { + + private static final long serialVersionUID = 7463222674719692880L; + + final Observer<? super T> downstream; + + public InnerDisposable(Observer<? super T> downstream, PublishConnection<T> parent) { + this.downstream = downstream; + lazySet(parent); + } + + @Override + public void dispose() { + PublishConnection<T> p = getAndSet(null); + if (p != null) { + p.remove(this); + } + } + + @Override + public boolean isDisposed() { + return get() == null; + } + } +} diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishClassic.java b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishClassic.java new file mode 100644 index 0000000000..f072779930 --- /dev/null +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishClassic.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import io.reactivex.ObservableSource; + +/** + * Interface to mark classic publish() operators to + * indicate refCount() should replace them with the Alt + * implementation. + * <p> + * Without this, hooking the connectables with an intercept + * implementation would result in the unintended lack + * or presense of the replacement by refCount(). + * + * @param <T> the element type of the sequence + * @since 2.2.10 + */ +public interface ObservablePublishClassic<T> { + + /** + * @return the upstream source of this publish operator + */ + ObservableSource<T> publishSource(); +} diff --git a/src/main/java/io/reactivex/observables/ConnectableObservable.java b/src/main/java/io/reactivex/observables/ConnectableObservable.java index b5e54054b1..09fa70899e 100644 --- a/src/main/java/io/reactivex/observables/ConnectableObservable.java +++ b/src/main/java/io/reactivex/observables/ConnectableObservable.java @@ -66,6 +66,23 @@ public final Disposable connect() { return cc.disposable; } + /** + * Apply a workaround for a race condition with the regular publish().refCount() + * so that racing observers and refCount won't hang. + * + * @return the ConnectableObservable to work with + * @since 2.2.10 + */ + @SuppressWarnings("unchecked") + private ConnectableObservable<T> onRefCount() { + if (this instanceof ObservablePublishClassic) { + return RxJavaPlugins.onAssembly( + new ObservablePublishAlt<T>(((ObservablePublishClassic<T>)this).publishSource()) + ); + } + return this; + } + /** * Returns an {@code Observable} that stays connected to this {@code ConnectableObservable} as long as there * is at least one subscription to this {@code ConnectableObservable}. @@ -83,7 +100,7 @@ public final Disposable connect() { @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public Observable<T> refCount() { - return RxJavaPlugins.onAssembly(new ObservableRefCount<T>(this)); + return RxJavaPlugins.onAssembly(new ObservableRefCount<T>(onRefCount())); } /** @@ -190,7 +207,7 @@ public final Observable<T> refCount(int subscriberCount, long timeout, TimeUnit ObjectHelper.verifyPositive(subscriberCount, "subscriberCount"); ObjectHelper.requireNonNull(unit, "unit is null"); ObjectHelper.requireNonNull(scheduler, "scheduler is null"); - return RxJavaPlugins.onAssembly(new ObservableRefCount<T>(this, subscriberCount, timeout, unit, scheduler)); + return RxJavaPlugins.onAssembly(new ObservableRefCount<T>(onRefCount(), subscriberCount, timeout, unit, scheduler)); } /** diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishAltTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishAltTest.java new file mode 100644 index 0000000000..414aa79c07 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishAltTest.java @@ -0,0 +1,1629 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import static org.junit.Assert.*; + +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; + +import org.junit.*; +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.Disposable; +import io.reactivex.exceptions.*; +import io.reactivex.flowables.ConnectableFlowable; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.fuseable.HasUpstreamPublisher; +import io.reactivex.internal.operators.flowable.FlowablePublish.*; +import io.reactivex.internal.schedulers.ImmediateThinScheduler; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.schedulers.*; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowablePublishAltTest { + + @Test + public void testPublish() throws InterruptedException { + final AtomicInteger counter = new AtomicInteger(); + ConnectableFlowable<String> f = Flowable.unsafeCreate(new Publisher<String>() { + + @Override + public void subscribe(final Subscriber<? super String> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + new Thread(new Runnable() { + + @Override + public void run() { + counter.incrementAndGet(); + subscriber.onNext("one"); + subscriber.onComplete(); + } + }).start(); + } + }).publish(); + + final CountDownLatch latch = new CountDownLatch(2); + + // subscribe once + f.subscribe(new Consumer<String>() { + + @Override + public void accept(String v) { + assertEquals("one", v); + latch.countDown(); + } + }); + + // subscribe again + f.subscribe(new Consumer<String>() { + + @Override + public void accept(String v) { + assertEquals("one", v); + latch.countDown(); + } + }); + + Disposable connection = f.connect(); + try { + if (!latch.await(1000, TimeUnit.MILLISECONDS)) { + fail("subscriptions did not receive values"); + } + assertEquals(1, counter.get()); + } finally { + connection.dispose(); + } + } + + @Test + public void testBackpressureFastSlow() { + ConnectableFlowable<Integer> is = Flowable.range(1, Flowable.bufferSize() * 2).publish(); + Flowable<Integer> fast = is.observeOn(Schedulers.computation()) + .doOnComplete(new Action() { + @Override + public void run() { + System.out.println("^^^^^^^^^^^^^ completed FAST"); + } + }); + + Flowable<Integer> slow = is.observeOn(Schedulers.computation()).map(new Function<Integer, Integer>() { + int c; + + @Override + public Integer apply(Integer i) { + if (c == 0) { + try { + Thread.sleep(500); + } catch (InterruptedException e) { + } + } + c++; + return i; + } + + }).doOnComplete(new Action() { + + @Override + public void run() { + System.out.println("^^^^^^^^^^^^^ completed SLOW"); + } + + }); + + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + Flowable.merge(fast, slow).subscribe(ts); + is.connect(); + ts.awaitTerminalEvent(); + ts.assertNoErrors(); + assertEquals(Flowable.bufferSize() * 4, ts.valueCount()); + } + + // use case from https://github.com/ReactiveX/RxJava/issues/1732 + @Test + public void testTakeUntilWithPublishedStreamUsingSelector() { + final AtomicInteger emitted = new AtomicInteger(); + Flowable<Integer> xs = Flowable.range(0, Flowable.bufferSize() * 2).doOnNext(new Consumer<Integer>() { + + @Override + public void accept(Integer t1) { + emitted.incrementAndGet(); + } + + }); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + xs.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { + + @Override + public Flowable<Integer> apply(Flowable<Integer> xs) { + return xs.takeUntil(xs.skipWhile(new Predicate<Integer>() { + + @Override + public boolean test(Integer i) { + return i <= 3; + } + + })); + } + + }).subscribe(ts); + ts.awaitTerminalEvent(); + ts.assertNoErrors(); + ts.assertValues(0, 1, 2, 3); + assertEquals(5, emitted.get()); + System.out.println(ts.values()); + } + + // use case from https://github.com/ReactiveX/RxJava/issues/1732 + @Test + public void testTakeUntilWithPublishedStream() { + Flowable<Integer> xs = Flowable.range(0, Flowable.bufferSize() * 2); + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + ConnectableFlowable<Integer> xsp = xs.publish(); + xsp.takeUntil(xsp.skipWhile(new Predicate<Integer>() { + + @Override + public boolean test(Integer i) { + return i <= 3; + } + + })).subscribe(ts); + xsp.connect(); + System.out.println(ts.values()); + } + + @Test(timeout = 10000) + public void testBackpressureTwoConsumers() { + final AtomicInteger sourceEmission = new AtomicInteger(); + final AtomicBoolean sourceUnsubscribed = new AtomicBoolean(); + final Flowable<Integer> source = Flowable.range(1, 100) + .doOnNext(new Consumer<Integer>() { + @Override + public void accept(Integer t1) { + sourceEmission.incrementAndGet(); + } + }) + .doOnCancel(new Action() { + @Override + public void run() { + sourceUnsubscribed.set(true); + } + }).share(); + ; + + final AtomicBoolean child1Unsubscribed = new AtomicBoolean(); + final AtomicBoolean child2Unsubscribed = new AtomicBoolean(); + + final TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(); + + final TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>() { + @Override + public void onNext(Integer t) { + if (valueCount() == 2) { + source.doOnCancel(new Action() { + @Override + public void run() { + child2Unsubscribed.set(true); + } + }).take(5).subscribe(ts2); + } + super.onNext(t); + } + }; + + source.doOnCancel(new Action() { + @Override + public void run() { + child1Unsubscribed.set(true); + } + }).take(5) + .subscribe(ts1); + + ts1.awaitTerminalEvent(); + ts2.awaitTerminalEvent(); + + ts1.assertNoErrors(); + ts2.assertNoErrors(); + + assertTrue(sourceUnsubscribed.get()); + assertTrue(child1Unsubscribed.get()); + assertTrue(child2Unsubscribed.get()); + + ts1.assertValues(1, 2, 3, 4, 5); + ts2.assertValues(4, 5, 6, 7, 8); + + assertEquals(8, sourceEmission.get()); + } + + @Test + public void testConnectWithNoSubscriber() { + TestScheduler scheduler = new TestScheduler(); + ConnectableFlowable<Long> cf = Flowable.interval(10, 10, TimeUnit.MILLISECONDS, scheduler).take(3).publish(); + cf.connect(); + // Emit 0 + scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); + TestSubscriber<Long> subscriber = new TestSubscriber<Long>(); + cf.subscribe(subscriber); + // Emit 1 and 2 + scheduler.advanceTimeBy(50, TimeUnit.MILLISECONDS); + subscriber.assertValues(1L, 2L); + subscriber.assertNoErrors(); + subscriber.assertTerminated(); + } + + @Test + public void testSubscribeAfterDisconnectThenConnect() { + ConnectableFlowable<Integer> source = Flowable.just(1).publish(); + + TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>(); + + source.subscribe(ts1); + + Disposable connection = source.connect(); + + ts1.assertValue(1); + ts1.assertNoErrors(); + ts1.assertTerminated(); + + TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(); + + source.subscribe(ts2); + + Disposable connection2 = source.connect(); + + ts2.assertValue(1); + ts2.assertNoErrors(); + ts2.assertTerminated(); + + System.out.println(connection); + System.out.println(connection2); + } + + @Test + public void testNoSubscriberRetentionOnCompleted() { + FlowablePublish<Integer> source = (FlowablePublish<Integer>)Flowable.just(1).publish(); + + TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>(); + + source.subscribe(ts1); + + ts1.assertNoValues(); + ts1.assertNoErrors(); + ts1.assertNotComplete(); + + source.connect(); + + ts1.assertValue(1); + ts1.assertNoErrors(); + ts1.assertTerminated(); + + assertNull(source.current.get()); + } + + @Test + public void testNonNullConnection() { + ConnectableFlowable<Object> source = Flowable.never().publish(); + + assertNotNull(source.connect()); + assertNotNull(source.connect()); + } + + @Test + public void testNoDisconnectSomeoneElse() { + ConnectableFlowable<Object> source = Flowable.never().publish(); + + Disposable connection1 = source.connect(); + Disposable connection2 = source.connect(); + + connection1.dispose(); + + Disposable connection3 = source.connect(); + + connection2.dispose(); + + assertTrue(checkPublishDisposed(connection1)); + assertTrue(checkPublishDisposed(connection2)); + assertFalse(checkPublishDisposed(connection3)); + } + + @SuppressWarnings("unchecked") + static boolean checkPublishDisposed(Disposable d) { + return ((FlowablePublish.PublishSubscriber<Object>)d).isDisposed(); + } + + @Test + public void testZeroRequested() { + ConnectableFlowable<Integer> source = Flowable.just(1).publish(); + + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L); + + source.subscribe(ts); + + ts.assertNoValues(); + ts.assertNoErrors(); + ts.assertNotComplete(); + + source.connect(); + + ts.assertNoValues(); + ts.assertNoErrors(); + ts.assertNotComplete(); + + ts.request(5); + + ts.assertValue(1); + ts.assertNoErrors(); + ts.assertTerminated(); + } + + @Test + public void testConnectIsIdempotent() { + final AtomicInteger calls = new AtomicInteger(); + Flowable<Integer> source = Flowable.unsafeCreate(new Publisher<Integer>() { + @Override + public void subscribe(Subscriber<? super Integer> t) { + t.onSubscribe(new BooleanSubscription()); + calls.getAndIncrement(); + } + }); + + ConnectableFlowable<Integer> conn = source.publish(); + + assertEquals(0, calls.get()); + + conn.connect(); + conn.connect(); + + assertEquals(1, calls.get()); + + conn.connect().dispose(); + + conn.connect(); + conn.connect(); + + assertEquals(2, calls.get()); + } + + @Test + public void syncFusedObserveOn() { + ConnectableFlowable<Integer> cf = Flowable.range(0, 1000).publish(); + Flowable<Integer> obs = cf.observeOn(Schedulers.computation()); + for (int i = 0; i < 1000; i++) { + for (int j = 1; j < 6; j++) { + List<TestSubscriber<Integer>> tss = new ArrayList<TestSubscriber<Integer>>(); + for (int k = 1; k < j; k++) { + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + tss.add(ts); + obs.subscribe(ts); + } + + Disposable connection = cf.connect(); + + for (TestSubscriber<Integer> ts : tss) { + ts.awaitDone(5, TimeUnit.SECONDS) + .assertSubscribed() + .assertValueCount(1000) + .assertNoErrors() + .assertComplete(); + } + connection.dispose(); + } + } + } + + @Test + public void syncFusedObserveOn2() { + ConnectableFlowable<Integer> cf = Flowable.range(0, 1000).publish(); + Flowable<Integer> obs = cf.observeOn(ImmediateThinScheduler.INSTANCE); + for (int i = 0; i < 1000; i++) { + for (int j = 1; j < 6; j++) { + List<TestSubscriber<Integer>> tss = new ArrayList<TestSubscriber<Integer>>(); + for (int k = 1; k < j; k++) { + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + tss.add(ts); + obs.subscribe(ts); + } + + Disposable connection = cf.connect(); + + for (TestSubscriber<Integer> ts : tss) { + ts.awaitDone(5, TimeUnit.SECONDS) + .assertSubscribed() + .assertValueCount(1000) + .assertNoErrors() + .assertComplete(); + } + connection.dispose(); + } + } + } + + @Test + public void asyncFusedObserveOn() { + ConnectableFlowable<Integer> cf = Flowable.range(0, 1000).observeOn(ImmediateThinScheduler.INSTANCE).publish(); + for (int i = 0; i < 1000; i++) { + for (int j = 1; j < 6; j++) { + List<TestSubscriber<Integer>> tss = new ArrayList<TestSubscriber<Integer>>(); + for (int k = 1; k < j; k++) { + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + tss.add(ts); + cf.subscribe(ts); + } + + Disposable connection = cf.connect(); + + for (TestSubscriber<Integer> ts : tss) { + ts.awaitDone(5, TimeUnit.SECONDS) + .assertSubscribed() + .assertValueCount(1000) + .assertNoErrors() + .assertComplete(); + } + connection.dispose(); + } + } + } + + @Test + public void testObserveOn() { + ConnectableFlowable<Integer> cf = Flowable.range(0, 1000).hide().publish(); + Flowable<Integer> obs = cf.observeOn(Schedulers.computation()); + for (int i = 0; i < 1000; i++) { + for (int j = 1; j < 6; j++) { + List<TestSubscriber<Integer>> tss = new ArrayList<TestSubscriber<Integer>>(); + for (int k = 1; k < j; k++) { + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + tss.add(ts); + obs.subscribe(ts); + } + + Disposable connection = cf.connect(); + + for (TestSubscriber<Integer> ts : tss) { + ts.awaitDone(5, TimeUnit.SECONDS) + .assertSubscribed() + .assertValueCount(1000) + .assertNoErrors() + .assertComplete(); + } + connection.dispose(); + } + } + } + + @Test + public void source() { + Flowable<Integer> f = Flowable.never(); + + assertSame(f, (((HasUpstreamPublisher<?>)f.publish()).source())); + } + + @Test + public void connectThrows() { + ConnectableFlowable<Integer> cf = Flowable.<Integer>empty().publish(); + try { + cf.connect(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) throws Exception { + throw new TestException(); + } + }); + } catch (TestException ex) { + // expected + } + } + + @Test + public void addRemoveRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final ConnectableFlowable<Integer> cf = Flowable.<Integer>empty().publish(); + + final TestSubscriber<Integer> ts = cf.test(); + + final TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + cf.subscribe(ts2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void disposeOnArrival() { + ConnectableFlowable<Integer> cf = Flowable.<Integer>empty().publish(); + + cf.test(Long.MAX_VALUE, true).assertEmpty(); + } + + @Test + public void disposeOnArrival2() { + Flowable<Integer> co = Flowable.<Integer>never().publish().autoConnect(); + + co.test(Long.MAX_VALUE, true).assertEmpty(); + } + + @Test + public void dispose() { + TestHelper.checkDisposed(Flowable.never().publish()); + + TestHelper.checkDisposed(Flowable.never().publish(Functions.<Flowable<Object>>identity())); + } + + @Test + public void empty() { + ConnectableFlowable<Integer> cf = Flowable.<Integer>empty().publish(); + + cf.connect(); + } + + @Test + public void take() { + ConnectableFlowable<Integer> cf = Flowable.range(1, 2).publish(); + + TestSubscriber<Integer> ts = cf.take(1).test(); + + cf.connect(); + + ts.assertResult(1); + } + + @Test + public void just() { + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + ConnectableFlowable<Integer> cf = pp.publish(); + + TestSubscriber<Integer> ts = new TestSubscriber<Integer>() { + @Override + public void onNext(Integer t) { + super.onNext(t); + pp.onComplete(); + } + }; + + cf.subscribe(ts); + cf.connect(); + + pp.onNext(1); + + ts.assertResult(1); + } + + @Test + public void nextCancelRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + final ConnectableFlowable<Integer> cf = pp.publish(); + + final TestSubscriber<Integer> ts = cf.test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts.cancel(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void badSource() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new Flowable<Integer>() { + @Override + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onNext(1); + subscriber.onComplete(); + subscriber.onNext(2); + subscriber.onError(new TestException()); + subscriber.onComplete(); + } + } + .publish() + .autoConnect() + .test() + .assertResult(1); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void noErrorLoss() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + ConnectableFlowable<Object> cf = Flowable.error(new TestException()).publish(); + + cf.connect(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void subscribeDisconnectRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + final ConnectableFlowable<Integer> cf = pp.publish(); + + final Disposable d = cf.connect(); + final TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + d.dispose(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + cf.subscribe(ts); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void selectorDisconnectsIndependentSource() { + PublishProcessor<Integer> pp = PublishProcessor.create(); + + pp.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { + @Override + public Flowable<Integer> apply(Flowable<Integer> v) throws Exception { + return Flowable.range(1, 2); + } + }) + .test() + .assertResult(1, 2); + + assertFalse(pp.hasSubscribers()); + } + + @Test(timeout = 5000) + public void selectorLatecommer() { + Flowable.range(1, 5) + .publish(new Function<Flowable<Integer>, Flowable<Integer>>() { + @Override + public Flowable<Integer> apply(Flowable<Integer> v) throws Exception { + return v.concatWith(v); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void mainError() { + Flowable.error(new TestException()) + .publish(Functions.<Flowable<Object>>identity()) + .test() + .assertFailure(TestException.class); + } + + @Test + public void selectorInnerError() { + PublishProcessor<Integer> pp = PublishProcessor.create(); + + pp.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { + @Override + public Flowable<Integer> apply(Flowable<Integer> v) throws Exception { + return Flowable.error(new TestException()); + } + }) + .test() + .assertFailure(TestException.class); + + assertFalse(pp.hasSubscribers()); + } + + @Test + public void preNextConnect() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final ConnectableFlowable<Integer> cf = Flowable.<Integer>empty().publish(); + + cf.connect(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + cf.test(); + } + }; + + TestHelper.race(r1, r1); + } + } + + @Test + public void connectRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final ConnectableFlowable<Integer> cf = Flowable.<Integer>empty().publish(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + cf.connect(); + } + }; + + TestHelper.race(r1, r1); + } + } + + @Test + public void selectorCrash() { + Flowable.just(1).publish(new Function<Flowable<Integer>, Flowable<Object>>() { + @Override + public Flowable<Object> apply(Flowable<Integer> v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void pollThrows() { + Flowable.just(1) + .map(new Function<Integer, Object>() { + @Override + public Object apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .compose(TestHelper.flowableStripBoundary()) + .publish() + .autoConnect() + .test() + .assertFailure(TestException.class); + } + + @Test + public void pollThrowsNoSubscribers() { + ConnectableFlowable<Integer> cf = Flowable.just(1, 2) + .map(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer v) throws Exception { + if (v == 2) { + throw new TestException(); + } + return v; + } + }) + .compose(TestHelper.<Integer>flowableStripBoundary()) + .publish(); + + TestSubscriber<Integer> ts = cf.take(1) + .test(); + + cf.connect(); + + ts.assertResult(1); + } + + @Test + public void dryRunCrash() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final TestSubscriber<Object> ts = new TestSubscriber<Object>(1L) { + @Override + public void onNext(Object t) { + super.onNext(t); + onComplete(); + cancel(); + } + }; + + Flowable.range(1, 10) + .map(new Function<Integer, Object>() { + @Override + public Object apply(Integer v) throws Exception { + if (v == 2) { + throw new TestException(); + } + return v; + } + }) + .publish() + .autoConnect() + .subscribe(ts); + + ts + .assertResult(1); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void overflowQueue() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + Flowable.create(new FlowableOnSubscribe<Object>() { + @Override + public void subscribe(FlowableEmitter<Object> s) throws Exception { + for (int i = 0; i < 10; i++) { + s.onNext(i); + } + } + }, BackpressureStrategy.MISSING) + .publish(8) + .autoConnect() + .test(0L) + .assertFailure(MissingBackpressureException.class); + + TestHelper.assertError(errors, 0, MissingBackpressureException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void delayedUpstreamOnSubscribe() { + final Subscriber<?>[] sub = { null }; + + new Flowable<Integer>() { + @Override + protected void subscribeActual(Subscriber<? super Integer> s) { + sub[0] = s; + } + } + .publish() + .connect() + .dispose(); + + BooleanSubscription bs = new BooleanSubscription(); + + sub[0].onSubscribe(bs); + + assertTrue(bs.isCancelled()); + } + + @Test + public void disposeRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final AtomicReference<Disposable> ref = new AtomicReference<Disposable>(); + + final ConnectableFlowable<Integer> cf = new Flowable<Integer>() { + @Override + protected void subscribeActual(Subscriber<? super Integer> s) { + s.onSubscribe(new BooleanSubscription()); + ref.set((Disposable)s); + } + }.publish(); + + cf.connect(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ref.get().dispose(); + } + }; + + TestHelper.race(r1, r1); + } + } + + @Test + public void removeNotPresent() { + final AtomicReference<PublishSubscriber<Integer>> ref = new AtomicReference<PublishSubscriber<Integer>>(); + + final ConnectableFlowable<Integer> cf = new Flowable<Integer>() { + @Override + @SuppressWarnings("unchecked") + protected void subscribeActual(Subscriber<? super Integer> s) { + s.onSubscribe(new BooleanSubscription()); + ref.set((PublishSubscriber<Integer>)s); + } + }.publish(); + + cf.connect(); + + ref.get().add(new InnerSubscriber<Integer>(new TestSubscriber<Integer>())); + ref.get().remove(null); + } + + @Test + @Ignore("publish() keeps consuming the upstream if there are no subscribers, 3.x should change this") + public void subscriberSwap() { + final ConnectableFlowable<Integer> cf = Flowable.range(1, 5).publish(); + + cf.connect(); + + TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>() { + @Override + public void onNext(Integer t) { + super.onNext(t); + cancel(); + onComplete(); + } + }; + + cf.subscribe(ts1); + + ts1.assertResult(1); + + TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(0); + cf.subscribe(ts2); + + ts2 + .assertEmpty() + .requestMore(4) + .assertResult(2, 3, 4, 5); + } + + @Test + public void subscriberLiveSwap() { + final ConnectableFlowable<Integer> cf = new FlowablePublishAlt<Integer>(Flowable.range(1, 5), 128); + + final TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(0); + + TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>() { + @Override + public void onNext(Integer t) { + super.onNext(t); + cancel(); + onComplete(); + cf.subscribe(ts2); + } + }; + + cf.subscribe(ts1); + + cf.connect(); + + ts1.assertResult(1); + + ts2 + .assertEmpty() + .requestMore(4) + .assertResult(2, 3, 4, 5); + } + + @Test + public void selectorSubscriberSwap() { + final AtomicReference<Flowable<Integer>> ref = new AtomicReference<Flowable<Integer>>(); + + Flowable.range(1, 5).publish(new Function<Flowable<Integer>, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(Flowable<Integer> f) throws Exception { + ref.set(f); + return Flowable.never(); + } + }).test(); + + ref.get().take(2).test().assertResult(1, 2); + + ref.get() + .test(0) + .assertEmpty() + .requestMore(2) + .assertValuesOnly(3, 4) + .requestMore(1) + .assertResult(3, 4, 5); + } + + @Test + public void leavingSubscriberOverrequests() { + final AtomicReference<Flowable<Integer>> ref = new AtomicReference<Flowable<Integer>>(); + + PublishProcessor<Integer> pp = PublishProcessor.create(); + + pp.publish(new Function<Flowable<Integer>, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(Flowable<Integer> f) throws Exception { + ref.set(f); + return Flowable.never(); + } + }).test(); + + TestSubscriber<Integer> ts1 = ref.get().take(2).test(); + + pp.onNext(1); + pp.onNext(2); + + ts1.assertResult(1, 2); + + pp.onNext(3); + pp.onNext(4); + + TestSubscriber<Integer> ts2 = ref.get().test(0L); + + ts2.assertEmpty(); + + ts2.requestMore(2); + + ts2.assertValuesOnly(3, 4); + } + + // call a transformer only if the input is non-empty + @Test + public void composeIfNotEmpty() { + final FlowableTransformer<Integer, Integer> transformer = new FlowableTransformer<Integer, Integer>() { + @Override + public Publisher<Integer> apply(Flowable<Integer> g) { + return g.map(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer v) throws Exception { + return v + 1; + } + }); + } + }; + + final AtomicInteger calls = new AtomicInteger(); + Flowable.range(1, 5) + .publish(new Function<Flowable<Integer>, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(final Flowable<Integer> shared) + throws Exception { + return shared.take(1).concatMap(new Function<Integer, Publisher<? extends Integer>>() { + @Override + public Publisher<? extends Integer> apply(Integer first) + throws Exception { + calls.incrementAndGet(); + return transformer.apply(Flowable.just(first).concatWith(shared)); + } + }); + } + }) + .test() + .assertResult(2, 3, 4, 5, 6); + + assertEquals(1, calls.get()); + } + + // call a transformer only if the input is non-empty + @Test + public void composeIfNotEmptyNotFused() { + final FlowableTransformer<Integer, Integer> transformer = new FlowableTransformer<Integer, Integer>() { + @Override + public Publisher<Integer> apply(Flowable<Integer> g) { + return g.map(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer v) throws Exception { + return v + 1; + } + }); + } + }; + + final AtomicInteger calls = new AtomicInteger(); + Flowable.range(1, 5).hide() + .publish(new Function<Flowable<Integer>, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(final Flowable<Integer> shared) + throws Exception { + return shared.take(1).concatMap(new Function<Integer, Publisher<? extends Integer>>() { + @Override + public Publisher<? extends Integer> apply(Integer first) + throws Exception { + calls.incrementAndGet(); + return transformer.apply(Flowable.just(first).concatWith(shared)); + } + }); + } + }) + .test() + .assertResult(2, 3, 4, 5, 6); + + assertEquals(1, calls.get()); + } + + // call a transformer only if the input is non-empty + @Test + public void composeIfNotEmptyIsEmpty() { + final FlowableTransformer<Integer, Integer> transformer = new FlowableTransformer<Integer, Integer>() { + @Override + public Publisher<Integer> apply(Flowable<Integer> g) { + return g.map(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer v) throws Exception { + return v + 1; + } + }); + } + }; + + final AtomicInteger calls = new AtomicInteger(); + Flowable.<Integer>empty().hide() + .publish(new Function<Flowable<Integer>, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(final Flowable<Integer> shared) + throws Exception { + return shared.take(1).concatMap(new Function<Integer, Publisher<? extends Integer>>() { + @Override + public Publisher<? extends Integer> apply(Integer first) + throws Exception { + calls.incrementAndGet(); + return transformer.apply(Flowable.just(first).concatWith(shared)); + } + }); + } + }) + .test() + .assertResult(); + + assertEquals(0, calls.get()); + } + + @Test + public void publishFunctionCancelOuterAfterOneInner() { + final AtomicReference<Flowable<Integer>> ref = new AtomicReference<Flowable<Integer>>(); + + PublishProcessor<Integer> pp = PublishProcessor.create(); + + final TestSubscriber<Integer> ts = pp.publish(new Function<Flowable<Integer>, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(Flowable<Integer> f) throws Exception { + ref.set(f); + return Flowable.never(); + } + }).test(); + + ref.get().subscribe(new TestSubscriber<Integer>() { + @Override + public void onNext(Integer t) { + super.onNext(t); + onComplete(); + ts.cancel(); + } + }); + + pp.onNext(1); + } + + @Test + public void publishFunctionCancelOuterAfterOneInnerBackpressured() { + final AtomicReference<Flowable<Integer>> ref = new AtomicReference<Flowable<Integer>>(); + + PublishProcessor<Integer> pp = PublishProcessor.create(); + + final TestSubscriber<Integer> ts = pp.publish(new Function<Flowable<Integer>, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(Flowable<Integer> f) throws Exception { + ref.set(f); + return Flowable.never(); + } + }).test(); + + ref.get().subscribe(new TestSubscriber<Integer>(1L) { + @Override + public void onNext(Integer t) { + super.onNext(t); + onComplete(); + ts.cancel(); + } + }); + + pp.onNext(1); + } + + @Test + public void publishCancelOneAsync() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + final AtomicReference<Flowable<Integer>> ref = new AtomicReference<Flowable<Integer>>(); + + pp.publish(new Function<Flowable<Integer>, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(Flowable<Integer> f) throws Exception { + ref.set(f); + return Flowable.never(); + } + }).test(); + + final TestSubscriber<Integer> ts1 = ref.get().test(); + TestSubscriber<Integer> ts2 = ref.get().test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + pp.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + ts1.cancel(); + } + }; + + TestHelper.race(r1, r2); + + ts2.assertValuesOnly(1); + } + } + + @Test + public void publishCancelOneAsync2() { + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + ConnectableFlowable<Integer> cf = pp.publish(); + + final TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>(); + + final AtomicReference<InnerSubscriber<Integer>> ref = new AtomicReference<InnerSubscriber<Integer>>(); + + cf.subscribe(new FlowableSubscriber<Integer>() { + @SuppressWarnings("unchecked") + @Override + public void onSubscribe(Subscription s) { + ts1.onSubscribe(new BooleanSubscription()); + // pretend to be cancelled without removing it from the subscriber list + ref.set((InnerSubscriber<Integer>)s); + } + + @Override + public void onNext(Integer t) { + ts1.onNext(t); + } + + @Override + public void onError(Throwable t) { + ts1.onError(t); + } + + @Override + public void onComplete() { + ts1.onComplete(); + } + }); + TestSubscriber<Integer> ts2 = cf.test(); + + cf.connect(); + + ref.get().set(Long.MIN_VALUE); + + pp.onNext(1); + + ts1.assertEmpty(); + ts2.assertValuesOnly(1); + } + + @Test + public void boundaryFusion() { + Flowable.range(1, 10000) + .observeOn(Schedulers.single()) + .map(new Function<Integer, String>() { + @Override + public String apply(Integer t) throws Exception { + String name = Thread.currentThread().getName(); + if (name.contains("RxSingleScheduler")) { + return "RxSingleScheduler"; + } + return name; + } + }) + .share() + .observeOn(Schedulers.computation()) + .distinct() + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult("RxSingleScheduler"); + } + + @Test + public void badRequest() { + TestHelper.assertBadRequestReported(Flowable.range(1, 5).publish()); + } + + @Test + @SuppressWarnings("unchecked") + public void splitCombineSubscriberChangeAfterOnNext() { + Flowable<Integer> source = Flowable.range(0, 20) + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription v) throws Exception { + System.out.println("Subscribed"); + } + }) + .publish(10) + .refCount() + ; + + Flowable<Integer> evenNumbers = source.filter(new Predicate<Integer>() { + @Override + public boolean test(Integer v) throws Exception { + return v % 2 == 0; + } + }); + + Flowable<Integer> oddNumbers = source.filter(new Predicate<Integer>() { + @Override + public boolean test(Integer v) throws Exception { + return v % 2 != 0; + } + }); + + final Single<Integer> getNextOdd = oddNumbers.first(0); + + TestSubscriber<List<Integer>> ts = evenNumbers.concatMap(new Function<Integer, Publisher<List<Integer>>>() { + @Override + public Publisher<List<Integer>> apply(Integer v) throws Exception { + return Single.zip( + Single.just(v), getNextOdd, + new BiFunction<Integer, Integer, List<Integer>>() { + @Override + public List<Integer> apply(Integer a, Integer b) throws Exception { + return Arrays.asList( a, b ); + } + } + ) + .toFlowable(); + } + }) + .takeWhile(new Predicate<List<Integer>>() { + @Override + public boolean test(List<Integer> v) throws Exception { + return v.get(0) < 20; + } + }) + .test(); + + ts + .assertResult( + Arrays.asList(0, 1), + Arrays.asList(2, 3), + Arrays.asList(4, 5), + Arrays.asList(6, 7), + Arrays.asList(8, 9), + Arrays.asList(10, 11), + Arrays.asList(12, 13), + Arrays.asList(14, 15), + Arrays.asList(16, 17), + Arrays.asList(18, 19) + ); + } + + @Test + @SuppressWarnings("unchecked") + public void splitCombineSubscriberChangeAfterOnNextFused() { + Flowable<Integer> source = Flowable.range(0, 20) + .publish(10) + .refCount() + ; + + Flowable<Integer> evenNumbers = source.filter(new Predicate<Integer>() { + @Override + public boolean test(Integer v) throws Exception { + return v % 2 == 0; + } + }); + + Flowable<Integer> oddNumbers = source.filter(new Predicate<Integer>() { + @Override + public boolean test(Integer v) throws Exception { + return v % 2 != 0; + } + }); + + final Single<Integer> getNextOdd = oddNumbers.first(0); + + TestSubscriber<List<Integer>> ts = evenNumbers.concatMap(new Function<Integer, Publisher<List<Integer>>>() { + @Override + public Publisher<List<Integer>> apply(Integer v) throws Exception { + return Single.zip( + Single.just(v), getNextOdd, + new BiFunction<Integer, Integer, List<Integer>>() { + @Override + public List<Integer> apply(Integer a, Integer b) throws Exception { + return Arrays.asList( a, b ); + } + } + ) + .toFlowable(); + } + }) + .takeWhile(new Predicate<List<Integer>>() { + @Override + public boolean test(List<Integer> v) throws Exception { + return v.get(0) < 20; + } + }) + .test(); + + ts + .assertResult( + Arrays.asList(0, 1), + Arrays.asList(2, 3), + Arrays.asList(4, 5), + Arrays.asList(6, 7), + Arrays.asList(8, 9), + Arrays.asList(10, 11), + Arrays.asList(12, 13), + Arrays.asList(14, 15), + Arrays.asList(16, 17), + Arrays.asList(18, 19) + ); + } + + @Test + public void altConnectCrash() { + try { + new FlowablePublishAlt<Integer>(Flowable.<Integer>empty(), 128) + .connect(new Consumer<Disposable>() { + @Override + public void accept(Disposable t) throws Exception { + throw new TestException(); + } + }); + fail("Should have thrown"); + } catch (TestException expected) { + // expected + } + } + + @Test + public void altConnectRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final ConnectableFlowable<Integer> cf = + new FlowablePublishAlt<Integer>(Flowable.<Integer>never(), 128); + + Runnable r = new Runnable() { + @Override + public void run() { + cf.connect(); + } + }; + + TestHelper.race(r, r); + } + } + + @Test + public void fusedPollCrash() { + Flowable.range(1, 5) + .map(new Function<Integer, Object>() { + @Override + public Object apply(Integer v) throws Exception { + throw new TestException(); + } + }) + .compose(TestHelper.flowableStripBoundary()) + .publish() + .refCount() + .test() + .assertFailure(TestException.class); + } + + @Test + public void syncFusedNoRequest() { + Flowable.range(1, 5) + .publish(1) + .refCount() + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void normalBackpressuredPolls() { + Flowable.range(1, 5) + .hide() + .publish(1) + .refCount() + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void emptyHidden() { + Flowable.empty() + .hide() + .publish(1) + .refCount() + .test() + .assertResult(); + } + + @Test + public void emptyFused() { + Flowable.empty() + .publish(1) + .refCount() + .test() + .assertResult(); + } + + @Test + public void overflowQueueRefCount() { + new Flowable<Integer>() { + @Override + protected void subscribeActual(Subscriber<? super Integer> s) { + s.onSubscribe(new BooleanSubscription()); + s.onNext(1); + s.onNext(2); + } + } + .publish(1) + .refCount() + .test(0) + .requestMore(1) + .assertFailure(MissingBackpressureException.class, 1); + } + + @Test + public void doubleErrorRefCount() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new Flowable<Integer>() { + @Override + protected void subscribeActual(Subscriber<? super Integer> s) { + s.onSubscribe(new BooleanSubscription()); + s.onError(new TestException("one")); + s.onError(new TestException("two")); + } + } + .publish(1) + .refCount() + .test(0) + .assertFailureAndMessage(TestException.class, "one"); + + TestHelper.assertUndeliverable(errors, 0, TestException.class, "two"); + assertEquals(1, errors.size()); + } finally { + RxJavaPlugins.reset(); + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java index eac12749f5..80af00c66f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java @@ -39,6 +39,28 @@ public class FlowablePublishTest { + // This will undo the workaround so that the plain ObservablePublish is still + // tested. + @Before + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void before() { + RxJavaPlugins.setOnConnectableFlowableAssembly(new Function<ConnectableFlowable, ConnectableFlowable>() { + @Override + public ConnectableFlowable apply(ConnectableFlowable co) throws Exception { + if (co instanceof FlowablePublishAlt) { + FlowablePublishAlt fpa = (FlowablePublishAlt) co; + return FlowablePublish.create(Flowable.fromPublisher(fpa.source()), fpa.publishBufferSize()); + } + return co; + } + }); + } + + @After + public void after() { + RxJavaPlugins.setOnConnectableFlowableAssembly(null); + } + @Test public void testPublish() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java new file mode 100644 index 0000000000..e048d47650 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java @@ -0,0 +1,1447 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.flowable; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; + +import org.junit.Test; +import org.mockito.InOrder; +import org.reactivestreams.*; + +import io.reactivex.*; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.*; +import io.reactivex.flowables.ConnectableFlowable; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.flowable.FlowableRefCount.RefConnection; +import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.internal.util.ExceptionHelper; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.*; +import io.reactivex.schedulers.*; +import io.reactivex.subscribers.TestSubscriber; + +public class FlowableRefCountAltTest { + + @Test + public void testRefCountAsync() { + final AtomicInteger subscribeCount = new AtomicInteger(); + final AtomicInteger nextCount = new AtomicInteger(); + Flowable<Long> r = Flowable.interval(0, 20, TimeUnit.MILLISECONDS) + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription s) { + subscribeCount.incrementAndGet(); + } + }) + .doOnNext(new Consumer<Long>() { + @Override + public void accept(Long l) { + nextCount.incrementAndGet(); + } + }) + .publish().refCount(); + + final AtomicInteger receivedCount = new AtomicInteger(); + Disposable d1 = r.subscribe(new Consumer<Long>() { + @Override + public void accept(Long l) { + receivedCount.incrementAndGet(); + } + }); + + Disposable d2 = r.subscribe(); + + try { + Thread.sleep(10); + } catch (InterruptedException e) { + } + + for (;;) { + int a = nextCount.get(); + int b = receivedCount.get(); + if (a > 10 && a < 20 && a == b) { + break; + } + if (a >= 20) { + break; + } + try { + Thread.sleep(20); + } catch (InterruptedException e) { + } + } + // give time to emit + + // now unsubscribe + d2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one subscriber getting a value but not the other + d1.dispose(); + + System.out.println("onNext: " + nextCount.get()); + + // should emit once for both subscribers + assertEquals(nextCount.get(), receivedCount.get()); + // only 1 subscribe + assertEquals(1, subscribeCount.get()); + } + + @Test + public void testRefCountSynchronous() { + final AtomicInteger subscribeCount = new AtomicInteger(); + final AtomicInteger nextCount = new AtomicInteger(); + Flowable<Integer> r = Flowable.just(1, 2, 3, 4, 5, 6, 7, 8, 9) + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription s) { + subscribeCount.incrementAndGet(); + } + }) + .doOnNext(new Consumer<Integer>() { + @Override + public void accept(Integer l) { + nextCount.incrementAndGet(); + } + }) + .publish().refCount(); + + final AtomicInteger receivedCount = new AtomicInteger(); + Disposable d1 = r.subscribe(new Consumer<Integer>() { + @Override + public void accept(Integer l) { + receivedCount.incrementAndGet(); + } + }); + + Disposable d2 = r.subscribe(); + + // give time to emit + try { + Thread.sleep(50); + } catch (InterruptedException e) { + } + + // now unsubscribe + d2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one subscriber getting a value but not the other + d1.dispose(); + + System.out.println("onNext Count: " + nextCount.get()); + + // it will emit twice because it is synchronous + assertEquals(nextCount.get(), receivedCount.get() * 2); + // it will subscribe twice because it is synchronous + assertEquals(2, subscribeCount.get()); + } + + @Test + public void testRefCountSynchronousTake() { + final AtomicInteger nextCount = new AtomicInteger(); + Flowable<Integer> r = Flowable.just(1, 2, 3, 4, 5, 6, 7, 8, 9) + .doOnNext(new Consumer<Integer>() { + @Override + public void accept(Integer l) { + System.out.println("onNext --------> " + l); + nextCount.incrementAndGet(); + } + }) + .take(4) + .publish().refCount(); + + final AtomicInteger receivedCount = new AtomicInteger(); + r.subscribe(new Consumer<Integer>() { + @Override + public void accept(Integer l) { + receivedCount.incrementAndGet(); + } + }); + + System.out.println("onNext: " + nextCount.get()); + + assertEquals(4, receivedCount.get()); + assertEquals(4, receivedCount.get()); + } + + @Test + public void testRepeat() { + final AtomicInteger subscribeCount = new AtomicInteger(); + final AtomicInteger unsubscribeCount = new AtomicInteger(); + Flowable<Long> r = Flowable.interval(0, 1, TimeUnit.MILLISECONDS) + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription s) { + System.out.println("******************************* Subscribe received"); + // when we are subscribed + subscribeCount.incrementAndGet(); + } + }) + .doOnCancel(new Action() { + @Override + public void run() { + System.out.println("******************************* Unsubscribe received"); + // when we are unsubscribed + unsubscribeCount.incrementAndGet(); + } + }) + .publish().refCount(); + + for (int i = 0; i < 10; i++) { + TestSubscriber<Long> ts1 = new TestSubscriber<Long>(); + TestSubscriber<Long> ts2 = new TestSubscriber<Long>(); + r.subscribe(ts1); + r.subscribe(ts2); + try { + Thread.sleep(50); + } catch (InterruptedException e) { + } + ts1.dispose(); + ts2.dispose(); + ts1.assertNoErrors(); + ts2.assertNoErrors(); + assertTrue(ts1.valueCount() > 0); + assertTrue(ts2.valueCount() > 0); + } + + assertEquals(10, subscribeCount.get()); + assertEquals(10, unsubscribeCount.get()); + } + + @Test + public void testConnectUnsubscribe() throws InterruptedException { + final CountDownLatch unsubscribeLatch = new CountDownLatch(1); + final CountDownLatch subscribeLatch = new CountDownLatch(1); + + Flowable<Long> f = synchronousInterval() + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription s) { + System.out.println("******************************* Subscribe received"); + // when we are subscribed + subscribeLatch.countDown(); + } + }) + .doOnCancel(new Action() { + @Override + public void run() { + System.out.println("******************************* Unsubscribe received"); + // when we are unsubscribed + unsubscribeLatch.countDown(); + } + }); + + TestSubscriber<Long> s = new TestSubscriber<Long>(); + f.publish().refCount().subscribeOn(Schedulers.newThread()).subscribe(s); + System.out.println("send unsubscribe"); + // wait until connected + subscribeLatch.await(); + // now unsubscribe + s.dispose(); + System.out.println("DONE sending unsubscribe ... now waiting"); + if (!unsubscribeLatch.await(3000, TimeUnit.MILLISECONDS)) { + System.out.println("Errors: " + s.errors()); + if (s.errors().size() > 0) { + s.errors().get(0).printStackTrace(); + } + fail("timed out waiting for unsubscribe"); + } + s.assertNoErrors(); + } + + @Test + public void testConnectUnsubscribeRaceConditionLoop() throws InterruptedException { + for (int i = 0; i < 100; i++) { + testConnectUnsubscribeRaceCondition(); + } + } + + @Test + public void testConnectUnsubscribeRaceCondition() throws InterruptedException { + final AtomicInteger subUnsubCount = new AtomicInteger(); + Flowable<Long> f = synchronousInterval() + .doOnCancel(new Action() { + @Override + public void run() { + System.out.println("******************************* Unsubscribe received"); + // when we are unsubscribed + subUnsubCount.decrementAndGet(); + } + }) + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription s) { + System.out.println("******************************* SUBSCRIBE received"); + subUnsubCount.incrementAndGet(); + } + }); + + TestSubscriber<Long> s = new TestSubscriber<Long>(); + + f.publish().refCount().subscribeOn(Schedulers.computation()).subscribe(s); + System.out.println("send unsubscribe"); + // now immediately unsubscribe while subscribeOn is racing to subscribe + s.dispose(); + // this generally will mean it won't even subscribe as it is already unsubscribed by the time connect() gets scheduled + // give time to the counter to update + Thread.sleep(10); + // either we subscribed and then unsubscribed, or we didn't ever even subscribe + assertEquals(0, subUnsubCount.get()); + + System.out.println("DONE sending unsubscribe ... now waiting"); + System.out.println("Errors: " + s.errors()); + if (s.errors().size() > 0) { + s.errors().get(0).printStackTrace(); + } + s.assertNoErrors(); + } + + private Flowable<Long> synchronousInterval() { + return Flowable.unsafeCreate(new Publisher<Long>() { + @Override + public void subscribe(Subscriber<? super Long> subscriber) { + final AtomicBoolean cancel = new AtomicBoolean(); + subscriber.onSubscribe(new Subscription() { + @Override + public void request(long n) { + + } + + @Override + public void cancel() { + cancel.set(true); + } + + }); + for (;;) { + if (cancel.get()) { + break; + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + subscriber.onNext(1L); + } + } + }); + } + + @Test + public void onlyFirstShouldSubscribeAndLastUnsubscribe() { + final AtomicInteger subscriptionCount = new AtomicInteger(); + final AtomicInteger unsubscriptionCount = new AtomicInteger(); + Flowable<Integer> flowable = Flowable.unsafeCreate(new Publisher<Integer>() { + @Override + public void subscribe(Subscriber<? super Integer> subscriber) { + subscriptionCount.incrementAndGet(); + subscriber.onSubscribe(new Subscription() { + @Override + public void request(long n) { + + } + + @Override + public void cancel() { + unsubscriptionCount.incrementAndGet(); + } + }); + } + }); + Flowable<Integer> refCounted = flowable.publish().refCount(); + + Disposable first = refCounted.subscribe(); + assertEquals(1, subscriptionCount.get()); + + Disposable second = refCounted.subscribe(); + assertEquals(1, subscriptionCount.get()); + + first.dispose(); + assertEquals(0, unsubscriptionCount.get()); + + second.dispose(); + assertEquals(1, unsubscriptionCount.get()); + } + + @Test + public void testRefCount() { + TestScheduler s = new TestScheduler(); + Flowable<Long> interval = Flowable.interval(100, TimeUnit.MILLISECONDS, s).publish().refCount(); + + // subscribe list1 + final List<Long> list1 = new ArrayList<Long>(); + Disposable d1 = interval.subscribe(new Consumer<Long>() { + @Override + public void accept(Long t1) { + list1.add(t1); + } + }); + + s.advanceTimeBy(200, TimeUnit.MILLISECONDS); + + assertEquals(2, list1.size()); + assertEquals(0L, list1.get(0).longValue()); + assertEquals(1L, list1.get(1).longValue()); + + // subscribe list2 + final List<Long> list2 = new ArrayList<Long>(); + Disposable d2 = interval.subscribe(new Consumer<Long>() { + @Override + public void accept(Long t1) { + list2.add(t1); + } + }); + + s.advanceTimeBy(300, TimeUnit.MILLISECONDS); + + // list 1 should have 5 items + assertEquals(5, list1.size()); + assertEquals(2L, list1.get(2).longValue()); + assertEquals(3L, list1.get(3).longValue()); + assertEquals(4L, list1.get(4).longValue()); + + // list 2 should only have 3 items + assertEquals(3, list2.size()); + assertEquals(2L, list2.get(0).longValue()); + assertEquals(3L, list2.get(1).longValue()); + assertEquals(4L, list2.get(2).longValue()); + + // unsubscribe list1 + d1.dispose(); + + // advance further + s.advanceTimeBy(300, TimeUnit.MILLISECONDS); + + // list 1 should still have 5 items + assertEquals(5, list1.size()); + + // list 2 should have 6 items + assertEquals(6, list2.size()); + assertEquals(5L, list2.get(3).longValue()); + assertEquals(6L, list2.get(4).longValue()); + assertEquals(7L, list2.get(5).longValue()); + + // unsubscribe list2 + d2.dispose(); + + // advance further + s.advanceTimeBy(1000, TimeUnit.MILLISECONDS); + + // subscribing a new one should start over because the source should have been unsubscribed + // subscribe list3 + final List<Long> list3 = new ArrayList<Long>(); + interval.subscribe(new Consumer<Long>() { + @Override + public void accept(Long t1) { + list3.add(t1); + } + }); + + s.advanceTimeBy(200, TimeUnit.MILLISECONDS); + + assertEquals(2, list3.size()); + assertEquals(0L, list3.get(0).longValue()); + assertEquals(1L, list3.get(1).longValue()); + + } + + @Test + public void testAlreadyUnsubscribedClient() { + Subscriber<Integer> done = CancelledSubscriber.INSTANCE; + + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + + Flowable<Integer> result = Flowable.just(1).publish().refCount(); + + result.subscribe(done); + + result.subscribe(subscriber); + + verify(subscriber).onNext(1); + verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + } + + @Test + public void testAlreadyUnsubscribedInterleavesWithClient() { + ReplayProcessor<Integer> source = ReplayProcessor.create(); + + Subscriber<Integer> done = CancelledSubscriber.INSTANCE; + + Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); + InOrder inOrder = inOrder(subscriber); + + Flowable<Integer> result = source.publish().refCount(); + + result.subscribe(subscriber); + + source.onNext(1); + + result.subscribe(done); + + source.onNext(2); + source.onComplete(); + + inOrder.verify(subscriber).onNext(1); + inOrder.verify(subscriber).onNext(2); + inOrder.verify(subscriber).onComplete(); + verify(subscriber, never()).onError(any(Throwable.class)); + } + + @Test + public void testConnectDisconnectConnectAndSubjectState() { + Flowable<Integer> f1 = Flowable.just(10); + Flowable<Integer> f2 = Flowable.just(20); + Flowable<Integer> combined = Flowable.combineLatest(f1, f2, new BiFunction<Integer, Integer, Integer>() { + @Override + public Integer apply(Integer t1, Integer t2) { + return t1 + t2; + } + }) + .publish().refCount(); + + TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>(); + TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(); + + combined.subscribe(ts1); + combined.subscribe(ts2); + + ts1.assertTerminated(); + ts1.assertNoErrors(); + ts1.assertValue(30); + + ts2.assertTerminated(); + ts2.assertNoErrors(); + ts2.assertValue(30); + } + + @Test(timeout = 10000) + public void testUpstreamErrorAllowsRetry() throws InterruptedException { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final AtomicInteger intervalSubscribed = new AtomicInteger(); + Flowable<String> interval = + Flowable.interval(200, TimeUnit.MILLISECONDS) + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription s) { + System.out.println("Subscribing to interval " + intervalSubscribed.incrementAndGet()); + } + } + ) + .flatMap(new Function<Long, Publisher<String>>() { + @Override + public Publisher<String> apply(Long t1) { + return Flowable.defer(new Callable<Publisher<String>>() { + @Override + public Publisher<String> call() { + return Flowable.<String>error(new TestException("Some exception")); + } + }); + } + }) + .onErrorResumeNext(new Function<Throwable, Publisher<String>>() { + @Override + public Publisher<String> apply(Throwable t1) { + return Flowable.error(t1); + } + }) + .publish() + .refCount(); + + interval + .doOnError(new Consumer<Throwable>() { + @Override + public void accept(Throwable t1) { + System.out.println("Subscriber 1 onError: " + t1); + } + }) + .retry(5) + .subscribe(new Consumer<String>() { + @Override + public void accept(String t1) { + System.out.println("Subscriber 1: " + t1); + } + }); + Thread.sleep(100); + interval + .doOnError(new Consumer<Throwable>() { + @Override + public void accept(Throwable t1) { + System.out.println("Subscriber 2 onError: " + t1); + } + }) + .retry(5) + .subscribe(new Consumer<String>() { + @Override + public void accept(String t1) { + System.out.println("Subscriber 2: " + t1); + } + }); + + Thread.sleep(1300); + + System.out.println(intervalSubscribed.get()); + assertEquals(6, intervalSubscribed.get()); + + TestHelper.assertError(errors, 0, OnErrorNotImplementedException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + private enum CancelledSubscriber implements FlowableSubscriber<Integer> { + INSTANCE; + + @Override public void onSubscribe(Subscription s) { + s.cancel(); + } + + @Override public void onNext(Integer o) { + } + + @Override public void onError(Throwable t) { + } + + @Override public void onComplete() { + } + } + + @Test + public void disposed() { + TestHelper.checkDisposed(Flowable.just(1).publish().refCount()); + } + + @Test + public void noOpConnect() { + final int[] calls = { 0 }; + Flowable<Integer> f = new ConnectableFlowable<Integer>() { + @Override + public void connect(Consumer<? super Disposable> connection) { + calls[0]++; + } + + @Override + protected void subscribeActual(Subscriber<? super Integer> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + } + }.refCount(); + + f.test(); + f.test(); + + assertEquals(1, calls[0]); + } + + Flowable<Object> source; + + @Test + public void replayNoLeak() throws Exception { + Thread.sleep(100); + System.gc(); + Thread.sleep(100); + + long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = Flowable.fromCallable(new Callable<Object>() { + @Override + public Object call() throws Exception { + return new byte[100 * 1000 * 1000]; + } + }) + .replay(1) + .refCount(); + + source.subscribe(); + + Thread.sleep(100); + System.gc(); + Thread.sleep(100); + + long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = null; + assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after); + } + + @Test + public void replayNoLeak2() throws Exception { + Thread.sleep(100); + System.gc(); + Thread.sleep(100); + + long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = Flowable.fromCallable(new Callable<Object>() { + @Override + public Object call() throws Exception { + return new byte[100 * 1000 * 1000]; + } + }).concatWith(Flowable.never()) + .replay(1) + .refCount(); + + Disposable d1 = source.subscribe(); + Disposable d2 = source.subscribe(); + + d1.dispose(); + d2.dispose(); + + d1 = null; + d2 = null; + + Thread.sleep(100); + System.gc(); + Thread.sleep(100); + + long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = null; + assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after); + } + + static final class ExceptionData extends Exception { + private static final long serialVersionUID = -6763898015338136119L; + + public final Object data; + + ExceptionData(Object data) { + this.data = data; + } + } + + @Test + public void publishNoLeak() throws Exception { + Thread.sleep(100); + System.gc(); + Thread.sleep(100); + + long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = Flowable.fromCallable(new Callable<Object>() { + @Override + public Object call() throws Exception { + throw new ExceptionData(new byte[100 * 1000 * 1000]); + } + }) + .publish() + .refCount(); + + source.subscribe(Functions.emptyConsumer(), Functions.emptyConsumer()); + + Thread.sleep(100); + System.gc(); + Thread.sleep(200); + + long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = null; + + assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after); + } + + @Test + public void publishNoLeak2() throws Exception { + System.gc(); + Thread.sleep(100); + + long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = Flowable.fromCallable(new Callable<Object>() { + @Override + public Object call() throws Exception { + return new byte[100 * 1000 * 1000]; + } + }).concatWith(Flowable.never()) + .publish() + .refCount(); + + Disposable d1 = source.test(); + Disposable d2 = source.test(); + + d1.dispose(); + d2.dispose(); + + d1 = null; + d2 = null; + + System.gc(); + Thread.sleep(100); + + long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = null; + assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after); + } + + @Test + public void replayIsUnsubscribed() { + ConnectableFlowable<Integer> cf = Flowable.just(1) + .replay(); + + if (cf instanceof Disposable) { + assertTrue(((Disposable)cf).isDisposed()); + + Disposable connection = cf.connect(); + + assertFalse(((Disposable)cf).isDisposed()); + + connection.dispose(); + + assertTrue(((Disposable)cf).isDisposed()); + } + } + + static final class BadFlowableSubscribe extends ConnectableFlowable<Object> { + + @Override + public void connect(Consumer<? super Disposable> connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Subscriber<? super Object> subscriber) { + throw new TestException("subscribeActual"); + } + } + + static final class BadFlowableDispose extends ConnectableFlowable<Object> implements Disposable { + + @Override + public void dispose() { + throw new TestException("dispose"); + } + + @Override + public boolean isDisposed() { + return false; + } + + @Override + public void connect(Consumer<? super Disposable> connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + } + } + + static final class BadFlowableConnect extends ConnectableFlowable<Object> { + + @Override + public void connect(Consumer<? super Disposable> connection) { + throw new TestException("connect"); + } + + @Override + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + } + } + + @Test + public void badSourceSubscribe() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + BadFlowableSubscribe bo = new BadFlowableSubscribe(); + + try { + bo.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void badSourceDispose() { + BadFlowableDispose bf = new BadFlowableDispose(); + + try { + bf.refCount() + .test() + .cancel(); + fail("Should have thrown"); + } catch (TestException expected) { + } + } + + @Test + public void badSourceConnect() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + BadFlowableConnect bf = new BadFlowableConnect(); + + try { + bf.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + static final class BadFlowableSubscribe2 extends ConnectableFlowable<Object> { + + int count; + + @Override + public void connect(Consumer<? super Disposable> connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Subscriber<? super Object> subscriber) { + if (++count == 1) { + subscriber.onSubscribe(new BooleanSubscription()); + } else { + throw new TestException("subscribeActual"); + } + } + } + + @Test + public void badSourceSubscribe2() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + BadFlowableSubscribe2 bf = new BadFlowableSubscribe2(); + + Flowable<Object> f = bf.refCount(); + f.test(); + try { + f.test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + static final class BadFlowableConnect2 extends ConnectableFlowable<Object> + implements Disposable { + + @Override + public void connect(Consumer<? super Disposable> connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); + } + + @Override + public void dispose() { + throw new TestException("dispose"); + } + + @Override + public boolean isDisposed() { + return false; + } + } + + @Test + public void badSourceCompleteDisconnect() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + BadFlowableConnect2 bf = new BadFlowableConnect2(); + + try { + bf.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test(timeout = 7500) + public void blockingSourceAsnycCancel() throws Exception { + BehaviorProcessor<Integer> bp = BehaviorProcessor.createDefault(1); + + Flowable<Integer> f = bp + .replay(1) + .refCount(); + + f.subscribe(); + + final AtomicBoolean interrupted = new AtomicBoolean(); + + f.switchMap(new Function<Integer, Publisher<? extends Object>>() { + @Override + public Publisher<? extends Object> apply(Integer v) throws Exception { + return Flowable.create(new FlowableOnSubscribe<Object>() { + @Override + public void subscribe(FlowableEmitter<Object> emitter) throws Exception { + while (!emitter.isCancelled()) { + Thread.sleep(100); + } + interrupted.set(true); + } + }, BackpressureStrategy.MISSING); + } + }) + .takeUntil(Flowable.timer(500, TimeUnit.MILLISECONDS)) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(); + + assertTrue(interrupted.get()); + } + + @Test + public void byCount() { + final int[] subscriptions = { 0 }; + + Flowable<Integer> source = Flowable.range(1, 5) + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription s) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .refCount(2); + + for (int i = 0; i < 3; i++) { + TestSubscriber<Integer> ts1 = source.test(); + + ts1.assertEmpty(); + + TestSubscriber<Integer> ts2 = source.test(); + + ts1.assertResult(1, 2, 3, 4, 5); + ts2.assertResult(1, 2, 3, 4, 5); + } + + assertEquals(3, subscriptions[0]); + } + + @Test + public void resubscribeBeforeTimeout() throws Exception { + final int[] subscriptions = { 0 }; + + PublishProcessor<Integer> pp = PublishProcessor.create(); + + Flowable<Integer> source = pp + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription s) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .refCount(500, TimeUnit.MILLISECONDS); + + TestSubscriber<Integer> ts1 = source.test(0); + + assertEquals(1, subscriptions[0]); + + ts1.cancel(); + + Thread.sleep(100); + + ts1 = source.test(0); + + assertEquals(1, subscriptions[0]); + + Thread.sleep(500); + + assertEquals(1, subscriptions[0]); + + pp.onNext(1); + pp.onNext(2); + pp.onNext(3); + pp.onNext(4); + pp.onNext(5); + pp.onComplete(); + + ts1.requestMore(5) + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void letitTimeout() throws Exception { + final int[] subscriptions = { 0 }; + + PublishProcessor<Integer> pp = PublishProcessor.create(); + + Flowable<Integer> source = pp + .doOnSubscribe(new Consumer<Subscription>() { + @Override + public void accept(Subscription s) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .refCount(1, 100, TimeUnit.MILLISECONDS); + + TestSubscriber<Integer> ts1 = source.test(0); + + assertEquals(1, subscriptions[0]); + + ts1.cancel(); + + assertTrue(pp.hasSubscribers()); + + Thread.sleep(200); + + assertFalse(pp.hasSubscribers()); + } + + @Test + public void error() { + Flowable.<Integer>error(new IOException()) + .publish() + .refCount(500, TimeUnit.MILLISECONDS) + .test() + .assertFailure(IOException.class); + } + + @Test + public void comeAndGo() { + PublishProcessor<Integer> pp = PublishProcessor.create(); + + Flowable<Integer> source = pp + .publish() + .refCount(1); + + TestSubscriber<Integer> ts1 = source.test(0); + + assertTrue(pp.hasSubscribers()); + + for (int i = 0; i < 3; i++) { + TestSubscriber<Integer> ts2 = source.test(); + ts1.cancel(); + ts1 = ts2; + } + + ts1.cancel(); + + assertFalse(pp.hasSubscribers()); + } + + @Test + public void unsubscribeSubscribeRace() { + for (int i = 0; i < 1000; i++) { + + final Flowable<Integer> source = Flowable.range(1, 5) + .replay() + .refCount(1) + ; + + final TestSubscriber<Integer> ts1 = source.test(0); + + final TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(0); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ts1.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + source.subscribe(ts2); + } + }; + + TestHelper.race(r1, r2, Schedulers.single()); + + ts2.requestMore(6) // FIXME RxJava replay() doesn't issue onComplete without request + .withTag("Round: " + i) + .assertResult(1, 2, 3, 4, 5); + } + } + + static final class BadFlowableDoubleOnX extends ConnectableFlowable<Object> + implements Disposable { + + @Override + public void connect(Consumer<? super Disposable> connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Subscriber<? super Object> subscriber) { + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onSubscribe(new BooleanSubscription()); + subscriber.onComplete(); + subscriber.onComplete(); + subscriber.onError(new TestException()); + } + + @Override + public void dispose() { + } + + @Override + public boolean isDisposed() { + return false; + } + } + + @Test + public void doubleOnX() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new BadFlowableDoubleOnX() + .refCount() + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void doubleOnXCount() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new BadFlowableDoubleOnX() + .refCount(1) + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void doubleOnXTime() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new BadFlowableDoubleOnX() + .refCount(5, TimeUnit.SECONDS, Schedulers.single()) + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void cancelTerminateStateExclusion() { + FlowableRefCount<Object> o = (FlowableRefCount<Object>)PublishProcessor.create() + .publish() + .refCount(); + + o.cancel(null); + + RefConnection rc = new RefConnection(o); + o.connection = null; + rc.subscriberCount = 0; + o.timeout(rc); + + rc.subscriberCount = 1; + o.timeout(rc); + + o.connection = rc; + o.timeout(rc); + + rc.subscriberCount = 0; + o.timeout(rc); + + // ------------------- + + rc.subscriberCount = 2; + rc.connected = false; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 1; + rc.connected = false; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 2; + rc.connected = true; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 1; + rc.connected = true; + o.connection = rc; + rc.set(null); + o.cancel(rc); + + o.connection = rc; + o.cancel(new RefConnection(o)); + } + + @Test + public void replayRefCountShallBeThreadSafe() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + Flowable<Integer> flowable = Flowable.just(1).replay(1).refCount(); + + TestSubscriber<Integer> ts1 = flowable + .subscribeOn(Schedulers.io()) + .test(); + + TestSubscriber<Integer> ts2 = flowable + .subscribeOn(Schedulers.io()) + .test(); + + ts1 + .withTag("" + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + ts2 + .withTag("" + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + } + } + + static final class TestConnectableFlowable<T> extends ConnectableFlowable<T> + implements Disposable { + + volatile boolean disposed; + + @Override + public void dispose() { + disposed = true; + } + + @Override + public boolean isDisposed() { + return disposed; + } + + @Override + public void connect(Consumer<? super Disposable> connection) { + // not relevant + } + + @Override + protected void subscribeActual(Subscriber<? super T> subscriber) { + // not relevant + } + } + + @Test + public void timeoutDisposesSource() { + FlowableRefCount<Object> o = (FlowableRefCount<Object>)new TestConnectableFlowable<Object>().refCount(); + + RefConnection rc = new RefConnection(o); + o.connection = rc; + + o.timeout(rc); + + assertTrue(((Disposable)o.source).isDisposed()); + } + + @Test + public void disconnectBeforeConnect() { + BehaviorProcessor<Integer> processor = BehaviorProcessor.create(); + + Flowable<Integer> flowable = processor + .replay(1) + .refCount(); + + flowable.takeUntil(Flowable.just(1)).test(); + + processor.onNext(2); + + flowable.take(1).test().assertResult(2); + } + + @Test + public void publishRefCountShallBeThreadSafe() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + Flowable<Integer> flowable = Flowable.just(1).publish().refCount(); + + TestSubscriber<Integer> subscriber1 = flowable + .subscribeOn(Schedulers.io()) + .test(); + + TestSubscriber<Integer> subscriber2 = flowable + .subscribeOn(Schedulers.io()) + .test(); + + subscriber1 + .withTag("subscriber1 " + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertNoErrors() + .assertComplete(); + + subscriber2 + .withTag("subscriber2 " + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertNoErrors() + .assertComplete(); + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index 673a0f4add..88aa2b17c1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -23,7 +23,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; -import org.junit.Test; +import org.junit.*; import org.mockito.InOrder; import org.reactivestreams.*; @@ -43,6 +43,28 @@ public class FlowableRefCountTest { + // This will undo the workaround so that the plain ObservablePublish is still + // tested. + @Before + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void before() { + RxJavaPlugins.setOnConnectableFlowableAssembly(new Function<ConnectableFlowable, ConnectableFlowable>() { + @Override + public ConnectableFlowable apply(ConnectableFlowable co) throws Exception { + if (co instanceof FlowablePublishAlt) { + FlowablePublishAlt fpa = (FlowablePublishAlt) co; + return FlowablePublish.create(Flowable.fromPublisher(fpa.source()), fpa.publishBufferSize()); + } + return co; + } + }); + } + + @After + public void after() { + RxJavaPlugins.setOnConnectableFlowableAssembly(null); + } + @Test public void testRefCountAsync() { final AtomicInteger subscribeCount = new AtomicInteger(); @@ -653,6 +675,7 @@ protected void subscribeActual(Subscriber<? super Integer> subscriber) { @Test public void replayNoLeak() throws Exception { + Thread.sleep(100); System.gc(); Thread.sleep(100); @@ -669,6 +692,7 @@ public Object call() throws Exception { source.subscribe(); + Thread.sleep(100); System.gc(); Thread.sleep(100); @@ -680,6 +704,7 @@ public Object call() throws Exception { @Test public void replayNoLeak2() throws Exception { + Thread.sleep(100); System.gc(); Thread.sleep(100); @@ -703,6 +728,7 @@ public Object call() throws Exception { d1 = null; d2 = null; + Thread.sleep(100); System.gc(); Thread.sleep(100); @@ -724,6 +750,7 @@ static final class ExceptionData extends Exception { @Test public void publishNoLeak() throws Exception { + Thread.sleep(100); System.gc(); Thread.sleep(100); @@ -740,6 +767,7 @@ public Object call() throws Exception { source.subscribe(Functions.emptyConsumer(), Functions.emptyConsumer()); + Thread.sleep(100); System.gc(); Thread.sleep(100); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishAltTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishAltTest.java new file mode 100644 index 0000000000..b268e5b2ed --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishAltTest.java @@ -0,0 +1,794 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import static org.junit.Assert.*; + +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; + +import org.junit.Test; + +import io.reactivex.*; +import io.reactivex.Observable; +import io.reactivex.Observer; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.TestException; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.fuseable.HasUpstreamObservableSource; +import io.reactivex.observables.ConnectableObservable; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.*; +import io.reactivex.subjects.PublishSubject; + +public class ObservablePublishAltTest { + + @Test + public void testPublish() throws InterruptedException { + final AtomicInteger counter = new AtomicInteger(); + ConnectableObservable<String> o = Observable.unsafeCreate(new ObservableSource<String>() { + + @Override + public void subscribe(final Observer<? super String> observer) { + observer.onSubscribe(Disposables.empty()); + new Thread(new Runnable() { + + @Override + public void run() { + counter.incrementAndGet(); + observer.onNext("one"); + observer.onComplete(); + } + }).start(); + } + }).publish(); + + final CountDownLatch latch = new CountDownLatch(2); + + // subscribe once + o.subscribe(new Consumer<String>() { + + @Override + public void accept(String v) { + assertEquals("one", v); + latch.countDown(); + } + }); + + // subscribe again + o.subscribe(new Consumer<String>() { + + @Override + public void accept(String v) { + assertEquals("one", v); + latch.countDown(); + } + }); + + Disposable connection = o.connect(); + try { + if (!latch.await(1000, TimeUnit.MILLISECONDS)) { + fail("subscriptions did not receive values"); + } + assertEquals(1, counter.get()); + } finally { + connection.dispose(); + } + } + + @Test + public void testBackpressureFastSlow() { + ConnectableObservable<Integer> is = Observable.range(1, Flowable.bufferSize() * 2).publish(); + Observable<Integer> fast = is.observeOn(Schedulers.computation()) + .doOnComplete(new Action() { + @Override + public void run() { + System.out.println("^^^^^^^^^^^^^ completed FAST"); + } + }); + + Observable<Integer> slow = is.observeOn(Schedulers.computation()).map(new Function<Integer, Integer>() { + int c; + + @Override + public Integer apply(Integer i) { + if (c == 0) { + try { + Thread.sleep(500); + } catch (InterruptedException e) { + } + } + c++; + return i; + } + + }).doOnComplete(new Action() { + + @Override + public void run() { + System.out.println("^^^^^^^^^^^^^ completed SLOW"); + } + + }); + + TestObserver<Integer> to = new TestObserver<Integer>(); + Observable.merge(fast, slow).subscribe(to); + is.connect(); + to.awaitTerminalEvent(); + to.assertNoErrors(); + assertEquals(Flowable.bufferSize() * 4, to.valueCount()); + } + + // use case from https://github.com/ReactiveX/RxJava/issues/1732 + @Test + public void testTakeUntilWithPublishedStreamUsingSelector() { + final AtomicInteger emitted = new AtomicInteger(); + Observable<Integer> xs = Observable.range(0, Flowable.bufferSize() * 2).doOnNext(new Consumer<Integer>() { + + @Override + public void accept(Integer t1) { + emitted.incrementAndGet(); + } + + }); + TestObserver<Integer> to = new TestObserver<Integer>(); + xs.publish(new Function<Observable<Integer>, Observable<Integer>>() { + + @Override + public Observable<Integer> apply(Observable<Integer> xs) { + return xs.takeUntil(xs.skipWhile(new Predicate<Integer>() { + + @Override + public boolean test(Integer i) { + return i <= 3; + } + + })); + } + + }).subscribe(to); + to.awaitTerminalEvent(); + to.assertNoErrors(); + to.assertValues(0, 1, 2, 3); + assertEquals(5, emitted.get()); + System.out.println(to.values()); + } + + // use case from https://github.com/ReactiveX/RxJava/issues/1732 + @Test + public void testTakeUntilWithPublishedStream() { + Observable<Integer> xs = Observable.range(0, Flowable.bufferSize() * 2); + TestObserver<Integer> to = new TestObserver<Integer>(); + ConnectableObservable<Integer> xsp = xs.publish(); + xsp.takeUntil(xsp.skipWhile(new Predicate<Integer>() { + + @Override + public boolean test(Integer i) { + return i <= 3; + } + + })).subscribe(to); + xsp.connect(); + System.out.println(to.values()); + } + + @Test(timeout = 10000) + public void testBackpressureTwoConsumers() { + final AtomicInteger sourceEmission = new AtomicInteger(); + final AtomicBoolean sourceUnsubscribed = new AtomicBoolean(); + final Observable<Integer> source = Observable.range(1, 100) + .doOnNext(new Consumer<Integer>() { + @Override + public void accept(Integer t1) { + sourceEmission.incrementAndGet(); + } + }) + .doOnDispose(new Action() { + @Override + public void run() { + sourceUnsubscribed.set(true); + } + }).share(); + ; + + final AtomicBoolean child1Unsubscribed = new AtomicBoolean(); + final AtomicBoolean child2Unsubscribed = new AtomicBoolean(); + + final TestObserver<Integer> to2 = new TestObserver<Integer>(); + + final TestObserver<Integer> to1 = new TestObserver<Integer>() { + @Override + public void onNext(Integer t) { + if (valueCount() == 2) { + source.doOnDispose(new Action() { + @Override + public void run() { + child2Unsubscribed.set(true); + } + }).take(5).subscribe(to2); + } + super.onNext(t); + } + }; + + source.doOnDispose(new Action() { + @Override + public void run() { + child1Unsubscribed.set(true); + } + }).take(5) + .subscribe(to1); + + to1.awaitTerminalEvent(); + to2.awaitTerminalEvent(); + + to1.assertNoErrors(); + to2.assertNoErrors(); + + assertTrue(sourceUnsubscribed.get()); + assertTrue(child1Unsubscribed.get()); + assertTrue(child2Unsubscribed.get()); + + to1.assertValues(1, 2, 3, 4, 5); + to2.assertValues(4, 5, 6, 7, 8); + + assertEquals(8, sourceEmission.get()); + } + + @Test + public void testConnectWithNoSubscriber() { + TestScheduler scheduler = new TestScheduler(); + ConnectableObservable<Long> co = Observable.interval(10, 10, TimeUnit.MILLISECONDS, scheduler).take(3).publish(); + co.connect(); + // Emit 0 + scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); + TestObserver<Long> to = new TestObserver<Long>(); + co.subscribe(to); + // Emit 1 and 2 + scheduler.advanceTimeBy(50, TimeUnit.MILLISECONDS); + to.assertValues(1L, 2L); + to.assertNoErrors(); + to.assertTerminated(); + } + + @Test + public void testSubscribeAfterDisconnectThenConnect() { + ConnectableObservable<Integer> source = Observable.just(1).publish(); + + TestObserver<Integer> to1 = new TestObserver<Integer>(); + + source.subscribe(to1); + + Disposable connection = source.connect(); + + to1.assertValue(1); + to1.assertNoErrors(); + to1.assertTerminated(); + + TestObserver<Integer> to2 = new TestObserver<Integer>(); + + source.subscribe(to2); + + Disposable connection2 = source.connect(); + + to2.assertValue(1); + to2.assertNoErrors(); + to2.assertTerminated(); + + System.out.println(connection); + System.out.println(connection2); + } + + @Test + public void testNoSubscriberRetentionOnCompleted() { + ObservablePublish<Integer> source = (ObservablePublish<Integer>)Observable.just(1).publish(); + + TestObserver<Integer> to1 = new TestObserver<Integer>(); + + source.subscribe(to1); + + to1.assertNoValues(); + to1.assertNoErrors(); + to1.assertNotComplete(); + + source.connect(); + + to1.assertValue(1); + to1.assertNoErrors(); + to1.assertTerminated(); + + assertNull(source.current.get()); + } + + @Test + public void testNonNullConnection() { + ConnectableObservable<Object> source = Observable.never().publish(); + + assertNotNull(source.connect()); + assertNotNull(source.connect()); + } + + @Test + public void testNoDisconnectSomeoneElse() { + ConnectableObservable<Object> source = Observable.never().publish(); + + Disposable connection1 = source.connect(); + Disposable connection2 = source.connect(); + + connection1.dispose(); + + Disposable connection3 = source.connect(); + + connection2.dispose(); + + assertTrue(checkPublishDisposed(connection1)); + assertTrue(checkPublishDisposed(connection2)); + assertFalse(checkPublishDisposed(connection3)); + } + + @SuppressWarnings("unchecked") + static boolean checkPublishDisposed(Disposable d) { + return ((ObservablePublish.PublishObserver<Object>)d).isDisposed(); + } + + @Test + public void testConnectIsIdempotent() { + final AtomicInteger calls = new AtomicInteger(); + Observable<Integer> source = Observable.unsafeCreate(new ObservableSource<Integer>() { + @Override + public void subscribe(Observer<? super Integer> t) { + t.onSubscribe(Disposables.empty()); + calls.getAndIncrement(); + } + }); + + ConnectableObservable<Integer> conn = source.publish(); + + assertEquals(0, calls.get()); + + conn.connect(); + conn.connect(); + + assertEquals(1, calls.get()); + + conn.connect().dispose(); + + conn.connect(); + conn.connect(); + + assertEquals(2, calls.get()); + } + + @Test + public void testObserveOn() { + ConnectableObservable<Integer> co = Observable.range(0, 1000).publish(); + Observable<Integer> obs = co.observeOn(Schedulers.computation()); + for (int i = 0; i < 1000; i++) { + for (int j = 1; j < 6; j++) { + List<TestObserver<Integer>> tos = new ArrayList<TestObserver<Integer>>(); + for (int k = 1; k < j; k++) { + TestObserver<Integer> to = new TestObserver<Integer>(); + tos.add(to); + obs.subscribe(to); + } + + Disposable connection = co.connect(); + + for (TestObserver<Integer> to : tos) { + to.awaitTerminalEvent(2, TimeUnit.SECONDS); + to.assertTerminated(); + to.assertNoErrors(); + assertEquals(1000, to.valueCount()); + } + connection.dispose(); + } + } + } + + @Test + public void preNextConnect() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final ConnectableObservable<Integer> co = Observable.<Integer>empty().publish(); + + co.connect(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + co.test(); + } + }; + + TestHelper.race(r1, r1); + } + } + + @Test + public void connectRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final ConnectableObservable<Integer> co = Observable.<Integer>empty().publish(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + co.connect(); + } + }; + + TestHelper.race(r1, r1); + } + } + + @Test + public void selectorCrash() { + Observable.just(1).publish(new Function<Observable<Integer>, ObservableSource<Object>>() { + @Override + public ObservableSource<Object> apply(Observable<Integer> v) throws Exception { + throw new TestException(); + } + }) + .test() + .assertFailure(TestException.class); + } + + @Test + public void source() { + Observable<Integer> o = Observable.never(); + + assertSame(o, (((HasUpstreamObservableSource<?>)o.publish()).source())); + } + + @Test + public void connectThrows() { + ConnectableObservable<Integer> co = Observable.<Integer>empty().publish(); + try { + co.connect(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) throws Exception { + throw new TestException(); + } + }); + } catch (TestException ex) { + // expected + } + } + + @Test + public void addRemoveRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final ConnectableObservable<Integer> co = Observable.<Integer>empty().publish(); + + final TestObserver<Integer> to = co.test(); + + final TestObserver<Integer> to2 = new TestObserver<Integer>(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + co.subscribe(to2); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void disposeOnArrival() { + ConnectableObservable<Integer> co = Observable.<Integer>empty().publish(); + + co.test(true).assertEmpty(); + } + + @Test + public void dispose() { + TestHelper.checkDisposed(Observable.never().publish()); + + TestHelper.checkDisposed(Observable.never().publish(Functions.<Observable<Object>>identity())); + } + + @Test + public void empty() { + ConnectableObservable<Integer> co = Observable.<Integer>empty().publish(); + + co.connect(); + } + + @Test + public void take() { + ConnectableObservable<Integer> co = Observable.range(1, 2).publish(); + + TestObserver<Integer> to = co.take(1).test(); + + co.connect(); + + to.assertResult(1); + } + + @Test + public void just() { + final PublishSubject<Integer> ps = PublishSubject.create(); + + ConnectableObservable<Integer> co = ps.publish(); + + TestObserver<Integer> to = new TestObserver<Integer>() { + @Override + public void onNext(Integer t) { + super.onNext(t); + ps.onComplete(); + } + }; + + co.subscribe(to); + co.connect(); + + ps.onNext(1); + + to.assertResult(1); + } + + @Test + public void nextCancelRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final PublishSubject<Integer> ps = PublishSubject.create(); + + final ConnectableObservable<Integer> co = ps.publish(); + + final TestObserver<Integer> to = co.test(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + ps.onNext(1); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + to.cancel(); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void badSource() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new Observable<Integer>() { + @Override + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onNext(1); + observer.onComplete(); + observer.onNext(2); + observer.onError(new TestException()); + observer.onComplete(); + } + } + .publish() + .autoConnect() + .test() + .assertResult(1); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void noErrorLoss() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + ConnectableObservable<Object> co = Observable.error(new TestException()).publish(); + + co.connect(); + + TestHelper.assertUndeliverable(errors, 0, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void subscribeDisconnectRace() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + + final PublishSubject<Integer> ps = PublishSubject.create(); + + final ConnectableObservable<Integer> co = ps.publish(); + + final Disposable d = co.connect(); + final TestObserver<Integer> to = new TestObserver<Integer>(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + d.dispose(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + co.subscribe(to); + } + }; + + TestHelper.race(r1, r2); + } + } + + @Test + public void selectorDisconnectsIndependentSource() { + PublishSubject<Integer> ps = PublishSubject.create(); + + ps.publish(new Function<Observable<Integer>, ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> apply(Observable<Integer> v) throws Exception { + return Observable.range(1, 2); + } + }) + .test() + .assertResult(1, 2); + + assertFalse(ps.hasObservers()); + } + + @Test(timeout = 5000) + public void selectorLatecommer() { + Observable.range(1, 5) + .publish(new Function<Observable<Integer>, ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> apply(Observable<Integer> v) throws Exception { + return v.concatWith(v); + } + }) + .test() + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void mainError() { + Observable.error(new TestException()) + .publish(Functions.<Observable<Object>>identity()) + .test() + .assertFailure(TestException.class); + } + + @Test + public void selectorInnerError() { + PublishSubject<Integer> ps = PublishSubject.create(); + + ps.publish(new Function<Observable<Integer>, ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> apply(Observable<Integer> v) throws Exception { + return Observable.error(new TestException()); + } + }) + .test() + .assertFailure(TestException.class); + + assertFalse(ps.hasObservers()); + } + + @Test + public void delayedUpstreamOnSubscribe() { + final Observer<?>[] sub = { null }; + + new Observable<Integer>() { + @Override + protected void subscribeActual(Observer<? super Integer> observer) { + sub[0] = observer; + } + } + .publish() + .connect() + .dispose(); + + Disposable bs = Disposables.empty(); + + sub[0].onSubscribe(bs); + + assertTrue(bs.isDisposed()); + } + + @Test + public void doubleOnSubscribe() { + TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<Object>>() { + @Override + public ObservableSource<Object> apply(final Observable<Object> o) + throws Exception { + return Observable.<Integer>never().publish(new Function<Observable<Integer>, ObservableSource<Object>>() { + @Override + public ObservableSource<Object> apply(Observable<Integer> v) + throws Exception { + return o; + } + }); + } + } + ); + } + + @Test + public void disposedUpfront() { + ConnectableObservable<Integer> co = Observable.just(1) + .concatWith(Observable.<Integer>never()) + .publish(); + + TestObserver<Integer> to1 = co.test(); + + TestObserver<Integer> to2 = co.test(true); + + co.connect(); + + to1.assertValuesOnly(1); + + to2.assertEmpty(); + + ((ObservablePublish<Integer>)co).current.get().remove(null); + } + + @Test + public void altConnectCrash() { + try { + new ObservablePublishAlt<Integer>(Observable.<Integer>empty()) + .connect(new Consumer<Disposable>() { + @Override + public void accept(Disposable t) throws Exception { + throw new TestException(); + } + }); + fail("Should have thrown"); + } catch (TestException expected) { + // expected + } + } + + @Test + public void altConnectRace() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + final ConnectableObservable<Integer> co = + new ObservablePublishAlt<Integer>(Observable.<Integer>never()); + + Runnable r = new Runnable() { + @Override + public void run() { + co.connect(); + } + }; + + TestHelper.race(r, r); + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java index 2f2a0e677e..7534f07346 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java @@ -19,7 +19,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; -import org.junit.Test; +import org.junit.*; import io.reactivex.*; import io.reactivex.Observable; @@ -37,6 +37,27 @@ public class ObservablePublishTest { + // This will undo the workaround so that the plain ObservablePublish is still + // tested. + @Before + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void before() { + RxJavaPlugins.setOnConnectableObservableAssembly(new Function<ConnectableObservable, ConnectableObservable>() { + @Override + public ConnectableObservable apply(ConnectableObservable co) throws Exception { + if (co instanceof ObservablePublishAlt) { + return ObservablePublish.create(((ObservablePublishAlt)co).source()); + } + return co; + } + }); + } + + @After + public void after() { + RxJavaPlugins.setOnConnectableObservableAssembly(null); + } + @Test public void testPublish() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java new file mode 100644 index 0000000000..effe8ef206 --- /dev/null +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java @@ -0,0 +1,1394 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex.internal.operators.observable; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; + +import org.junit.Test; +import org.mockito.InOrder; + +import io.reactivex.*; +import io.reactivex.Observable; +import io.reactivex.Observer; +import io.reactivex.disposables.*; +import io.reactivex.exceptions.*; +import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.observable.ObservableRefCount.RefConnection; +import io.reactivex.internal.util.ExceptionHelper; +import io.reactivex.observables.ConnectableObservable; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.*; +import io.reactivex.subjects.*; + +public class ObservableRefCountAltTest { + + @Test + public void testRefCountAsync() { + final AtomicInteger subscribeCount = new AtomicInteger(); + final AtomicInteger nextCount = new AtomicInteger(); + Observable<Long> r = Observable.interval(0, 25, TimeUnit.MILLISECONDS) + .doOnSubscribe(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) { + subscribeCount.incrementAndGet(); + } + }) + .doOnNext(new Consumer<Long>() { + @Override + public void accept(Long l) { + nextCount.incrementAndGet(); + } + }) + .publish().refCount(); + + final AtomicInteger receivedCount = new AtomicInteger(); + Disposable d1 = r.subscribe(new Consumer<Long>() { + @Override + public void accept(Long l) { + receivedCount.incrementAndGet(); + } + }); + + Disposable d2 = r.subscribe(); + + // give time to emit + try { + Thread.sleep(260); + } catch (InterruptedException e) { + } + + // now unsubscribe + d2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one Observer getting a value but not the other + d1.dispose(); + + System.out.println("onNext: " + nextCount.get()); + + // should emit once for both subscribers + assertEquals(nextCount.get(), receivedCount.get()); + // only 1 subscribe + assertEquals(1, subscribeCount.get()); + } + + @Test + public void testRefCountSynchronous() { + final AtomicInteger subscribeCount = new AtomicInteger(); + final AtomicInteger nextCount = new AtomicInteger(); + Observable<Integer> r = Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9) + .doOnSubscribe(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) { + subscribeCount.incrementAndGet(); + } + }) + .doOnNext(new Consumer<Integer>() { + @Override + public void accept(Integer l) { + nextCount.incrementAndGet(); + } + }) + .publish().refCount(); + + final AtomicInteger receivedCount = new AtomicInteger(); + Disposable d1 = r.subscribe(new Consumer<Integer>() { + @Override + public void accept(Integer l) { + receivedCount.incrementAndGet(); + } + }); + + Disposable d2 = r.subscribe(); + + // give time to emit + try { + Thread.sleep(50); + } catch (InterruptedException e) { + } + + // now unsubscribe + d2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one Observer getting a value but not the other + d1.dispose(); + + System.out.println("onNext Count: " + nextCount.get()); + + // it will emit twice because it is synchronous + assertEquals(nextCount.get(), receivedCount.get() * 2); + // it will subscribe twice because it is synchronous + assertEquals(2, subscribeCount.get()); + } + + @Test + public void testRefCountSynchronousTake() { + final AtomicInteger nextCount = new AtomicInteger(); + Observable<Integer> r = Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9) + .doOnNext(new Consumer<Integer>() { + @Override + public void accept(Integer l) { + System.out.println("onNext --------> " + l); + nextCount.incrementAndGet(); + } + }) + .take(4) + .publish().refCount(); + + final AtomicInteger receivedCount = new AtomicInteger(); + r.subscribe(new Consumer<Integer>() { + @Override + public void accept(Integer l) { + receivedCount.incrementAndGet(); + } + }); + + System.out.println("onNext: " + nextCount.get()); + + assertEquals(4, receivedCount.get()); + assertEquals(4, receivedCount.get()); + } + + @Test + public void testRepeat() { + final AtomicInteger subscribeCount = new AtomicInteger(); + final AtomicInteger unsubscribeCount = new AtomicInteger(); + Observable<Long> r = Observable.interval(0, 1, TimeUnit.MILLISECONDS) + .doOnSubscribe(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) { + System.out.println("******************************* Subscribe received"); + // when we are subscribed + subscribeCount.incrementAndGet(); + } + }) + .doOnDispose(new Action() { + @Override + public void run() { + System.out.println("******************************* Unsubscribe received"); + // when we are unsubscribed + unsubscribeCount.incrementAndGet(); + } + }) + .publish().refCount(); + + for (int i = 0; i < 10; i++) { + TestObserver<Long> to1 = new TestObserver<Long>(); + TestObserver<Long> to2 = new TestObserver<Long>(); + r.subscribe(to1); + r.subscribe(to2); + try { + Thread.sleep(50); + } catch (InterruptedException e) { + } + to1.dispose(); + to2.dispose(); + to1.assertNoErrors(); + to2.assertNoErrors(); + assertTrue(to1.valueCount() > 0); + assertTrue(to2.valueCount() > 0); + } + + assertEquals(10, subscribeCount.get()); + assertEquals(10, unsubscribeCount.get()); + } + + @Test + public void testConnectUnsubscribe() throws InterruptedException { + final CountDownLatch unsubscribeLatch = new CountDownLatch(1); + final CountDownLatch subscribeLatch = new CountDownLatch(1); + + Observable<Long> o = synchronousInterval() + .doOnSubscribe(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) { + System.out.println("******************************* Subscribe received"); + // when we are subscribed + subscribeLatch.countDown(); + } + }) + .doOnDispose(new Action() { + @Override + public void run() { + System.out.println("******************************* Unsubscribe received"); + // when we are unsubscribed + unsubscribeLatch.countDown(); + } + }); + + TestObserver<Long> observer = new TestObserver<Long>(); + o.publish().refCount().subscribeOn(Schedulers.newThread()).subscribe(observer); + System.out.println("send unsubscribe"); + // wait until connected + subscribeLatch.await(); + // now unsubscribe + observer.dispose(); + System.out.println("DONE sending unsubscribe ... now waiting"); + if (!unsubscribeLatch.await(3000, TimeUnit.MILLISECONDS)) { + System.out.println("Errors: " + observer.errors()); + if (observer.errors().size() > 0) { + observer.errors().get(0).printStackTrace(); + } + fail("timed out waiting for unsubscribe"); + } + observer.assertNoErrors(); + } + + @Test + public void testConnectUnsubscribeRaceConditionLoop() throws InterruptedException { + for (int i = 0; i < 100; i++) { + testConnectUnsubscribeRaceCondition(); + } + } + + @Test + public void testConnectUnsubscribeRaceCondition() throws InterruptedException { + final AtomicInteger subUnsubCount = new AtomicInteger(); + Observable<Long> o = synchronousInterval() + .doOnDispose(new Action() { + @Override + public void run() { + System.out.println("******************************* Unsubscribe received"); + // when we are unsubscribed + subUnsubCount.decrementAndGet(); + } + }) + .doOnSubscribe(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) { + System.out.println("******************************* SUBSCRIBE received"); + subUnsubCount.incrementAndGet(); + } + }); + + TestObserver<Long> observer = new TestObserver<Long>(); + + o.publish().refCount().subscribeOn(Schedulers.computation()).subscribe(observer); + System.out.println("send unsubscribe"); + // now immediately unsubscribe while subscribeOn is racing to subscribe + observer.dispose(); + + // this generally will mean it won't even subscribe as it is already unsubscribed by the time connect() gets scheduled + // give time to the counter to update + Thread.sleep(10); + + // make sure we wait a bit in case the counter is still nonzero + int counter = 200; + while (subUnsubCount.get() != 0 && counter-- != 0) { + Thread.sleep(10); + } + // either we subscribed and then unsubscribed, or we didn't ever even subscribe + assertEquals(0, subUnsubCount.get()); + + System.out.println("DONE sending unsubscribe ... now waiting"); + System.out.println("Errors: " + observer.errors()); + if (observer.errors().size() > 0) { + observer.errors().get(0).printStackTrace(); + } + observer.assertNoErrors(); + } + + private Observable<Long> synchronousInterval() { + return Observable.unsafeCreate(new ObservableSource<Long>() { + @Override + public void subscribe(Observer<? super Long> observer) { + final AtomicBoolean cancel = new AtomicBoolean(); + observer.onSubscribe(Disposables.fromRunnable(new Runnable() { + @Override + public void run() { + cancel.set(true); + } + })); + for (;;) { + if (cancel.get()) { + break; + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + observer.onNext(1L); + } + } + }); + } + + @Test + public void onlyFirstShouldSubscribeAndLastUnsubscribe() { + final AtomicInteger subscriptionCount = new AtomicInteger(); + final AtomicInteger unsubscriptionCount = new AtomicInteger(); + Observable<Integer> o = Observable.unsafeCreate(new ObservableSource<Integer>() { + @Override + public void subscribe(Observer<? super Integer> observer) { + subscriptionCount.incrementAndGet(); + observer.onSubscribe(Disposables.fromRunnable(new Runnable() { + @Override + public void run() { + unsubscriptionCount.incrementAndGet(); + } + })); + } + }); + Observable<Integer> refCounted = o.publish().refCount(); + + Disposable first = refCounted.subscribe(); + assertEquals(1, subscriptionCount.get()); + + Disposable second = refCounted.subscribe(); + assertEquals(1, subscriptionCount.get()); + + first.dispose(); + assertEquals(0, unsubscriptionCount.get()); + + second.dispose(); + assertEquals(1, unsubscriptionCount.get()); + } + + @Test + public void testRefCount() { + TestScheduler s = new TestScheduler(); + Observable<Long> interval = Observable.interval(100, TimeUnit.MILLISECONDS, s).publish().refCount(); + + // subscribe list1 + final List<Long> list1 = new ArrayList<Long>(); + Disposable d1 = interval.subscribe(new Consumer<Long>() { + @Override + public void accept(Long t1) { + list1.add(t1); + } + }); + + s.advanceTimeBy(200, TimeUnit.MILLISECONDS); + + assertEquals(2, list1.size()); + assertEquals(0L, list1.get(0).longValue()); + assertEquals(1L, list1.get(1).longValue()); + + // subscribe list2 + final List<Long> list2 = new ArrayList<Long>(); + Disposable d2 = interval.subscribe(new Consumer<Long>() { + @Override + public void accept(Long t1) { + list2.add(t1); + } + }); + + s.advanceTimeBy(300, TimeUnit.MILLISECONDS); + + // list 1 should have 5 items + assertEquals(5, list1.size()); + assertEquals(2L, list1.get(2).longValue()); + assertEquals(3L, list1.get(3).longValue()); + assertEquals(4L, list1.get(4).longValue()); + + // list 2 should only have 3 items + assertEquals(3, list2.size()); + assertEquals(2L, list2.get(0).longValue()); + assertEquals(3L, list2.get(1).longValue()); + assertEquals(4L, list2.get(2).longValue()); + + // unsubscribe list1 + d1.dispose(); + + // advance further + s.advanceTimeBy(300, TimeUnit.MILLISECONDS); + + // list 1 should still have 5 items + assertEquals(5, list1.size()); + + // list 2 should have 6 items + assertEquals(6, list2.size()); + assertEquals(5L, list2.get(3).longValue()); + assertEquals(6L, list2.get(4).longValue()); + assertEquals(7L, list2.get(5).longValue()); + + // unsubscribe list2 + d2.dispose(); + + // advance further + s.advanceTimeBy(1000, TimeUnit.MILLISECONDS); + + // subscribing a new one should start over because the source should have been unsubscribed + // subscribe list3 + final List<Long> list3 = new ArrayList<Long>(); + interval.subscribe(new Consumer<Long>() { + @Override + public void accept(Long t1) { + list3.add(t1); + } + }); + + s.advanceTimeBy(200, TimeUnit.MILLISECONDS); + + assertEquals(2, list3.size()); + assertEquals(0L, list3.get(0).longValue()); + assertEquals(1L, list3.get(1).longValue()); + + } + + @Test + public void testAlreadyUnsubscribedClient() { + Observer<Integer> done = DisposingObserver.INSTANCE; + + Observer<Integer> o = TestHelper.mockObserver(); + + Observable<Integer> result = Observable.just(1).publish().refCount(); + + result.subscribe(done); + + result.subscribe(o); + + verify(o).onNext(1); + verify(o).onComplete(); + verify(o, never()).onError(any(Throwable.class)); + } + + @Test + public void testAlreadyUnsubscribedInterleavesWithClient() { + ReplaySubject<Integer> source = ReplaySubject.create(); + + Observer<Integer> done = DisposingObserver.INSTANCE; + + Observer<Integer> o = TestHelper.mockObserver(); + InOrder inOrder = inOrder(o); + + Observable<Integer> result = source.publish().refCount(); + + result.subscribe(o); + + source.onNext(1); + + result.subscribe(done); + + source.onNext(2); + source.onComplete(); + + inOrder.verify(o).onNext(1); + inOrder.verify(o).onNext(2); + inOrder.verify(o).onComplete(); + verify(o, never()).onError(any(Throwable.class)); + } + + @Test + public void testConnectDisconnectConnectAndSubjectState() { + Observable<Integer> o1 = Observable.just(10); + Observable<Integer> o2 = Observable.just(20); + Observable<Integer> combined = Observable.combineLatest(o1, o2, new BiFunction<Integer, Integer, Integer>() { + @Override + public Integer apply(Integer t1, Integer t2) { + return t1 + t2; + } + }) + .publish().refCount(); + + TestObserver<Integer> to1 = new TestObserver<Integer>(); + TestObserver<Integer> to2 = new TestObserver<Integer>(); + + combined.subscribe(to1); + combined.subscribe(to2); + + to1.assertTerminated(); + to1.assertNoErrors(); + to1.assertValue(30); + + to2.assertTerminated(); + to2.assertNoErrors(); + to2.assertValue(30); + } + + @Test(timeout = 10000) + public void testUpstreamErrorAllowsRetry() throws InterruptedException { + final AtomicInteger intervalSubscribed = new AtomicInteger(); + Observable<String> interval = + Observable.interval(200, TimeUnit.MILLISECONDS) + .doOnSubscribe(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) { + System.out.println("Subscribing to interval " + intervalSubscribed.incrementAndGet()); + } + } + ) + .flatMap(new Function<Long, Observable<String>>() { + @Override + public Observable<String> apply(Long t1) { + return Observable.defer(new Callable<Observable<String>>() { + @Override + public Observable<String> call() { + return Observable.<String>error(new Exception("Some exception")); + } + }); + } + }) + .onErrorResumeNext(new Function<Throwable, Observable<String>>() { + @Override + public Observable<String> apply(Throwable t1) { + return Observable.<String>error(t1); + } + }) + .publish() + .refCount(); + + interval + .doOnError(new Consumer<Throwable>() { + @Override + public void accept(Throwable t1) { + System.out.println("Observer 1 onError: " + t1); + } + }) + .retry(5) + .subscribe(new Consumer<String>() { + @Override + public void accept(String t1) { + System.out.println("Observer 1: " + t1); + } + }); + Thread.sleep(100); + interval + .doOnError(new Consumer<Throwable>() { + @Override + public void accept(Throwable t1) { + System.out.println("Observer 2 onError: " + t1); + } + }) + .retry(5) + .subscribe(new Consumer<String>() { + @Override + public void accept(String t1) { + System.out.println("Observer 2: " + t1); + } + }); + + Thread.sleep(1300); + + System.out.println(intervalSubscribed.get()); + assertEquals(6, intervalSubscribed.get()); + } + + private enum DisposingObserver implements Observer<Integer> { + INSTANCE; + + @Override + public void onSubscribe(Disposable d) { + d.dispose(); + } + + @Override + public void onNext(Integer t) { + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onComplete() { + } + } + + @Test + public void disposed() { + TestHelper.checkDisposed(Observable.just(1).publish().refCount()); + } + + @Test + public void noOpConnect() { + final int[] calls = { 0 }; + Observable<Integer> o = new ConnectableObservable<Integer>() { + @Override + public void connect(Consumer<? super Disposable> connection) { + calls[0]++; + } + + @Override + protected void subscribeActual(Observer<? super Integer> observer) { + observer.onSubscribe(Disposables.disposed()); + } + }.refCount(); + + o.test(); + o.test(); + + assertEquals(1, calls[0]); + } + Observable<Object> source; + + @Test + public void replayNoLeak() throws Exception { + System.gc(); + Thread.sleep(100); + + long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = Observable.fromCallable(new Callable<Object>() { + @Override + public Object call() throws Exception { + return new byte[100 * 1000 * 1000]; + } + }) + .replay(1) + .refCount(); + + source.subscribe(); + + System.gc(); + Thread.sleep(100); + + long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = null; + assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after); + } + + @Test + public void replayNoLeak2() throws Exception { + System.gc(); + Thread.sleep(100); + + long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = Observable.fromCallable(new Callable<Object>() { + @Override + public Object call() throws Exception { + return new byte[100 * 1000 * 1000]; + } + }).concatWith(Observable.never()) + .replay(1) + .refCount(); + + Disposable d1 = source.subscribe(); + Disposable d2 = source.subscribe(); + + d1.dispose(); + d2.dispose(); + + d1 = null; + d2 = null; + + System.gc(); + Thread.sleep(100); + + long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = null; + assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after); + } + + static final class ExceptionData extends Exception { + private static final long serialVersionUID = -6763898015338136119L; + + public final Object data; + + ExceptionData(Object data) { + this.data = data; + } + } + + @Test + public void publishNoLeak() throws Exception { + System.gc(); + Thread.sleep(100); + + long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = Observable.fromCallable(new Callable<Object>() { + @Override + public Object call() throws Exception { + throw new ExceptionData(new byte[100 * 1000 * 1000]); + } + }) + .publish() + .refCount(); + + source.subscribe(Functions.emptyConsumer(), Functions.emptyConsumer()); + + System.gc(); + Thread.sleep(100); + + long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = null; + assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after); + } + + @Test + public void publishNoLeak2() throws Exception { + System.gc(); + Thread.sleep(100); + + long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = Observable.fromCallable(new Callable<Object>() { + @Override + public Object call() throws Exception { + return new byte[100 * 1000 * 1000]; + } + }).concatWith(Observable.never()) + .publish() + .refCount(); + + Disposable d1 = source.test(); + Disposable d2 = source.test(); + + d1.dispose(); + d2.dispose(); + + d1 = null; + d2 = null; + + System.gc(); + Thread.sleep(100); + + long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + source = null; + assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after); + } + + @Test + public void replayIsUnsubscribed() { + ConnectableObservable<Integer> co = Observable.just(1).concatWith(Observable.<Integer>never()) + .replay(); + + if (co instanceof Disposable) { + assertTrue(((Disposable)co).isDisposed()); + + Disposable connection = co.connect(); + + assertFalse(((Disposable)co).isDisposed()); + + connection.dispose(); + + assertTrue(((Disposable)co).isDisposed()); + } + } + + static final class BadObservableSubscribe extends ConnectableObservable<Object> { + + @Override + public void connect(Consumer<? super Disposable> connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Observer<? super Object> observer) { + throw new TestException("subscribeActual"); + } + } + + static final class BadObservableDispose extends ConnectableObservable<Object> implements Disposable { + + @Override + public void dispose() { + throw new TestException("dispose"); + } + + @Override + public boolean isDisposed() { + return false; + } + + @Override + public void connect(Consumer<? super Disposable> connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + } + } + + static final class BadObservableConnect extends ConnectableObservable<Object> { + + @Override + public void connect(Consumer<? super Disposable> connection) { + throw new TestException("connect"); + } + + @Override + protected void subscribeActual(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + } + } + + @Test + public void badSourceSubscribe() { + BadObservableSubscribe bo = new BadObservableSubscribe(); + + try { + bo.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } + + @Test + public void badSourceDispose() { + BadObservableDispose bo = new BadObservableDispose(); + + try { + bo.refCount() + .test() + .cancel(); + fail("Should have thrown"); + } catch (TestException expected) { + } + } + + @Test + public void badSourceConnect() { + BadObservableConnect bo = new BadObservableConnect(); + + try { + bo.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } + + static final class BadObservableSubscribe2 extends ConnectableObservable<Object> { + + int count; + + @Override + public void connect(Consumer<? super Disposable> connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Observer<? super Object> observer) { + if (++count == 1) { + observer.onSubscribe(Disposables.empty()); + } else { + throw new TestException("subscribeActual"); + } + } + } + + @Test + public void badSourceSubscribe2() { + BadObservableSubscribe2 bo = new BadObservableSubscribe2(); + + Observable<Object> o = bo.refCount(); + o.test(); + try { + o.test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } + + static final class BadObservableConnect2 extends ConnectableObservable<Object> + implements Disposable { + + @Override + public void connect(Consumer<? super Disposable> connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); + } + + @Override + public void dispose() { + throw new TestException("dispose"); + } + + @Override + public boolean isDisposed() { + return false; + } + } + + @Test + public void badSourceCompleteDisconnect() { + BadObservableConnect2 bo = new BadObservableConnect2(); + + try { + bo.refCount() + .test(); + fail("Should have thrown"); + } catch (NullPointerException ex) { + assertTrue(ex.getCause() instanceof TestException); + } + } + + @Test(timeout = 7500) + public void blockingSourceAsnycCancel() throws Exception { + BehaviorSubject<Integer> bs = BehaviorSubject.createDefault(1); + + Observable<Integer> o = bs + .replay(1) + .refCount(); + + o.subscribe(); + + final AtomicBoolean interrupted = new AtomicBoolean(); + + o.switchMap(new Function<Integer, ObservableSource<? extends Object>>() { + @Override + public ObservableSource<? extends Object> apply(Integer v) throws Exception { + return Observable.create(new ObservableOnSubscribe<Object>() { + @Override + public void subscribe(ObservableEmitter<Object> emitter) throws Exception { + while (!emitter.isDisposed()) { + Thread.sleep(100); + } + interrupted.set(true); + } + }); + } + }) + .take(500, TimeUnit.MILLISECONDS) + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(); + + assertTrue(interrupted.get()); + } + + @Test + public void byCount() { + final int[] subscriptions = { 0 }; + + Observable<Integer> source = Observable.range(1, 5) + .doOnSubscribe(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .refCount(2); + + for (int i = 0; i < 3; i++) { + TestObserver<Integer> to1 = source.test(); + + to1.withTag("to1 " + i); + to1.assertEmpty(); + + TestObserver<Integer> to2 = source.test(); + + to2.withTag("to2 " + i); + + to1.assertResult(1, 2, 3, 4, 5); + to2.assertResult(1, 2, 3, 4, 5); + } + + assertEquals(3, subscriptions[0]); + } + + @Test + public void resubscribeBeforeTimeout() throws Exception { + final int[] subscriptions = { 0 }; + + PublishSubject<Integer> ps = PublishSubject.create(); + + Observable<Integer> source = ps + .doOnSubscribe(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .refCount(500, TimeUnit.MILLISECONDS); + + TestObserver<Integer> to1 = source.test(); + + assertEquals(1, subscriptions[0]); + + to1.cancel(); + + Thread.sleep(100); + + to1 = source.test(); + + assertEquals(1, subscriptions[0]); + + Thread.sleep(500); + + assertEquals(1, subscriptions[0]); + + ps.onNext(1); + ps.onNext(2); + ps.onNext(3); + ps.onNext(4); + ps.onNext(5); + ps.onComplete(); + + to1 + .assertResult(1, 2, 3, 4, 5); + } + + @Test + public void letitTimeout() throws Exception { + final int[] subscriptions = { 0 }; + + PublishSubject<Integer> ps = PublishSubject.create(); + + Observable<Integer> source = ps + .doOnSubscribe(new Consumer<Disposable>() { + @Override + public void accept(Disposable d) throws Exception { + subscriptions[0]++; + } + }) + .publish() + .refCount(1, 100, TimeUnit.MILLISECONDS); + + TestObserver<Integer> to1 = source.test(); + + assertEquals(1, subscriptions[0]); + + to1.cancel(); + + assertTrue(ps.hasObservers()); + + Thread.sleep(200); + + assertFalse(ps.hasObservers()); + } + + @Test + public void error() { + Observable.<Integer>error(new IOException()) + .publish() + .refCount(500, TimeUnit.MILLISECONDS) + .test() + .assertFailure(IOException.class); + } + + @Test + public void comeAndGo() { + PublishSubject<Integer> ps = PublishSubject.create(); + + Observable<Integer> source = ps + .publish() + .refCount(1); + + TestObserver<Integer> to1 = source.test(); + + assertTrue(ps.hasObservers()); + + for (int i = 0; i < 3; i++) { + TestObserver<Integer> to2 = source.test(); + to1.cancel(); + to1 = to2; + } + + to1.cancel(); + + assertFalse(ps.hasObservers()); + } + + @Test + public void unsubscribeSubscribeRace() { + for (int i = 0; i < 1000; i++) { + + final Observable<Integer> source = Observable.range(1, 5) + .replay() + .refCount(1) + ; + + final TestObserver<Integer> to1 = source.test(); + + final TestObserver<Integer> to2 = new TestObserver<Integer>(); + + Runnable r1 = new Runnable() { + @Override + public void run() { + to1.cancel(); + } + }; + + Runnable r2 = new Runnable() { + @Override + public void run() { + source.subscribe(to2); + } + }; + + TestHelper.race(r1, r2, Schedulers.single()); + + to2 + .withTag("Round: " + i) + .assertResult(1, 2, 3, 4, 5); + } + } + + static final class BadObservableDoubleOnX extends ConnectableObservable<Object> + implements Disposable { + + @Override + public void connect(Consumer<? super Disposable> connection) { + try { + connection.accept(Disposables.empty()); + } catch (Throwable ex) { + throw ExceptionHelper.wrapOrThrow(ex); + } + } + + @Override + protected void subscribeActual(Observer<? super Object> observer) { + observer.onSubscribe(Disposables.empty()); + observer.onSubscribe(Disposables.empty()); + observer.onComplete(); + observer.onComplete(); + observer.onError(new TestException()); + } + + @Override + public void dispose() { + } + + @Override + public boolean isDisposed() { + return false; + } + } + + @Test + public void doubleOnX() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new BadObservableDoubleOnX() + .refCount() + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void doubleOnXCount() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new BadObservableDoubleOnX() + .refCount(1) + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void doubleOnXTime() { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + new BadObservableDoubleOnX() + .refCount(5, TimeUnit.SECONDS, Schedulers.single()) + .test() + .assertResult(); + + TestHelper.assertError(errors, 0, ProtocolViolationException.class); + TestHelper.assertUndeliverable(errors, 1, TestException.class); + } finally { + RxJavaPlugins.reset(); + } + } + + @Test + public void cancelTerminateStateExclusion() { + ObservableRefCount<Object> o = (ObservableRefCount<Object>)PublishSubject.create() + .publish() + .refCount(); + + o.cancel(null); + + o.cancel(new RefConnection(o)); + + RefConnection rc = new RefConnection(o); + o.connection = null; + rc.subscriberCount = 0; + o.timeout(rc); + + rc.subscriberCount = 1; + o.timeout(rc); + + o.connection = rc; + o.timeout(rc); + + rc.subscriberCount = 0; + o.timeout(rc); + + // ------------------- + + rc.subscriberCount = 2; + rc.connected = false; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 1; + rc.connected = false; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 2; + rc.connected = true; + o.connection = rc; + o.cancel(rc); + + rc.subscriberCount = 1; + rc.connected = true; + o.connection = rc; + rc.lazySet(null); + o.cancel(rc); + + o.connection = rc; + o.cancel(new RefConnection(o)); + } + + @Test + public void replayRefCountShallBeThreadSafe() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + Observable<Integer> observable = Observable.just(1).replay(1).refCount(); + + TestObserver<Integer> observer1 = observable + .subscribeOn(Schedulers.io()) + .test(); + + TestObserver<Integer> observer2 = observable + .subscribeOn(Schedulers.io()) + .test(); + + observer1 + .withTag("" + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + observer2 + .withTag("" + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + } + } + + static final class TestConnectableObservable<T> extends ConnectableObservable<T> + implements Disposable { + + volatile boolean disposed; + + @Override + public void dispose() { + disposed = true; + } + + @Override + public boolean isDisposed() { + return disposed; + } + + @Override + public void connect(Consumer<? super Disposable> connection) { + // not relevant + } + + @Override + protected void subscribeActual(Observer<? super T> observer) { + // not relevant + } + } + + @Test + public void timeoutDisposesSource() { + ObservableRefCount<Object> o = (ObservableRefCount<Object>)new TestConnectableObservable<Object>().refCount(); + + RefConnection rc = new RefConnection(o); + o.connection = rc; + + o.timeout(rc); + + assertTrue(((Disposable)o.source).isDisposed()); + } + + @Test + public void disconnectBeforeConnect() { + BehaviorSubject<Integer> subject = BehaviorSubject.create(); + + Observable<Integer> observable = subject + .replay(1) + .refCount(); + + observable.takeUntil(Observable.just(1)).test(); + + subject.onNext(2); + + observable.take(1).test().assertResult(2); + } + + @Test + public void publishRefCountShallBeThreadSafe() { + for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { + Observable<Integer> observable = Observable.just(1).publish().refCount(); + + TestObserver<Integer> observer1 = observable + .subscribeOn(Schedulers.io()) + .test(); + + TestObserver<Integer> observer2 = observable + .subscribeOn(Schedulers.io()) + .test(); + + observer1 + .withTag("observer1 " + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertNoErrors() + .assertComplete(); + + observer2 + .withTag("observer2 " + i) + .awaitDone(5, TimeUnit.SECONDS) + .assertNoErrors() + .assertComplete(); + } + } +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index 0f0d930d8d..48a9ff2d5a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -23,7 +23,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; -import org.junit.Test; +import org.junit.*; import org.mockito.InOrder; import io.reactivex.*; @@ -43,6 +43,27 @@ public class ObservableRefCountTest { + // This will undo the workaround so that the plain ObservablePublish is still + // tested. + @Before + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void before() { + RxJavaPlugins.setOnConnectableObservableAssembly(new Function<ConnectableObservable, ConnectableObservable>() { + @Override + public ConnectableObservable apply(ConnectableObservable co) throws Exception { + if (co instanceof ObservablePublishAlt) { + return ObservablePublish.create(((ObservablePublishAlt)co).source()); + } + return co; + } + }); + } + + @After + public void after() { + RxJavaPlugins.setOnConnectableObservableAssembly(null); + } + @Test public void testRefCountAsync() { final AtomicInteger subscribeCount = new AtomicInteger(); From 0df3285af53be02dedeabbcded56fc789b554b58 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 21 Jun 2019 07:33:56 +0200 Subject: [PATCH 371/417] Release 2.2.10 --- CHANGES.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 7a5a441cea..df4bd2c840 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,22 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.10 - June 21, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.10%7C)) + +#### Bugfixes + + - [Pull 6499](https://github.com/ReactiveX/RxJava/pull/6499): Add missing null check to `BufferExactBoundedObserver`. + - [Pull 6505](https://github.com/ReactiveX/RxJava/pull/6505): Fix `publish().refCount()` hang due to race. + - [Pull 6522](https://github.com/ReactiveX/RxJava/pull/6522): Fix `concatMapDelayError` not continuing on fused inner source crash. + +#### Documentation changes + + - [Pull 6496](https://github.com/ReactiveX/RxJava/pull/6496): Fix outdated links in `Additional-Reading.md`. + - [Pull 6497](https://github.com/ReactiveX/RxJava/pull/6497): Fix links in `Alphabetical-List-of-Observable-Operators.md`. + - [Pull 6504](https://github.com/ReactiveX/RxJava/pull/6504): Fix various Javadocs & imports. + - [Pull 6506](https://github.com/ReactiveX/RxJava/pull/6506): Expand the Javadoc of `Flowable`. + - [Pull 6510](https://github.com/ReactiveX/RxJava/pull/6510): Correct "Reactive-Streams" to "Reactive Streams" in documentation. + ### Version 2.2.9 - May 30, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.9%7C)) #### Bugfixes From 0f4a3b981ac3efc4d4e7b03093202ade810132b9 Mon Sep 17 00:00:00 2001 From: jimin <slievrly@163.com> Date: Thu, 27 Jun 2019 23:00:04 +0800 Subject: [PATCH 372/417] simplify junit (#6546) --- src/test/java/io/reactivex/NotificationTest.java | 6 +++--- .../reactivex/completable/CompletableTest.java | 2 +- .../io/reactivex/exceptions/OnNextValueTest.java | 2 +- .../reactivex/flowable/FlowableMergeTests.java | 4 ++-- .../flowable/FlowableNotificationTest.java | 16 ++++++++-------- .../flowable/BlockingFlowableLatestTest.java | 12 ++++++------ .../flowable/BlockingFlowableMostRecentTest.java | 6 +++--- .../flowable/BlockingFlowableNextTest.java | 2 +- .../flowable/BlockingFlowableToFutureTest.java | 2 +- .../flowable/BlockingFlowableToIteratorTest.java | 12 ++++++------ .../FlowableOnBackpressureBufferTest.java | 2 +- .../flowable/FlowableUnsubscribeOnTest.java | 2 +- .../observable/BlockingObservableLatestTest.java | 12 ++++++------ .../BlockingObservableMostRecentTest.java | 6 +++--- .../observable/BlockingObservableNextTest.java | 2 +- .../BlockingObservableToFutureTest.java | 2 +- .../BlockingObservableToIteratorTest.java | 12 ++++++------ .../observable/ObservableGroupByTest.java | 2 +- .../observable/ObservableUnsubscribeOnTest.java | 2 +- .../internal/util/NotificationLiteTest.java | 2 +- .../internal/util/VolatileSizeArrayListTest.java | 16 ++++++++-------- .../observable/ObservableMergeTests.java | 4 ++-- .../io/reactivex/plugins/RxJavaPluginsTest.java | 2 +- .../processors/ReplayProcessorTest.java | 2 +- .../processors/UnicastProcessorTest.java | 12 ++++++------ .../AbstractSchedulerConcurrencyTests.java | 2 +- .../schedulers/ComputationSchedulerTests.java | 2 +- .../java/io/reactivex/schedulers/TimedTest.java | 2 +- .../schedulers/TrampolineSchedulerTest.java | 2 +- .../io/reactivex/subjects/ReplaySubjectTest.java | 2 +- .../reactivex/subjects/UnicastSubjectTest.java | 12 ++++++------ 31 files changed, 83 insertions(+), 83 deletions(-) diff --git a/src/test/java/io/reactivex/NotificationTest.java b/src/test/java/io/reactivex/NotificationTest.java index c3283edd3c..504c0425bc 100644 --- a/src/test/java/io/reactivex/NotificationTest.java +++ b/src/test/java/io/reactivex/NotificationTest.java @@ -41,11 +41,11 @@ public void valueOfOnCompleteIsNull() { @Test public void notEqualsToObject() { Notification<Integer> n1 = Notification.createOnNext(0); - assertFalse(n1.equals(0)); + assertNotEquals(0, n1); Notification<Integer> n2 = Notification.createOnError(new TestException()); - assertFalse(n2.equals(0)); + assertNotEquals(0, n2); Notification<Integer> n3 = Notification.createOnComplete(); - assertFalse(n3.equals(0)); + assertNotEquals(0, n3); } @Test diff --git a/src/test/java/io/reactivex/completable/CompletableTest.java b/src/test/java/io/reactivex/completable/CompletableTest.java index 80f4b49d5a..3fda12b46e 100644 --- a/src/test/java/io/reactivex/completable/CompletableTest.java +++ b/src/test/java/io/reactivex/completable/CompletableTest.java @@ -4326,7 +4326,7 @@ public boolean test(Throwable t) { Assert.assertEquals(2, errors.size()); Assert.assertTrue(errors.get(0).toString(), errors.get(0) instanceof TestException); - Assert.assertEquals(errors.get(0).toString(), null, errors.get(0).getMessage()); + Assert.assertNull(errors.get(0).toString(), errors.get(0).getMessage()); Assert.assertTrue(errors.get(1).toString(), errors.get(1) instanceof TestException); Assert.assertEquals(errors.get(1).toString(), "Forced inner failure", errors.get(1).getMessage()); } diff --git a/src/test/java/io/reactivex/exceptions/OnNextValueTest.java b/src/test/java/io/reactivex/exceptions/OnNextValueTest.java index 6e0541436b..c0d9df5981 100644 --- a/src/test/java/io/reactivex/exceptions/OnNextValueTest.java +++ b/src/test/java/io/reactivex/exceptions/OnNextValueTest.java @@ -71,7 +71,7 @@ public void onError(Throwable e) { assertTrue(trace, trace.contains("OnNextValue")); - assertTrue("No Cause on throwable" + e, e.getCause() != null); + assertNotNull("No Cause on throwable" + e, e.getCause()); // assertTrue(e.getCause().getClass().getSimpleName() + " no OnNextValue", // e.getCause() instanceof OnErrorThrowable.OnNextValue); } diff --git a/src/test/java/io/reactivex/flowable/FlowableMergeTests.java b/src/test/java/io/reactivex/flowable/FlowableMergeTests.java index 5c96bcf096..5facc6665f 100644 --- a/src/test/java/io/reactivex/flowable/FlowableMergeTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableMergeTests.java @@ -69,7 +69,7 @@ public void testMergeCovariance3() { assertTrue(values.get(0) instanceof HorrorMovie); assertTrue(values.get(1) instanceof Movie); - assertTrue(values.get(2) != null); + assertNotNull(values.get(2)); assertTrue(values.get(3) instanceof HorrorMovie); } @@ -92,7 +92,7 @@ public Publisher<Movie> call() { assertTrue(values.get(0) instanceof HorrorMovie); assertTrue(values.get(1) instanceof Movie); - assertTrue(values.get(2) != null); + assertNotNull(values.get(2)); assertTrue(values.get(3) instanceof HorrorMovie); } diff --git a/src/test/java/io/reactivex/flowable/FlowableNotificationTest.java b/src/test/java/io/reactivex/flowable/FlowableNotificationTest.java index e068cb7399..37b79676d3 100644 --- a/src/test/java/io/reactivex/flowable/FlowableNotificationTest.java +++ b/src/test/java/io/reactivex/flowable/FlowableNotificationTest.java @@ -23,28 +23,28 @@ public class FlowableNotificationTest { public void testOnNextIntegerNotificationDoesNotEqualNullNotification() { final Notification<Integer> integerNotification = Notification.createOnNext(1); final Notification<Integer> nullNotification = Notification.createOnNext(null); - Assert.assertFalse(integerNotification.equals(nullNotification)); + Assert.assertNotEquals(integerNotification, nullNotification); } @Test(expected = NullPointerException.class) public void testOnNextNullNotificationDoesNotEqualIntegerNotification() { final Notification<Integer> integerNotification = Notification.createOnNext(1); final Notification<Integer> nullNotification = Notification.createOnNext(null); - Assert.assertFalse(nullNotification.equals(integerNotification)); + Assert.assertNotEquals(nullNotification, integerNotification); } @Test public void testOnNextIntegerNotificationsWhenEqual() { final Notification<Integer> integerNotification = Notification.createOnNext(1); final Notification<Integer> integerNotification2 = Notification.createOnNext(1); - Assert.assertTrue(integerNotification.equals(integerNotification2)); + Assert.assertEquals(integerNotification, integerNotification2); } @Test public void testOnNextIntegerNotificationsWhenNotEqual() { final Notification<Integer> integerNotification = Notification.createOnNext(1); final Notification<Integer> integerNotification2 = Notification.createOnNext(2); - Assert.assertFalse(integerNotification.equals(integerNotification2)); + Assert.assertNotEquals(integerNotification, integerNotification2); } @Test @@ -52,7 +52,7 @@ public void testOnNextIntegerNotificationsWhenNotEqual() { public void testOnErrorIntegerNotificationDoesNotEqualNullNotification() { final Notification<Integer> integerNotification = Notification.createOnError(new Exception()); final Notification<Integer> nullNotification = Notification.createOnError(null); - Assert.assertFalse(integerNotification.equals(nullNotification)); + Assert.assertNotEquals(integerNotification, nullNotification); } @Test @@ -60,7 +60,7 @@ public void testOnErrorIntegerNotificationDoesNotEqualNullNotification() { public void testOnErrorNullNotificationDoesNotEqualIntegerNotification() { final Notification<Integer> integerNotification = Notification.createOnError(new Exception()); final Notification<Integer> nullNotification = Notification.createOnError(null); - Assert.assertFalse(nullNotification.equals(integerNotification)); + Assert.assertNotEquals(nullNotification, integerNotification); } @Test @@ -68,13 +68,13 @@ public void testOnErrorIntegerNotificationsWhenEqual() { final Exception exception = new Exception(); final Notification<Integer> onErrorNotification = Notification.createOnError(exception); final Notification<Integer> onErrorNotification2 = Notification.createOnError(exception); - Assert.assertTrue(onErrorNotification.equals(onErrorNotification2)); + Assert.assertEquals(onErrorNotification, onErrorNotification2); } @Test public void testOnErrorIntegerNotificationWhenNotEqual() { final Notification<Integer> onErrorNotification = Notification.createOnError(new Exception()); final Notification<Integer> onErrorNotification2 = Notification.createOnError(new Exception()); - Assert.assertFalse(onErrorNotification.equals(onErrorNotification2)); + Assert.assertNotEquals(onErrorNotification, onErrorNotification2); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableLatestTest.java index 92dcd3dd02..a0249db01e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableLatestTest.java @@ -43,13 +43,13 @@ public void testSimple() { for (int i = 0; i < 9; i++) { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(true, it.hasNext()); + Assert.assertTrue(it.hasNext()); Assert.assertEquals(Long.valueOf(i), it.next()); } scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(false, it.hasNext()); + Assert.assertFalse(it.hasNext()); } @Test(timeout = 1000) @@ -68,13 +68,13 @@ public void testSameSourceMultipleIterators() { for (int i = 0; i < 9; i++) { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(true, it.hasNext()); + Assert.assertTrue(it.hasNext()); Assert.assertEquals(Long.valueOf(i), it.next()); } scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(false, it.hasNext()); + Assert.assertFalse(it.hasNext()); } } @@ -86,7 +86,7 @@ public void testEmpty() { Iterator<Long> it = iter.iterator(); - Assert.assertEquals(false, it.hasNext()); + Assert.assertFalse(it.hasNext()); it.next(); } @@ -165,7 +165,7 @@ public void testFasterSource() { source.onNext(7); source.onComplete(); - Assert.assertEquals(false, it.hasNext()); + Assert.assertFalse(it.hasNext()); } @Ignore("THe target is an enum") diff --git a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecentTest.java b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecentTest.java index 26e6eb5716..70a43694d4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecentTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecentTest.java @@ -28,7 +28,7 @@ public class BlockingFlowableMostRecentTest { @Test public void testMostRecentNull() { - assertEquals(null, Flowable.<Void>never().blockingMostRecent(null).iterator().next()); + assertNull(Flowable.<Void>never().blockingMostRecent(null).iterator().next()); } @Test @@ -87,12 +87,12 @@ public void testSingleSourceManyIterators() { for (int i = 0; i < 9; i++) { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(true, it.hasNext()); + Assert.assertTrue(it.hasNext()); Assert.assertEquals(Long.valueOf(i), it.next()); } scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(false, it.hasNext()); + Assert.assertFalse(it.hasNext()); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableNextTest.java b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableNextTest.java index 32ee150cf3..e2e2cc4337 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableNextTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableNextTest.java @@ -318,7 +318,7 @@ public void testSingleSourceManyIterators() throws InterruptedException { BlockingFlowableNext.NextIterator<Long> it = (BlockingFlowableNext.NextIterator<Long>)iter.iterator(); for (long i = 0; i < 10; i++) { - Assert.assertEquals(true, it.hasNext()); + Assert.assertTrue(it.hasNext()); Assert.assertEquals(j + "th iteration next", Long.valueOf(i), it.next()); } terminal.onNext(1); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToFutureTest.java b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToFutureTest.java index d90b0b2f43..c1363a452b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToFutureTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToFutureTest.java @@ -120,6 +120,6 @@ public void testGetWithEmptyFlowable() throws Throwable { public void testGetWithASingleNullItem() throws Exception { Flowable<String> obs = Flowable.just((String)null); Future<String> f = obs.toFuture(); - assertEquals(null, f.get()); + assertNull(f.get()); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java index 412d59ac5f..df3fe6d62c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java @@ -33,16 +33,16 @@ public void testToIterator() { Iterator<String> it = obs.blockingIterable().iterator(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals("one", it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals("two", it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals("three", it.next()); - assertEquals(false, it.hasNext()); + assertFalse(it.hasNext()); } @@ -60,10 +60,10 @@ public void subscribe(Subscriber<? super String> subscriber) { Iterator<String> it = obs.blockingIterable().iterator(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals("one", it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); it.next(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java index 84793d3136..f44fbc8353 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java @@ -143,7 +143,7 @@ public void run() { int size = ts.values().size(); assertTrue(size <= 150); // will get up to 50 more - assertTrue(ts.values().get(size - 1) == size - 1); + assertEquals((long)ts.values().get(size - 1), size - 1); } static final Flowable<Long> infinite = Flowable.unsafeCreate(new Publisher<Long>() { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java index cd6f22ea56..36112023bb 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java @@ -73,7 +73,7 @@ public void subscribe(Subscriber<? super Integer> t1) { System.out.println("unsubscribeThread: " + unsubscribeThread); System.out.println("subscribeThread.get(): " + subscribeThread.get()); - assertTrue(unsubscribeThread == uiEventLoop.getThread()); + assertSame(unsubscribeThread, uiEventLoop.getThread()); ts.assertValues(1, 2); ts.assertTerminated(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableLatestTest.java b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableLatestTest.java index cdd95c58f2..27aa27ec2d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableLatestTest.java @@ -44,13 +44,13 @@ public void testSimple() { for (int i = 0; i < 9; i++) { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(true, it.hasNext()); + Assert.assertTrue(it.hasNext()); Assert.assertEquals(Long.valueOf(i), it.next()); } scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(false, it.hasNext()); + Assert.assertFalse(it.hasNext()); } @Test(timeout = 1000) @@ -69,13 +69,13 @@ public void testSameSourceMultipleIterators() { for (int i = 0; i < 9; i++) { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(true, it.hasNext()); + Assert.assertTrue(it.hasNext()); Assert.assertEquals(Long.valueOf(i), it.next()); } scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(false, it.hasNext()); + Assert.assertFalse(it.hasNext()); } } @@ -87,7 +87,7 @@ public void testEmpty() { Iterator<Long> it = iter.iterator(); - Assert.assertEquals(false, it.hasNext()); + Assert.assertFalse(it.hasNext()); it.next(); } @@ -166,7 +166,7 @@ public void testFasterSource() { source.onNext(7); source.onComplete(); - Assert.assertEquals(false, it.hasNext()); + Assert.assertFalse(it.hasNext()); } @Test(expected = UnsupportedOperationException.class) diff --git a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecentTest.java b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecentTest.java index 5a277d6ddd..a109beb2d7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecentTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecentTest.java @@ -28,7 +28,7 @@ public class BlockingObservableMostRecentTest { @Test public void testMostRecentNull() { - assertEquals(null, Observable.<Void>never().blockingMostRecent(null).iterator().next()); + assertNull(Observable.<Void>never().blockingMostRecent(null).iterator().next()); } static <T> Iterable<T> mostRecent(Observable<T> source, T initialValue) { @@ -91,12 +91,12 @@ public void testSingleSourceManyIterators() { for (int i = 0; i < 9; i++) { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(true, it.hasNext()); + Assert.assertTrue(it.hasNext()); Assert.assertEquals(Long.valueOf(i), it.next()); } scheduler.advanceTimeBy(1, TimeUnit.SECONDS); - Assert.assertEquals(false, it.hasNext()); + Assert.assertFalse(it.hasNext()); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableNextTest.java b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableNextTest.java index 2b8e670c16..947a2a027d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableNextTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableNextTest.java @@ -323,7 +323,7 @@ public void testSingleSourceManyIterators() throws InterruptedException { BlockingObservableNext.NextIterator<Long> it = (BlockingObservableNext.NextIterator<Long>)iter.iterator(); for (long i = 0; i < 10; i++) { - Assert.assertEquals(true, it.hasNext()); + Assert.assertTrue(it.hasNext()); Assert.assertEquals(j + "th iteration next", Long.valueOf(i), it.next()); } terminal.onNext(1); diff --git a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToFutureTest.java b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToFutureTest.java index f4fa707ee4..632d3dad72 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToFutureTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToFutureTest.java @@ -121,6 +121,6 @@ public void testGetWithEmptyFlowable() throws Throwable { public void testGetWithASingleNullItem() throws Exception { Observable<String> obs = Observable.just((String)null); Future<String> f = obs.toFuture(); - assertEquals(null, f.get()); + assertNull(f.get()); } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToIteratorTest.java b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToIteratorTest.java index af22e83993..f79b2a294d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToIteratorTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToIteratorTest.java @@ -34,16 +34,16 @@ public void testToIterator() { Iterator<String> it = obs.blockingIterable().iterator(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals("one", it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals("two", it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals("three", it.next()); - assertEquals(false, it.hasNext()); + assertFalse(it.hasNext()); } @@ -61,10 +61,10 @@ public void subscribe(Observer<? super String> observer) { Iterator<String> it = obs.blockingIterable().iterator(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals("one", it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); it.next(); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java index 42f441bd10..31bb5cf6a0 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java @@ -1364,7 +1364,7 @@ public void accept(String s) { }); } }); - assertEquals(null, key[0]); + assertNull(key[0]); assertEquals(Arrays.asList("a", "b", "c"), values); } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java index 2b7d7f4141..1067ff37c9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java @@ -72,7 +72,7 @@ public void subscribe(Observer<? super Integer> t1) { System.out.println("unsubscribeThread: " + unsubscribeThread); System.out.println("subscribeThread.get(): " + subscribeThread.get()); - assertTrue(unsubscribeThread.toString(), unsubscribeThread == uiEventLoop.getThread()); + assertSame(unsubscribeThread.toString(), unsubscribeThread, uiEventLoop.getThread()); observer.assertValues(1, 2); observer.assertTerminated(); diff --git a/src/test/java/io/reactivex/internal/util/NotificationLiteTest.java b/src/test/java/io/reactivex/internal/util/NotificationLiteTest.java index 36bfe52566..f6e463c7da 100644 --- a/src/test/java/io/reactivex/internal/util/NotificationLiteTest.java +++ b/src/test/java/io/reactivex/internal/util/NotificationLiteTest.java @@ -45,6 +45,6 @@ public void errorNotificationCompare() { assertEquals(ex.hashCode(), n1.hashCode()); - assertFalse(n1.equals(NotificationLite.complete())); + assertNotEquals(n1, NotificationLite.complete()); } } diff --git a/src/test/java/io/reactivex/internal/util/VolatileSizeArrayListTest.java b/src/test/java/io/reactivex/internal/util/VolatileSizeArrayListTest.java index 6086fff7e3..00d3119b32 100644 --- a/src/test/java/io/reactivex/internal/util/VolatileSizeArrayListTest.java +++ b/src/test/java/io/reactivex/internal/util/VolatileSizeArrayListTest.java @@ -82,22 +82,22 @@ public void normal() { VolatileSizeArrayList<Integer> list2 = new VolatileSizeArrayList<Integer>(); list2.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)); - assertFalse(list2.equals(list)); - assertFalse(list.equals(list2)); + assertNotEquals(list2, list); + assertNotEquals(list, list2); list2.add(7); - assertTrue(list2.equals(list)); - assertTrue(list.equals(list2)); + assertEquals(list2, list); + assertEquals(list, list2); List<Integer> list3 = new ArrayList<Integer>(); list3.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)); - assertFalse(list3.equals(list)); - assertFalse(list.equals(list3)); + assertNotEquals(list3, list); + assertNotEquals(list, list3); list3.add(7); - assertTrue(list3.equals(list)); - assertTrue(list.equals(list3)); + assertEquals(list3, list); + assertEquals(list, list3); assertEquals(list.hashCode(), list3.hashCode()); assertEquals(list.toString(), list3.toString()); diff --git a/src/test/java/io/reactivex/observable/ObservableMergeTests.java b/src/test/java/io/reactivex/observable/ObservableMergeTests.java index c7ee01c591..1d68a5d28e 100644 --- a/src/test/java/io/reactivex/observable/ObservableMergeTests.java +++ b/src/test/java/io/reactivex/observable/ObservableMergeTests.java @@ -68,7 +68,7 @@ public void testMergeCovariance3() { assertTrue(values.get(0) instanceof HorrorMovie); assertTrue(values.get(1) instanceof Movie); - assertTrue(values.get(2) != null); + assertNotNull(values.get(2)); assertTrue(values.get(3) instanceof HorrorMovie); } @@ -91,7 +91,7 @@ public Observable<Movie> call() { assertTrue(values.get(0) instanceof HorrorMovie); assertTrue(values.get(1) instanceof Movie); - assertTrue(values.get(2) != null); + assertNotNull(values.get(2)); assertTrue(values.get(3) instanceof HorrorMovie); } diff --git a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java index efd4642d7e..229dc7c873 100644 --- a/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java +++ b/src/test/java/io/reactivex/plugins/RxJavaPluginsTest.java @@ -2070,7 +2070,7 @@ public void run() { Thread t = value.get(); assertNotNull(t); - assertTrue(expectedThreadName.equals(t.getName())); + assertEquals(expectedThreadName, t.getName()); } catch (Exception e) { fail(); } finally { diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index cf930b062a..7ecc2bea31 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -1051,7 +1051,7 @@ public void peekStateTimeAndSizeValueExpired() { scheduler.advanceTimeBy(2, TimeUnit.DAYS); - assertEquals(null, rp.getValue()); + assertNull(rp.getValue()); assertEquals(0, rp.getValues().length); assertNull(rp.getValues(new Integer[2])[0]); } diff --git a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java index 5bbe6dca75..84335845a9 100644 --- a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java @@ -132,9 +132,9 @@ public void onTerminateCalledWhenOnError() { } }); - assertEquals(false, didRunOnTerminate.get()); + assertFalse(didRunOnTerminate.get()); us.onError(new RuntimeException("some error")); - assertEquals(true, didRunOnTerminate.get()); + assertTrue(didRunOnTerminate.get()); } @Test @@ -147,9 +147,9 @@ public void onTerminateCalledWhenOnComplete() { } }); - assertEquals(false, didRunOnTerminate.get()); + assertFalse(didRunOnTerminate.get()); us.onComplete(); - assertEquals(true, didRunOnTerminate.get()); + assertTrue(didRunOnTerminate.get()); } @Test @@ -164,9 +164,9 @@ public void onTerminateCalledWhenCanceled() { final Disposable subscribe = us.subscribe(); - assertEquals(false, didRunOnTerminate.get()); + assertFalse(didRunOnTerminate.get()); subscribe.dispose(); - assertEquals(true, didRunOnTerminate.get()); + assertTrue(didRunOnTerminate.get()); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java b/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java index 3605c74679..af489f5650 100644 --- a/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java +++ b/src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java @@ -405,7 +405,7 @@ public void accept(Integer t) { throw new RuntimeException("The latch should have released if we are async.", e); } - assertFalse(Thread.currentThread().getName().equals(currentThreadName)); + assertNotEquals(Thread.currentThread().getName(), currentThreadName); System.out.println("Thread: " + Thread.currentThread().getName()); System.out.println("t: " + t); count.incrementAndGet(); diff --git a/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java b/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java index b33efed40b..86ae8ac54e 100644 --- a/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java +++ b/src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java @@ -122,7 +122,7 @@ public final void testMergeWithExecutorScheduler() { @Override public String apply(Integer t) { - assertFalse(Thread.currentThread().getName().equals(currentThreadName)); + assertNotEquals(Thread.currentThread().getName(), currentThreadName); assertTrue(Thread.currentThread().getName().startsWith("RxComputationThreadPool")); return "Value_" + t + "_Thread_" + Thread.currentThread().getName(); } diff --git a/src/test/java/io/reactivex/schedulers/TimedTest.java b/src/test/java/io/reactivex/schedulers/TimedTest.java index 7e8cb41e1a..c380188665 100644 --- a/src/test/java/io/reactivex/schedulers/TimedTest.java +++ b/src/test/java/io/reactivex/schedulers/TimedTest.java @@ -75,7 +75,7 @@ public void equalsWith() { assertNotEquals(new Object(), t1); - assertFalse(t1.equals(new Object())); + assertNotEquals(t1, new Object()); } @Test diff --git a/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java b/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java index 2768a12b1a..b125d43252 100644 --- a/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java @@ -51,7 +51,7 @@ public final void testMergeWithCurrentThreadScheduler1() { @Override public String apply(Integer t) { - assertTrue(Thread.currentThread().getName().equals(currentThreadName)); + assertEquals(Thread.currentThread().getName(), currentThreadName); return "Value_" + t + "_Thread_" + Thread.currentThread().getName(); } }); diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java index aa91270226..c836e179b5 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java @@ -965,7 +965,7 @@ public void peekStateTimeAndSizeValueExpired() { scheduler.advanceTimeBy(2, TimeUnit.DAYS); - assertEquals(null, rp.getValue()); + assertNull(rp.getValue()); assertEquals(0, rp.getValues().length); assertNull(rp.getValues(new Integer[2])[0]); } diff --git a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java index ca13ba0495..9b0a16879d 100644 --- a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java @@ -168,9 +168,9 @@ public void onTerminateCalledWhenOnError() { } }); - assertEquals(false, didRunOnTerminate.get()); + assertFalse(didRunOnTerminate.get()); us.onError(new RuntimeException("some error")); - assertEquals(true, didRunOnTerminate.get()); + assertTrue(didRunOnTerminate.get()); } @Test @@ -183,9 +183,9 @@ public void onTerminateCalledWhenOnComplete() { } }); - assertEquals(false, didRunOnTerminate.get()); + assertFalse(didRunOnTerminate.get()); us.onComplete(); - assertEquals(true, didRunOnTerminate.get()); + assertTrue(didRunOnTerminate.get()); } @Test @@ -200,9 +200,9 @@ public void onTerminateCalledWhenCanceled() { final Disposable subscribe = us.subscribe(); - assertEquals(false, didRunOnTerminate.get()); + assertFalse(didRunOnTerminate.get()); subscribe.dispose(); - assertEquals(true, didRunOnTerminate.get()); + assertTrue(didRunOnTerminate.get()); } @Test(expected = NullPointerException.class) From 67b9cf6ac86907e83044e516b82f6594409b091c Mon Sep 17 00:00:00 2001 From: jimin <slievrly@163.com> Date: Fri, 28 Jun 2019 13:22:00 +0800 Subject: [PATCH 373/417] remove unnecessary import (#6545) --- src/test/java/io/reactivex/completable/CompletableTest.java | 1 - src/test/java/io/reactivex/disposables/DisposablesTest.java | 1 - src/test/java/io/reactivex/flowable/FlowableTests.java | 1 - .../operators/completable/CompletableFromCallableTest.java | 1 - .../reactivex/internal/operators/flowable/FlowableAllTest.java | 1 - .../reactivex/internal/operators/flowable/FlowableAnyTest.java | 1 - .../internal/operators/flowable/FlowableAsObservableTest.java | 1 - .../internal/operators/flowable/FlowableBufferTest.java | 1 - .../internal/operators/flowable/FlowableCombineLatestTest.java | 1 - .../internal/operators/flowable/FlowableConcatTest.java | 1 - .../internal/operators/flowable/FlowableDebounceTest.java | 1 - .../internal/operators/flowable/FlowableDelayTest.java | 1 - .../internal/operators/flowable/FlowableDematerializeTest.java | 1 - .../internal/operators/flowable/FlowableDistinctTest.java | 1 - .../operators/flowable/FlowableDistinctUntilChangedTest.java | 1 - .../internal/operators/flowable/FlowableDoOnEachTest.java | 1 - .../internal/operators/flowable/FlowableFilterTest.java | 1 - .../internal/operators/flowable/FlowableFlatMapTest.java | 1 - .../internal/operators/flowable/FlowableFromCallableTest.java | 1 - .../internal/operators/flowable/FlowableFromIterableTest.java | 1 - .../internal/operators/flowable/FlowableGroupByTest.java | 1 - .../internal/operators/flowable/FlowableGroupJoinTest.java | 1 - .../reactivex/internal/operators/flowable/FlowableHideTest.java | 1 - .../reactivex/internal/operators/flowable/FlowableJoinTest.java | 1 - .../reactivex/internal/operators/flowable/FlowableMapTest.java | 2 -- .../operators/flowable/FlowableMergeDelayErrorTest.java | 1 - .../internal/operators/flowable/FlowableMergeTest.java | 1 - .../internal/operators/flowable/FlowableObserveOnTest.java | 1 - .../flowable/FlowableOnErrorResumeNextViaFunctionTest.java | 1 - .../internal/operators/flowable/FlowableRangeLongTest.java | 1 - .../internal/operators/flowable/FlowableRangeTest.java | 1 - .../internal/operators/flowable/FlowableReduceTest.java | 1 - .../internal/operators/flowable/FlowableRefCountAltTest.java | 1 - .../internal/operators/flowable/FlowableRefCountTest.java | 1 - .../internal/operators/flowable/FlowableRepeatTest.java | 1 - .../internal/operators/flowable/FlowableReplayTest.java | 1 - .../internal/operators/flowable/FlowableRetryTest.java | 1 - .../operators/flowable/FlowableRetryWithPredicateTest.java | 1 - .../internal/operators/flowable/FlowableSampleTest.java | 1 - .../reactivex/internal/operators/flowable/FlowableScanTest.java | 1 - .../internal/operators/flowable/FlowableSequenceEqualTest.java | 1 - .../internal/operators/flowable/FlowableSingleTest.java | 1 - .../internal/operators/flowable/FlowableSkipLastTimedTest.java | 1 - .../internal/operators/flowable/FlowableSkipWhileTest.java | 1 - .../internal/operators/flowable/FlowableSwitchTest.java | 1 - .../internal/operators/flowable/FlowableTakeLastTest.java | 1 - .../reactivex/internal/operators/flowable/FlowableTakeTest.java | 1 - .../operators/flowable/FlowableTakeUntilPredicateTest.java | 1 - .../internal/operators/flowable/FlowableTakeWhileTest.java | 1 - .../internal/operators/flowable/FlowableThrottleFirstTest.java | 1 - .../internal/operators/flowable/FlowableTimeoutTests.java | 1 - .../operators/flowable/FlowableTimeoutWithSelectorTest.java | 1 - .../internal/operators/flowable/FlowableTimerTest.java | 1 - .../internal/operators/flowable/FlowableToListTest.java | 1 - .../operators/flowable/FlowableWindowWithFlowableTest.java | 1 - .../internal/operators/flowable/FlowableWindowWithSizeTest.java | 1 - .../internal/operators/flowable/FlowableWithLatestFromTest.java | 1 - .../internal/operators/flowable/FlowableZipIterableTest.java | 1 - .../reactivex/internal/operators/flowable/FlowableZipTest.java | 1 - .../internal/operators/maybe/MaybeFromCallableTest.java | 1 - .../internal/operators/observable/ObservableAllTest.java | 1 - .../internal/operators/observable/ObservableAnyTest.java | 1 - .../internal/operators/observable/ObservableBufferTest.java | 1 - .../operators/observable/ObservableCombineLatestTest.java | 1 - .../internal/operators/observable/ObservableDebounceTest.java | 1 - .../internal/operators/observable/ObservableDelayTest.java | 1 - .../operators/observable/ObservableDematerializeTest.java | 1 - .../internal/operators/observable/ObservableDistinctTest.java | 1 - .../observable/ObservableDistinctUntilChangedTest.java | 1 - .../internal/operators/observable/ObservableDoOnEachTest.java | 1 - .../internal/operators/observable/ObservableFilterTest.java | 1 - .../internal/operators/observable/ObservableFlatMapTest.java | 1 - .../operators/observable/ObservableFromCallableTest.java | 1 - .../operators/observable/ObservableFromIterableTest.java | 1 - .../internal/operators/observable/ObservableGroupJoinTest.java | 1 - .../internal/operators/observable/ObservableJoinTest.java | 1 - .../internal/operators/observable/ObservableLastTest.java | 1 - .../internal/operators/observable/ObservableMapTest.java | 1 - .../internal/operators/observable/ObservableObserveOnTest.java | 1 - .../observable/ObservableOnErrorResumeNextViaFunctionTest.java | 1 - .../internal/operators/observable/ObservableRangeLongTest.java | 1 - .../internal/operators/observable/ObservableRangeTest.java | 1 - .../internal/operators/observable/ObservableReduceTest.java | 1 - .../operators/observable/ObservableRefCountAltTest.java | 1 - .../internal/operators/observable/ObservableRefCountTest.java | 1 - .../internal/operators/observable/ObservableRepeatTest.java | 1 - .../internal/operators/observable/ObservableReplayTest.java | 1 - .../internal/operators/observable/ObservableRetryTest.java | 1 - .../operators/observable/ObservableRetryWithPredicateTest.java | 1 - .../internal/operators/observable/ObservableSampleTest.java | 1 - .../internal/operators/observable/ObservableScanTest.java | 1 - .../operators/observable/ObservableSequenceEqualTest.java | 1 - .../internal/operators/observable/ObservableSkipLastTest.java | 1 - .../operators/observable/ObservableSkipLastTimedTest.java | 1 - .../internal/operators/observable/ObservableSkipWhileTest.java | 1 - .../internal/operators/observable/ObservableSwitchTest.java | 1 - .../internal/operators/observable/ObservableTakeLastTest.java | 1 - .../operators/observable/ObservableTakeLastTimedTest.java | 1 - .../internal/operators/observable/ObservableTakeTest.java | 1 - .../operators/observable/ObservableTakeUntilPredicateTest.java | 1 - .../internal/operators/observable/ObservableTimeoutTests.java | 1 - .../operators/observable/ObservableTimeoutWithSelectorTest.java | 1 - .../internal/operators/observable/ObservableTimerTest.java | 1 - .../internal/operators/observable/ObservableToListTest.java | 1 - .../observable/ObservableWindowWithObservableTest.java | 1 - .../operators/observable/ObservableZipIterableTest.java | 1 - .../internal/operators/observable/ObservableZipTest.java | 1 - .../internal/operators/single/SingleFromCallableTest.java | 1 - src/test/java/io/reactivex/observable/ObservableTest.java | 1 - src/test/java/io/reactivex/processors/AsyncProcessorTest.java | 1 - .../java/io/reactivex/processors/BehaviorProcessorTest.java | 1 - src/test/java/io/reactivex/processors/PublishProcessorTest.java | 1 - src/test/java/io/reactivex/processors/ReplayProcessorTest.java | 1 - src/test/java/io/reactivex/single/SingleNullTests.java | 1 - src/test/java/io/reactivex/subjects/AsyncSubjectTest.java | 1 - src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java | 1 - src/test/java/io/reactivex/subjects/PublishSubjectTest.java | 1 - src/test/java/io/reactivex/subjects/ReplaySubjectTest.java | 1 - .../java/io/reactivex/subscribers/SerializedSubscriberTest.java | 1 - 119 files changed, 120 deletions(-) diff --git a/src/test/java/io/reactivex/completable/CompletableTest.java b/src/test/java/io/reactivex/completable/CompletableTest.java index 3fda12b46e..40e52c8e24 100644 --- a/src/test/java/io/reactivex/completable/CompletableTest.java +++ b/src/test/java/io/reactivex/completable/CompletableTest.java @@ -14,7 +14,6 @@ package io.reactivex.completable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/disposables/DisposablesTest.java b/src/test/java/io/reactivex/disposables/DisposablesTest.java index 779b85fead..531838acc1 100644 --- a/src/test/java/io/reactivex/disposables/DisposablesTest.java +++ b/src/test/java/io/reactivex/disposables/DisposablesTest.java @@ -14,7 +14,6 @@ package io.reactivex.disposables; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/flowable/FlowableTests.java b/src/test/java/io/reactivex/flowable/FlowableTests.java index fa8026da6c..c9e226da9e 100644 --- a/src/test/java/io/reactivex/flowable/FlowableTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableTests.java @@ -14,7 +14,6 @@ package io.reactivex.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java index b0d551a64e..412e3a2d1f 100644 --- a/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.completable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.concurrent.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java index e859766ca8..409510b23f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java index 76d4b034b7..5c8a9d6f84 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java index a297911040..7dd78955ee 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.assertFalse; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import org.junit.Test; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index e79130ff41..8edd8e7cd2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java index 4443a71759..a96b8c8193 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.lang.reflect.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java index 772f559733..c1faba86d4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.lang.reflect.Method; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java index 8df7c9c193..459d63e5c1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java index 401b9c62b4..cf1817e0e4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java index 66fd932dcc..723d3b1e59 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.flowable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java index 448e963d49..86b6200440 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java index 7c5eb993e1..0ea9353505 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.flowable; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java index 4a9ac3eca2..e61fdc4b38 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java index 85093c4576..a6928a1157 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.flowable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index 4c1441775b..953a5f44dc 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java index f3239001ee..254274b1cf 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java @@ -17,7 +17,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java index e33556cb4e..d2e15fa60d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index 97a0a5ca23..63d6152a3e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java index b9e1b4f995..0704878805 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java @@ -16,7 +16,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java index af85b261c6..fbc4708710 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.assertFalse; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import org.junit.Test; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java index 14a5ec3d59..e8f71d7aae 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java @@ -15,7 +15,6 @@ */ package io.reactivex.internal.operators.flowable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java index 9ebc328d56..0ff960c4cc 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; @@ -24,7 +23,6 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.Flowable; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java index 67129c956b..671abc314e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java @@ -25,7 +25,6 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.Flowable; import io.reactivex.exceptions.*; import io.reactivex.functions.LongConsumer; import io.reactivex.internal.subscriptions.BooleanSubscription; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java index 010da8bd69..34a732be7c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java @@ -15,7 +15,6 @@ import static java.util.Arrays.asList; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.lang.reflect.Method; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java index ca4bd28986..ba640c3e5a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java index 06f10e835d..8d3cef82d0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java index 470e0e8cc0..e3d67bb8a2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java index b0af47585b..3772aefd85 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java index 37d7012065..af88de841f 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java index e048d47650..2ee23b2dc1 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index 88aa2b17c1..3cb5f57fb0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java index fd5061d9ed..46d240b620 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java index b3bea718bd..56daf0c5e5 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.lang.management.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java index a47a5d6eca..d0c73867e6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java index de31e283a4..c24e4f5f7d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java index 74cbcc24c2..1ea39f76ce 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.assertFalse; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.concurrent.TimeUnit; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java index 7e761ca53f..1b2b9ac4ca 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java @@ -24,7 +24,6 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.Flowable; import io.reactivex.exceptions.*; import io.reactivex.flowable.*; import io.reactivex.flowable.FlowableEventStream.Event; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java index fb65114e42..b40a40bb56 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.flowable; -import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java index 62f662804f..71085466cb 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java index d24a84b4b6..31c8294a64 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.flowable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.concurrent.TimeUnit; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipWhileTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipWhileTest.java index b9574cd8ef..0ac4a1369e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipWhileTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipWhileTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.flowable; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import org.junit.Test; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java index dc5f2a8313..c1d8c4134c 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java index b0d1af43c7..3320650881 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java @@ -24,7 +24,6 @@ import org.reactivestreams.Subscriber; import io.reactivex.*; -import io.reactivex.Flowable; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.schedulers.Schedulers; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java index 91d4d4ea8b..59d049a7c0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java index acba2b1294..72e08bd1b3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.flowable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java index 97eac27982..f99b7d1d86 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java index 2e5fd020e7..12fc35760e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.flowable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java index 7e4b97c899..5f6aa08fa6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java @@ -15,7 +15,6 @@ import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java index 178e015413..d1ba19d32b 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java index e5b9c61de4..b02fea95b3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java index ffa4d0eba3..08dc9c244d 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.flowable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java index 919ca0e468..ce321df789 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java index b6fb51f6d2..af412d9a02 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java index 070176bdb0..c534ddd990 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipIterableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipIterableTest.java index a86de18f52..2ca5481fc3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipIterableTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java index 12f81c33e0..ee691d93c2 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.lang.reflect.*; diff --git a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCallableTest.java index 7a56347a32..44f50947ee 100644 --- a/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCallableTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.maybe; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java index dc8445068c..e53fd7161c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java index 7c66cba3f6..fcdc13fee9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 66a4e24dc0..92299a5754 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java index 55256bccd8..418a19678e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java index 01bf61ac6e..e1c96cd135 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDelayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDelayTest.java index 1088f2abc1..40e396b314 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDelayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDelayTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java index d815a70ea5..d2c5a4ca57 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctTest.java index 8114d64f9a..67f73d3ede 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java index b0ba634354..6bd333e814 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java index 161ae3db9e..a22c969c9b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFilterTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFilterTest.java index e855c07820..7ac6418db7 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFilterTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFilterTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import org.junit.Test; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index 960722060a..b4da14e9a1 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java index 542165907f..c10d53db36 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java @@ -17,7 +17,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromIterableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromIterableTest.java index 3b0a9d4970..5ed25eb269 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFromIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFromIterableTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java index 3f902cb4a4..59c5a96332 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java @@ -16,7 +16,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableJoinTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableJoinTest.java index 8ced523827..00a733959d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableJoinTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableJoinTest.java @@ -15,7 +15,6 @@ */ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableLastTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableLastTest.java index 6f3ecd39c8..77f02bfe71 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableLastTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.NoSuchElementException; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMapTest.java index 3d824be862..4d271a4197 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMapTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java index 8d948b2592..a60328a899 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java index b8b3f67f1e..fa48b217f8 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeLongTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeLongTest.java index d09ec0d6ce..dfe1713902 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeLongTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeLongTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.ArrayList; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeTest.java index cbdc0130ec..d54847c0b2 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRangeTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.ArrayList; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java index cb6e61e8f6..c1c7ffbeb6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java index effe8ef206..5fc3aea8c6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index 48a9ff2d5a..96be759db2 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java index dbb72e21ef..538b4a0c69 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java index 40d09f4f33..7c768f36cc 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.lang.management.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java index 0055449ef5..ab7998c8a1 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java index 7b0322ab87..debeb8eec4 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java index 01f04653f2..7e3098216c 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.concurrent.TimeUnit; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java index 35df1a462e..e078f92505 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java index 4a7a33ddd6..da996cfc22 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.*; import org.junit.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java index b89d70b8df..c97f851700 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.Arrays; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimedTest.java index 50df641a26..3cf4d2e155 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimedTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.concurrent.TimeUnit; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipWhileTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipWhileTest.java index d4772b1a6a..9e809b88cc 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipWhileTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSkipWhileTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import org.junit.Test; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java index 610f49eac4..7e3d4dc505 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java index 34ab87312b..1eb89adc6a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.concurrent.atomic.AtomicInteger; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java index bc933f9b02..9269bd0b5a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.concurrent.TimeUnit; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java index a9b9ae35d9..341409f958 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java index 0e6f040972..9fa6c21bca 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java index 935922b67c..9d517ec1be 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java @@ -15,7 +15,6 @@ import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.io.IOException; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java index 3dad40f34a..a0d8a93ebe 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java index c8af9d88b8..124283dc1f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java index 18447143aa..1f28cfc5d2 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java @@ -13,7 +13,6 @@ package io.reactivex.internal.operators.observable; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java index a82e876464..9f8969222b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipIterableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipIterableTest.java index 971359d8ad..f05c41cfd3 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipIterableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipIterableTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java index ba86f16175..14fda0058d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java @@ -14,7 +14,6 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java b/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java index 2c4ebcc321..23fb50c01d 100644 --- a/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java +++ b/src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java @@ -33,7 +33,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; public class SingleFromCallableTest { diff --git a/src/test/java/io/reactivex/observable/ObservableTest.java b/src/test/java/io/reactivex/observable/ObservableTest.java index ab915ffa53..f59a41857e 100644 --- a/src/test/java/io/reactivex/observable/ObservableTest.java +++ b/src/test/java/io/reactivex/observable/ObservableTest.java @@ -14,7 +14,6 @@ package io.reactivex.observable; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; diff --git a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java index 963171d30e..3d85d97eee 100644 --- a/src/test/java/io/reactivex/processors/AsyncProcessorTest.java +++ b/src/test/java/io/reactivex/processors/AsyncProcessorTest.java @@ -14,7 +14,6 @@ package io.reactivex.processors; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.concurrent.TimeUnit; diff --git a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java index a0e3996f41..d465aa7a56 100644 --- a/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java +++ b/src/test/java/io/reactivex/processors/BehaviorProcessorTest.java @@ -14,7 +14,6 @@ package io.reactivex.processors; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/processors/PublishProcessorTest.java b/src/test/java/io/reactivex/processors/PublishProcessorTest.java index f91e61551f..980ed84187 100644 --- a/src/test/java/io/reactivex/processors/PublishProcessorTest.java +++ b/src/test/java/io/reactivex/processors/PublishProcessorTest.java @@ -14,7 +14,6 @@ package io.reactivex.processors; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.ArrayList; diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index 7ecc2bea31..2279f500c8 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -14,7 +14,6 @@ package io.reactivex.processors; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.lang.management.*; diff --git a/src/test/java/io/reactivex/single/SingleNullTests.java b/src/test/java/io/reactivex/single/SingleNullTests.java index ff7ddf19d0..059f106ffe 100644 --- a/src/test/java/io/reactivex/single/SingleNullTests.java +++ b/src/test/java/io/reactivex/single/SingleNullTests.java @@ -22,7 +22,6 @@ import org.reactivestreams.*; import io.reactivex.*; -import io.reactivex.SingleOperator; import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; diff --git a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java index efd643e8d9..c1be4ab34c 100644 --- a/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/AsyncSubjectTest.java @@ -14,7 +14,6 @@ package io.reactivex.subjects; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.concurrent.TimeUnit; diff --git a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java index 9a2b52f8f7..1a6f48a0e7 100644 --- a/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java @@ -14,7 +14,6 @@ package io.reactivex.subjects; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java index 7731d508f8..fc20c7b195 100644 --- a/src/test/java/io/reactivex/subjects/PublishSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/PublishSubjectTest.java @@ -14,7 +14,6 @@ package io.reactivex.subjects; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.ArrayList; diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java index c836e179b5..3d02387c92 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java @@ -14,7 +14,6 @@ package io.reactivex.subjects; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.lang.management.*; diff --git a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java index c38105eb68..e0524350c9 100644 --- a/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java +++ b/src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java @@ -14,7 +14,6 @@ package io.reactivex.subscribers; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; From 5c83b50893143a265cfeab299d087affc9d7c566 Mon Sep 17 00:00:00 2001 From: Artem Hluhovskyi <hluhovskyi@gmail.com> Date: Fri, 5 Jul 2019 00:03:42 +0300 Subject: [PATCH 374/417] Fix NPE when debouncing empty source (#6560) --- .../internal/operators/flowable/FlowableDebounce.java | 4 +++- .../operators/observable/ObservableDebounce.java | 4 +++- .../operators/flowable/FlowableDebounceTest.java | 10 ++++++++++ .../operators/observable/ObservableDebounceTest.java | 10 ++++++++++ 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounce.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounce.java index 92b1c48254..143e61ec55 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounce.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounce.java @@ -119,7 +119,9 @@ public void onComplete() { if (!DisposableHelper.isDisposed(d)) { @SuppressWarnings("unchecked") DebounceInnerSubscriber<T, U> dis = (DebounceInnerSubscriber<T, U>)d; - dis.emit(); + if (dis != null) { + dis.emit(); + } DisposableHelper.dispose(debouncer); downstream.onComplete(); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounce.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounce.java index 2c056eb70e..db8b9d4794 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounce.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableDebounce.java @@ -112,7 +112,9 @@ public void onComplete() { if (d != DisposableHelper.DISPOSED) { @SuppressWarnings("unchecked") DebounceInnerObserver<T, U> dis = (DebounceInnerObserver<T, U>)d; - dis.emit(); + if (dis != null) { + dis.emit(); + } DisposableHelper.dispose(debouncer); downstream.onComplete(); } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java index 459d63e5c1..aacff6e5af 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java @@ -546,4 +546,14 @@ public void timedError() { .test() .assertFailure(TestException.class); } + + @Test + public void debounceOnEmpty() { + Flowable.empty().debounce(new Function<Object, Publisher<Object>>() { + @Override + public Publisher<Object> apply(Object o) { + return Flowable.just(new Object()); + } + }).subscribe(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java index e1c96cd135..aa24f68cd9 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java @@ -504,4 +504,14 @@ public void timedError() { .test() .assertFailure(TestException.class); } + + @Test + public void debounceOnEmpty() { + Observable.empty().debounce(new Function<Object, ObservableSource<Object>>() { + @Override + public ObservableSource<Object> apply(Object o) { + return Observable.just(new Object()); + } + }).subscribe(); + } } From 5550b6303db96763640dd3490101dcbd4f37d87f Mon Sep 17 00:00:00 2001 From: Supasin Tatiyanupanwong <supasin@tatiyanupanwong.me> Date: Mon, 15 Jul 2019 15:53:21 +0700 Subject: [PATCH 375/417] Fix JavaDocs of Single.doOnTerminate refer to onComplete notification (#6565) --- src/main/java/io/reactivex/Single.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 3dd0776e11..299e6da76f 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -2501,13 +2501,13 @@ public final Single<T> doOnSubscribe(final Consumer<? super Disposable> onSubscr * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnTerminate.png" alt=""> * <p> - * This differs from {@code doAfterTerminate} in that this happens <em>before</em> the {@code onComplete} or + * This differs from {@code doAfterTerminate} in that this happens <em>before</em> the {@code onSuccess} or * {@code onError} notification. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnTerminate} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> - * @param onTerminate the action to invoke when the consumer calls {@code onComplete} or {@code onError} + * @param onTerminate the action to invoke when the consumer calls {@code onSuccess} or {@code onError} * @return the new Single instance * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> * @see #doOnTerminate(Action) From e7842014e9b80304723c488fa1fcffe2b32a228b Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 30 Jul 2019 10:54:54 +0200 Subject: [PATCH 376/417] 2.x: Fix mergeWith not canceling other when the main fails (#6599) * 2.x: Fix mergeWith not canceling other when the main fails * Switch to OpenJDK compilation as OracleJDK is not available * Add more time to refCount testing * More time again * Looks like 250ms is still not enough, let's loop --- .travis.yml | 2 +- .../FlowableMergeWithCompletable.java | 2 +- .../flowable/FlowableMergeWithMaybe.java | 2 +- .../flowable/FlowableMergeWithSingle.java | 2 +- .../ObservableMergeWithCompletable.java | 2 +- .../observable/ObservableMergeWithMaybe.java | 2 +- .../observable/ObservableMergeWithSingle.java | 2 +- .../FlowableMergeWithCompletableTest.java | 36 +++++++++++++++++++ .../flowable/FlowableMergeWithMaybeTest.java | 36 +++++++++++++++++++ .../flowable/FlowableMergeWithSingleTest.java | 36 +++++++++++++++++++ .../ObservableMergeWithCompletableTest.java | 36 +++++++++++++++++++ .../ObservableMergeWithMaybeTest.java | 35 ++++++++++++++++++ .../ObservableMergeWithSingleTest.java | 36 +++++++++++++++++++ .../observable/ObservableRefCountAltTest.java | 29 +++++++++------ .../observable/ObservableRefCountTest.java | 16 ++++----- 15 files changed, 249 insertions(+), 25 deletions(-) diff --git a/.travis.yml b/.travis.yml index 83835caeba..9c5c0f6909 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: java jdk: -- oraclejdk8 +- openjdk8 # force upgrade Java8 as per https://github.com/travis-ci/travis-ci/issues/4042 (fixes compilation issue) #addons: diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java index 271bd9c50d..c65386bbb1 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletable.java @@ -86,7 +86,7 @@ public void onNext(T t) { @Override public void onError(Throwable ex) { - SubscriptionHelper.cancel(mainSubscription); + DisposableHelper.dispose(otherObserver); HalfSerializer.onError(downstream, ex, this, error); } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java index a32a0c92fc..1787d5fce3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java @@ -143,7 +143,7 @@ public void onNext(T t) { @Override public void onError(Throwable ex) { if (error.addThrowable(ex)) { - SubscriptionHelper.cancel(mainSubscription); + DisposableHelper.dispose(otherObserver); drain(); } else { RxJavaPlugins.onError(ex); diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java index 586bc07c07..486cb73f8c 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java @@ -143,7 +143,7 @@ public void onNext(T t) { @Override public void onError(Throwable ex) { if (error.addThrowable(ex)) { - SubscriptionHelper.cancel(mainSubscription); + DisposableHelper.dispose(otherObserver); drain(); } else { RxJavaPlugins.onError(ex); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java index fa020b6ae4..3b9e649062 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletable.java @@ -80,7 +80,7 @@ public void onNext(T t) { @Override public void onError(Throwable ex) { - DisposableHelper.dispose(mainDisposable); + DisposableHelper.dispose(otherObserver); HalfSerializer.onError(downstream, ex, this, error); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java index 23b2532d9b..e7caad3b21 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybe.java @@ -106,7 +106,7 @@ public void onNext(T t) { @Override public void onError(Throwable ex) { if (error.addThrowable(ex)) { - DisposableHelper.dispose(mainDisposable); + DisposableHelper.dispose(otherObserver); drain(); } else { RxJavaPlugins.onError(ex); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java index 20c4d21b5c..7332a29a25 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingle.java @@ -106,7 +106,7 @@ public void onNext(T t) { @Override public void onError(Throwable ex) { if (error.addThrowable(ex)) { - DisposableHelper.dispose(mainDisposable); + DisposableHelper.dispose(otherObserver); drain(); } else { RxJavaPlugins.onError(ex); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletableTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletableTest.java index cf5b7917a6..18f5551e4a 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithCompletableTest.java @@ -136,4 +136,40 @@ public void run() { ts.assertResult(1); } } + + @Test + public void cancelOtherOnMainError() { + PublishProcessor<Integer> pp = PublishProcessor.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestSubscriber<Integer> ts = pp.mergeWith(cs).test(); + + assertTrue(pp.hasSubscribers()); + assertTrue(cs.hasObservers()); + + pp.onError(new TestException()); + + ts.assertFailure(TestException.class); + + assertFalse("main has observers!", pp.hasSubscribers()); + assertFalse("other has observers", cs.hasObservers()); + } + + @Test + public void cancelMainOnOtherError() { + PublishProcessor<Integer> pp = PublishProcessor.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestSubscriber<Integer> ts = pp.mergeWith(cs).test(); + + assertTrue(pp.hasSubscribers()); + assertTrue(cs.hasObservers()); + + cs.onError(new TestException()); + + ts.assertFailure(TestException.class); + + assertFalse("main has observers!", pp.hasSubscribers()); + assertFalse("other has observers", cs.hasObservers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybeTest.java index c38bf6ae7b..676c9074c3 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybeTest.java @@ -401,4 +401,40 @@ public void onNext(Integer t) { ts.assertValueCount(Flowable.bufferSize()); ts.assertComplete(); } + + @Test + public void cancelOtherOnMainError() { + PublishProcessor<Integer> pp = PublishProcessor.create(); + MaybeSubject<Integer> ms = MaybeSubject.create(); + + TestSubscriber<Integer> ts = pp.mergeWith(ms).test(); + + assertTrue(pp.hasSubscribers()); + assertTrue(ms.hasObservers()); + + pp.onError(new TestException()); + + ts.assertFailure(TestException.class); + + assertFalse("main has observers!", pp.hasSubscribers()); + assertFalse("other has observers", ms.hasObservers()); + } + + @Test + public void cancelMainOnOtherError() { + PublishProcessor<Integer> pp = PublishProcessor.create(); + MaybeSubject<Integer> ms = MaybeSubject.create(); + + TestSubscriber<Integer> ts = pp.mergeWith(ms).test(); + + assertTrue(pp.hasSubscribers()); + assertTrue(ms.hasObservers()); + + ms.onError(new TestException()); + + ts.assertFailure(TestException.class); + + assertFalse("main has observers!", pp.hasSubscribers()); + assertFalse("other has observers", ms.hasObservers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingleTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingleTest.java index 2ab0568a7e..6a182785da 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingleTest.java @@ -397,4 +397,40 @@ public void onNext(Integer t) { ts.assertValueCount(Flowable.bufferSize()); ts.assertComplete(); } + + @Test + public void cancelOtherOnMainError() { + PublishProcessor<Integer> pp = PublishProcessor.create(); + SingleSubject<Integer> ss = SingleSubject.create(); + + TestSubscriber<Integer> ts = pp.mergeWith(ss).test(); + + assertTrue(pp.hasSubscribers()); + assertTrue(ss.hasObservers()); + + pp.onError(new TestException()); + + ts.assertFailure(TestException.class); + + assertFalse("main has observers!", pp.hasSubscribers()); + assertFalse("other has observers", ss.hasObservers()); + } + + @Test + public void cancelMainOnOtherError() { + PublishProcessor<Integer> pp = PublishProcessor.create(); + SingleSubject<Integer> ss = SingleSubject.create(); + + TestSubscriber<Integer> ts = pp.mergeWith(ss).test(); + + assertTrue(pp.hasSubscribers()); + assertTrue(ss.hasObservers()); + + ss.onError(new TestException()); + + ts.assertFailure(TestException.class); + + assertFalse("main has observers!", pp.hasSubscribers()); + assertFalse("other has observers", ss.hasObservers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletableTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletableTest.java index 872509e164..d9a54c916a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletableTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithCompletableTest.java @@ -135,4 +135,40 @@ protected void subscribeActual(Observer<? super Integer> observer) { .test() .assertResult(1); } + + @Test + public void cancelOtherOnMainError() { + PublishSubject<Integer> ps = PublishSubject.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver<Integer> to = ps.mergeWith(cs).test(); + + assertTrue(ps.hasObservers()); + assertTrue(cs.hasObservers()); + + ps.onError(new TestException()); + + to.assertFailure(TestException.class); + + assertFalse("main has observers!", ps.hasObservers()); + assertFalse("other has observers", cs.hasObservers()); + } + + @Test + public void cancelMainOnOtherError() { + PublishSubject<Integer> ps = PublishSubject.create(); + CompletableSubject cs = CompletableSubject.create(); + + TestObserver<Integer> to = ps.mergeWith(cs).test(); + + assertTrue(ps.hasObservers()); + assertTrue(cs.hasObservers()); + + cs.onError(new TestException()); + + to.assertFailure(TestException.class); + + assertFalse("main has observers!", ps.hasObservers()); + assertFalse("other has observers", cs.hasObservers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java index a70e4c2fa8..ee9eb9b576 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithMaybeTest.java @@ -272,4 +272,39 @@ public void onNext(Integer t) { to.assertResult(0, 1, 2, 3, 4); } + @Test + public void cancelOtherOnMainError() { + PublishSubject<Integer> ps = PublishSubject.create(); + MaybeSubject<Integer> ms = MaybeSubject.create(); + + TestObserver<Integer> to = ps.mergeWith(ms).test(); + + assertTrue(ps.hasObservers()); + assertTrue(ms.hasObservers()); + + ps.onError(new TestException()); + + to.assertFailure(TestException.class); + + assertFalse("main has observers!", ps.hasObservers()); + assertFalse("other has observers", ms.hasObservers()); + } + + @Test + public void cancelMainOnOtherError() { + PublishSubject<Integer> ps = PublishSubject.create(); + MaybeSubject<Integer> ms = MaybeSubject.create(); + + TestObserver<Integer> to = ps.mergeWith(ms).test(); + + assertTrue(ps.hasObservers()); + assertTrue(ms.hasObservers()); + + ms.onError(new TestException()); + + to.assertFailure(TestException.class); + + assertFalse("main has observers!", ps.hasObservers()); + assertFalse("other has observers", ms.hasObservers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java index 25ce78d486..0d8fb3432b 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableMergeWithSingleTest.java @@ -263,4 +263,40 @@ public void onNext(Integer t) { to.assertResult(0, 1, 2, 3, 4); } + + @Test + public void cancelOtherOnMainError() { + PublishSubject<Integer> ps = PublishSubject.create(); + SingleSubject<Integer> ss = SingleSubject.create(); + + TestObserver<Integer> to = ps.mergeWith(ss).test(); + + assertTrue(ps.hasObservers()); + assertTrue(ss.hasObservers()); + + ps.onError(new TestException()); + + to.assertFailure(TestException.class); + + assertFalse("main has observers!", ps.hasObservers()); + assertFalse("other has observers", ss.hasObservers()); + } + + @Test + public void cancelMainOnOtherError() { + PublishSubject<Integer> ps = PublishSubject.create(); + SingleSubject<Integer> ss = SingleSubject.create(); + + TestObserver<Integer> to = ps.mergeWith(ss).test(); + + assertTrue(ps.hasObservers()); + assertTrue(ss.hasObservers()); + + ss.onError(new TestException()); + + to.assertFailure(TestException.class); + + assertFalse("main has observers!", ps.hasObservers()); + assertFalse("other has observers", ss.hasObservers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java index 5fc3aea8c6..05aada6b84 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java @@ -630,7 +630,7 @@ protected void subscribeActual(Observer<? super Integer> observer) { @Test public void replayNoLeak() throws Exception { System.gc(); - Thread.sleep(100); + Thread.sleep(250); long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -646,7 +646,7 @@ public Object call() throws Exception { source.subscribe(); System.gc(); - Thread.sleep(100); + Thread.sleep(250); long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -657,7 +657,7 @@ public Object call() throws Exception { @Test public void replayNoLeak2() throws Exception { System.gc(); - Thread.sleep(100); + Thread.sleep(250); long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -680,7 +680,7 @@ public Object call() throws Exception { d2 = null; System.gc(); - Thread.sleep(100); + Thread.sleep(250); long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -701,7 +701,7 @@ static final class ExceptionData extends Exception { @Test public void publishNoLeak() throws Exception { System.gc(); - Thread.sleep(100); + Thread.sleep(250); long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -716,10 +716,19 @@ public Object call() throws Exception { source.subscribe(Functions.emptyConsumer(), Functions.emptyConsumer()); - System.gc(); - Thread.sleep(100); + long after = 0L; - long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + for (int i = 0; i < 10; i++) { + System.gc(); + + after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + + if (start + 20 * 1000 * 1000 > after) { + break; + } + + Thread.sleep(100); + } source = null; assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after); @@ -728,7 +737,7 @@ public Object call() throws Exception { @Test public void publishNoLeak2() throws Exception { System.gc(); - Thread.sleep(100); + Thread.sleep(250); long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -751,7 +760,7 @@ public Object call() throws Exception { d2 = null; System.gc(); - Thread.sleep(100); + Thread.sleep(250); long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index 96be759db2..99a2a79f79 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -651,7 +651,7 @@ protected void subscribeActual(Observer<? super Integer> observer) { @Test public void replayNoLeak() throws Exception { System.gc(); - Thread.sleep(100); + Thread.sleep(250); long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -667,7 +667,7 @@ public Object call() throws Exception { source.subscribe(); System.gc(); - Thread.sleep(100); + Thread.sleep(250); long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -678,7 +678,7 @@ public Object call() throws Exception { @Test public void replayNoLeak2() throws Exception { System.gc(); - Thread.sleep(100); + Thread.sleep(250); long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -701,7 +701,7 @@ public Object call() throws Exception { d2 = null; System.gc(); - Thread.sleep(100); + Thread.sleep(250); long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -722,7 +722,7 @@ static final class ExceptionData extends Exception { @Test public void publishNoLeak() throws Exception { System.gc(); - Thread.sleep(100); + Thread.sleep(250); long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -738,7 +738,7 @@ public Object call() throws Exception { source.subscribe(Functions.emptyConsumer(), Functions.emptyConsumer()); System.gc(); - Thread.sleep(100); + Thread.sleep(250); long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -749,7 +749,7 @@ public Object call() throws Exception { @Test public void publishNoLeak2() throws Exception { System.gc(); - Thread.sleep(100); + Thread.sleep(250); long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); @@ -772,7 +772,7 @@ public Object call() throws Exception { d2 = null; System.gc(); - Thread.sleep(100); + Thread.sleep(250); long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); From 70f25df30ba5a1e3dfbff474dd0e70f44de2a519 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 30 Jul 2019 11:20:17 +0200 Subject: [PATCH 377/417] 2.x: ObservableBlockingSubscribe compares with wrong object (#6601) --- .../operators/observable/ObservableBlockingSubscribe.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableBlockingSubscribe.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableBlockingSubscribe.java index 4373a321aa..589b71c5f9 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableBlockingSubscribe.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableBlockingSubscribe.java @@ -61,7 +61,7 @@ public static <T> void subscribe(ObservableSource<? extends T> o, Observer<? sup } } if (bs.isDisposed() - || o == BlockingObserver.TERMINATED + || v == BlockingObserver.TERMINATED || NotificationLite.acceptFull(v, observer)) { break; } From a0290b0e56b80721c6a574038981ecf379f75041 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 30 Jul 2019 12:47:50 +0200 Subject: [PATCH 378/417] 2.x: Fix truncation bugs in replay() and ReplaySubject/Processor (#6602) --- .../operators/flowable/FlowableReplay.java | 7 +- .../observable/ObservableReplay.java | 7 +- .../reactivex/processors/ReplayProcessor.java | 5 ++ .../io/reactivex/subjects/ReplaySubject.java | 5 ++ .../io/reactivex/TimesteppingScheduler.java | 60 +++++++++++++++ .../processors/ReplayProcessorTest.java | 75 +++++++++++++++++++ .../reactivex/subjects/ReplaySubjectTest.java | 75 +++++++++++++++++++ 7 files changed, 232 insertions(+), 2 deletions(-) create mode 100644 src/test/java/io/reactivex/TimesteppingScheduler.java diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java index 7a02482b4b..196596f1b2 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java @@ -773,6 +773,11 @@ final void removeFirst() { } setFirst(head); + // correct the tail if all items have been removed + head = get(); + if (head.get() == null) { + tail = head; + } } /** * Arranges the given node is the new head from now on. @@ -1015,7 +1020,7 @@ void truncate() { int e = 0; for (;;) { if (next != null) { - if (size > limit) { + if (size > limit && size > 1) { // never truncate the very last item just added e++; size--; prev = next; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java index 197ada9706..2818d975f1 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java @@ -638,6 +638,11 @@ final void trimHead() { } setFirst(head); + // correct the tail if all items have been removed + head = get(); + if (head.get() == null) { + tail = head; + } } /** * Arranges the given node is the new head from now on. @@ -839,7 +844,7 @@ void truncate() { int e = 0; for (;;) { if (next != null) { - if (size > limit) { + if (size > limit && size > 1) { // never truncate the very last item just added e++; size--; prev = next; diff --git a/src/main/java/io/reactivex/processors/ReplayProcessor.java b/src/main/java/io/reactivex/processors/ReplayProcessor.java index ff98ff25d9..b04a17d07e 100644 --- a/src/main/java/io/reactivex/processors/ReplayProcessor.java +++ b/src/main/java/io/reactivex/processors/ReplayProcessor.java @@ -1070,6 +1070,10 @@ void trim() { TimedNode<T> h = head; for (;;) { + if (size <= 1) { + head = h; + break; + } TimedNode<T> next = h.get(); if (next == null) { head = h; @@ -1082,6 +1086,7 @@ void trim() { } h = next; + size--; } } diff --git a/src/main/java/io/reactivex/subjects/ReplaySubject.java b/src/main/java/io/reactivex/subjects/ReplaySubject.java index 703692bd57..622854b5ec 100644 --- a/src/main/java/io/reactivex/subjects/ReplaySubject.java +++ b/src/main/java/io/reactivex/subjects/ReplaySubject.java @@ -1071,6 +1071,10 @@ void trim() { TimedNode<Object> h = head; for (;;) { + if (size <= 1) { + head = h; + break; + } TimedNode<Object> next = h.get(); if (next == null) { head = h; @@ -1083,6 +1087,7 @@ void trim() { } h = next; + size--; } } diff --git a/src/test/java/io/reactivex/TimesteppingScheduler.java b/src/test/java/io/reactivex/TimesteppingScheduler.java new file mode 100644 index 0000000000..73996cc56f --- /dev/null +++ b/src/test/java/io/reactivex/TimesteppingScheduler.java @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import java.util.concurrent.TimeUnit; + +import io.reactivex.Scheduler; +import io.reactivex.disposables.*; + +/** + * Basic scheduler that produces an ever increasing {@link #now(TimeUnit)} value. + * Use this scheduler only as a time source! + */ +public class TimesteppingScheduler extends Scheduler { + + final class TimesteppingWorker extends Worker { + @Override + public void dispose() { + } + + @Override + public boolean isDisposed() { + return false; + } + + @Override + public Disposable schedule(Runnable run, long delay, TimeUnit unit) { + run.run(); + return Disposables.disposed(); + } + + @Override + public long now(TimeUnit unit) { + return time++; + } + } + + long time; + + @Override + public Worker createWorker() { + return new TimesteppingWorker(); + } + + @Override + public long now(TimeUnit unit) { + return time++; + } +} \ No newline at end of file diff --git a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java index 2279f500c8..b59d20fb94 100644 --- a/src/test/java/io/reactivex/processors/ReplayProcessorTest.java +++ b/src/test/java/io/reactivex/processors/ReplayProcessorTest.java @@ -1750,4 +1750,79 @@ public void accept(byte[] v) throws Exception { + " -> " + after.get() / 1024.0 / 1024.0); } } + + @Test + public void timeAndSizeNoTerminalTruncationOnTimechange() { + ReplayProcessor<Integer> rp = ReplayProcessor.createWithTimeAndSize(1, TimeUnit.SECONDS, new TimesteppingScheduler(), 1); + + TestSubscriber<Integer> ts = rp.test(); + + rp.onNext(1); + rp.cleanupBuffer(); + rp.onComplete(); + + ts.assertNoErrors() + .assertComplete(); + } + + @Test + public void timeAndSizeNoTerminalTruncationOnTimechange2() { + ReplayProcessor<Integer> rp = ReplayProcessor.createWithTimeAndSize(1, TimeUnit.SECONDS, new TimesteppingScheduler(), 1); + + TestSubscriber<Integer> ts = rp.test(); + + rp.onNext(1); + rp.cleanupBuffer(); + rp.onNext(2); + rp.cleanupBuffer(); + rp.onComplete(); + + ts.assertNoErrors() + .assertComplete(); + } + + @Test + public void timeAndSizeNoTerminalTruncationOnTimechange3() { + ReplayProcessor<Integer> rp = ReplayProcessor.createWithTimeAndSize(1, TimeUnit.SECONDS, new TimesteppingScheduler(), 1); + + TestSubscriber<Integer> ts = rp.test(); + + rp.onNext(1); + rp.onNext(2); + rp.onComplete(); + + ts.assertNoErrors() + .assertComplete(); + } + + @Test + public void timeAndSizeNoTerminalTruncationOnTimechange4() { + ReplayProcessor<Integer> rp = ReplayProcessor.createWithTimeAndSize(1, TimeUnit.SECONDS, new TimesteppingScheduler(), 10); + + TestSubscriber<Integer> ts = rp.test(); + + rp.onNext(1); + rp.onNext(2); + rp.onComplete(); + + ts.assertNoErrors() + .assertComplete(); + } + + @Test + public void timeAndSizeRemoveCorrectNumberOfOld() { + TestScheduler scheduler = new TestScheduler(); + ReplayProcessor<Integer> rp = ReplayProcessor.createWithTimeAndSize(1, TimeUnit.SECONDS, scheduler, 2); + + rp.onNext(1); + rp.onNext(2); + rp.onNext(3); + + scheduler.advanceTimeBy(2, TimeUnit.SECONDS); + + rp.onNext(4); + rp.onNext(5); + + rp.test().assertValuesOnly(4, 5); + } } diff --git a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java index 3d02387c92..ce098ca16d 100644 --- a/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java +++ b/src/test/java/io/reactivex/subjects/ReplaySubjectTest.java @@ -1342,4 +1342,79 @@ public void accept(byte[] v) throws Exception { + " -> " + after.get() / 1024.0 / 1024.0); } } + + @Test + public void timeAndSizeNoTerminalTruncationOnTimechange() { + ReplaySubject<Integer> rs = ReplaySubject.createWithTimeAndSize(1, TimeUnit.SECONDS, new TimesteppingScheduler(), 1); + + TestObserver<Integer> to = rs.test(); + + rs.onNext(1); + rs.cleanupBuffer(); + rs.onComplete(); + + to.assertNoErrors() + .assertComplete(); + } + + @Test + public void timeAndSizeNoTerminalTruncationOnTimechange2() { + ReplaySubject<Integer> rs = ReplaySubject.createWithTimeAndSize(1, TimeUnit.SECONDS, new TimesteppingScheduler(), 1); + + TestObserver<Integer> to = rs.test(); + + rs.onNext(1); + rs.cleanupBuffer(); + rs.onNext(2); + rs.cleanupBuffer(); + rs.onComplete(); + + to.assertNoErrors() + .assertComplete(); + } + + @Test + public void timeAndSizeNoTerminalTruncationOnTimechange3() { + ReplaySubject<Integer> rs = ReplaySubject.createWithTimeAndSize(1, TimeUnit.SECONDS, new TimesteppingScheduler(), 1); + + TestObserver<Integer> to = rs.test(); + + rs.onNext(1); + rs.onNext(2); + rs.onComplete(); + + to.assertNoErrors() + .assertComplete(); + } + + @Test + public void timeAndSizeNoTerminalTruncationOnTimechange4() { + ReplaySubject<Integer> rs = ReplaySubject.createWithTimeAndSize(1, TimeUnit.SECONDS, new TimesteppingScheduler(), 10); + + TestObserver<Integer> to = rs.test(); + + rs.onNext(1); + rs.onNext(2); + rs.onComplete(); + + to.assertNoErrors() + .assertComplete(); + } + + @Test + public void timeAndSizeRemoveCorrectNumberOfOld() { + TestScheduler scheduler = new TestScheduler(); + ReplaySubject<Integer> rs = ReplaySubject.createWithTimeAndSize(1, TimeUnit.SECONDS, scheduler, 2); + + rs.onNext(1); + rs.onNext(2); + rs.onNext(3); // remove 1 due to maxSize, size == 2 + + scheduler.advanceTimeBy(2, TimeUnit.SECONDS); + + rs.onNext(4); // remove 2 due to maxSize, remove 3 due to age, size == 1 + rs.onNext(5); // size == 2 + + rs.test().assertValuesOnly(4, 5); + } } From 17a8eef0f660f58deed7f7ee399915a61ce404d6 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 2 Aug 2019 08:23:52 +0200 Subject: [PATCH 379/417] Release 2.2.11 --- CHANGES.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index df4bd2c840..5e373bc389 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,19 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.11 - August 2, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.11%7C)) + +#### Bugfixes + + - [Pull 6560](https://github.com/ReactiveX/RxJava/pull/6560): Fix NPE when debouncing an empty source. + - [Pull 6599](https://github.com/ReactiveX/RxJava/pull/6599): Fix `mergeWith` not canceling other when the main fails. + - [Pull 6601](https://github.com/ReactiveX/RxJava/pull/6601): `ObservableBlockingSubscribe` compares with wrong object. + - [Pull 6602](https://github.com/ReactiveX/RxJava/pull/): Fix truncation bugs in `replay()` and `ReplaySubject`/`Processor`. + +#### Documentation changes + + - [Pull 6565](https://github.com/ReactiveX/RxJava/pull/6565): Fix JavaDocs of `Single.doOnTerminate` refer to `onComplete` notification. + ### Version 2.2.10 - June 21, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.10%7C)) #### Bugfixes From 8db356994aa1ffb7553261e0404527125279c391 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 14 Aug 2019 12:12:41 +0200 Subject: [PATCH 380/417] 2.x: Fix switchMap incorrect sync-fusion & error management (#6618) --- .../operators/flowable/FlowableSwitchMap.java | 9 ++++- .../observable/ObservableSwitchMap.java | 1 + .../flowable/FlowableSwitchTest.java | 28 +++++++++++++++ .../observable/ObservableSwitchTest.java | 35 +++++++++++++++++-- 4 files changed, 70 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java index 9730bd38b2..d3832d4edc 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java @@ -314,7 +314,7 @@ void drain() { if (r != Long.MAX_VALUE) { requested.addAndGet(-e); } - inner.get().request(e); + inner.request(e); } } @@ -398,6 +398,7 @@ public void onError(Throwable t) { if (index == p.unique && p.error.addThrowable(t)) { if (!p.delayErrors) { p.upstream.cancel(); + p.done = true; } done = true; p.drain(); @@ -418,5 +419,11 @@ public void onComplete() { public void cancel() { SubscriptionHelper.cancel(this); } + + public void request(long n) { + if (fusionMode != QueueSubscription.SYNC) { + get().request(n); + } + } } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java index 8c5aa371dc..4e97ea405d 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java @@ -314,6 +314,7 @@ void innerError(SwitchMapInnerObserver<T, R> inner, Throwable ex) { if (inner.index == unique && errors.addThrowable(ex)) { if (!delayErrors) { upstream.dispose(); + done = true; } inner.done = true; drain(); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java index c1d8c4134c..b4880d4ff6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java @@ -1201,4 +1201,32 @@ public Object apply(Integer w) throws Exception { .assertNoErrors() .assertComplete(); } + + @Test + public void switchMapFusedIterable() { + Flowable.range(1, 2) + .switchMap(new Function<Integer, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(Integer v) + throws Exception { + return Flowable.fromIterable(Arrays.asList(v * 10)); + } + }) + .test() + .assertResult(10, 20); + } + + @Test + public void switchMapHiddenIterable() { + Flowable.range(1, 2) + .switchMap(new Function<Integer, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(Integer v) + throws Exception { + return Flowable.fromIterable(Arrays.asList(v * 10)).hide(); + } + }) + .test() + .assertResult(10, 20); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java index 7e3d4dc505..100052f028 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java @@ -14,9 +14,10 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; -import java.util.List; +import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.*; @@ -24,6 +25,8 @@ import org.mockito.InOrder; import io.reactivex.*; +import io.reactivex.Observable; +import io.reactivex.Observer; import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.*; @@ -33,7 +36,7 @@ import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; -import io.reactivex.subjects.*; +import io.reactivex.subjects.PublishSubject; public class ObservableSwitchTest { @@ -1191,4 +1194,32 @@ public Object apply(Integer w) throws Exception { .assertNoErrors() .assertComplete(); } + + @Test + public void switchMapFusedIterable() { + Observable.range(1, 2) + .switchMap(new Function<Integer, Observable<Integer>>() { + @Override + public Observable<Integer> apply(Integer v) + throws Exception { + return Observable.fromIterable(Arrays.asList(v * 10)); + } + }) + .test() + .assertResult(10, 20); + } + + @Test + public void switchMapHiddenIterable() { + Observable.range(1, 2) + .switchMap(new Function<Integer, Observable<Integer>>() { + @Override + public Observable<Integer> apply(Integer v) + throws Exception { + return Observable.fromIterable(Arrays.asList(v * 10)).hide(); + } + }) + .test() + .assertResult(10, 20); + } } From a9df239eefacd5761febca24c6076cd95702bee9 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 21 Aug 2019 16:25:39 +0200 Subject: [PATCH 381/417] 2.x: Fix blockingIterable hang when force-disposed (#6627) --- src/main/java/io/reactivex/Flowable.java | 6 ++-- .../flowable/BlockingFlowableIterable.java | 12 ++++++-- .../operators/flowable/FlowableSwitchMap.java | 2 +- .../BlockingObservableIterable.java | 12 ++++++-- .../BlockingFlowableToIteratorTest.java | 28 ++++++++++++++++++ .../flowable/FlowableBufferTest.java | 1 + .../BlockingObservableNextTest.java | 7 ++--- .../BlockingObservableToIteratorTest.java | 29 ++++++++++++++++++- .../observable/ObservableBufferTest.java | 1 + .../schedulers/TrampolineSchedulerTest.java | 1 - 10 files changed, 85 insertions(+), 14 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 4fe78199fe..91333947e9 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -89,7 +89,7 @@ * </code></pre> * <p> * The Reactive Streams specification is relatively strict when defining interactions between {@code Publisher}s and {@code Subscriber}s, so much so - * that there is a significant performance penalty due certain timing requirements and the need to prepare for invalid + * that there is a significant performance penalty due certain timing requirements and the need to prepare for invalid * request amounts via {@link Subscription#request(long)}. * Therefore, RxJava has introduced the {@link FlowableSubscriber} interface that indicates the consumer can be driven with relaxed rules. * All RxJava operators are implemented with these relaxed rules in mind. @@ -112,7 +112,7 @@ * * // could be some blocking operation * Thread.sleep(1000); - * + * * // the consumer might have cancelled the flow * if (emitter.isCancelled() { * return; @@ -138,7 +138,7 @@ * RxJava reactive sources, such as {@code Flowable}, are generally synchronous and sequential in nature. In the ReactiveX design, the location (thread) * where operators run is <i>orthogonal</i> to when the operators can work with data. This means that asynchrony and parallelism * has to be explicitly expressed via operators such as {@link #subscribeOn(Scheduler)}, {@link #observeOn(Scheduler)} and {@link #parallel()}. In general, - * operators featuring a {@link Scheduler} parameter are introducing this type of asynchrony into the flow. + * operators featuring a {@link Scheduler} parameter are introducing this type of asynchrony into the flow. * <p> * For more information see the <a href="http://reactivex.io/documentation/Publisher.html">ReactiveX * documentation</a>. diff --git a/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java b/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java index af6613b224..d09af33ee0 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java @@ -62,7 +62,7 @@ static final class BlockingFlowableIterator<T> long produced; volatile boolean done; - Throwable error; + volatile Throwable error; BlockingFlowableIterator(int batchSize) { this.queue = new SpscArrayQueue<T>(batchSize); @@ -75,6 +75,13 @@ static final class BlockingFlowableIterator<T> @Override public boolean hasNext() { for (;;) { + if (isDisposed()) { + Throwable e = error; + if (e != null) { + throw ExceptionHelper.wrapOrThrow(e); + } + return false; + } boolean d = done; boolean empty = queue.isEmpty(); if (d) { @@ -90,7 +97,7 @@ public boolean hasNext() { BlockingHelper.verifyNonBlocking(); lock.lock(); try { - while (!done && queue.isEmpty()) { + while (!done && queue.isEmpty() && !isDisposed()) { condition.await(); } } catch (InterruptedException ex) { @@ -175,6 +182,7 @@ public void remove() { @Override public void dispose() { SubscriptionHelper.cancel(this); + signalConsumer(); } @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java index d3832d4edc..4d0bc47158 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java @@ -419,7 +419,7 @@ public void onComplete() { public void cancel() { SubscriptionHelper.cancel(this); } - + public void request(long n) { if (fusionMode != QueueSubscription.SYNC) { get().request(n); diff --git a/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java b/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java index 3fdd26f9b6..24a7cb7701 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java +++ b/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableIterable.java @@ -53,7 +53,7 @@ static final class BlockingObservableIterator<T> final Condition condition; volatile boolean done; - Throwable error; + volatile Throwable error; BlockingObservableIterator(int batchSize) { this.queue = new SpscLinkedArrayQueue<T>(batchSize); @@ -64,6 +64,13 @@ static final class BlockingObservableIterator<T> @Override public boolean hasNext() { for (;;) { + if (isDisposed()) { + Throwable e = error; + if (e != null) { + throw ExceptionHelper.wrapOrThrow(e); + } + return false; + } boolean d = done; boolean empty = queue.isEmpty(); if (d) { @@ -80,7 +87,7 @@ public boolean hasNext() { BlockingHelper.verifyNonBlocking(); lock.lock(); try { - while (!done && queue.isEmpty()) { + while (!done && queue.isEmpty() && !isDisposed()) { condition.await(); } } finally { @@ -146,6 +153,7 @@ public void remove() { @Override public void dispose() { DisposableHelper.dispose(this); + signalConsumer(); } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java index df3fe6d62c..68490f9257 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java @@ -16,14 +16,18 @@ import static org.junit.Assert.*; import java.util.*; +import java.util.concurrent.TimeUnit; import org.junit.*; import org.reactivestreams.*; import io.reactivex.Flowable; +import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.*; import io.reactivex.internal.operators.flowable.BlockingFlowableIterable.BlockingFlowableIterator; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.schedulers.Schedulers; public class BlockingFlowableToIteratorTest { @@ -185,4 +189,28 @@ protected void subscribeActual(Subscriber<? super Integer> s) { it.next(); } + + @Test(expected = NoSuchElementException.class) + public void disposedIteratorHasNextReturns() { + Iterator<Integer> it = PublishProcessor.<Integer>create() + .blockingIterable().iterator(); + ((Disposable)it).dispose(); + assertFalse(it.hasNext()); + it.next(); + } + + @Test + public void asyncDisposeUnblocks() { + final Iterator<Integer> it = PublishProcessor.<Integer>create() + .blockingIterable().iterator(); + + Schedulers.single().scheduleDirect(new Runnable() { + @Override + public void run() { + ((Disposable)it).dispose(); + } + }, 1, TimeUnit.SECONDS); + + assertFalse(it.hasNext()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java index 8edd8e7cd2..d0023d3e38 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java @@ -2770,6 +2770,7 @@ public void timedSizeBufferAlreadyCleared() { } @Test + @SuppressWarnings("unchecked") public void bufferExactFailingSupplier() { Flowable.empty() .buffer(1, TimeUnit.SECONDS, Schedulers.computation(), 10, new Callable<List<Object>>() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableNextTest.java b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableNextTest.java index 947a2a027d..b854c317b2 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableNextTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableNextTest.java @@ -28,7 +28,6 @@ import io.reactivex.exceptions.TestException; import io.reactivex.internal.operators.observable.BlockingObservableNext.NextObserver; import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.processors.BehaviorProcessor; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.*; @@ -332,9 +331,9 @@ public void testSingleSourceManyIterators() throws InterruptedException { @Test public void testSynchronousNext() { - assertEquals(1, BehaviorProcessor.createDefault(1).take(1).blockingSingle().intValue()); - assertEquals(2, BehaviorProcessor.createDefault(2).blockingIterable().iterator().next().intValue()); - assertEquals(3, BehaviorProcessor.createDefault(3).blockingNext().iterator().next().intValue()); + assertEquals(1, BehaviorSubject.createDefault(1).take(1).blockingSingle().intValue()); + assertEquals(2, BehaviorSubject.createDefault(2).blockingIterable().iterator().next().intValue()); + assertEquals(3, BehaviorSubject.createDefault(3).blockingNext().iterator().next().intValue()); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToIteratorTest.java b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToIteratorTest.java index f79b2a294d..324b7c2172 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToIteratorTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/BlockingObservableToIteratorTest.java @@ -16,15 +16,18 @@ import static org.junit.Assert.*; import java.util.*; +import java.util.concurrent.TimeUnit; import org.junit.*; import io.reactivex.Observable; import io.reactivex.ObservableSource; import io.reactivex.Observer; -import io.reactivex.disposables.Disposables; +import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.internal.operators.observable.BlockingObservableIterable.BlockingObservableIterator; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.subjects.PublishSubject; public class BlockingObservableToIteratorTest { @@ -119,4 +122,28 @@ public void remove() { BlockingObservableIterator<Integer> it = new BlockingObservableIterator<Integer>(128); it.remove(); } + + @Test(expected = NoSuchElementException.class) + public void disposedIteratorHasNextReturns() { + Iterator<Integer> it = PublishSubject.<Integer>create() + .blockingIterable().iterator(); + ((Disposable)it).dispose(); + assertFalse(it.hasNext()); + it.next(); + } + + @Test + public void asyncDisposeUnblocks() { + final Iterator<Integer> it = PublishSubject.<Integer>create() + .blockingIterable().iterator(); + + Schedulers.single().scheduleDirect(new Runnable() { + @Override + public void run() { + ((Disposable)it).dispose(); + } + }, 1, TimeUnit.SECONDS); + + assertFalse(it.hasNext()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index 92299a5754..16ba2fab6d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -2137,6 +2137,7 @@ public ObservableSource<List<Object>> apply(Observable<Object> o) } @Test + @SuppressWarnings("unchecked") public void bufferExactFailingSupplier() { Observable.empty() .buffer(1, TimeUnit.SECONDS, Schedulers.computation(), 10, new Callable<List<Object>>() { diff --git a/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java b/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java index b125d43252..9f651bb50e 100644 --- a/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java +++ b/src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java @@ -31,7 +31,6 @@ import org.reactivestreams.Subscriber; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; public class TrampolineSchedulerTest extends AbstractSchedulerTests { From fa406d12f016ed96c62459f774e78da7c8877450 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 22 Aug 2019 22:08:49 +0200 Subject: [PATCH 382/417] 2.x: Fix refCount() not resetting when cross-canceled (#6629) * 2.x: Fix refCount() not resetting when cross-canceled * Undo test timeout comment --- .../operators/flowable/FlowableRefCount.java | 40 ++++++++++++++----- .../observable/ObservableRefCount.java | 40 ++++++++++++++----- .../flowable/FlowableRefCountAltTest.java | 19 +++++++++ .../flowable/FlowableRefCountTest.java | 20 ++++++++++ .../observable/ObservableRefCountAltTest.java | 19 +++++++++ .../observable/ObservableRefCountTest.java | 19 +++++++++ 6 files changed, 137 insertions(+), 20 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java index 02ed97b462..2da1306632 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableRefCount.java @@ -115,22 +115,42 @@ void cancel(RefConnection rc) { void terminated(RefConnection rc) { synchronized (this) { - if (connection != null && connection == rc) { - connection = null; - if (rc.timer != null) { - rc.timer.dispose(); + if (source instanceof FlowablePublishClassic) { + if (connection != null && connection == rc) { + connection = null; + clearTimer(rc); } - } - if (--rc.subscriberCount == 0) { - if (source instanceof Disposable) { - ((Disposable)source).dispose(); - } else if (source instanceof ResettableConnectable) { - ((ResettableConnectable)source).resetIf(rc.get()); + + if (--rc.subscriberCount == 0) { + reset(rc); + } + } else { + if (connection != null && connection == rc) { + clearTimer(rc); + if (--rc.subscriberCount == 0) { + connection = null; + reset(rc); + } } } } } + void clearTimer(RefConnection rc) { + if (rc.timer != null) { + rc.timer.dispose(); + rc.timer = null; + } + } + + void reset(RefConnection rc) { + if (source instanceof Disposable) { + ((Disposable)source).dispose(); + } else if (source instanceof ResettableConnectable) { + ((ResettableConnectable)source).resetIf(rc.get()); + } + } + void timeout(RefConnection rc) { synchronized (this) { if (rc.subscriberCount == 0 && rc == connection) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java index 5306f4481d..27e633c664 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableRefCount.java @@ -112,22 +112,42 @@ void cancel(RefConnection rc) { void terminated(RefConnection rc) { synchronized (this) { - if (connection != null && connection == rc) { - connection = null; - if (rc.timer != null) { - rc.timer.dispose(); + if (source instanceof ObservablePublishClassic) { + if (connection != null && connection == rc) { + connection = null; + clearTimer(rc); } - } - if (--rc.subscriberCount == 0) { - if (source instanceof Disposable) { - ((Disposable)source).dispose(); - } else if (source instanceof ResettableConnectable) { - ((ResettableConnectable)source).resetIf(rc.get()); + + if (--rc.subscriberCount == 0) { + reset(rc); + } + } else { + if (connection != null && connection == rc) { + clearTimer(rc); + if (--rc.subscriberCount == 0) { + connection = null; + reset(rc); + } } } } } + void clearTimer(RefConnection rc) { + if (rc.timer != null) { + rc.timer.dispose(); + rc.timer = null; + } + } + + void reset(RefConnection rc) { + if (source instanceof Disposable) { + ((Disposable)source).dispose(); + } else if (source instanceof ResettableConnectable) { + ((ResettableConnectable)source).resetIf(rc.get()); + } + } + void timeout(RefConnection rc) { synchronized (this) { if (rc.subscriberCount == 0 && rc == connection) { diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java index 2ee23b2dc1..c8eca05dca 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountAltTest.java @@ -1443,4 +1443,23 @@ public void publishRefCountShallBeThreadSafe() { .assertComplete(); } } + + @Test + public void upstreamTerminationTriggersAnotherCancel() throws Exception { + ReplayProcessor<Integer> rp = ReplayProcessor.create(); + rp.onNext(1); + rp.onComplete(); + + Flowable<Integer> shared = rp.share(); + + shared + .buffer(shared.debounce(5, TimeUnit.SECONDS)) + .test() + .assertValueCount(2); + + shared + .buffer(shared.debounce(5, TimeUnit.SECONDS)) + .test() + .assertValueCount(2); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java index 3cb5f57fb0..c032e61da5 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.io.IOException; @@ -1436,4 +1437,23 @@ public void disconnectBeforeConnect() { flowable.take(1).test().assertResult(2); } + + @Test + public void upstreamTerminationTriggersAnotherCancel() throws Exception { + ReplayProcessor<Integer> rp = ReplayProcessor.create(); + rp.onNext(1); + rp.onComplete(); + + Flowable<Integer> shared = rp.share(); + + shared + .buffer(shared.debounce(5, TimeUnit.SECONDS)) + .test() + .assertValueCount(2); + + shared + .buffer(shared.debounce(5, TimeUnit.SECONDS)) + .test() + .assertValueCount(2); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java index 05aada6b84..0f675bd15d 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountAltTest.java @@ -1399,4 +1399,23 @@ public void publishRefCountShallBeThreadSafe() { .assertComplete(); } } + + @Test + public void upstreamTerminationTriggersAnotherCancel() throws Exception { + ReplaySubject<Integer> rs = ReplaySubject.create(); + rs.onNext(1); + rs.onComplete(); + + Observable<Integer> shared = rs.share(); + + shared + .buffer(shared.debounce(5, TimeUnit.SECONDS)) + .test() + .assertValueCount(2); + + shared + .buffer(shared.debounce(5, TimeUnit.SECONDS)) + .test() + .assertValueCount(2); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java index 99a2a79f79..485afc54e1 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java @@ -1380,4 +1380,23 @@ public void disconnectBeforeConnect() { observable.take(1).test().assertResult(2); } + + @Test + public void upstreamTerminationTriggersAnotherCancel() throws Exception { + ReplaySubject<Integer> rs = ReplaySubject.create(); + rs.onNext(1); + rs.onComplete(); + + Observable<Integer> shared = rs.share(); + + shared + .buffer(shared.debounce(5, TimeUnit.SECONDS)) + .test() + .assertValueCount(2); + + shared + .buffer(shared.debounce(5, TimeUnit.SECONDS)) + .test() + .assertValueCount(2); + } } From 13772a173cb6a59643dfd5eaf023a1412f804096 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sun, 25 Aug 2019 20:30:24 +0200 Subject: [PATCH 383/417] Release 2.2.12 --- CHANGES.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 5e373bc389..fb4c345d29 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,14 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.12 - August 25, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.12%7C)) + +#### Bugfixes + + - [Pull 6618](https://github.com/ReactiveX/RxJava/pull/6618): Fix `switchMap` incorrect sync-fusion & error management. + - [Pull 6627](https://github.com/ReactiveX/RxJava/pull/6627): Fix `blockingIterable` hang when force-disposed. + - [Pull 6629](https://github.com/ReactiveX/RxJava/pull/6629): Fix `refCount` not resetting when cross-canceled. + ### Version 2.2.11 - August 2, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.11%7C)) #### Bugfixes From cc690ff2f757873b11cd075ebc22262f76f28459 Mon Sep 17 00:00:00 2001 From: akarnokd <akarnokd@gmail.com> Date: Wed, 28 Aug 2019 13:08:50 +0200 Subject: [PATCH 384/417] 2.x: Avoid using System.getProperties(), some cleanup, up RS 1.0.3 --- build.gradle | 2 +- .../CompletableAndThenCompletable.java | 2 +- .../operators/flowable/FlowablePublish.java | 1 + .../flowable/FlowablePublishAlt.java | 1 + .../flowable/FlowablePublishClassic.java | 2 + .../observable/ObservablePublishAlt.java | 4 +- .../observable/ObservablePublishClassic.java | 1 + .../schedulers/SchedulerPoolFactory.java | 60 ++++++++------ .../reactivex/observers/BaseTestConsumer.java | 1 - .../schedulers/SchedulerPoolFactoryTest.java | 82 +++++++++++-------- 10 files changed, 91 insertions(+), 65 deletions(-) diff --git a/build.gradle b/build.gradle index 2f33e66093..48565d07d0 100644 --- a/build.gradle +++ b/build.gradle @@ -52,7 +52,7 @@ targetCompatibility = JavaVersion.VERSION_1_6 // --------------------------------------- def junitVersion = "4.12" -def reactiveStreamsVersion = "1.0.2" +def reactiveStreamsVersion = "1.0.3" def mockitoVersion = "2.1.0" def jmhLibVersion = "1.20" def testNgVersion = "6.11" diff --git a/src/main/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletable.java b/src/main/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletable.java index 20d2332214..ff7b6cced5 100644 --- a/src/main/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletable.java +++ b/src/main/java/io/reactivex/internal/operators/completable/CompletableAndThenCompletable.java @@ -84,7 +84,7 @@ static final class NextObserver implements CompletableObserver { final CompletableObserver downstream; - public NextObserver(AtomicReference<Disposable> parent, CompletableObserver downstream) { + NextObserver(AtomicReference<Disposable> parent, CompletableObserver downstream) { this.parent = parent; this.downstream = downstream; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java index e573f3daf3..b325d2b78d 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java @@ -79,6 +79,7 @@ public Publisher<T> source() { } /** + * The internal buffer size of this FloawblePublish operator. * @return The internal buffer size of this FloawblePublish operator. */ @Override diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishAlt.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishAlt.java index d58ba84503..932e0bf003 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishAlt.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishAlt.java @@ -62,6 +62,7 @@ public Publisher<T> source() { } /** + * The internal buffer size of this FloawblePublishAlt operator. * @return The internal buffer size of this FloawblePublishAlt operator. */ public int publishBufferSize() { diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishClassic.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishClassic.java index 0cbf70efad..27ded26592 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishClassic.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowablePublishClassic.java @@ -30,11 +30,13 @@ public interface FlowablePublishClassic<T> { /** + * The upstream source of this publish operator. * @return the upstream source of this publish operator */ Publisher<T> publishSource(); /** + * The internal buffer size of this publish operator. * @return the internal buffer size of this publish operator */ int publishBufferSize(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishAlt.java b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishAlt.java index 771e58dda8..a9e62babde 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishAlt.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishAlt.java @@ -146,7 +146,7 @@ static final class PublishConnection<T> Throwable error; @SuppressWarnings("unchecked") - public PublishConnection(AtomicReference<PublishConnection<T>> current) { + PublishConnection(AtomicReference<PublishConnection<T>> current) { this.connect = new AtomicBoolean(); this.current = current; this.upstream = new AtomicReference<Disposable>(); @@ -261,7 +261,7 @@ static final class InnerDisposable<T> final Observer<? super T> downstream; - public InnerDisposable(Observer<? super T> downstream, PublishConnection<T> parent) { + InnerDisposable(Observer<? super T> downstream, PublishConnection<T> parent) { this.downstream = downstream; lazySet(parent); } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishClassic.java b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishClassic.java index f072779930..b2bfe87f71 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishClassic.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservablePublishClassic.java @@ -30,6 +30,7 @@ public interface ObservablePublishClassic<T> { /** + * The upstream source of this publish operator. * @return the upstream source of this publish operator */ ObservableSource<T> publishSource(); diff --git a/src/main/java/io/reactivex/internal/schedulers/SchedulerPoolFactory.java b/src/main/java/io/reactivex/internal/schedulers/SchedulerPoolFactory.java index b0b1339d29..ab465046aa 100644 --- a/src/main/java/io/reactivex/internal/schedulers/SchedulerPoolFactory.java +++ b/src/main/java/io/reactivex/internal/schedulers/SchedulerPoolFactory.java @@ -20,6 +20,8 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; +import io.reactivex.functions.Function; + /** * Manages the creating of ScheduledExecutorServices and sets up purging. */ @@ -90,40 +92,48 @@ public static void shutdown() { } static { - Properties properties = System.getProperties(); - - PurgeProperties pp = new PurgeProperties(); - pp.load(properties); - - PURGE_ENABLED = pp.purgeEnable; - PURGE_PERIOD_SECONDS = pp.purgePeriod; + SystemPropertyAccessor propertyAccessor = new SystemPropertyAccessor(); + PURGE_ENABLED = getBooleanProperty(true, PURGE_ENABLED_KEY, true, true, propertyAccessor); + PURGE_PERIOD_SECONDS = getIntProperty(PURGE_ENABLED, PURGE_PERIOD_SECONDS_KEY, 1, 1, propertyAccessor); start(); } - static final class PurgeProperties { - - boolean purgeEnable; - - int purgePeriod; - - void load(Properties properties) { - if (properties.containsKey(PURGE_ENABLED_KEY)) { - purgeEnable = Boolean.parseBoolean(properties.getProperty(PURGE_ENABLED_KEY)); - } else { - purgeEnable = true; + static int getIntProperty(boolean enabled, String key, int defaultNotFound, int defaultNotEnabled, Function<String, String> propertyAccessor) { + if (enabled) { + try { + String value = propertyAccessor.apply(key); + if (value == null) { + return defaultNotFound; + } + return Integer.parseInt(value); + } catch (Throwable ex) { + return defaultNotFound; } + } + return defaultNotEnabled; + } - if (purgeEnable && properties.containsKey(PURGE_PERIOD_SECONDS_KEY)) { - try { - purgePeriod = Integer.parseInt(properties.getProperty(PURGE_PERIOD_SECONDS_KEY)); - } catch (NumberFormatException ex) { - purgePeriod = 1; + static boolean getBooleanProperty(boolean enabled, String key, boolean defaultNotFound, boolean defaultNotEnabled, Function<String, String> propertyAccessor) { + if (enabled) { + try { + String value = propertyAccessor.apply(key); + if (value == null) { + return defaultNotFound; } - } else { - purgePeriod = 1; + return "true".equals(value); + } catch (Throwable ex) { + return defaultNotFound; } } + return defaultNotEnabled; + } + + static final class SystemPropertyAccessor implements Function<String, String> { + @Override + public String apply(String t) throws Exception { + return System.getProperty(t); + } } /** diff --git a/src/main/java/io/reactivex/observers/BaseTestConsumer.java b/src/main/java/io/reactivex/observers/BaseTestConsumer.java index 61db5a2356..4c92c27468 100644 --- a/src/main/java/io/reactivex/observers/BaseTestConsumer.java +++ b/src/main/java/io/reactivex/observers/BaseTestConsumer.java @@ -555,7 +555,6 @@ public final U assertValues(T... values) { * @return this * @since 2.2 */ - @SuppressWarnings("unchecked") public final U assertValuesOnly(T... values) { return assertSubscribed() .assertValues(values) diff --git a/src/test/java/io/reactivex/internal/schedulers/SchedulerPoolFactoryTest.java b/src/test/java/io/reactivex/internal/schedulers/SchedulerPoolFactoryTest.java index 603929ddb4..24b3daa801 100644 --- a/src/test/java/io/reactivex/internal/schedulers/SchedulerPoolFactoryTest.java +++ b/src/test/java/io/reactivex/internal/schedulers/SchedulerPoolFactoryTest.java @@ -18,12 +18,11 @@ import static org.junit.Assert.*; -import java.util.Properties; - import org.junit.Test; import io.reactivex.TestHelper; -import io.reactivex.internal.schedulers.SchedulerPoolFactory.PurgeProperties; +import io.reactivex.functions.Function; +import io.reactivex.internal.functions.Functions; import io.reactivex.schedulers.Schedulers; public class SchedulerPoolFactoryTest { @@ -78,53 +77,66 @@ public void run() { } @Test - public void loadPurgeProperties() { - Properties props1 = new Properties(); - - PurgeProperties pp = new PurgeProperties(); - pp.load(props1); - - assertTrue(pp.purgeEnable); - assertEquals(pp.purgePeriod, 1); + public void boolPropertiesDisabledReturnsDefaultDisabled() throws Throwable { + assertTrue(SchedulerPoolFactory.getBooleanProperty(false, "key", false, true, failingPropertiesAccessor)); + assertFalse(SchedulerPoolFactory.getBooleanProperty(false, "key", true, false, failingPropertiesAccessor)); } @Test - public void loadPurgePropertiesDisabled() { - Properties props1 = new Properties(); - props1.setProperty(SchedulerPoolFactory.PURGE_ENABLED_KEY, "false"); + public void boolPropertiesEnabledMissingReturnsDefaultMissing() throws Throwable { + assertTrue(SchedulerPoolFactory.getBooleanProperty(true, "key", true, false, missingPropertiesAccessor)); + assertFalse(SchedulerPoolFactory.getBooleanProperty(true, "key", false, true, missingPropertiesAccessor)); + } - PurgeProperties pp = new PurgeProperties(); - pp.load(props1); + @Test + public void boolPropertiesFailureReturnsDefaultMissing() throws Throwable { + assertTrue(SchedulerPoolFactory.getBooleanProperty(true, "key", true, false, failingPropertiesAccessor)); + assertFalse(SchedulerPoolFactory.getBooleanProperty(true, "key", false, true, failingPropertiesAccessor)); + } - assertFalse(pp.purgeEnable); - assertEquals(pp.purgePeriod, 1); + @Test + public void boolPropertiesReturnsValue() throws Throwable { + assertTrue(SchedulerPoolFactory.getBooleanProperty(true, "true", true, false, Functions.<String>identity())); + assertFalse(SchedulerPoolFactory.getBooleanProperty(true, "false", false, true, Functions.<String>identity())); } @Test - public void loadPurgePropertiesEnabledCustomPeriod() { - Properties props1 = new Properties(); - props1.setProperty(SchedulerPoolFactory.PURGE_ENABLED_KEY, "true"); - props1.setProperty(SchedulerPoolFactory.PURGE_PERIOD_SECONDS_KEY, "2"); + public void intPropertiesDisabledReturnsDefaultDisabled() throws Throwable { + assertEquals(-1, SchedulerPoolFactory.getIntProperty(false, "key", 0, -1, failingPropertiesAccessor)); + assertEquals(-1, SchedulerPoolFactory.getIntProperty(false, "key", 1, -1, failingPropertiesAccessor)); + } - PurgeProperties pp = new PurgeProperties(); - pp.load(props1); + @Test + public void intPropertiesEnabledMissingReturnsDefaultMissing() throws Throwable { + assertEquals(-1, SchedulerPoolFactory.getIntProperty(true, "key", -1, 0, missingPropertiesAccessor)); + assertEquals(-1, SchedulerPoolFactory.getIntProperty(true, "key", -1, 1, missingPropertiesAccessor)); + } - assertTrue(pp.purgeEnable); - assertEquals(pp.purgePeriod, 2); + @Test + public void intPropertiesFailureReturnsDefaultMissing() throws Throwable { + assertEquals(-1, SchedulerPoolFactory.getIntProperty(true, "key", -1, 0, failingPropertiesAccessor)); + assertEquals(-1, SchedulerPoolFactory.getIntProperty(true, "key", -1, 1, failingPropertiesAccessor)); } @Test - public void loadPurgePropertiesEnabledCustomPeriodNaN() { - Properties props1 = new Properties(); - props1.setProperty(SchedulerPoolFactory.PURGE_ENABLED_KEY, "true"); - props1.setProperty(SchedulerPoolFactory.PURGE_PERIOD_SECONDS_KEY, "abc"); + public void intPropertiesReturnsValue() throws Throwable { + assertEquals(1, SchedulerPoolFactory.getIntProperty(true, "1", 0, 4, Functions.<String>identity())); + assertEquals(2, SchedulerPoolFactory.getIntProperty(true, "2", 3, 5, Functions.<String>identity())); + } - PurgeProperties pp = new PurgeProperties(); - pp.load(props1); + static final Function<String, String> failingPropertiesAccessor = new Function<String, String>() { + @Override + public String apply(String v) throws Exception { + throw new SecurityException(); + } + }; - assertTrue(pp.purgeEnable); - assertEquals(pp.purgePeriod, 1); - } + static final Function<String, String> missingPropertiesAccessor = new Function<String, String>() { + @Override + public String apply(String v) throws Exception { + return null; + } + }; @Test public void putIntoPoolNoPurge() { From 71bfcae35b8052c21e8564c417ae0a870eb5ddb8 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 13 Sep 2019 17:50:08 +0200 Subject: [PATCH 385/417] 3.x: Fix takeLast(time) last events time window calculation. (#6653) --- .../observable/ObservableTakeLastTimed.java | 3 ++- .../io/reactivex/TimesteppingScheduler.java | 11 ++++++--- .../flowable/FlowableTakeLastTimedTest.java | 23 +++++++++++++++++++ .../ObservableTakeLastTimedTest.java | 23 +++++++++++++++++++ 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimed.java index 7bd29092b4..213588032b 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimed.java @@ -139,6 +139,7 @@ void drain() { final Observer<? super T> a = downstream; final SpscLinkedArrayQueue<Object> q = queue; final boolean delayError = this.delayError; + final long timestampLimit = scheduler.now(unit) - time; for (;;) { if (cancelled) { @@ -171,7 +172,7 @@ void drain() { @SuppressWarnings("unchecked") T o = (T)q.poll(); - if ((Long)ts < scheduler.now(unit) - time) { + if ((Long)ts < timestampLimit) { continue; } diff --git a/src/test/java/io/reactivex/TimesteppingScheduler.java b/src/test/java/io/reactivex/TimesteppingScheduler.java index 73996cc56f..1bf0df2b8e 100644 --- a/src/test/java/io/reactivex/TimesteppingScheduler.java +++ b/src/test/java/io/reactivex/TimesteppingScheduler.java @@ -42,11 +42,13 @@ public Disposable schedule(Runnable run, long delay, TimeUnit unit) { @Override public long now(TimeUnit unit) { - return time++; + return TimesteppingScheduler.this.now(unit); } } - long time; + public long time; + + public boolean stepEnabled; @Override public Worker createWorker() { @@ -55,6 +57,9 @@ public Worker createWorker() { @Override public long now(TimeUnit unit) { - return time++; + if (stepEnabled) { + return time++; + } + return time; } } \ No newline at end of file diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java index 4864cac7f6..5f2cda82ea 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTimedTest.java @@ -336,4 +336,27 @@ public Publisher<Object> apply(Flowable<Object> f) throws Exception { public void badRequest() { TestHelper.assertBadRequestReported(PublishProcessor.create().takeLast(1, TimeUnit.SECONDS)); } + + @Test + public void lastWindowIsFixedInTime() { + TimesteppingScheduler scheduler = new TimesteppingScheduler(); + scheduler.stepEnabled = false; + + PublishProcessor<Integer> pp = PublishProcessor.create(); + + TestSubscriber<Integer> ts = pp + .takeLast(2, TimeUnit.SECONDS, scheduler) + .test(); + + pp.onNext(1); + pp.onNext(2); + pp.onNext(3); + pp.onNext(4); + + scheduler.stepEnabled = true; + + pp.onComplete(); + + ts.assertResult(1, 2, 3, 4); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java index 9269bd0b5a..2aa3f38c7e 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java @@ -275,4 +275,27 @@ public void run() { TestHelper.race(r1, r2); } } + + @Test + public void lastWindowIsFixedInTime() { + TimesteppingScheduler scheduler = new TimesteppingScheduler(); + scheduler.stepEnabled = false; + + PublishSubject<Integer> ps = PublishSubject.create(); + + TestObserver<Integer> to = ps + .takeLast(2, TimeUnit.SECONDS, scheduler) + .test(); + + ps.onNext(1); + ps.onNext(2); + ps.onNext(3); + ps.onNext(4); + + scheduler.stepEnabled = true; + + ps.onComplete(); + + to.assertResult(1, 2, 3, 4); + } } From 1cf6e3e73a1ac48abca17d8e76b18b946cf86a8a Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 30 Sep 2019 12:43:09 +0200 Subject: [PATCH 386/417] 2.x: Fix size+time bound window not creating windows properly (#6657) --- .../flowable/FlowableWindowTimed.java | 2 +- .../observable/ObservableWindowTimed.java | 2 +- .../flowable/FlowableWindowTests.java | 45 ++++++++++++++++++- .../flowable/FlowableWindowWithTimeTest.java | 14 +++--- .../ObservableWindowWithTimeTest.java | 14 +++--- .../observable/ObservableWindowTests.java | 44 ++++++++++++++++++ 6 files changed, 106 insertions(+), 15 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java index ae284ef27a..00f783a39e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java @@ -498,7 +498,7 @@ void drainLoop() { if (isHolder) { ConsumerIndexHolder consumerIndexHolder = (ConsumerIndexHolder) o; - if (restartTimerOnMaxSize || producerIndex == consumerIndexHolder.index) { + if (!restartTimerOnMaxSize || producerIndex == consumerIndexHolder.index) { w.onComplete(); count = 0; w = UnicastProcessor.<T>create(bufferSize); diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java index 1ffc0f475e..406d8f03ff 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java @@ -444,7 +444,7 @@ void drainLoop() { if (isHolder) { ConsumerIndexHolder consumerIndexHolder = (ConsumerIndexHolder) o; - if (restartTimerOnMaxSize || producerIndex == consumerIndexHolder.index) { + if (!restartTimerOnMaxSize || producerIndex == consumerIndexHolder.index) { w.onComplete(); count = 0; w = UnicastSubject.create(bufferSize); diff --git a/src/test/java/io/reactivex/flowable/FlowableWindowTests.java b/src/test/java/io/reactivex/flowable/FlowableWindowTests.java index 9ef4211aa4..08151bcb8b 100644 --- a/src/test/java/io/reactivex/flowable/FlowableWindowTests.java +++ b/src/test/java/io/reactivex/flowable/FlowableWindowTests.java @@ -16,11 +16,15 @@ import static org.junit.Assert.*; import java.util.*; +import java.util.concurrent.TimeUnit; import org.junit.Test; -import io.reactivex.Flowable; +import io.reactivex.*; import io.reactivex.functions.*; +import io.reactivex.processors.PublishProcessor; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; public class FlowableWindowTests { @@ -50,4 +54,43 @@ public void accept(List<Integer> xs) { assertEquals(2, lists.size()); } + + @Test + public void timeSizeWindowAlternatingBounds() { + TestScheduler scheduler = new TestScheduler(); + PublishProcessor<Integer> pp = PublishProcessor.create(); + + TestSubscriber<List<Integer>> ts = pp.window(5, TimeUnit.SECONDS, scheduler, 2) + .flatMapSingle(new Function<Flowable<Integer>, SingleSource<List<Integer>>>() { + @Override + public SingleSource<List<Integer>> apply(Flowable<Integer> v) { + return v.toList(); + } + }) + .test(); + + pp.onNext(1); + pp.onNext(2); + ts.assertValueCount(1); // size bound hit + + scheduler.advanceTimeBy(1, TimeUnit.SECONDS); + pp.onNext(3); + scheduler.advanceTimeBy(6, TimeUnit.SECONDS); + ts.assertValueCount(2); // time bound hit + + pp.onNext(4); + pp.onNext(5); + + ts.assertValueCount(3); // size bound hit again + + pp.onNext(4); + + scheduler.advanceTimeBy(6, TimeUnit.SECONDS); + + ts.assertValueCount(4) + .assertNoErrors() + .assertNotComplete(); + + ts.cancel(); + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java index 157faae1a5..37d8928571 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java @@ -64,17 +64,19 @@ public void subscribe(Subscriber<? super String> subscriber) { Flowable<Flowable<String>> windowed = source.window(100, TimeUnit.MILLISECONDS, scheduler, 2); windowed.subscribe(observeWindow(list, lists)); - scheduler.advanceTimeTo(100, TimeUnit.MILLISECONDS); + scheduler.advanceTimeTo(95, TimeUnit.MILLISECONDS); assertEquals(1, lists.size()); assertEquals(lists.get(0), list("one", "two")); - scheduler.advanceTimeTo(200, TimeUnit.MILLISECONDS); - assertEquals(2, lists.size()); - assertEquals(lists.get(1), list("three", "four")); + scheduler.advanceTimeTo(195, TimeUnit.MILLISECONDS); + assertEquals(3, lists.size()); + assertTrue(lists.get(1).isEmpty()); + assertEquals(lists.get(2), list("three", "four")); scheduler.advanceTimeTo(300, TimeUnit.MILLISECONDS); - assertEquals(3, lists.size()); - assertEquals(lists.get(2), list("five")); + assertEquals(5, lists.size()); + assertTrue(lists.get(3).isEmpty()); + assertEquals(lists.get(4), list("five")); } @Test diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java index 4eb90f4e50..fbd90088ed 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java @@ -64,17 +64,19 @@ public void subscribe(Observer<? super String> observer) { Observable<Observable<String>> windowed = source.window(100, TimeUnit.MILLISECONDS, scheduler, 2); windowed.subscribe(observeWindow(list, lists)); - scheduler.advanceTimeTo(100, TimeUnit.MILLISECONDS); + scheduler.advanceTimeTo(95, TimeUnit.MILLISECONDS); assertEquals(1, lists.size()); assertEquals(lists.get(0), list("one", "two")); - scheduler.advanceTimeTo(200, TimeUnit.MILLISECONDS); - assertEquals(2, lists.size()); - assertEquals(lists.get(1), list("three", "four")); + scheduler.advanceTimeTo(195, TimeUnit.MILLISECONDS); + assertEquals(3, lists.size()); + assertTrue(lists.get(1).isEmpty()); + assertEquals(lists.get(2), list("three", "four")); scheduler.advanceTimeTo(300, TimeUnit.MILLISECONDS); - assertEquals(3, lists.size()); - assertEquals(lists.get(2), list("five")); + assertEquals(5, lists.size()); + assertTrue(lists.get(3).isEmpty()); + assertEquals(lists.get(4), list("five")); } @Test diff --git a/src/test/java/io/reactivex/observable/ObservableWindowTests.java b/src/test/java/io/reactivex/observable/ObservableWindowTests.java index d4c68fd63b..701b07e0b7 100644 --- a/src/test/java/io/reactivex/observable/ObservableWindowTests.java +++ b/src/test/java/io/reactivex/observable/ObservableWindowTests.java @@ -16,11 +16,16 @@ import static org.junit.Assert.*; import java.util.*; +import java.util.concurrent.TimeUnit; import org.junit.Test; import io.reactivex.Observable; +import io.reactivex.SingleSource; import io.reactivex.functions.*; +import io.reactivex.observers.TestObserver; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subjects.PublishSubject; public class ObservableWindowTests { @@ -50,4 +55,43 @@ public void accept(List<Integer> xs) { assertEquals(2, lists.size()); } + + @Test + public void timeSizeWindowAlternatingBounds() { + TestScheduler scheduler = new TestScheduler(); + PublishSubject<Integer> ps = PublishSubject.create(); + + TestObserver<List<Integer>> to = ps.window(5, TimeUnit.SECONDS, scheduler, 2) + .flatMapSingle(new Function<Observable<Integer>, SingleSource<List<Integer>>>() { + @Override + public SingleSource<List<Integer>> apply(Observable<Integer> v) { + return v.toList(); + } + }) + .test(); + + ps.onNext(1); + ps.onNext(2); + to.assertValueCount(1); // size bound hit + + scheduler.advanceTimeBy(1, TimeUnit.SECONDS); + ps.onNext(3); + scheduler.advanceTimeBy(6, TimeUnit.SECONDS); + to.assertValueCount(2); // time bound hit + + ps.onNext(4); + ps.onNext(5); + + to.assertValueCount(3); // size bound hit again + + ps.onNext(4); + + scheduler.advanceTimeBy(6, TimeUnit.SECONDS); + + to.assertValueCount(4) + .assertNoErrors() + .assertNotComplete(); + + to.dispose(); + } } From d4eae73fb2c8f09f9ab05de22444009cb0ea4c45 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 3 Oct 2019 09:46:59 +0200 Subject: [PATCH 387/417] Release 2.2.13 --- CHANGES.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index fb4c345d29..af5f1d3074 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,18 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.13 - October 3, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.13%7C)) + +#### Dependencies + + - [Commit cc690ff2](https://github.com/ReactiveX/RxJava/commit/cc690ff2f757873b11cd075ebc22262f76f28459): Upgrade to **Reactive Streams 1.0.3**. + +#### Bugfixes + + - [Commit cc690ff2](https://github.com/ReactiveX/RxJava/commit/cc690ff2f757873b11cd075ebc22262f76f28459): Avoid using `System.getProperties()`. + - [Pull 6653](https://github.com/ReactiveX/RxJava/pull/6653): Fix `takeLast(time)` last events time window calculation. + - [Pull 6657](https://github.com/ReactiveX/RxJava/pull/6657): Fix size+time bound `window` not creating windows properly. + ### Version 2.2.12 - August 25, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.12%7C)) #### Bugfixes From 70fe91c7f7074cc36df93e3e2b22b077d9786ffe Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 17 Oct 2019 16:38:46 +0200 Subject: [PATCH 388/417] 2.x: Fix concurrent clear() calls when fused chains are canceled (#6677) --- .../operators/flowable/FlowableGroupBy.java | 3 +- .../FlowableOnBackpressureBuffer.java | 2 +- .../processors/UnicastProcessor.java | 8 +- .../io/reactivex/subjects/UnicastSubject.java | 5 +- .../flowable/FlowableGroupByTest.java | 85 ++++++++++++++++++- .../FlowableOnBackpressureBufferTest.java | 40 ++++++++- .../processors/UnicastProcessorTest.java | 41 ++++++++- .../subjects/UnicastSubjectTest.java | 40 ++++++++- 8 files changed, 208 insertions(+), 16 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java index 719645afe9..11ec41a0f2 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java @@ -262,7 +262,7 @@ public void cancel(K key) { if (groupCount.decrementAndGet() == 0) { upstream.cancel(); - if (getAndIncrement() == 0) { + if (!outputFused && getAndIncrement() == 0) { queue.clear(); } } @@ -288,7 +288,6 @@ void drainFused() { for (;;) { if (cancelled.get()) { - q.clear(); return; } diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBuffer.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBuffer.java index 20caa2c7e3..8cbb73ebf2 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBuffer.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBuffer.java @@ -150,7 +150,7 @@ public void cancel() { cancelled = true; upstream.cancel(); - if (getAndIncrement() == 0) { + if (!outputFused && getAndIncrement() == 0) { queue.clear(); } } diff --git a/src/main/java/io/reactivex/processors/UnicastProcessor.java b/src/main/java/io/reactivex/processors/UnicastProcessor.java index 94547b88fb..ec4d6c1a77 100644 --- a/src/main/java/io/reactivex/processors/UnicastProcessor.java +++ b/src/main/java/io/reactivex/processors/UnicastProcessor.java @@ -347,7 +347,6 @@ void drainFused(Subscriber<? super T> a) { for (;;) { if (cancelled) { - q.clear(); downstream.lazySet(null); return; } @@ -550,10 +549,11 @@ public void cancel() { doTerminate(); - if (!enableOperatorFusion) { - if (wip.getAndIncrement() == 0) { + downstream.lazySet(null); + if (wip.getAndIncrement() == 0) { + downstream.lazySet(null); + if (!enableOperatorFusion) { queue.clear(); - downstream.lazySet(null); } } } diff --git a/src/main/java/io/reactivex/subjects/UnicastSubject.java b/src/main/java/io/reactivex/subjects/UnicastSubject.java index 8c3eae8af0..20aadbd460 100644 --- a/src/main/java/io/reactivex/subjects/UnicastSubject.java +++ b/src/main/java/io/reactivex/subjects/UnicastSubject.java @@ -420,7 +420,6 @@ void drainFused(Observer<? super T> a) { if (disposed) { downstream.lazySet(null); - q.clear(); return; } boolean d = done; @@ -558,7 +557,9 @@ public void dispose() { downstream.lazySet(null); if (wip.getAndIncrement() == 0) { downstream.lazySet(null); - queue.clear(); + if (!enableOperatorFusion) { + queue.clear(); + } } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index 63d6152a3e..85501e2578 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.io.IOException; @@ -29,12 +30,13 @@ import com.google.common.cache.*; import io.reactivex.*; -import io.reactivex.exceptions.TestException; +import io.reactivex.exceptions.*; import io.reactivex.flowables.GroupedFlowable; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; -import io.reactivex.internal.fuseable.QueueFuseable; +import io.reactivex.internal.fuseable.*; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; @@ -2205,4 +2207,83 @@ public void accept(Object object) { }}; return evictingMapFactory; } + + @Test + public void fusedNoConcurrentCleanDueToCancel() { + for (int j = 0; j < TestHelper.RACE_LONG_LOOPS; j++) { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + final AtomicReference<QueueSubscription<GroupedFlowable<Object, Integer>>> qs = new AtomicReference<QueueSubscription<GroupedFlowable<Object, Integer>>>(); + + final TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(); + + pp.groupBy(Functions.identity(), Functions.<Integer>identity(), false, 4) + .subscribe(new FlowableSubscriber<GroupedFlowable<Object, Integer>>() { + + boolean once; + + @Override + public void onNext(GroupedFlowable<Object, Integer> g) { + if (!once) { + try { + GroupedFlowable<Object, Integer> t = qs.get().poll(); + if (t != null) { + once = true; + t.subscribe(ts2); + } + } catch (Throwable ignored) { + // not relevant here + } + } + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onComplete() { + } + + @Override + public void onSubscribe(Subscription s) { + @SuppressWarnings("unchecked") + QueueSubscription<GroupedFlowable<Object, Integer>> q = (QueueSubscription<GroupedFlowable<Object, Integer>>)s; + qs.set(q); + q.requestFusion(QueueFuseable.ANY); + q.request(1); + } + }) + ; + + Runnable r1 = new Runnable() { + @Override + public void run() { + qs.get().cancel(); + qs.get().clear(); + } + }; + Runnable r2 = new Runnable() { + @Override + public void run() { + ts2.cancel(); + } + }; + + for (int i = 0; i < 100; i++) { + pp.onNext(i); + } + + TestHelper.race(r1, r2); + + if (!errors.isEmpty()) { + throw new CompositeException(errors); + } + } finally { + RxJavaPlugins.reset(); + } + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java index f44fbc8353..be7fe522da 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBufferTest.java @@ -15,17 +15,22 @@ import static org.junit.Assert.*; +import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import org.reactivestreams.*; -import io.reactivex.Flowable; +import io.reactivex.*; import io.reactivex.exceptions.*; import io.reactivex.functions.*; +import io.reactivex.internal.functions.Functions; import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.observers.TestObserver; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.*; @@ -307,4 +312,37 @@ public void fusionRejected() { SubscriberFusion.assertFusion(ts, QueueFuseable.NONE) .assertEmpty(); } + + @Test + public void fusedNoConcurrentCleanDueToCancel() { + for (int j = 0; j < TestHelper.RACE_LONG_LOOPS; j++) { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + TestObserver<Integer> to = pp.onBackpressureBuffer(4, false, true) + .observeOn(Schedulers.io()) + .map(Functions.<Integer>identity()) + .observeOn(Schedulers.single()) + .firstOrError() + .test(); + + for (int i = 0; pp.hasSubscribers(); i++) { + pp.onNext(i); + } + + to + .awaitDone(5, TimeUnit.SECONDS) + ; + + if (!errors.isEmpty()) { + throw new CompositeException(errors); + } + + to.assertResult(0); + } finally { + RxJavaPlugins.reset(); + } + } + } } diff --git a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java index 84335845a9..7b96e03b53 100644 --- a/src/test/java/io/reactivex/processors/UnicastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/UnicastProcessorTest.java @@ -16,16 +16,20 @@ import static org.junit.Assert.*; import java.util.List; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import io.reactivex.*; import io.reactivex.disposables.Disposable; -import io.reactivex.exceptions.TestException; -import io.reactivex.internal.fuseable.*; +import io.reactivex.exceptions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.*; public class UnicastProcessorTest extends FlowableProcessorTest<Object> { @@ -438,4 +442,37 @@ public void unicastSubscriptionBadRequest() { RxJavaPlugins.reset(); } } + + @Test + public void fusedNoConcurrentCleanDueToCancel() { + for (int j = 0; j < TestHelper.RACE_LONG_LOOPS; j++) { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final UnicastProcessor<Integer> us = UnicastProcessor.create(); + + TestObserver<Integer> to = us + .observeOn(Schedulers.io()) + .map(Functions.<Integer>identity()) + .observeOn(Schedulers.single()) + .firstOrError() + .test(); + + for (int i = 0; us.hasSubscribers(); i++) { + us.onNext(i); + } + + to + .awaitDone(5, TimeUnit.SECONDS) + ; + + if (!errors.isEmpty()) { + throw new CompositeException(errors); + } + + to.assertResult(0); + } finally { + RxJavaPlugins.reset(); + } + } + } } diff --git a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java index 9b0a16879d..ea68601722 100644 --- a/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java +++ b/src/test/java/io/reactivex/subjects/UnicastSubjectTest.java @@ -17,16 +17,19 @@ import static org.mockito.Mockito.mock; import java.util.List; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import io.reactivex.*; import io.reactivex.disposables.*; -import io.reactivex.exceptions.TestException; -import io.reactivex.internal.fuseable.*; +import io.reactivex.exceptions.*; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.fuseable.QueueFuseable; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; public class UnicastSubjectTest extends SubjectTest<Integer> { @@ -456,4 +459,37 @@ public void drainFusedFailFastEmpty() { to.assertEmpty(); } + + @Test + public void fusedNoConcurrentCleanDueToCancel() { + for (int j = 0; j < TestHelper.RACE_LONG_LOOPS; j++) { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final UnicastSubject<Integer> us = UnicastSubject.create(); + + TestObserver<Integer> to = us + .observeOn(Schedulers.io()) + .map(Functions.<Integer>identity()) + .observeOn(Schedulers.single()) + .firstOrError() + .test(); + + for (int i = 0; us.hasObservers(); i++) { + us.onNext(i); + } + + to + .awaitDone(5, TimeUnit.SECONDS) + ; + + if (!errors.isEmpty()) { + throw new CompositeException(errors); + } + + to.assertResult(0); + } finally { + RxJavaPlugins.reset(); + } + } + } } From 90ae2a39a7cf527c353253d2374474fede58aef4 Mon Sep 17 00:00:00 2001 From: Thiyagarajan <38608518+thiyagu-7@users.noreply.github.com> Date: Fri, 18 Oct 2019 11:47:18 +0530 Subject: [PATCH 389/417] Backport marble diagrams for Single from 3.x (#6681) --- src/main/java/io/reactivex/Single.java | 91 ++++++++++++++++++++++++-- 1 file changed, 85 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/Single.java b/src/main/java/io/reactivex/Single.java index 299e6da76f..15ef6b6c14 100644 --- a/src/main/java/io/reactivex/Single.java +++ b/src/main/java/io/reactivex/Single.java @@ -400,6 +400,8 @@ public static <T> Flowable<T> concatArray(SingleSource<? extends T>... sources) /** * Concatenates a sequence of SingleSource eagerly into a single stream of values. * <p> + * <img width="640" height="257" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatArrayEager.png" alt=""> + * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source SingleSources. The operator buffers the value emitted by these SingleSources and then drains them * in order, each one after the previous one completes. @@ -1108,6 +1110,8 @@ public static <T> Flowable<T> merge( /** * Merges an Iterable sequence of SingleSource instances into a single Flowable sequence, * running all SingleSources at once and delaying any error(s) until all sources succeed or fail. + * <p> + * <img width="640" height="469" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeDelayError.i.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -1132,6 +1136,8 @@ public static <T> Flowable<T> mergeDelayError(Iterable<? extends SingleSource<? /** * Merges a Flowable sequence of SingleSource instances into a single Flowable sequence, * running all SingleSources at once and delaying any error(s) until all sources succeed or fail. + * <p> + * <img width="640" height="356" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeDelayError.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> @@ -1159,7 +1165,7 @@ public static <T> Flowable<T> mergeDelayError(Publisher<? extends SingleSource<? * Flattens two Singles into a single Flowable, without any transformation, delaying * any error(s) until all sources succeed or fail. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt=""> + * <img width="640" height="554" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeDelayError.2.png" alt=""> * <p> * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by * using the {@code mergeDelayError} method. @@ -1197,7 +1203,7 @@ public static <T> Flowable<T> mergeDelayError( * Flattens three Singles into a single Flowable, without any transformation, delaying * any error(s) until all sources succeed or fail. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt=""> + * <img width="640" height="496" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeDelayError.3.png" alt=""> * <p> * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by using * the {@code mergeDelayError} method. @@ -1239,7 +1245,7 @@ public static <T> Flowable<T> mergeDelayError( * Flattens four Singles into a single Flowable, without any transformation, delaying * any error(s) until all sources succeed or fail. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt=""> + * <img width="640" height="509" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeDelayError.4.png" alt=""> * <p> * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by using * the {@code mergeDelayError} method. @@ -1370,6 +1376,8 @@ public static <T> Single<Boolean> equals(final SingleSource<? extends T> first, /** * <strong>Advanced use only:</strong> creates a Single instance without * any safeguards by using a callback that is called with a SingleObserver. + * <p> + * <img width="640" height="261" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.unsafeCreate.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code unsafeCreate} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1396,6 +1404,8 @@ public static <T> Single<T> unsafeCreate(SingleSource<T> onSubscribe) { /** * Allows using and disposing a resource while running a SingleSource instance generated from * that resource (similar to a try-with-resources). + * <p> + * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.using.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1423,6 +1433,8 @@ public static <T, U> Single<T> using(Callable<U> resourceSupplier, /** * Allows using and disposing a resource while running a SingleSource instance generated from * that resource (similar to a try-with-resources). + * <p> + * <img width="640" height="325" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.using.b.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd> @@ -1460,6 +1472,8 @@ public static <T, U> Single<T> using( /** * Wraps a SingleSource instance into a new Single instance if not already a Single * instance. + * <p> + * <img width="640" height="350" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.wrap.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code wrap} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2067,6 +2081,7 @@ public final <R> Single<R> compose(SingleTransformer<? super T, ? extends R> tra /** * Stores the success value or exception from the current Single and replays it to late SingleObservers. * <p> + * <img width="640" height="363" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.cache.png" alt=""> * The returned Single subscribes to the current Single when the first SingleObserver subscribes. * <dl> * <dt><b>Scheduler:</b></dt> @@ -2085,6 +2100,8 @@ public final Single<T> cache() { /** * Casts the success value of the current Single into the target type or signals a * ClassCastException if not compatible. + * <p> + * <img width="640" height="393" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.cast.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code cast} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2225,6 +2242,8 @@ public final Single<T> delay(final long time, final TimeUnit unit, final Schedul /** * Delays the actual subscription to the current Single until the given other CompletableSource * completes. + * <p> + * <img width="640" height="309" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.c.png" alt=""> * <p>If the delaying source signals an error, that error is re-emitted and no subscription * to the current Single happens. * <dl> @@ -2247,6 +2266,8 @@ public final Single<T> delaySubscription(CompletableSource other) { /** * Delays the actual subscription to the current Single until the given other SingleSource * signals success. + * <p> + * <img width="640" height="309" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.s.png" alt=""> * <p>If the delaying source signals an error, that error is re-emitted and no subscription * to the current Single happens. * <dl> @@ -2270,6 +2291,8 @@ public final <U> Single<T> delaySubscription(SingleSource<U> other) { /** * Delays the actual subscription to the current Single until the given other ObservableSource * signals its first value or completes. + * <p> + * <img width="640" height="214" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.o.png" alt=""> * <p>If the delaying source signals an error, that error is re-emitted and no subscription * to the current Single happens. * <dl> @@ -2293,6 +2316,8 @@ public final <U> Single<T> delaySubscription(ObservableSource<U> other) { /** * Delays the actual subscription to the current Single until the given other Publisher * signals its first value or completes. + * <p> + * <img width="640" height="214" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.p.png" alt=""> * <p>If the delaying source signals an error, that error is re-emitted and no subscription * to the current Single happens. * <p>The other source is consumed in an unbounded manner (requesting Long.MAX_VALUE from it). @@ -2320,6 +2345,8 @@ public final <U> Single<T> delaySubscription(Publisher<U> other) { /** * Delays the actual subscription to the current Single until the given time delay elapsed. + * <p> + * <img width="640" height="472" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code delaySubscription} does by default subscribe to the current Single @@ -2338,6 +2365,8 @@ public final Single<T> delaySubscription(long time, TimeUnit unit) { /** * Delays the actual subscription to the current Single until the given time delay elapsed. + * <p> + * <img width="640" height="420" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.ts.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code delaySubscription} does by default subscribe to the current Single @@ -2360,6 +2389,8 @@ public final Single<T> delaySubscription(long time, TimeUnit unit, Scheduler sch * {@code onSuccess}, {@code onError} or {@code onComplete} signals as a * {@link Maybe} source. * <p> + * <img width="640" height="341" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.dematerialize.png" alt=""> + * <p> * The intended use of the {@code selector} function is to perform a * type-safe identity mapping (see example) on a source that is already of type * {@code Notification<T>}. The Java language doesn't allow @@ -2547,6 +2578,8 @@ public final Single<T> doOnSuccess(final Consumer<? super T> onSuccess) { /** * Calls the shared consumer with the error sent via onError or the value * via onSuccess for each SingleObserver that subscribes to the current Single. + * <p> + * <img width="640" height="264" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doOnEvent.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnEvent} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2817,6 +2850,8 @@ public final Completable flatMapCompletable(final Function<? super T, ? extends /** * Waits in a blocking fashion until the current Single signals a success value (which is returned) or * an exception (which is propagated). + * <p> + * <img width="640" height="429" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.blockingGet.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingGet} does not operate by default on a particular {@link Scheduler}.</dd> @@ -2844,6 +2879,8 @@ public final T blockingGet() { * and providing a new {@code SingleObserver}, containing the custom operator's intended business logic, that will be * used in the subscription process going further upstream. * <p> + * <img width="640" height="304" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.lift.png" alt=""> + * <p> * Generally, such a new {@code SingleObserver} will wrap the downstream's {@code SingleObserver} and forwards the * {@code onSuccess} and {@code onError} events from the upstream directly or according to the * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the @@ -3031,6 +3068,8 @@ public final Single<Notification<T>> materialize() { /** * Signals true if the current Single signals a success value that is Object-equals with the value * provided. + * <p> + * <img width="640" height="401" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.contains.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code contains} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3048,6 +3087,8 @@ public final Single<Boolean> contains(Object value) { /** * Signals true if the current Single signals a success value that is equal with * the value provided by calling a bi-predicate. + * <p> + * <img width="640" height="401" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.contains.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code contains} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3249,6 +3290,8 @@ public final Single<T> onErrorResumeNext( /** * Nulls out references to the upstream producer and downstream SingleObserver if * the sequence is terminated or downstream calls dispose(). + * <p> + * <img width="640" height="346" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onTerminateDetach.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3356,6 +3399,8 @@ public final Flowable<T> repeatUntil(BooleanSupplier stop) { /** * Repeatedly re-subscribes to the current Single indefinitely if it fails with an onError. + * <p> + * <img width="640" height="399" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retry.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3372,6 +3417,8 @@ public final Single<T> retry() { /** * Repeatedly re-subscribe at most the specified times to the current Single * if it fails with an onError. + * <p> + * <img width="640" height="329" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retry.n.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3389,6 +3436,8 @@ public final Single<T> retry(long times) { /** * Re-subscribe to the current Single if the given predicate returns true when the Single fails * with an onError. + * <p> + * <img width="640" height="230" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retry.f2.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3407,6 +3456,8 @@ public final Single<T> retry(BiPredicate<? super Integer, ? super Throwable> pre /** * Repeatedly re-subscribe at most times or until the predicate returns false, whichever happens first * if it fails with an onError. + * <p> + * <img width="640" height="259" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retry.nf.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3427,6 +3478,8 @@ public final Single<T> retry(long times, Predicate<? super Throwable> predicate) /** * Re-subscribe to the current Single if the given predicate returns true when the Single fails * with an onError. + * <p> + * <img width="640" height="240" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retry.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3446,6 +3499,8 @@ public final Single<T> retry(Predicate<? super Throwable> predicate) { * Re-subscribes to the current Single if and when the Publisher returned by the handler * function signals a value. * <p> + * <img width="640" height="405" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retryWhen.png" alt=""> + * <p> * If the Publisher signals an onComplete, the resulting Single will signal a NoSuchElementException. * <p> * Note that the inner {@code Publisher} returned by the handler function should signal @@ -3492,6 +3547,8 @@ public final Single<T> retryWhen(Function<? super Flowable<Throwable>, ? extends /** * Subscribes to a Single but ignore its emission or notification. * <p> + * <img width="640" height="340" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribe.png" alt=""> + * <p> * If the Single emits an error, it is wrapped into an * {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} * and routed to the RxJavaPlugins.onError handler. @@ -3511,6 +3568,8 @@ public final Disposable subscribe() { /** * Subscribes to a Single and provides a composite callback to handle the item it emits * or any error notification it issues. + * <p> + * <img width="640" height="340" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribe.c2.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3538,6 +3597,8 @@ public final Disposable subscribe(final BiConsumer<? super T, ? super Throwable> /** * Subscribes to a Single and provides a callback to handle the item it emits. * <p> + * <img width="640" height="341" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribe.c.png" alt=""> + * <p> * If the Single emits an error, it is wrapped into an * {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException} * and routed to the RxJavaPlugins.onError handler. @@ -3562,6 +3623,8 @@ public final Disposable subscribe(Consumer<? super T> onSuccess) { /** * Subscribes to a Single and provides callbacks to handle the item it emits or any error notification it * issues. + * <p> + * <img width="640" height="340" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribe.cc.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3623,6 +3686,8 @@ public final void subscribe(SingleObserver<? super T> observer) { /** * Subscribes a given SingleObserver (subclass) to this Single and returns the given * SingleObserver as is. + * <p> + * <img width="640" height="338" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribeWith.png" alt=""> * <p>Usage example: * <pre><code> * Single<Integer> source = Single.just(1); @@ -3680,7 +3745,7 @@ public final Single<T> subscribeOn(final Scheduler scheduler) { * termination of {@code other}, this will emit a {@link CancellationException} rather than go to * {@link SingleObserver#onSuccess(Object)}. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt=""> + * <img width="640" height="333" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.takeUntil.c.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3705,7 +3770,7 @@ public final Single<T> takeUntil(final CompletableSource other) { * emission of an item from {@code other}, this will emit a {@link CancellationException} rather than go to * {@link SingleObserver#onSuccess(Object)}. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt=""> + * <img width="640" height="215" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.takeUntil.p.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The {@code other} publisher is consumed in an unbounded fashion but will be @@ -3737,7 +3802,7 @@ public final <E> Single<T> takeUntil(final Publisher<E> other) { * emission of an item from {@code other}, this will emit a {@link CancellationException} rather than go to * {@link SingleObserver#onSuccess(Object)}. * <p> - * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt=""> + * <img width="640" height="314" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.takeUntil.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd> @@ -3761,6 +3826,8 @@ public final <E> Single<T> takeUntil(final SingleSource<? extends E> other) { /** * Signals a TimeoutException if the current Single doesn't signal a success value within the * specified timeout window. + * <p> + * <img width="640" height="364" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} signals the TimeoutException on the {@code computation} {@link Scheduler}.</dd> @@ -3779,6 +3846,8 @@ public final Single<T> timeout(long timeout, TimeUnit unit) { /** * Signals a TimeoutException if the current Single doesn't signal a success value within the * specified timeout window. + * <p> + * <img width="640" height="334" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} signals the TimeoutException on the {@link Scheduler} you specify.</dd> @@ -3799,6 +3868,8 @@ public final Single<T> timeout(long timeout, TimeUnit unit, Scheduler scheduler) /** * Runs the current Single and if it doesn't signal within the specified timeout window, it is * disposed and the other SingleSource subscribed to. + * <p> + * <img width="640" height="283" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.sb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} subscribes to the other SingleSource on the {@link Scheduler} you specify.</dd> @@ -3821,6 +3892,8 @@ public final Single<T> timeout(long timeout, TimeUnit unit, Scheduler scheduler, /** * Runs the current Single and if it doesn't signal within the specified timeout window, it is * disposed and the other SingleSource subscribed to. + * <p> + * <img width="640" height="282" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.b.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeout} subscribes to the other SingleSource on @@ -4005,6 +4078,8 @@ public final Observable<T> toObservable() { /** * Returns a Single which makes sure when a SingleObserver disposes the Disposable, * that call is propagated up on the specified scheduler. + * <p> + * <img width="640" height="693" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.unsubscribeOn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.</dd> @@ -4058,6 +4133,8 @@ public final <U, R> Single<R> zipWith(SingleSource<U> other, BiFunction<? super /** * Creates a TestObserver and subscribes * it to this Single. + * <p> + * <img width="640" height="442" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.test.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code test} does not operate by default on a particular {@link Scheduler}.</dd> @@ -4075,6 +4152,8 @@ public final TestObserver<T> test() { /** * Creates a TestObserver optionally in cancelled state, then subscribes it to this Single. + * <p> + * <img width="640" height="482" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.test.b.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code test} does not operate by default on a particular {@link Scheduler}.</dd> From bbaea423449872ae388b338fc9c3111b78087345 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 29 Oct 2019 09:38:44 +0100 Subject: [PATCH 390/417] 2.x: Fix window(time) possible interrupts while terminating (#6684) --- .../flowable/FlowableWindowTimed.java | 40 +-- .../observable/ObservableWindowTimed.java | 35 +-- .../flowable/FlowableWindowWithTimeTest.java | 243 ++++++++++++++++- .../ObservableWindowWithTimeTest.java | 244 +++++++++++++++++- 4 files changed, 503 insertions(+), 59 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java index 00f783a39e..2db0eba8cc 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowTimed.java @@ -160,7 +160,6 @@ public void onError(Throwable t) { } downstream.onError(t); - dispose(); } @Override @@ -171,7 +170,6 @@ public void onComplete() { } downstream.onComplete(); - dispose(); } @Override @@ -184,22 +182,15 @@ public void cancel() { cancelled = true; } - public void dispose() { - DisposableHelper.dispose(timer); - } - @Override public void run() { - if (cancelled) { terminated = true; - dispose(); } queue.offer(NEXT); if (enter()) { drainLoop(); } - } void drainLoop() { @@ -221,13 +212,13 @@ void drainLoop() { if (d && (o == null || o == NEXT)) { window = null; q.clear(); - dispose(); Throwable err = error; if (err != null) { w.onError(err); } else { w.onComplete(); } + timer.dispose(); return; } @@ -251,8 +242,8 @@ void drainLoop() { window = null; queue.clear(); upstream.cancel(); - dispose(); a.onError(new MissingBackpressureException("Could not deliver first window due to lack of requests.")); + timer.dispose(); return; } } else { @@ -396,7 +387,7 @@ public void onNext(T t) { window = null; upstream.cancel(); downstream.onError(new MissingBackpressureException("Could not deliver window due to lack of requests")); - dispose(); + disposeTimer(); return; } } else { @@ -424,7 +415,6 @@ public void onError(Throwable t) { } downstream.onError(t); - dispose(); } @Override @@ -435,7 +425,6 @@ public void onComplete() { } downstream.onComplete(); - dispose(); } @Override @@ -448,8 +437,8 @@ public void cancel() { cancelled = true; } - public void dispose() { - DisposableHelper.dispose(timer); + public void disposeTimer() { + timer.dispose(); Worker w = worker; if (w != null) { w.dispose(); @@ -468,7 +457,7 @@ void drainLoop() { if (terminated) { upstream.cancel(); q.clear(); - dispose(); + disposeTimer(); return; } @@ -488,7 +477,7 @@ void drainLoop() { } else { w.onComplete(); } - dispose(); + disposeTimer(); return; } @@ -515,7 +504,7 @@ void drainLoop() { queue.clear(); upstream.cancel(); a.onError(new MissingBackpressureException("Could not deliver first window due to lack of requests.")); - dispose(); + disposeTimer(); return; } } @@ -554,7 +543,7 @@ void drainLoop() { window = null; upstream.cancel(); downstream.onError(new MissingBackpressureException("Could not deliver window due to lack of requests")); - dispose(); + disposeTimer(); return; } } else { @@ -585,7 +574,6 @@ public void run() { p.queue.offer(this); } else { p.terminated = true; - p.dispose(); } if (p.enter()) { p.drainLoop(); @@ -682,7 +670,6 @@ public void onError(Throwable t) { } downstream.onError(t); - dispose(); } @Override @@ -693,7 +680,6 @@ public void onComplete() { } downstream.onComplete(); - dispose(); } @Override @@ -706,10 +692,6 @@ public void cancel() { cancelled = true; } - public void dispose() { - worker.dispose(); - } - void complete(UnicastProcessor<T> w) { queue.offer(new SubjectWork<T>(w, false)); if (enter()) { @@ -730,9 +712,9 @@ void drainLoop() { for (;;) { if (terminated) { upstream.cancel(); - dispose(); q.clear(); ws.clear(); + worker.dispose(); return; } @@ -756,7 +738,7 @@ void drainLoop() { } } ws.clear(); - dispose(); + worker.dispose(); return; } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java index 406d8f03ff..5214d2b225 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java @@ -15,14 +15,13 @@ import java.util.*; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import io.reactivex.*; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.Scheduler.Worker; import io.reactivex.disposables.Disposable; -import io.reactivex.internal.disposables.DisposableHelper; +import io.reactivex.internal.disposables.*; import io.reactivex.internal.observers.QueueDrainObserver; import io.reactivex.internal.queue.MpscLinkedQueue; import io.reactivex.internal.util.NotificationLite; @@ -85,7 +84,7 @@ static final class WindowExactUnboundedObserver<T> UnicastSubject<T> window; - final AtomicReference<Disposable> timer = new AtomicReference<Disposable>(); + final SequentialDisposable timer = new SequentialDisposable(); static final Object NEXT = new Object(); @@ -114,7 +113,7 @@ public void onSubscribe(Disposable d) { if (!cancelled) { Disposable task = scheduler.schedulePeriodicallyDirect(this, timespan, timespan, unit); - DisposableHelper.replace(timer, task); + timer.replace(task); } } } @@ -146,7 +145,6 @@ public void onError(Throwable t) { drainLoop(); } - disposeTimer(); downstream.onError(t); } @@ -157,7 +155,6 @@ public void onComplete() { drainLoop(); } - disposeTimer(); downstream.onComplete(); } @@ -171,15 +168,10 @@ public boolean isDisposed() { return cancelled; } - void disposeTimer() { - DisposableHelper.dispose(timer); - } - @Override public void run() { if (cancelled) { terminated = true; - disposeTimer(); } queue.offer(NEXT); if (enter()) { @@ -206,13 +198,13 @@ void drainLoop() { if (d && (o == null || o == NEXT)) { window = null; q.clear(); - disposeTimer(); Throwable err = error; if (err != null) { w.onError(err); } else { w.onComplete(); } + timer.dispose(); return; } @@ -266,7 +258,7 @@ static final class WindowExactBoundedObserver<T> volatile boolean terminated; - final AtomicReference<Disposable> timer = new AtomicReference<Disposable>(); + final SequentialDisposable timer = new SequentialDisposable(); WindowExactBoundedObserver( Observer<? super Observable<T>> actual, @@ -312,7 +304,7 @@ public void onSubscribe(Disposable d) { task = scheduler.schedulePeriodicallyDirect(consumerIndexHolder, timespan, timespan, unit); } - DisposableHelper.replace(timer, task); + timer.replace(task); } } @@ -370,7 +362,6 @@ public void onError(Throwable t) { } downstream.onError(t); - disposeTimer(); } @Override @@ -381,7 +372,6 @@ public void onComplete() { } downstream.onComplete(); - disposeTimer(); } @Override @@ -428,13 +418,13 @@ void drainLoop() { if (d && (empty || isHolder)) { window = null; q.clear(); - disposeTimer(); Throwable err = error; if (err != null) { w.onError(err); } else { w.onComplete(); } + disposeTimer(); return; } @@ -507,7 +497,6 @@ public void run() { p.queue.offer(this); } else { p.terminated = true; - p.disposeTimer(); } if (p.enter()) { p.drainLoop(); @@ -592,7 +581,6 @@ public void onError(Throwable t) { } downstream.onError(t); - disposeWorker(); } @Override @@ -603,7 +591,6 @@ public void onComplete() { } downstream.onComplete(); - disposeWorker(); } @Override @@ -616,10 +603,6 @@ public boolean isDisposed() { return cancelled; } - void disposeWorker() { - worker.dispose(); - } - void complete(UnicastSubject<T> w) { queue.offer(new SubjectWork<T>(w, false)); if (enter()) { @@ -640,9 +623,9 @@ void drainLoop() { for (;;) { if (terminated) { upstream.dispose(); - disposeWorker(); q.clear(); ws.clear(); + worker.dispose(); return; } @@ -665,8 +648,8 @@ void drainLoop() { w.onComplete(); } } - disposeWorker(); ws.clear(); + worker.dispose(); return; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java index 37d8928571..56e1a736e6 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.*; import java.util.*; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; import java.util.concurrent.atomic.*; import org.junit.*; @@ -918,5 +918,244 @@ public void nextWindowMissingBackpressureDrainOnTime() { .assertError(MissingBackpressureException.class) .assertNotComplete(); } -} + @Test + public void exactTimeBoundNoInterruptWindowOutputOnComplete() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + pp.window(100, TimeUnit.MILLISECONDS) + .doOnNext(new Consumer<Flowable<Integer>>() { + int count; + @Override + public void accept(Flowable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + pp.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + pp.onComplete(); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } + + @Test + public void exactTimeBoundNoInterruptWindowOutputOnError() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + pp.window(100, TimeUnit.MILLISECONDS) + .doOnNext(new Consumer<Flowable<Integer>>() { + int count; + @Override + public void accept(Flowable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + pp.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + pp.onError(new TestException()); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } + + @Test + public void exactTimeAndSizeBoundNoInterruptWindowOutputOnComplete() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + pp.window(100, TimeUnit.MILLISECONDS, 10) + .doOnNext(new Consumer<Flowable<Integer>>() { + int count; + @Override + public void accept(Flowable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + pp.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + pp.onComplete(); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } + + @Test + public void exactTimeAndSizeBoundNoInterruptWindowOutputOnError() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + pp.window(100, TimeUnit.MILLISECONDS, 10) + .doOnNext(new Consumer<Flowable<Integer>>() { + int count; + @Override + public void accept(Flowable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + pp.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + pp.onError(new TestException()); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } + + @Test + public void skipTimeAndSizeBoundNoInterruptWindowOutputOnComplete() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + pp.window(90, 100, TimeUnit.MILLISECONDS) + .doOnNext(new Consumer<Flowable<Integer>>() { + int count; + @Override + public void accept(Flowable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + pp.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + pp.onComplete(); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } + + @Test + public void skipTimeAndSizeBoundNoInterruptWindowOutputOnError() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishProcessor<Integer> pp = PublishProcessor.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + pp.window(90, 100, TimeUnit.MILLISECONDS) + .doOnNext(new Consumer<Flowable<Integer>>() { + int count; + @Override + public void accept(Flowable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + pp.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + pp.onError(new TestException()); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } +} diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java index fbd90088ed..8500d52948 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithTimeTest.java @@ -16,8 +16,8 @@ import static org.junit.Assert.*; import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; import org.junit.*; @@ -708,4 +708,244 @@ public void countRestartsOnTimeTick() { .assertNoErrors() .assertNotComplete(); } + + @Test + public void exactTimeBoundNoInterruptWindowOutputOnComplete() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishSubject<Integer> ps = PublishSubject.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + ps.window(100, TimeUnit.MILLISECONDS) + .doOnNext(new Consumer<Observable<Integer>>() { + int count; + @Override + public void accept(Observable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + ps.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + ps.onComplete(); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } + + @Test + public void exactTimeBoundNoInterruptWindowOutputOnError() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishSubject<Integer> ps = PublishSubject.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + ps.window(100, TimeUnit.MILLISECONDS) + .doOnNext(new Consumer<Observable<Integer>>() { + int count; + @Override + public void accept(Observable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + ps.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + ps.onError(new TestException()); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } + + @Test + public void exactTimeAndSizeBoundNoInterruptWindowOutputOnComplete() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishSubject<Integer> ps = PublishSubject.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + ps.window(100, TimeUnit.MILLISECONDS, 10) + .doOnNext(new Consumer<Observable<Integer>>() { + int count; + @Override + public void accept(Observable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + ps.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + ps.onComplete(); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } + + @Test + public void exactTimeAndSizeBoundNoInterruptWindowOutputOnError() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishSubject<Integer> ps = PublishSubject.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + ps.window(100, TimeUnit.MILLISECONDS, 10) + .doOnNext(new Consumer<Observable<Integer>>() { + int count; + @Override + public void accept(Observable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + ps.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + ps.onError(new TestException()); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } + + @Test + public void skipTimeAndSizeBoundNoInterruptWindowOutputOnComplete() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishSubject<Integer> ps = PublishSubject.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + ps.window(90, 100, TimeUnit.MILLISECONDS) + .doOnNext(new Consumer<Observable<Integer>>() { + int count; + @Override + public void accept(Observable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + ps.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + ps.onComplete(); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } + + @Test + public void skipTimeAndSizeBoundNoInterruptWindowOutputOnError() throws Exception { + final AtomicBoolean isInterrupted = new AtomicBoolean(); + + final PublishSubject<Integer> ps = PublishSubject.create(); + + final CountDownLatch doOnNextDone = new CountDownLatch(1); + final CountDownLatch secondWindowProcessing = new CountDownLatch(1); + + ps.window(90, 100, TimeUnit.MILLISECONDS) + .doOnNext(new Consumer<Observable<Integer>>() { + int count; + @Override + public void accept(Observable<Integer> v) throws Exception { + System.out.println(Thread.currentThread()); + if (count++ == 1) { + secondWindowProcessing.countDown(); + try { + Thread.sleep(200); + isInterrupted.set(Thread.interrupted()); + } catch (InterruptedException ex) { + isInterrupted.set(true); + } + doOnNextDone.countDown(); + } + } + }) + .test(); + + ps.onNext(1); + + assertTrue(secondWindowProcessing.await(5, TimeUnit.SECONDS)); + + ps.onError(new TestException()); + + assertTrue(doOnNextDone.await(5, TimeUnit.SECONDS)); + + assertFalse("The doOnNext got interrupted!", isInterrupted.get()); + } } From d0a59e13daabfb227a290d2253b2fcf27e2bb246 Mon Sep 17 00:00:00 2001 From: Seungmin <rfrost77@gmail.com> Date: Fri, 1 Nov 2019 14:40:20 -0700 Subject: [PATCH 391/417] Update Backpressure.md (#6685) Fixes Backpressure.md on https://github.com/ReactiveX/RxJava/issues/6132 Fix Images on Backpressure.md crashed on wrong address. Put full address of images. --- docs/Backpressure.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/Backpressure.md b/docs/Backpressure.md index d9e7bfa65a..8feec0d487 100644 --- a/docs/Backpressure.md +++ b/docs/Backpressure.md @@ -20,7 +20,7 @@ Cold Observables are ideal for the reactive pull model of backpressure described Your first line of defense against the problems of over-producing Observables is to use some of the ordinary set of Observable operators to reduce the number of emitted items to a more manageable number. The examples in this section will show how you might use such operators to handle a bursty Observable like the one illustrated in the following marble diagram: -<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.bursty.png" width="640" height="35" />​ +<img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.bursty.png" width="640" height="35" />​ By fine-tuning the parameters to these operators you can ensure that a slow-consuming observer is not overwhelmed by a fast-producing Observable. @@ -33,7 +33,7 @@ The following diagrams show how you could use each of these operators on the bur ### sample (or throttleLast) The `sample` operator periodically "dips" into the sequence and emits only the most recently emitted item during each dip: -<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.sample.png" width="640" height="260" />​ +<img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.sample.png" width="640" height="260" />​ ````groovy Observable<Integer> burstySampled = bursty.sample(500, TimeUnit.MILLISECONDS); ```` @@ -41,7 +41,7 @@ Observable<Integer> burstySampled = bursty.sample(500, TimeUnit.MILLISECONDS); ### throttleFirst The `throttleFirst` operator is similar, but emits not the most recently emitted item, but the first item that was emitted after the previous "dip": -<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.throttleFirst.png" width="640" height="260" />​ +<img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.throttleFirst.png" width="640" height="260" />​ ````groovy Observable<Integer> burstyThrottled = bursty.throttleFirst(500, TimeUnit.MILLISECONDS); ```` @@ -49,7 +49,7 @@ Observable<Integer> burstyThrottled = bursty.throttleFirst(500, TimeUnit.MILLISE ### debounce (or throttleWithTimeout) The `debounce` operator emits only those items from the source Observable that are not followed by another item within a specified duration: -<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.debounce.png" width="640" height="240" />​ +<img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.debounce.png" width="640" height="240" />​ ````groovy Observable<Integer> burstyDebounced = bursty.debounce(10, TimeUnit.MILLISECONDS); ```` @@ -64,14 +64,14 @@ The following diagrams show how you could use each of these operators on the bur You could, for example, close and emit a buffer of items from the bursty Observable periodically, at a regular interval of time: -<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.buffer2.png" width="640" height="270" />​ +<img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.buffer2.png" width="640" height="270" />​ ````groovy Observable<List<Integer>> burstyBuffered = bursty.buffer(500, TimeUnit.MILLISECONDS); ```` Or you could get fancy, and collect items in buffers during the bursty periods and emit them at the end of each burst, by using the `debounce` operator to emit a buffer closing indicator to the `buffer` operator: -<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.buffer1.png" width="640" height="500" />​ +<img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.buffer1.png" width="640" height="500" />​ ````groovy // we have to multicast the original bursty Observable so we can use it // both as our source and as the source for our buffer closing selector: @@ -86,14 +86,14 @@ Observable<List<Integer>> burstyBuffered = burstyMulticast.buffer(burstyDebounce `window` is similar to `buffer`. One variant of `window` allows you to periodically emit Observable windows of items at a regular interval of time: -<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.window1.png" width="640" height="325" />​ +<img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.window1.png" width="640" height="325" />​ ````groovy Observable<Observable<Integer>> burstyWindowed = bursty.window(500, TimeUnit.MILLISECONDS); ```` You could also choose to emit a new window each time you have collected a particular number of items from the source Observable: -<img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.window2.png" width="640" height="325" />​ +<img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.window2.png" width="640" height="325" />​ ````groovy Observable<Observable<Integer>> burstyWindowed = bursty.window(5); ```` @@ -158,11 +158,11 @@ For this to work, though, Observables _A_ and _B_ must respond correctly to the <dl> <dt><tt>onBackpressureBuffer</tt></dt> - <dd>maintains a buffer of all emissions from the source Observable and emits them to downstream Subscribers according to the <tt>request</tt>s they generate<br /><img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.obp.buffer.png" width="640" height="300" /><br />an experimental version of this operator (not available in RxJava 1.0) allows you to set the capacity of the buffer; applying this operator will cause the resulting Observable to terminate with an error if this buffer is overrun​</dd> + <dd>maintains a buffer of all emissions from the source Observable and emits them to downstream Subscribers according to the <tt>request</tt>s they generate<br /><img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.obp.buffer.png" width="640" height="300" /><br />an experimental version of this operator (not available in RxJava 1.0) allows you to set the capacity of the buffer; applying this operator will cause the resulting Observable to terminate with an error if this buffer is overrun​</dd> <dt><tt>onBackpressureDrop</tt></dt> - <dd>drops emissions from the source Observable unless there is a pending <tt>request</tt> from a downstream Subscriber, in which case it will emit enough items to fulfill the request<br /><img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.obp.drop.png" width="640" height="245" />​</dd> + <dd>drops emissions from the source Observable unless there is a pending <tt>request</tt> from a downstream Subscriber, in which case it will emit enough items to fulfill the request<br /><img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.obp.drop.png" width="640" height="245" />​</dd> <dt><tt>onBackpressureBlock</tt> <em style="color: #f00;">(experimental, not in RxJava 1.0)</em></dt> - <dd>blocks the thread on which the source Observable is operating until such time as a Subscriber issues a <tt>request</tt> for items, and then unblocks the thread only so long as there are pending requests<br /><img src="http://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.obp.block.png" width="640" height="245" /></dd> + <dd>blocks the thread on which the source Observable is operating until such time as a Subscriber issues a <tt>request</tt> for items, and then unblocks the thread only so long as there are pending requests<br /><img src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/bp.obp.block.png" width="640" height="245" /></dd> </dl> If you do not apply any of these operators to an Observable that does not support backpressure, _and_ if either you as the Subscriber or some operator between you and the Observable attempts to apply reactive pull backpressure, you will encounter a `MissingBackpressureException` which you will be notified of via your `onError()` callback. @@ -172,4 +172,4 @@ If you do not apply any of these operators to an Observable that does not suppor If the standard operators are providing the expected behavior, [one can write custom operators in RxJava](https://github.com/ReactiveX/RxJava/wiki/Implementing-custom-operators-(draft)). # See also -* [RxJava 0.20.0-RC1 release notes](https://github.com/ReactiveX/RxJava/releases/tag/0.20.0-RC1) \ No newline at end of file +* [RxJava 0.20.0-RC1 release notes](https://github.com/ReactiveX/RxJava/releases/tag/0.20.0-RC1) From 5f01b089340623369ec7c5c556695f7e75518d56 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sat, 2 Nov 2019 15:05:42 +0100 Subject: [PATCH 392/417] Release 2.2.14 --- CHANGES.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index af5f1d3074..5e6bac5bc0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,17 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.14 - November 2, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.14%7C)) + +#### Bugfixes + + - [Pull 6677](https://github.com/ReactiveX/RxJava/pull/6677): Fix concurrent `clear()` calls when fused chains are canceled. + - [Pull 6684](https://github.com/ReactiveX/RxJava/pull/6684): Fix `window(time)` possible interrupts while terminating. + +#### Documentation changes + + - [Pull 6681](https://github.com/ReactiveX/RxJava/pull/6681): Backport marble diagrams for `Single` from 3.x. + ### Version 2.2.13 - October 3, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.13%7C)) #### Dependencies From ca0f2d7467e7d89b94e1688ae770d7dc745d17b1 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 7 Nov 2019 22:13:03 +0100 Subject: [PATCH 393/417] 2.x: Add ProGuard rule to avoid j.u.c.Flow warnings due to RS 1.0.3 (#6704) --- src/main/resources/META-INF/proguard/rxjava2.pro | 1 + 1 file changed, 1 insertion(+) create mode 100644 src/main/resources/META-INF/proguard/rxjava2.pro diff --git a/src/main/resources/META-INF/proguard/rxjava2.pro b/src/main/resources/META-INF/proguard/rxjava2.pro new file mode 100644 index 0000000000..aafc7262f1 --- /dev/null +++ b/src/main/resources/META-INF/proguard/rxjava2.pro @@ -0,0 +1 @@ +-dontwarn java.util.concurrent.Flow \ No newline at end of file From 3cb610f498be27770c45a8ce2964bb9f813c7b05 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 8 Nov 2019 07:27:52 +0100 Subject: [PATCH 394/417] 2.x: ProGuard R8 dont warn Flow* classes (#6705) --- src/main/resources/META-INF/proguard/rxjava2.pro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/META-INF/proguard/rxjava2.pro b/src/main/resources/META-INF/proguard/rxjava2.pro index aafc7262f1..d51378e562 100644 --- a/src/main/resources/META-INF/proguard/rxjava2.pro +++ b/src/main/resources/META-INF/proguard/rxjava2.pro @@ -1 +1 @@ --dontwarn java.util.concurrent.Flow \ No newline at end of file +-dontwarn java.util.concurrent.Flow* \ No newline at end of file From 52dee7dbcd03ff1f6b7fa3fbc1ebdd8663d9213b Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 12 Nov 2019 12:05:45 +0100 Subject: [PATCH 395/417] 2.x: Fix concurrent clear in observeOn while output-fused (#6710) --- .../operators/flowable/FlowableObserveOn.java | 2 +- .../observable/ObservableObserveOn.java | 2 +- .../flowable/FlowableObserveOnTest.java | 35 +++++++++++++++++++ .../observable/ObservableObserveOnTest.java | 35 ++++++++++++++++++- 4 files changed, 71 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java index 2a7d499d1a..3431f3a50b 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java @@ -154,7 +154,7 @@ public final void cancel() { upstream.cancel(); worker.dispose(); - if (getAndIncrement() == 0) { + if (!outputFused && getAndIncrement() == 0) { queue.clear(); } } diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java index abf1f0bb85..56de30041e 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java @@ -145,7 +145,7 @@ public void dispose() { disposed = true; upstream.dispose(); worker.dispose(); - if (getAndIncrement() == 0) { + if (!outputFused && getAndIncrement() == 0) { queue.clear(); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java index ba640c3e5a..a5abff03ef 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; @@ -34,6 +35,7 @@ import io.reactivex.internal.operators.flowable.FlowableObserveOn.BaseObserveOnSubscriber; import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.internal.subscriptions.BooleanSubscription; +import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.*; import io.reactivex.schedulers.*; @@ -1940,4 +1942,37 @@ public void workerNotDisposedPrematurelyNormalInAsyncOutConditional() { assertEquals(1, s.disposedCount.get()); } + + @Test + public void fusedNoConcurrentCleanDueToCancel() { + for (int j = 0; j < TestHelper.RACE_LONG_LOOPS; j++) { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final UnicastProcessor<Integer> up = UnicastProcessor.create(); + + TestObserver<Integer> to = up.hide() + .observeOn(Schedulers.io()) + .observeOn(Schedulers.single()) + .unsubscribeOn(Schedulers.computation()) + .firstOrError() + .test(); + + for (int i = 0; up.hasSubscribers() && i < 10000; i++) { + up.onNext(i); + } + + to + .awaitDone(5, TimeUnit.SECONDS) + ; + + if (!errors.isEmpty()) { + throw new CompositeException(errors); + } + + to.assertResult(0); + } finally { + RxJavaPlugins.reset(); + } + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java index a60328a899..48cbe91908 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java @@ -14,6 +14,7 @@ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; @@ -28,7 +29,7 @@ import io.reactivex.Observer; import io.reactivex.annotations.Nullable; import io.reactivex.disposables.*; -import io.reactivex.exceptions.TestException; +import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.fuseable.*; import io.reactivex.internal.operators.flowable.FlowableObserveOnTest.DisposeTrackingScheduler; @@ -813,4 +814,36 @@ public void workerNotDisposedPrematurelyNormalInAsyncOut() { assertEquals(1, s.disposedCount.get()); } + @Test + public void fusedNoConcurrentCleanDueToCancel() { + for (int j = 0; j < TestHelper.RACE_LONG_LOOPS; j++) { + List<Throwable> errors = TestHelper.trackPluginErrors(); + try { + final UnicastSubject<Integer> us = UnicastSubject.create(); + + TestObserver<Integer> to = us.hide() + .observeOn(Schedulers.io()) + .observeOn(Schedulers.single()) + .unsubscribeOn(Schedulers.computation()) + .firstOrError() + .test(); + + for (int i = 0; us.hasObservers() && i < 10000; i++) { + us.onNext(i); + } + + to + .awaitDone(5, TimeUnit.SECONDS) + ; + + if (!errors.isEmpty()) { + throw new CompositeException(errors); + } + + to.assertResult(0); + } finally { + RxJavaPlugins.reset(); + } + } + } } From aeb5f2c703a0126cf51ca4520e2c4a725cb1e752 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 15 Nov 2019 00:06:56 +0100 Subject: [PATCH 396/417] 2.x: Fix MulticastProcessor not requesting more after limit is reached (#6715) --- .../processors/MulticastProcessor.java | 1 + .../processors/MulticastProcessorTest.java | 37 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/main/java/io/reactivex/processors/MulticastProcessor.java b/src/main/java/io/reactivex/processors/MulticastProcessor.java index 317244313f..31b7a64fea 100644 --- a/src/main/java/io/reactivex/processors/MulticastProcessor.java +++ b/src/main/java/io/reactivex/processors/MulticastProcessor.java @@ -569,6 +569,7 @@ void drain() { } } + consumed = c; missed = wip.addAndGet(-missed); if (missed == 0) { break; diff --git a/src/test/java/io/reactivex/processors/MulticastProcessorTest.java b/src/test/java/io/reactivex/processors/MulticastProcessorTest.java index 63a7b1a60b..d541dffb3e 100644 --- a/src/test/java/io/reactivex/processors/MulticastProcessorTest.java +++ b/src/test/java/io/reactivex/processors/MulticastProcessorTest.java @@ -783,4 +783,41 @@ public void noUpstream() { assertTrue(mp.hasSubscribers()); } + @Test + public void requestUpstreamPrefetchNonFused() { + for (int j = 1; j < 12; j++) { + MulticastProcessor<Integer> mp = MulticastProcessor.create(j, true); + + TestSubscriber<Integer> ts = mp.test(0).withTag("Prefetch: " + j); + + Flowable.range(1, 10).hide().subscribe(mp); + + ts.assertEmpty() + .requestMore(3) + .assertValuesOnly(1, 2, 3) + .requestMore(3) + .assertValuesOnly(1, 2, 3, 4, 5, 6) + .requestMore(4) + .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + } + + @Test + public void requestUpstreamPrefetchNonFused2() { + for (int j = 1; j < 12; j++) { + MulticastProcessor<Integer> mp = MulticastProcessor.create(j, true); + + TestSubscriber<Integer> ts = mp.test(0).withTag("Prefetch: " + j); + + Flowable.range(1, 10).hide().subscribe(mp); + + ts.assertEmpty() + .requestMore(2) + .assertValuesOnly(1, 2) + .requestMore(2) + .assertValuesOnly(1, 2, 3, 4) + .requestMore(6) + .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + } } From 170f9522a7d5e1c58f38b727d542bed954ee5617 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 21 Nov 2019 09:55:23 +0100 Subject: [PATCH 397/417] 2.x: Fix parallel() on grouped flowable not replenishing properly (#6720) --- .../operators/flowable/FlowableGroupBy.java | 20 +++++++++---- .../flowable/FlowableGroupByTest.java | 30 +++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java index 11ec41a0f2..8fd358c26e 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java @@ -709,17 +709,25 @@ public T poll() { produced++; return v; } - int p = produced; - if (p != 0) { - produced = 0; - parent.upstream.request(p); - } + tryReplenish(); return null; } @Override public boolean isEmpty() { - return queue.isEmpty(); + if (queue.isEmpty()) { + tryReplenish(); + return true; + } + return false; + } + + void tryReplenish() { + int p = produced; + if (p != 0) { + produced = 0; + parent.upstream.request(p); + } } @Override diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index 85501e2578..0db7abc639 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -2286,4 +2286,34 @@ public void run() { } } } + + @Test + public void fusedParallelGroupProcessing() { + Flowable.range(0, 500000) + .subscribeOn(Schedulers.single()) + .groupBy(new Function<Integer, Integer>() { + @Override + public Integer apply(Integer i) { + return i % 2; + } + }) + .flatMap(new Function<GroupedFlowable<Integer, Integer>, Publisher<Integer>>() { + @Override + public Publisher<Integer> apply(GroupedFlowable<Integer, Integer> g) { + return g.getKey() == 0 + ? g + .parallel() + .runOn(Schedulers.computation()) + .map(Functions.<Integer>identity()) + .sequential() + : g.map(Functions.<Integer>identity()) // no need to use hide + ; + } + }) + .test() + .awaitDone(20, TimeUnit.SECONDS) + .assertValueCount(500000) + .assertComplete() + .assertNoErrors(); + } } From 5e1bc1780726419b765b983d693fa17fad7ef8a9 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 21 Nov 2019 09:55:39 +0100 Subject: [PATCH 398/417] 2.x: Update javadoc for observeOn to mention its eagerness (#6722) --- src/main/java/io/reactivex/Flowable.java | 18 ++++++++++++++++++ src/main/java/io/reactivex/Observable.java | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 91333947e9..0490daf3c2 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -11590,6 +11590,11 @@ public final Flowable<T> mergeWith(@NonNull CompletableSource other) { * asynchronous. If strict event ordering is required, consider using the {@link #observeOn(Scheduler, boolean)} overload. * <p> * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/observeOn.png" alt=""> + * <p> + * This operator keeps emitting as many signals as it can on the given Scheduler's Worker thread, + * which may result in a longer than expected occupation of this thread. In other terms, + * it does not allow per-signal fairness in case the worker runs on a shared underlying thread. + * If such fairness and signal/work interleaving is preferred, use the delay operator with zero time instead. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator honors backpressure from downstream and expects it from the source {@code Publisher}. Violating this @@ -11610,6 +11615,7 @@ public final Flowable<T> mergeWith(@NonNull CompletableSource other) { * @see #subscribeOn * @see #observeOn(Scheduler, boolean) * @see #observeOn(Scheduler, boolean, int) + * @see #delay(long, TimeUnit, Scheduler) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -11623,6 +11629,11 @@ public final Flowable<T> observeOn(Scheduler scheduler) { * asynchronously with a bounded buffer and optionally delays onError notifications. * <p> * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/observeOn.png" alt=""> + * <p> + * This operator keeps emitting as many signals as it can on the given Scheduler's Worker thread, + * which may result in a longer than expected occupation of this thread. In other terms, + * it does not allow per-signal fairness in case the worker runs on a shared underlying thread. + * If such fairness and signal/work interleaving is preferred, use the delay operator with zero time instead. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator honors backpressure from downstream and expects it from the source {@code Publisher}. Violating this @@ -11647,6 +11658,7 @@ public final Flowable<T> observeOn(Scheduler scheduler) { * @see #subscribeOn * @see #observeOn(Scheduler) * @see #observeOn(Scheduler, boolean, int) + * @see #delay(long, TimeUnit, Scheduler, boolean) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -11660,6 +11672,11 @@ public final Flowable<T> observeOn(Scheduler scheduler, boolean delayError) { * asynchronously with a bounded buffer of configurable size and optionally delays onError notifications. * <p> * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/observeOn.png" alt=""> + * <p> + * This operator keeps emitting as many signals as it can on the given Scheduler's Worker thread, + * which may result in a longer than expected occupation of this thread. In other terms, + * it does not allow per-signal fairness in case the worker runs on a shared underlying thread. + * If such fairness and signal/work interleaving is preferred, use the delay operator with zero time instead. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>This operator honors backpressure from downstream and expects it from the source {@code Publisher}. Violating this @@ -11685,6 +11702,7 @@ public final Flowable<T> observeOn(Scheduler scheduler, boolean delayError) { * @see #subscribeOn * @see #observeOn(Scheduler) * @see #observeOn(Scheduler, boolean) + * @see #delay(long, TimeUnit, Scheduler, boolean) */ @CheckReturnValue @NonNull diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index d2f11d2b5b..865b5563cc 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -9902,6 +9902,11 @@ public final Observable<T> mergeWith(@NonNull CompletableSource other) { * asynchronous. If strict event ordering is required, consider using the {@link #observeOn(Scheduler, boolean)} overload. * <p> * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/observeOn.png" alt=""> + * <p> + * This operator keeps emitting as many signals as it can on the given Scheduler's Worker thread, + * which may result in a longer than expected occupation of this thread. In other terms, + * it does not allow per-signal fairness in case the worker runs on a shared underlying thread. + * If such fairness and signal/work interleaving is preferred, use the delay operator with zero time instead. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> @@ -9918,6 +9923,7 @@ public final Observable<T> mergeWith(@NonNull CompletableSource other) { * @see #subscribeOn * @see #observeOn(Scheduler, boolean) * @see #observeOn(Scheduler, boolean, int) + * @see #delay(long, TimeUnit, Scheduler) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @@ -9930,6 +9936,11 @@ public final Observable<T> observeOn(Scheduler scheduler) { * asynchronously with an unbounded buffer with {@link Flowable#bufferSize()} "island size" and optionally delays onError notifications. * <p> * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/observeOn.png" alt=""> + * <p> + * This operator keeps emitting as many signals as it can on the given Scheduler's Worker thread, + * which may result in a longer than expected occupation of this thread. In other terms, + * it does not allow per-signal fairness in case the worker runs on a shared underlying thread. + * If such fairness and signal/work interleaving is preferred, use the delay operator with zero time instead. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> @@ -9950,6 +9961,7 @@ public final Observable<T> observeOn(Scheduler scheduler) { * @see #subscribeOn * @see #observeOn(Scheduler) * @see #observeOn(Scheduler, boolean, int) + * @see #delay(long, TimeUnit, Scheduler, boolean) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @@ -9962,6 +9974,11 @@ public final Observable<T> observeOn(Scheduler scheduler, boolean delayError) { * asynchronously with an unbounded buffer of configurable "island size" and optionally delays onError notifications. * <p> * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/observeOn.png" alt=""> + * <p> + * This operator keeps emitting as many signals as it can on the given Scheduler's Worker thread, + * which may result in a longer than expected occupation of this thread. In other terms, + * it does not allow per-signal fairness in case the worker runs on a shared underlying thread. + * If such fairness and signal/work interleaving is preferred, use the delay operator with zero time instead. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> @@ -9983,6 +10000,7 @@ public final Observable<T> observeOn(Scheduler scheduler, boolean delayError) { * @see #subscribeOn * @see #observeOn(Scheduler) * @see #observeOn(Scheduler, boolean) + * @see #delay(long, TimeUnit, Scheduler, boolean) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) From 56d6e91e310113a2f3a529993f3c51983a022a85 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sun, 24 Nov 2019 09:37:35 +0100 Subject: [PATCH 399/417] Release 2.2.15 --- CHANGES.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 5e6bac5bc0..43d7a65dba 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,22 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.15 - November 24, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.15%7C)) + +#### Bugfixes + + - [Pull 6715](https://github.com/ReactiveX/RxJava/pull/6715): Fix `MulticastProcessor` not requesting more after limit is reached. + - [Pull 6710](https://github.com/ReactiveX/RxJava/pull/6710): Fix concurrent `clear` in `observeOn` while output-fused. + - [Pull 6720](https://github.com/ReactiveX/RxJava/pull/6720): Fix `parallel()` on grouped flowable not replenishing properly. + +#### Documentation changes + + - [Pull 6722](https://github.com/ReactiveX/RxJava/pull/6722): Update javadoc for `observeOn` to mention its eagerness. + +#### Other changes + + - [Pull 6704](https://github.com/ReactiveX/RxJava/pull/6704): Add ProGuard rule to avoid `j.u.c.Flow` warnings due to RS 1.0.3. + ### Version 2.2.14 - November 2, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.14%7C)) #### Bugfixes From 31b407f3d66a1c36dcadd37a85f89b68ec62ff16 Mon Sep 17 00:00:00 2001 From: Lugduni Desrosiers <36016544+ddunig2@users.noreply.github.com> Date: Fri, 6 Dec 2019 02:58:12 -0500 Subject: [PATCH 400/417] backporting #6729 to 2.x branch. (#6746) --- src/main/java/io/reactivex/Flowable.java | 10 +++++++--- src/main/java/io/reactivex/Observable.java | 11 ++++++++--- .../io/reactivex/disposables/ActionDisposable.java | 3 +++ .../flowable/BlockingFlowableMostRecent.java | 4 ---- .../observable/BlockingObservableMostRecent.java | 4 ---- 5 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/main/java/io/reactivex/Flowable.java b/src/main/java/io/reactivex/Flowable.java index 0490daf3c2..41cde991a7 100644 --- a/src/main/java/io/reactivex/Flowable.java +++ b/src/main/java/io/reactivex/Flowable.java @@ -8266,7 +8266,6 @@ public final Single<Boolean> contains(final Object item) { * @return a Single that emits a single item: the number of items emitted by the source Publisher as a * 64-bit Long item * @see <a href="http://reactivex.io/documentation/operators/count.html">ReactiveX operators documentation: Count</a> - * @see #count() */ @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @@ -15121,6 +15120,7 @@ public final Flowable<T> switchIfEmpty(Publisher<? extends T> other) { * Publisher * @return a Flowable that emits the items emitted by the Publisher returned from applying {@code func} to the most recently emitted item emitted by the source Publisher * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> + * @see #switchMapDelayError(Function) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -15156,6 +15156,7 @@ public final <R> Flowable<R> switchMap(Function<? super T, ? extends Publisher<? * the number of elements to prefetch from the current active inner Publisher * @return a Flowable that emits the items emitted by the Publisher returned from applying {@code func} to the most recently emitted item emitted by the source Publisher * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> + * @see #switchMapDelayError(Function, int) */ @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @@ -15245,7 +15246,7 @@ public final Completable switchMapCompletable(@NonNull Function<? super T, ? ext * {@link CompletableSource} to be subscribed to and awaited for * (non blockingly) for its terminal event * @return the new Completable instance - * @see #switchMapCompletableDelayError(Function) + * @see #switchMapCompletable(Function) * @since 2.2 */ @CheckReturnValue @@ -15283,6 +15284,7 @@ public final Completable switchMapCompletableDelayError(@NonNull Function<? supe * Publisher * @return a Flowable that emits the items emitted by the Publisher returned from applying {@code func} to the most recently emitted item emitted by the source Publisher * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> + * @see #switchMap(Function) * @since 2.0 */ @CheckReturnValue @@ -15320,6 +15322,7 @@ public final <R> Flowable<R> switchMapDelayError(Function<? super T, ? extends P * the number of elements to prefetch from the current active inner Publisher * @return a Flowable that emits the items emitted by the Publisher returned from applying {@code func} to the most recently emitted item emitted by the source Publisher * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> + * @see #switchMap(Function, int) * @since 2.0 */ @CheckReturnValue @@ -15373,6 +15376,7 @@ <R> Flowable<R> switchMap0(Function<? super T, ? extends Publisher<? extends R>> * and get subscribed to. * @return the new Flowable instance * @see #switchMapMaybe(Function) + * @see #switchMapMaybeDelayError(Function) * @since 2.2 */ @CheckReturnValue @@ -15444,7 +15448,7 @@ public final <R> Flowable<R> switchMapMaybeDelayError(@NonNull Function<? super * return a {@code SingleSource} to replace the current active inner source * and get subscribed to. * @return the new Flowable instance - * @see #switchMapSingle(Function) + * @see #switchMapSingleDelayError(Function) * @since 2.2 */ @CheckReturnValue diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index 865b5563cc..43f1f14483 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -7283,7 +7283,6 @@ public final Single<Boolean> contains(final Object element) { * @return a Single that emits a single item: the number of items emitted by the source ObservableSource as a * 64-bit Long item * @see <a href="http://reactivex.io/documentation/operators/count.html">ReactiveX operators documentation: Count</a> - * @see #count() */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -12405,6 +12404,7 @@ public final Observable<T> switchIfEmpty(ObservableSource<? extends T> other) { * ObservableSource * @return an Observable that emits the items emitted by the ObservableSource returned from applying {@code func} to the most recently emitted item emitted by the source ObservableSource * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> + * @see #switchMapDelayError(Function) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -12434,6 +12434,7 @@ public final <R> Observable<R> switchMap(Function<? super T, ? extends Observabl * the number of elements to prefetch from the current active inner ObservableSource * @return an Observable that emits the items emitted by the ObservableSource returned from applying {@code func} to the most recently emitted item emitted by the source ObservableSource * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> + * @see #switchMapDelayError(Function, int) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @@ -12524,7 +12525,7 @@ public final Completable switchMapCompletable(@NonNull Function<? super T, ? ext * {@link CompletableSource} to be subscribed to and awaited for * (non blockingly) for its terminal event * @return the new Completable instance - * @see #switchMapCompletableDelayError(Function) + * @see #switchMapCompletable(Function) * @since 2.2 */ @CheckReturnValue @@ -12560,7 +12561,7 @@ public final Completable switchMapCompletableDelayError(@NonNull Function<? supe * return a {@code MaybeSource} to replace the current active inner source * and get subscribed to. * @return the new Observable instance - * @see #switchMapMaybe(Function) + * @see #switchMapMaybeDelayError(Function) * @since 2.2 */ @CheckReturnValue @@ -12616,6 +12617,7 @@ public final <R> Observable<R> switchMapMaybeDelayError(@NonNull Function<? supe * SingleSource * @return an Observable that emits the item emitted by the SingleSource returned from applying {@code func} to the most recently emitted item emitted by the source ObservableSource * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> + * @see #switchMapSingleDelayError(Function) * @since 2.2 */ @CheckReturnValue @@ -12647,6 +12649,7 @@ public final <R> Observable<R> switchMapSingle(@NonNull Function<? super T, ? ex * SingleSource * @return an Observable that emits the item emitted by the SingleSource returned from applying {@code func} to the most recently emitted item emitted by the source ObservableSource * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> + * @see #switchMapSingle(Function) * @since 2.2 */ @CheckReturnValue @@ -12678,6 +12681,7 @@ public final <R> Observable<R> switchMapSingleDelayError(@NonNull Function<? sup * ObservableSource * @return an Observable that emits the items emitted by the ObservableSource returned from applying {@code func} to the most recently emitted item emitted by the source ObservableSource * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> + * @see #switchMap(Function) * @since 2.0 */ @CheckReturnValue @@ -12709,6 +12713,7 @@ public final <R> Observable<R> switchMapDelayError(Function<? super T, ? extends * the number of elements to prefetch from the current active inner ObservableSource * @return an Observable that emits the items emitted by the ObservableSource returned from applying {@code func} to the most recently emitted item emitted by the source ObservableSource * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> + * @see #switchMap(Function, int) * @since 2.0 */ @CheckReturnValue diff --git a/src/main/java/io/reactivex/disposables/ActionDisposable.java b/src/main/java/io/reactivex/disposables/ActionDisposable.java index 447dfe2e34..f553f8b58e 100644 --- a/src/main/java/io/reactivex/disposables/ActionDisposable.java +++ b/src/main/java/io/reactivex/disposables/ActionDisposable.java @@ -16,6 +16,9 @@ import io.reactivex.functions.Action; import io.reactivex.internal.util.ExceptionHelper; +/** + * A Disposable container that manages an Action instance. + */ final class ActionDisposable extends ReferenceDisposable<Action> { private static final long serialVersionUID = -8219729196779211169L; diff --git a/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecent.java b/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecent.java index 298a3f21be..235d8507dc 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecent.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecent.java @@ -42,10 +42,6 @@ public BlockingFlowableMostRecent(Flowable<T> source, T initialValue) { public Iterator<T> iterator() { MostRecentSubscriber<T> mostRecentSubscriber = new MostRecentSubscriber<T>(initialValue); - /** - * Subscribe instead of unsafeSubscribe since this is the final subscribe in the chain - * since it is for BlockingObservable. - */ source.subscribe(mostRecentSubscriber); return mostRecentSubscriber.getIterable(); diff --git a/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecent.java b/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecent.java index 90a603f65c..04940be5e6 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecent.java +++ b/src/main/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecent.java @@ -42,10 +42,6 @@ public BlockingObservableMostRecent(ObservableSource<T> source, T initialValue) public Iterator<T> iterator() { MostRecentObserver<T> mostRecentObserver = new MostRecentObserver<T>(initialValue); - /** - * Subscribe instead of unsafeSubscribe since this is the final subscribe in the chain - * since it is for BlockingObservable. - */ source.subscribe(mostRecentObserver); return mostRecentObserver.getIterable(); From 52346a140c29b659023f87e348c26889b6b39b13 Mon Sep 17 00:00:00 2001 From: Mark Sholte <mgsholte@users.noreply.github.com> Date: Wed, 11 Dec 2019 02:20:42 -0600 Subject: [PATCH 401/417] 2.x: Zip, CombineLatest, and Amb operators throw when supplied with ObservableSource implementation that doesn't subclass Observable (#6754) * 2.x: Zip, CombineLatest, and Amb operators throw when supplied with ObservableSource implementation that doesn't subclass Observable #6753 * 2.x: add tests for allowing arbitrary ObservableSource implementations --- .../operators/observable/ObservableAmb.java | 2 +- .../observable/ObservableCombineLatest.java | 2 +- .../operators/observable/ObservableZip.java | 2 +- .../observable/ObservableAmbTest.java | 17 +++++++++++ .../ObservableCombineLatestTest.java | 29 +++++++++++++++++++ .../observable/ObservableZipTest.java | 29 +++++++++++++++++++ 6 files changed, 78 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java index 2ed4fcd93b..53068e7a91 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableAmb.java @@ -36,7 +36,7 @@ public void subscribeActual(Observer<? super T> observer) { ObservableSource<? extends T>[] sources = this.sources; int count = 0; if (sources == null) { - sources = new Observable[8]; + sources = new ObservableSource[8]; try { for (ObservableSource<? extends T> p : sourcesIterable) { if (p == null) { diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java index ccbfc8e6d3..56b62cdfeb 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java @@ -49,7 +49,7 @@ public void subscribeActual(Observer<? super R> observer) { ObservableSource<? extends T>[] sources = this.sources; int count = 0; if (sources == null) { - sources = new Observable[8]; + sources = new ObservableSource[8]; for (ObservableSource<? extends T> p : sourcesIterable) { if (count == sources.length) { ObservableSource<? extends T>[] b = new ObservableSource[count + (count >> 2)]; diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java index af465c43c6..7f00383834 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableZip.java @@ -50,7 +50,7 @@ public void subscribeActual(Observer<? super R> observer) { ObservableSource<? extends T>[] sources = this.sources; int count = 0; if (sources == null) { - sources = new Observable[8]; + sources = new ObservableSource[8]; for (ObservableSource<? extends T> p : sourcesIterable) { if (count == sources.length) { ObservableSource<? extends T>[] b = new ObservableSource[count + (count >> 2)]; diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java index 6e2c737f75..a76b8f22e6 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableAmbTest.java @@ -264,6 +264,23 @@ public void singleIterable() { .assertResult(1); } + /** + * Ensures that an ObservableSource implementation can be supplied that doesn't subclass Observable + */ + @Test + public void singleIterableNotSubclassingObservable() { + final ObservableSource<Integer> s1 = new ObservableSource<Integer>() { + @Override + public void subscribe (final Observer<? super Integer> observer) { + Observable.just(1).subscribe(observer); + } + }; + + Observable.amb(Collections.singletonList(s1)) + .test() + .assertResult(1); + } + @SuppressWarnings("unchecked") @Test public void disposed() { diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java index 418a19678e..736a0bd9b5 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java @@ -787,6 +787,34 @@ public Object apply(Object[] a) throws Exception { .assertResult("[1, 2]"); } + /** + * Ensures that an ObservableSource implementation can be supplied that doesn't subclass Observable + */ + @Test + public void combineLatestIterableOfSourcesNotSubclassingObservable() { + final ObservableSource<Integer> s1 = new ObservableSource<Integer>() { + @Override + public void subscribe (final Observer<? super Integer> observer) { + Observable.just(1).subscribe(observer); + } + }; + final ObservableSource<Integer> s2 = new ObservableSource<Integer>() { + @Override + public void subscribe (final Observer<? super Integer> observer) { + Observable.just(2).subscribe(observer); + } + }; + + Observable.combineLatest(Arrays.asList(s1, s2), new Function<Object[], Object>() { + @Override + public Object apply(Object[] a) throws Exception { + return Arrays.toString(a); + } + }) + .test() + .assertResult("[1, 2]"); + } + @Test @SuppressWarnings("unchecked") public void combineLatestDelayErrorArrayOfSources() { @@ -1216,4 +1244,5 @@ public Object apply(Object[] a) throws Exception { .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class, 42); } + } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java index 14fda0058d..eca18c71b3 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java @@ -1350,6 +1350,34 @@ public Object apply(Object[] a) throws Exception { .assertResult("[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]"); } + /** + * Ensures that an ObservableSource implementation can be supplied that doesn't subclass Observable + */ + @Test + public void zipIterableNotSubclassingObservable() { + final ObservableSource<Integer> s1 = new ObservableSource<Integer>() { + @Override + public void subscribe (final Observer<? super Integer> observer) { + Observable.just(1).subscribe(observer); + } + }; + final ObservableSource<Integer> s2 = new ObservableSource<Integer>() { + @Override + public void subscribe (final Observer<? super Integer> observer) { + Observable.just(2).subscribe(observer); + } + }; + + Observable.zip(Arrays.asList(s1, s2), new Function<Object[], Object>() { + @Override + public Object apply(Object[] a) throws Exception { + return Arrays.toString(a); + } + }) + .test() + .assertResult("[1, 2]"); + } + @Test public void dispose() { TestHelper.checkDisposed(Observable.zip(Observable.just(1), Observable.just(1), new BiFunction<Integer, Integer, Object>() { @@ -1457,4 +1485,5 @@ public Object apply(Object[] a) throws Exception { assertEquals(0, counter.get()); } + } From ea2c79654accfdfaef580389a12086a1dfacc3eb Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sun, 15 Dec 2019 08:15:28 +0100 Subject: [PATCH 402/417] Release 2.2.16 --- CHANGES.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 43d7a65dba..c37f51f161 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,16 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.16 - December 15, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.16%7C)) + +#### Bugfixes + + - [Pull 6754](https://github.com/ReactiveX/RxJava/pull/6754): Fix `amb`, `combineLatest` and `zip` `Iterable` overloads throwing `ArrayStoreException` for `ObservableSource`s. + +#### Documentation changes + + - [Pull 6746](https://github.com/ReactiveX/RxJava/pull/6746): Fix self-see references, some comments. + ### Version 2.2.15 - November 24, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.15%7C)) #### Bugfixes From 0b3b300425c3ae471ad5136a2bbeb9bd50f58849 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Thu, 9 Jan 2020 08:57:22 +0100 Subject: [PATCH 403/417] 2.x: Fix Flowable.flatMap not canceling the inner sources on outer error (#6827) --- .../operators/flowable/FlowableFlatMap.java | 5 +++ .../flowable/FlowableFlatMapTest.java | 34 +++++++++++++++++++ .../observable/ObservableFlatMapTest.java | 34 +++++++++++++++++++ 3 files changed, 73 insertions(+) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java index c68e82bb93..a7631de8b8 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java @@ -322,6 +322,11 @@ public void onError(Throwable t) { } if (errs.addThrowable(t)) { done = true; + if (!delayErrors) { + for (InnerSubscriber<?, ?> a : subscribers.getAndSet(CANCELLED)) { + a.dispose(); + } + } drain(); } else { RxJavaPlugins.onError(t); diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index 953a5f44dc..d121eea54e 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -1123,4 +1123,38 @@ public void accept(Integer v) throws Exception { assertFalse(pp3.hasSubscribers()); assertFalse(pp4.hasSubscribers()); } + + @Test + public void mainErrorsInnerCancelled() { + PublishProcessor<Integer> pp1 = PublishProcessor.create(); + PublishProcessor<Integer> pp2 = PublishProcessor.create(); + + pp1 + .flatMap(Functions.justFunction(pp2)) + .test(); + + pp1.onNext(1); + assertTrue("No subscribers?", pp2.hasSubscribers()); + + pp1.onError(new TestException()); + + assertFalse("Has subscribers?", pp2.hasSubscribers()); + } + + @Test + public void innerErrorsMainCancelled() { + PublishProcessor<Integer> pp1 = PublishProcessor.create(); + PublishProcessor<Integer> pp2 = PublishProcessor.create(); + + pp1 + .flatMap(Functions.justFunction(pp2)) + .test(); + + pp1.onNext(1); + assertTrue("No subscribers?", pp2.hasSubscribers()); + + pp2.onError(new TestException()); + + assertFalse("Has subscribers?", pp1.hasSubscribers()); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index b4da14e9a1..5e0fa7cf8a 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -1084,4 +1084,38 @@ public void accept(Integer v) throws Exception { assertFalse(ps3.hasObservers()); assertFalse(ps4.hasObservers()); } + + @Test + public void mainErrorsInnerCancelled() { + PublishSubject<Integer> ps1 = PublishSubject.create(); + PublishSubject<Integer> ps2 = PublishSubject.create(); + + ps1 + .flatMap(Functions.justFunction(ps2)) + .test(); + + ps1.onNext(1); + assertTrue("No subscribers?", ps2.hasObservers()); + + ps1.onError(new TestException()); + + assertFalse("Has subscribers?", ps2.hasObservers()); + } + + @Test + public void innerErrorsMainCancelled() { + PublishSubject<Integer> ps1 = PublishSubject.create(); + PublishSubject<Integer> ps2 = PublishSubject.create(); + + ps1 + .flatMap(Functions.justFunction(ps2)) + .test(); + + ps1.onNext(1); + assertTrue("No subscribers?", ps2.hasObservers()); + + ps2.onError(new TestException()); + + assertFalse("Has subscribers?", ps1.hasObservers()); + } } From 030528bcd1c7202c7c20b7f4a7f7ee102833540e Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sun, 12 Jan 2020 16:50:06 +0100 Subject: [PATCH 404/417] Release 2.2.17 --- CHANGES.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index c37f51f161..9af1b4f879 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,12 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.17 - January 12, 2020 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.17%7C)) + +#### Bugfixes + + - [Pull 6827](https://github.com/ReactiveX/RxJava/pull/6827): Fix `Flowable.flatMap` not canceling the inner sources on outer error. + ### Version 2.2.16 - December 15, 2019 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.16%7C)) #### Bugfixes From e7538584a4a066241bc64480a96ff9066b0a1b17 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 29 Jan 2020 11:57:11 +0100 Subject: [PATCH 405/417] 2.x: Fig groupBy not requesting more if a group is cancelled with buffered items (#6894) --- .../operators/flowable/FlowableGroupBy.java | 23 +++++++--- .../flowable/FlowableGroupByTest.java | 46 ++++++++++++++++--- 2 files changed, 57 insertions(+), 12 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java index 8fd358c26e..99a63c7b91 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java @@ -518,6 +518,7 @@ public void request(long n) { public void cancel() { if (cancelled.compareAndSet(false, true)) { parent.cancel(key); + drain(); } } @@ -568,7 +569,6 @@ void drainFused() { for (;;) { if (a != null) { if (cancelled.get()) { - q.clear(); return; } @@ -623,7 +623,7 @@ void drainNormal() { T v = q.poll(); boolean empty = v == null; - if (checkTerminated(d, empty, a, delayError)) { + if (checkTerminated(d, empty, a, delayError, e)) { return; } @@ -636,7 +636,7 @@ void drainNormal() { e++; } - if (e == r && checkTerminated(done, q.isEmpty(), a, delayError)) { + if (e == r && checkTerminated(done, q.isEmpty(), a, delayError, e)) { return; } @@ -658,9 +658,15 @@ void drainNormal() { } } - boolean checkTerminated(boolean d, boolean empty, Subscriber<? super T> a, boolean delayError) { + boolean checkTerminated(boolean d, boolean empty, Subscriber<? super T> a, boolean delayError, long emitted) { if (cancelled.get()) { - queue.clear(); + // make sure buffered items can get replenished + while (queue.poll() != null) { + emitted++; + } + if (emitted != 0) { + parent.upstream.request(emitted); + } return true; } @@ -732,7 +738,12 @@ void tryReplenish() { @Override public void clear() { - queue.clear(); + // make sure buffered items can get replenished + SpscLinkedArrayQueue<T> q = queue; + while (q.poll() != null) { + produced++; + } + tryReplenish(); } } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java index 0db7abc639..cb52621bac 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java @@ -2215,20 +2215,20 @@ public void fusedNoConcurrentCleanDueToCancel() { try { final PublishProcessor<Integer> pp = PublishProcessor.create(); - final AtomicReference<QueueSubscription<GroupedFlowable<Object, Integer>>> qs = new AtomicReference<QueueSubscription<GroupedFlowable<Object, Integer>>>(); + final AtomicReference<QueueSubscription<GroupedFlowable<Integer, Integer>>> qs = new AtomicReference<QueueSubscription<GroupedFlowable<Integer, Integer>>>(); final TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(); - pp.groupBy(Functions.identity(), Functions.<Integer>identity(), false, 4) - .subscribe(new FlowableSubscriber<GroupedFlowable<Object, Integer>>() { + pp.groupBy(Functions.<Integer>identity(), Functions.<Integer>identity(), false, 4) + .subscribe(new FlowableSubscriber<GroupedFlowable<Integer, Integer>>() { boolean once; @Override - public void onNext(GroupedFlowable<Object, Integer> g) { + public void onNext(GroupedFlowable<Integer, Integer> g) { if (!once) { try { - GroupedFlowable<Object, Integer> t = qs.get().poll(); + GroupedFlowable<Integer, Integer> t = qs.get().poll(); if (t != null) { once = true; t.subscribe(ts2); @@ -2250,7 +2250,7 @@ public void onComplete() { @Override public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") - QueueSubscription<GroupedFlowable<Object, Integer>> q = (QueueSubscription<GroupedFlowable<Object, Integer>>)s; + QueueSubscription<GroupedFlowable<Integer, Integer>> q = (QueueSubscription<GroupedFlowable<Integer, Integer>>)s; qs.set(q); q.requestFusion(QueueFuseable.ANY); q.request(1); @@ -2316,4 +2316,38 @@ public Publisher<Integer> apply(GroupedFlowable<Integer, Integer> g) { .assertComplete() .assertNoErrors(); } + + @Test + public void cancelledGroupResumesRequesting() { + final List<TestSubscriber<Integer>> tss = new ArrayList<TestSubscriber<Integer>>(); + final AtomicInteger counter = new AtomicInteger(); + final AtomicBoolean done = new AtomicBoolean(); + Flowable.range(1, 1000) + .doOnNext(new Consumer<Integer>() { + @Override + public void accept(Integer v) throws Exception { + counter.getAndIncrement(); + } + }) + .groupBy(Functions.justFunction(1)) + .subscribe(new Consumer<GroupedFlowable<Integer, Integer>>() { + @Override + public void accept(GroupedFlowable<Integer, Integer> v) throws Exception { + TestSubscriber<Integer> ts = TestSubscriber.create(0L); + tss.add(ts); + v.subscribe(ts); + } + }, Functions.emptyConsumer(), new Action() { + @Override + public void run() throws Exception { + done.set(true); + } + }); + + while (!done.get()) { + tss.remove(0).cancel(); + } + + assertEquals(1000, counter.get()); + } } From 32653cc4079df726fb33cb9ff9674bd5997e4bc9 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 14 Feb 2020 15:12:13 +0100 Subject: [PATCH 406/417] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index fd53e02083..21e4679a44 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ RxJava is a Java VM implementation of [Reactive Extensions](http://reactivex.io) It extends the [observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) to support sequences of data/events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety and concurrent data structures. +:warning: The 2.x version is now in **maintenance mode** and will be supported only through bugfixes until **February 28, 2021**. No new features, behavior changes or documentation adjustments will be accepted or applied to 2.x. It is recommended to migrate to [3.x](https://github.com/ReactiveX/RxJava/tree/3.x) within this time period. + #### Version 2.x ([Javadoc](http://reactivex.io/RxJava/2.x/javadoc/)) - single dependency: [Reactive Streams](https://github.com/reactive-streams/reactive-streams-jvm) From e2b7816f2bcf89491cad68cb35a9e36368a29d97 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 21 Feb 2020 18:17:32 +0100 Subject: [PATCH 407/417] Release 2.2.18 --- CHANGES.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 9af1b4f879..9e5980180b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,14 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.18 - February 21, 2020 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.18%7C)) + +:warning: The 2.x version line is now in **maintenance mode** and will be supported only through bugfixes until **February 28, 2021**. No new features, behavior changes or documentation adjustments will be accepted or applied to 2.x. It is recommended to migrate to [3.x](https://github.com/ReactiveX/RxJava/tree/3.x) within this time period. + +#### Bugfixes + + - [Pull 6894](https://github.com/ReactiveX/RxJava/pull/6894): Fix `groupBy` not requesting more if a group is cancelled with buffered items. + ### Version 2.2.17 - January 12, 2020 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.17%7C)) #### Bugfixes From 7980c85b18dd46ec2cd2cf49477363f1268d3a98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Karnok?= <akarnokd@gmail.com> Date: Thu, 27 Feb 2020 20:47:36 +0100 Subject: [PATCH 408/417] 2.x: Fix switchMap not canceling properly during onNext-cancel races --- .../operators/flowable/FlowableSwitchMap.java | 1 - .../flowable/FlowableSwitchTest.java | 73 ++++++++++++++++++- .../observable/ObservableSwitchTest.java | 72 +++++++++++++++++- 3 files changed, 143 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java index 4d0bc47158..caf8c235c4 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java @@ -199,7 +199,6 @@ void drain() { for (;;) { if (cancelled) { - active.lazySet(null); return; } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java index b4880d4ff6..794e43e273 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java @@ -14,11 +14,12 @@ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.*; import org.junit.*; import org.mockito.InOrder; @@ -1229,4 +1230,74 @@ public Publisher<Integer> apply(Integer v) .test() .assertResult(10, 20); } + + @Test + public void cancellationShouldTriggerInnerCancellationRace() throws Throwable { + final AtomicInteger outer = new AtomicInteger(); + final AtomicInteger inner = new AtomicInteger(); + + int n = 10000; + for (int i = 0; i < n; i++) { + Flowable.<Integer>create(new FlowableOnSubscribe<Integer>() { + @Override + public void subscribe(FlowableEmitter<Integer> it) + throws Exception { + it.onNext(0); + } + }, BackpressureStrategy.MISSING) + .switchMap(new Function<Integer, Publisher<? extends Object>>() { + @Override + public Publisher<? extends Object> apply(Integer v) + throws Exception { + return createFlowable(inner); + } + }) + .observeOn(Schedulers.computation()) + .doFinally(new Action() { + @Override + public void run() throws Exception { + outer.incrementAndGet(); + } + }) + .take(1) + .blockingSubscribe(Functions.emptyConsumer(), new Consumer<Throwable>() { + @Override + public void accept(Throwable e) throws Exception { + e.printStackTrace(); + } + }); + } + + Thread.sleep(100); + assertEquals(inner.get(), outer.get()); + assertEquals(n, inner.get()); + } + + Flowable<Integer> createFlowable(final AtomicInteger inner) { + return Flowable.<Integer>unsafeCreate(new Publisher<Integer>() { + @Override + public void subscribe(Subscriber<? super Integer> s) { + final SerializedSubscriber<Integer> it = new SerializedSubscriber<Integer>(s); + it.onSubscribe(new BooleanSubscription()); + Schedulers.io().scheduleDirect(new Runnable() { + @Override + public void run() { + it.onNext(1); + } + }, 0, TimeUnit.MILLISECONDS); + Schedulers.io().scheduleDirect(new Runnable() { + @Override + public void run() { + it.onNext(2); + } + }, 0, TimeUnit.MILLISECONDS); + } + }) + .doFinally(new Action() { + @Override + public void run() throws Exception { + inner.incrementAndGet(); + } + }); + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java index 100052f028..83b5a51270 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java @@ -33,7 +33,7 @@ import io.reactivex.internal.functions.Functions; import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.internal.util.ExceptionHelper; -import io.reactivex.observers.TestObserver; +import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; import io.reactivex.subjects.PublishSubject; @@ -1222,4 +1222,74 @@ public Observable<Integer> apply(Integer v) .test() .assertResult(10, 20); } + + @Test + public void cancellationShouldTriggerInnerCancellationRace() throws Throwable { + final AtomicInteger outer = new AtomicInteger(); + final AtomicInteger inner = new AtomicInteger(); + + int n = 10000; + for (int i = 0; i < n; i++) { + Observable.<Integer>create(new ObservableOnSubscribe<Integer>() { + @Override + public void subscribe(ObservableEmitter<Integer> it) + throws Exception { + it.onNext(0); + } + }) + .switchMap(new Function<Integer, ObservableSource<Integer>>() { + @Override + public ObservableSource<Integer> apply(Integer v) + throws Exception { + return createObservable(inner); + } + }) + .observeOn(Schedulers.computation()) + .doFinally(new Action() { + @Override + public void run() throws Exception { + outer.incrementAndGet(); + } + }) + .take(1) + .blockingSubscribe(Functions.emptyConsumer(), new Consumer<Throwable>() { + @Override + public void accept(Throwable e) throws Exception { + e.printStackTrace(); + } + }); + } + + Thread.sleep(100); + assertEquals(inner.get(), outer.get()); + assertEquals(n, inner.get()); + } + + Observable<Integer> createObservable(final AtomicInteger inner) { + return Observable.<Integer>unsafeCreate(new ObservableSource<Integer>() { + @Override + public void subscribe(Observer<? super Integer> observer) { + final SerializedObserver<Integer> it = new SerializedObserver<Integer>(observer); + it.onSubscribe(Disposables.empty()); + Schedulers.io().scheduleDirect(new Runnable() { + @Override + public void run() { + it.onNext(1); + } + }, 0, TimeUnit.MILLISECONDS); + Schedulers.io().scheduleDirect(new Runnable() { + @Override + public void run() { + it.onNext(2); + } + }, 0, TimeUnit.MILLISECONDS); + } + }) + .doFinally(new Action() { + @Override + public void run() throws Exception { + inner.incrementAndGet(); + } + }); + } } From 7ca43c7398810ee87c57f7f2165104822c0a4662 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Fri, 13 Mar 2020 09:01:13 +0100 Subject: [PATCH 409/417] Update CHANGES.md --- CHANGES.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 9e5980180b..6ac577fdb0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,16 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.19 - March 14, 2020 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.19%7C)) +[JavaDocs](http://reactivex.io/RxJava/2.x/javadoc/2.2.19) + +:warning: The 2.x version line is now in **maintenance mode** and will be supported only through bugfixes until **February 28, 2021**. No new features, behavior changes or documentation adjustments will be accepted or applied to 2.x. It is recommended to migrate to [3.x](https://github.com/ReactiveX/RxJava/tree/3.x) within this time period. + +#### Bugfixes + + - [Commit 7980c85b](https://github.com/ReactiveX/RxJava/commit/7980c85b18dd46ec2cd2cf49477363f1268d3a98): Fix `switchMap` not canceling properly during `onNext`-`cancel` races. + + ### Version 2.2.18 - February 21, 2020 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.18%7C)) :warning: The 2.x version line is now in **maintenance mode** and will be supported only through bugfixes until **February 28, 2021**. No new features, behavior changes or documentation adjustments will be accepted or applied to 2.x. It is recommended to migrate to [3.x](https://github.com/ReactiveX/RxJava/tree/3.x) within this time period. From 2cb20bd41efe70556ef7d346ee60f70e20548bae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Juli=C3=A1n=20Garc=C3=ADa=20Granado?= <vjgarciaw@gmail.com> Date: Wed, 15 Apr 2020 09:50:58 +0200 Subject: [PATCH 410/417] 2.x: Fix Observable.flatMap with maxConcurrency hangs (#6947) (#6960) --- .../observable/ObservableFlatMap.java | 39 +++++++++++++------ .../flowable/FlowableFlatMapTest.java | 23 +++++++++++ .../observable/ObservableFlatMapTest.java | 23 +++++++++++ 3 files changed, 73 insertions(+), 12 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java index a4766f389d..73a5306513 100644 --- a/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java +++ b/src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java @@ -334,6 +334,7 @@ void drainLoop() { if (checkTerminate()) { return; } + int innerCompleted = 0; SimplePlainQueue<U> svq = queue; if (svq != null) { @@ -349,9 +350,18 @@ void drainLoop() { } child.onNext(o); + innerCompleted++; } } + if (innerCompleted != 0) { + if (maxConcurrency != Integer.MAX_VALUE) { + subscribeMore(innerCompleted); + innerCompleted = 0; + } + continue; + } + boolean d = done; svq = queue; InnerObserver<?, ?>[] inner = observers.get(); @@ -376,7 +386,6 @@ void drainLoop() { return; } - int innerCompleted = 0; if (n != 0) { long startId = lastId; int index = lastIndex; @@ -463,20 +472,12 @@ void drainLoop() { if (innerCompleted != 0) { if (maxConcurrency != Integer.MAX_VALUE) { - while (innerCompleted-- != 0) { - ObservableSource<? extends U> p; - synchronized (this) { - p = sources.poll(); - if (p == null) { - wip--; - continue; - } - } - subscribeInner(p); - } + subscribeMore(innerCompleted); + innerCompleted = 0; } continue; } + missed = addAndGet(-missed); if (missed == 0) { break; @@ -484,6 +485,20 @@ void drainLoop() { } } + void subscribeMore(int innerCompleted) { + while (innerCompleted-- != 0) { + ObservableSource<? extends U> p; + synchronized (this) { + p = sources.poll(); + if (p == null) { + wip--; + continue; + } + } + subscribeInner(p); + } + } + boolean checkTerminate() { if (cancelled) { return true; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java index d121eea54e..e232af7bd4 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java @@ -1157,4 +1157,27 @@ public void innerErrorsMainCancelled() { assertFalse("Has subscribers?", pp1.hasSubscribers()); } + + @Test(timeout = 5000) + public void mixedScalarAsync() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + Flowable + .range(0, 20) + .flatMap(new Function<Integer, Publisher<?>>() { + @Override + public Publisher<?> apply(Integer integer) throws Exception { + if (integer % 5 != 0) { + return Flowable + .just(integer); + } + + return Flowable + .just(-integer) + .observeOn(Schedulers.computation()); + } + }, false, 1) + .ignoreElements() + .blockingAwait(); + } + } } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java index 5e0fa7cf8a..61fbd21c7f 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java @@ -1118,4 +1118,27 @@ public void innerErrorsMainCancelled() { assertFalse("Has subscribers?", ps1.hasObservers()); } + + @Test(timeout = 5000) + public void mixedScalarAsync() { + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + Observable + .range(0, 20) + .flatMap(new Function<Integer, ObservableSource<?>>() { + @Override + public ObservableSource<?> apply(Integer integer) throws Exception { + if (integer % 5 != 0) { + return Observable + .just(integer); + } + + return Observable + .just(-integer) + .observeOn(Schedulers.computation()); + } + }, false, 1) + .ignoreElements() + .blockingAwait(); + } + } } From b13a45e161f37c927e99d8def5f156834a83befb Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Wed, 23 Sep 2020 09:22:50 +0200 Subject: [PATCH 411/417] 2.x: Fix toFlowable(ERROR) not cancelling upon MBE (#7084) --- .../flowable/FlowableOnBackpressureError.java | 1 + .../FlowableOnBackpressureErrorTest.java | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java index f60c43bc31..556e54b8c3 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureError.java @@ -65,6 +65,7 @@ public void onNext(T t) { downstream.onNext(t); BackpressureHelper.produced(this, 1); } else { + upstream.cancel(); onError(new MissingBackpressureException("could not emit value due to lack of requests")); } } diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureErrorTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureErrorTest.java index 3be409e862..9afb864d40 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureErrorTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureErrorTest.java @@ -13,11 +13,16 @@ package io.reactivex.internal.operators.flowable; +import static org.junit.Assert.*; + import org.junit.Test; import org.reactivestreams.Publisher; import io.reactivex.*; +import io.reactivex.exceptions.MissingBackpressureException; import io.reactivex.functions.Function; +import io.reactivex.subjects.PublishSubject; +import io.reactivex.subscribers.TestSubscriber; public class FlowableOnBackpressureErrorTest { @@ -50,4 +55,20 @@ public Object apply(Flowable<Integer> f) throws Exception { } }, false, 1, 1, 1); } + + @Test + public void overflowCancels() { + PublishSubject<Integer> ps = PublishSubject.create(); + + TestSubscriber<Integer> ts = ps.toFlowable(BackpressureStrategy.ERROR) + .test(0L); + + assertTrue(ps.hasObservers()); + + ps.onNext(1); + + assertFalse(ps.hasObservers()); + + ts.assertFailure(MissingBackpressureException.class); + } } From 3d6403be8d9ada65016762a6bec417e268f482e3 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Mon, 5 Oct 2020 17:49:36 +0200 Subject: [PATCH 412/417] 2.x: Fix Flowable.concatMap backpressure w/ scalars (#7091) * 2.x: Fix Flowable.concatMap backpressure w/ scalars * Replace Java 8 constructs --- .../operators/flowable/FlowableConcatMap.java | 16 ++--- .../flowable/FlowableConcatMapTest.java | 68 ++++++++++++++++++- 2 files changed, 74 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java index f3dc0c58b8..64df7cc122 100644 --- a/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java +++ b/src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java @@ -13,7 +13,7 @@ package io.reactivex.internal.operators.flowable; import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.*; import org.reactivestreams.*; @@ -332,7 +332,7 @@ void drain() { continue; } else { active = true; - inner.setSubscription(new WeakScalarSubscription<R>(vr, inner)); + inner.setSubscription(new SimpleScalarSubscription<R>(vr, inner)); } } else { @@ -349,20 +349,20 @@ void drain() { } } - static final class WeakScalarSubscription<T> implements Subscription { + static final class SimpleScalarSubscription<T> + extends AtomicBoolean + implements Subscription { final Subscriber<? super T> downstream; final T value; - boolean once; - WeakScalarSubscription(T value, Subscriber<? super T> downstream) { + SimpleScalarSubscription(T value, Subscriber<? super T> downstream) { this.value = value; this.downstream = downstream; } @Override public void request(long n) { - if (n > 0 && !once) { - once = true; + if (n > 0 && compareAndSet(false, true)) { Subscriber<? super T> a = downstream; a.onNext(value); a.onComplete(); @@ -538,7 +538,7 @@ void drain() { continue; } else { active = true; - inner.setSubscription(new WeakScalarSubscription<R>(vr, inner)); + inner.setSubscription(new SimpleScalarSubscription<R>(vr, inner)); } } else { active = true; diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java index d9fe79977f..8bd29121a0 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java @@ -24,7 +24,9 @@ import io.reactivex.*; import io.reactivex.exceptions.*; import io.reactivex.functions.*; -import io.reactivex.internal.operators.flowable.FlowableConcatMap.WeakScalarSubscription; +import io.reactivex.internal.functions.Functions; +import io.reactivex.internal.operators.flowable.FlowableConcatMap.SimpleScalarSubscription; +import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.TestSubscriber; @@ -33,7 +35,7 @@ public class FlowableConcatMapTest { @Test public void weakSubscriptionRequest() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0); - WeakScalarSubscription<Integer> ws = new WeakScalarSubscription<Integer>(1, ts); + SimpleScalarSubscription<Integer> ws = new SimpleScalarSubscription<Integer>(1, ts); ts.onSubscribe(ws); ws.request(0); @@ -105,6 +107,68 @@ public Publisher<? extends Object> apply(String v) .assertResult("RxSingleScheduler"); } + @Test + public void innerScalarRequestRace() { + final Flowable<Integer> just = Flowable.just(1); + final int n = 1000; + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final PublishProcessor<Flowable<Integer>> source = PublishProcessor.create(); + + final TestSubscriber<Integer> ts = source + .concatMap(Functions.<Flowable<Integer>>identity(), n + 1) + .test(1L); + + TestHelper.race(new Runnable() { + @Override + public void run() { + for (int j = 0; j < n; j++) { + source.onNext(just); + } + } + }, new Runnable() { + @Override + public void run() { + for (int j = 0; j < n; j++) { + ts.request(1); + } + } + }); + + ts.assertValueCount(n); + } + } + + @Test + public void innerScalarRequestRaceDelayError() { + final Flowable<Integer> just = Flowable.just(1); + final int n = 1000; + for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { + final PublishProcessor<Flowable<Integer>> source = PublishProcessor.create(); + + final TestSubscriber<Integer> ts = source + .concatMapDelayError(Functions.<Flowable<Integer>>identity(), n + 1, true) + .test(1L); + + TestHelper.race(new Runnable() { + @Override + public void run() { + for (int j = 0; j < n; j++) { + source.onNext(just); + } + } + }, new Runnable() { + @Override + public void run() { + for (int j = 0; j < n; j++) { + ts.request(1); + } + } + }); + + ts.assertValueCount(n); + } + } + @Test public void pollThrows() { Flowable.just(1) From 947b05fb9d44de2231aa148ef2eb3a6edc07fcfd Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 6 Oct 2020 09:07:35 +0200 Subject: [PATCH 413/417] Release 2.2.20 --- CHANGES.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 6ac577fdb0..3321e0f855 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,17 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.20 - October 6, 2020 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.20%7C)) +[JavaDocs](http://reactivex.io/RxJava/2.x/javadoc/2.2.20) + +:warning: The 2.x version line is now in **maintenance mode** and will be supported only through bugfixes until **February 28, 2021**. No new features, behavior changes or documentation adjustments will be accepted or applied to 2.x. It is recommended to migrate to [3.x](https://github.com/ReactiveX/RxJava/tree/3.x) within this time period. + +#### Bugfixes + +- Fix `Observable.flatMap` with `maxConcurrency` hangs (#6960) +- Fix `Observable.toFlowable(ERROR)` not cancelling upon `MissingBackpressureException` (#7084) +- Fix `Flowable.concatMap` backpressure with scalars. (#7091) + ### Version 2.2.19 - March 14, 2020 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.19%7C)) [JavaDocs](http://reactivex.io/RxJava/2.x/javadoc/2.2.19) From f31aed36fd9d47edf0177164c54c64d4dc28c818 Mon Sep 17 00:00:00 2001 From: Sergio Garcia <elphake@gmail.com> Date: Tue, 26 Jan 2021 06:47:29 +0000 Subject: [PATCH 414/417] Support for scheduled release of threads in Io Scheduler (#7162) --- .../internal/schedulers/IoScheduler.java | 22 +++++-- .../io/reactivex/schedulers/Schedulers.java | 19 ++++++ .../schedulers/IoScheduledReleaseTest.java | 58 +++++++++++++++++++ 3 files changed, 95 insertions(+), 4 deletions(-) create mode 100644 src/test/java/io/reactivex/internal/schedulers/IoScheduledReleaseTest.java diff --git a/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java b/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java index d806321bf3..02cb44a1d3 100644 --- a/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java +++ b/src/main/java/io/reactivex/internal/schedulers/IoScheduler.java @@ -48,6 +48,10 @@ public final class IoScheduler extends Scheduler { /** The name of the system property for setting the thread priority for this Scheduler. */ private static final String KEY_IO_PRIORITY = "rx2.io-priority"; + /** The name of the system property for setting the release behaviour for this Scheduler. */ + private static final String KEY_SCHEDULED_RELEASE = "rx2.io-scheduled-release"; + static boolean USE_SCHEDULED_RELEASE; + static final CachedWorkerPool NONE; static { @@ -63,6 +67,8 @@ public final class IoScheduler extends Scheduler { EVICTOR_THREAD_FACTORY = new RxThreadFactory(EVICTOR_THREAD_NAME_PREFIX, priority); + USE_SCHEDULED_RELEASE = Boolean.getBoolean(KEY_SCHEDULED_RELEASE); + NONE = new CachedWorkerPool(0, null, WORKER_THREAD_FACTORY); NONE.shutdown(); } @@ -200,7 +206,7 @@ public int size() { return pool.get().allWorkers.size(); } - static final class EventLoopWorker extends Scheduler.Worker { + static final class EventLoopWorker extends Scheduler.Worker implements Runnable { private final CompositeDisposable tasks; private final CachedWorkerPool pool; private final ThreadWorker threadWorker; @@ -217,12 +223,20 @@ static final class EventLoopWorker extends Scheduler.Worker { public void dispose() { if (once.compareAndSet(false, true)) { tasks.dispose(); - - // releasing the pool should be the last action - pool.release(threadWorker); + if (USE_SCHEDULED_RELEASE) { + threadWorker.scheduleActual(this, 0, TimeUnit.NANOSECONDS, null); + } else { + // releasing the pool should be the last action + pool.release(threadWorker); + } } } + @Override + public void run() { + pool.release(threadWorker); + } + @Override public boolean isDisposed() { return once.get(); diff --git a/src/main/java/io/reactivex/schedulers/Schedulers.java b/src/main/java/io/reactivex/schedulers/Schedulers.java index 9e070690b8..dfd6bfe756 100644 --- a/src/main/java/io/reactivex/schedulers/Schedulers.java +++ b/src/main/java/io/reactivex/schedulers/Schedulers.java @@ -31,6 +31,8 @@ * <ul> * <li>{@code rx2.io-keep-alive-time} (long): sets the keep-alive time of the {@link #io()} Scheduler workers, default is {@link IoScheduler#KEEP_ALIVE_TIME_DEFAULT}</li> * <li>{@code rx2.io-priority} (int): sets the thread priority of the {@link #io()} Scheduler, default is {@link Thread#NORM_PRIORITY}</li> + * <li>{@code rx2.io-scheduled-release} (boolean): {@code true} sets the worker release mode of the + * {@link #io()} Scheduler to <em>scheduled</em>, default is {@code false} for <em>eager</em> mode.</li> * <li>{@code rx2.computation-threads} (int): sets the number of threads in the {@link #computation()} Scheduler, default is the number of available CPUs</li> * <li>{@code rx2.computation-priority} (int): sets the thread priority of the {@link #computation()} Scheduler, default is {@link Thread#NORM_PRIORITY}</li> * <li>{@code rx2.newthread-priority} (int): sets the thread priority of the {@link #newThread()} Scheduler, default is {@link Thread#NORM_PRIORITY}</li> @@ -113,6 +115,8 @@ private Schedulers() { * <ul> * <li>{@code rx2.computation-threads} (int): sets the number of threads in the {@link #computation()} Scheduler, default is the number of available CPUs</li> * <li>{@code rx2.computation-priority} (int): sets the thread priority of the {@link #computation()} Scheduler, default is {@link Thread#NORM_PRIORITY}</li> + * <li>{@code rx2.io-scheduled-release} (boolean): {@code true} sets the worker release mode of the + * {@code #io()} Scheduler to <em>scheduled</em>, default is {@code false} for <em>eager</em> mode.</li> * </ul> * <p> * The default value of this scheduler can be overridden at initialization time via the @@ -129,6 +133,21 @@ private Schedulers() { * <p>Operators on the base reactive classes that use this scheduler are marked with the * @{@link io.reactivex.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.annotations.SchedulerSupport#COMPUTATION COMPUTATION}) * annotation. + * <p> + * When the {@link Scheduler.Worker} is disposed, the underlying worker can be released to the cached worker pool in two modes: + * <ul> + * <li>In <em>eager</em> mode (default), the underlying worker is returned immediately to the cached worker pool + * and can be reused much quicker by operators. The drawback is that if the currently running task doesn't + * respond to interruption in time or at all, this may lead to delays or deadlock with the reuse use of the + * underlying worker. + * </li> + * <li>In <em>scheduled</em> mode (enabled via the system parameter {@code rx2.io-scheduled-release} + * set to {@code true}), the underlying worker is returned to the cached worker pool only after the currently running task + * has finished. This can help prevent premature reuse of the underlying worker and likely won't lead to delays or + * deadlock with such reuses. The drawback is that the delay in release may lead to an excess amount of underlying + * workers being created. + * </li> + * </ul> * @return a {@link Scheduler} meant for computation-bound work */ @NonNull diff --git a/src/test/java/io/reactivex/internal/schedulers/IoScheduledReleaseTest.java b/src/test/java/io/reactivex/internal/schedulers/IoScheduledReleaseTest.java new file mode 100644 index 0000000000..7eaaa377c0 --- /dev/null +++ b/src/test/java/io/reactivex/internal/schedulers/IoScheduledReleaseTest.java @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.reactivex.internal.schedulers; + +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.annotations.NonNull; +import io.reactivex.functions.Function; +import io.reactivex.schedulers.Schedulers; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; + +public class IoScheduledReleaseTest { + + /* This test will be stuck in a deadlock if IoScheduler.USE_SCHEDULED_RELEASE is not set */ + @Test + public void scheduledRelease() { + boolean savedScheduledRelease = IoScheduler.USE_SCHEDULED_RELEASE; + IoScheduler.USE_SCHEDULED_RELEASE = true; + try { + Flowable.just("item") + .observeOn(Schedulers.io()) + .firstOrError() + .map(new Function<String, String>() { + @Override + public String apply(@NonNull final String item) throws Exception { + for (int i = 0; i < 50; i++) { + Completable.complete() + .observeOn(Schedulers.io()) + .blockingAwait(); + } + return "Done"; + } + }) + .ignoreElement() + .test() + .awaitDone(5, TimeUnit.SECONDS) + .assertComplete(); + } finally { + IoScheduler.USE_SCHEDULED_RELEASE = savedScheduledRelease; + } + } +} From 776f0e55d97432799def8927c0e770154500686b Mon Sep 17 00:00:00 2001 From: SergejIsbrecht <4427685+SergejIsbrecht@users.noreply.github.com> Date: Thu, 28 Jan 2021 16:49:51 +0100 Subject: [PATCH 415/417] 2.x: Introduce property rx2.scheduler.use-nanotime (#7154) (#7170) Co-authored-by: Sergej Isbrecht <sergej.isbrecht@gmail.com> --- src/main/java/io/reactivex/Scheduler.java | 42 +++++++++++-- .../io/reactivex/schedulers/Schedulers.java | 2 + src/test/java/io/reactivex/SchedulerTest.java | 61 +++++++++++++++++++ 3 files changed, 99 insertions(+), 6 deletions(-) create mode 100644 src/test/java/io/reactivex/SchedulerTest.java diff --git a/src/main/java/io/reactivex/Scheduler.java b/src/main/java/io/reactivex/Scheduler.java index 2e99e288f1..882fdaa060 100644 --- a/src/main/java/io/reactivex/Scheduler.java +++ b/src/main/java/io/reactivex/Scheduler.java @@ -61,8 +61,9 @@ * interface which can grant access to the original or hooked {@code Runnable}, thus, a repeated {@code RxJavaPlugins.onSchedule} * can detect the earlier hook and not apply a new one over again. * <p> - * The default implementation of {@link #now(TimeUnit)} and {@link Worker#now(TimeUnit)} methods to return current - * {@link System#currentTimeMillis()} value in the desired time unit. Custom {@code Scheduler} implementations can override this + * The default implementation of {@link #now(TimeUnit)} and {@link Worker#now(TimeUnit)} methods to return current {@link System#currentTimeMillis()} + * value in the desired time unit, unless {@code rx2.scheduler.use-nanotime} (boolean) is set. When the property is set to + * {@code true}, the method uses {@link System#nanoTime()} as its basis instead. Custom {@code Scheduler} implementations can override this * to provide specialized time accounting (such as virtual time to be advanced programmatically). * Note that operators requiring a {@code Scheduler} may rely on either of the {@code now()} calls provided by * {@code Scheduler} or {@code Worker} respectively, therefore, it is recommended they represent a logically @@ -89,6 +90,34 @@ * All methods on the {@code Scheduler} and {@code Worker} classes should be thread safe. */ public abstract class Scheduler { + /** + * Value representing whether to use {@link System#nanoTime()}, or default as clock for {@link #now(TimeUnit)} + * and {@link Scheduler.Worker#now(TimeUnit)} + * <p> + * Associated system parameter: + * <ul> + * <li>{@code rx2.scheduler.use-nanotime}, boolean, default {@code false} + * </ul> + */ + static boolean IS_DRIFT_USE_NANOTIME = Boolean.getBoolean("rx2.scheduler.use-nanotime"); + + /** + * Returns the current clock time depending on state of {@link Scheduler#IS_DRIFT_USE_NANOTIME} in given {@code unit} + * <p> + * By default {@link System#currentTimeMillis()} will be used as the clock. When the property is set + * {@link System#nanoTime()} will be used. + * <p> + * @param unit the time unit + * @return the 'current time' in given unit + * @throws NullPointerException if {@code unit} is {@code null} + */ + static long computeNow(TimeUnit unit) { + if(!IS_DRIFT_USE_NANOTIME) { + return unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS); + } + return unit.convert(System.nanoTime(), TimeUnit.NANOSECONDS); + } + /** * The tolerance for a clock drift in nanoseconds where the periodic scheduler will rebase. * <p> @@ -131,7 +160,7 @@ public static long clockDriftTolerance() { * @since 2.0 */ public long now(@NonNull TimeUnit unit) { - return unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS); + return computeNow(unit); } /** @@ -332,8 +361,9 @@ public <S extends Scheduler & Disposable> S when(@NonNull Function<Flowable<Flow * track the individual {@code Runnable} tasks while they are waiting to be executed (with or without delay) so that * {@link #dispose()} can prevent their execution or potentially interrupt them if they are currently running. * <p> - * The default implementation of the {@link #now(TimeUnit)} method returns current - * {@link System#currentTimeMillis()} value in the desired time unit. Custom {@code Worker} implementations can override this + * The default implementation of the {@link #now(TimeUnit)} method returns current {@link System#currentTimeMillis()} + * value in the desired time unit, unless {@code rx2.scheduler.use-nanotime} (boolean) is set. When the property is set to + * {@code true}, the method uses {@link System#nanoTime()} as its basis instead. Custom {@code Worker} implementations can override this * to provide specialized time accounting (such as virtual time to be advanced programmatically). * Note that operators requiring a scheduler may rely on either of the {@code now()} calls provided by * {@code Scheduler} or {@code Worker} respectively, therefore, it is recommended they represent a logically @@ -448,7 +478,7 @@ public Disposable schedulePeriodically(@NonNull Runnable run, final long initial * @since 2.0 */ public long now(@NonNull TimeUnit unit) { - return unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS); + return computeNow(unit); } /** diff --git a/src/main/java/io/reactivex/schedulers/Schedulers.java b/src/main/java/io/reactivex/schedulers/Schedulers.java index dfd6bfe756..5af187c121 100644 --- a/src/main/java/io/reactivex/schedulers/Schedulers.java +++ b/src/main/java/io/reactivex/schedulers/Schedulers.java @@ -39,6 +39,8 @@ * <li>{@code rx2.single-priority} (int): sets the thread priority of the {@link #single()} Scheduler, default is {@link Thread#NORM_PRIORITY}</li> * <li>{@code rx2.purge-enabled} (boolean): enables periodic purging of all Scheduler's backing thread pools, default is false</li> * <li>{@code rx2.purge-period-seconds} (int): specifies the periodic purge interval of all Scheduler's backing thread pools, default is 1 second</li> + * <li>{@code rx2.scheduler.use-nanotime} (boolean): {@code true} instructs {@code Scheduler} to use {@link System#nanoTime()} for {@link Scheduler#now(TimeUnit)}, + * instead of default {@link System#currentTimeMillis()} ({@code false})</li> * </ul> */ public final class Schedulers { diff --git a/src/test/java/io/reactivex/SchedulerTest.java b/src/test/java/io/reactivex/SchedulerTest.java new file mode 100644 index 0000000000..39bcb0ae4b --- /dev/null +++ b/src/test/java/io/reactivex/SchedulerTest.java @@ -0,0 +1,61 @@ +/** + * Copyright (c) 2016-present, RxJava Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See + * the License for the specific language governing permissions and limitations under the License. + */ + +package io.reactivex; + +import org.junit.After; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +/** + * Same as {@link io.reactivex.schedulers.SchedulerTest}, but different package, to access + * package-private fields. + */ +public class SchedulerTest { + private static final String DRIFT_USE_NANOTIME = "rx2.scheduler.use-nanotime"; + + @After + public void cleanup() { + // reset value to default in order to not influence other tests + Scheduler.IS_DRIFT_USE_NANOTIME = false; + } + + @Test + public void driftUseNanoTimeNotSetByDefault() { + assertFalse(Scheduler.IS_DRIFT_USE_NANOTIME); + assertFalse(Boolean.getBoolean(DRIFT_USE_NANOTIME)); + } + + @Test + public void computeNow_currentTimeMillis() { + TimeUnit unit = TimeUnit.MILLISECONDS; + assertTrue(isInRange(System.currentTimeMillis(), Scheduler.computeNow(unit), unit, 250, TimeUnit.MILLISECONDS)); + } + + @Test + public void computeNow_nanoTime() { + TimeUnit unit = TimeUnit.NANOSECONDS; + Scheduler.IS_DRIFT_USE_NANOTIME = true; + + assertFalse(isInRange(System.currentTimeMillis(), Scheduler.computeNow(unit), unit, 250, TimeUnit.MILLISECONDS)); + assertTrue(isInRange(System.nanoTime(), Scheduler.computeNow(unit), TimeUnit.NANOSECONDS, 250, TimeUnit.MILLISECONDS)); + } + + private boolean isInRange(long start, long stop, TimeUnit source, long maxDiff, TimeUnit diffUnit) { + long diff = Math.abs(stop - start); + return diffUnit.convert(diff, source) <= maxDiff; + } +} From 725ea89629568301ab7d9b21cafdf8c648a14da9 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Sat, 13 Feb 2021 10:13:43 +0100 Subject: [PATCH 416/417] Update CHANGES.md --- CHANGES.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 3321e0f855..8842673756 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,17 @@ The changelog of version 1.x can be found at https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md +### Version 2.2.21 - February 10, 2021 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.21%7C)) +[JavaDocs](http://reactivex.io/RxJava/2.x/javadoc/2.2.21) + +:warning: This is the last planned update for the 2.x version line. After **February 28, 2021**, 2.x becomes **End-of-Life** (EoL); no further patches, bugfixes, enhancements, documentation or support will be provided by the project. + + +#### Enhancements + +- Add a system parameter to allow scheduled worker release in the Io `Scheduler`. (#7162) +- Add a system parameter to allow `Scheduler`s to use `System.nanoTime()` for `now()`. (#7170) + ### Version 2.2.20 - October 6, 2020 ([Maven](http://search.maven.org/#artifactdetails%7Cio.reactivex.rxjava2%7Crxjava%7C2.2.20%7C)) [JavaDocs](http://reactivex.io/RxJava/2.x/javadoc/2.2.20) From 24df131ecc012aa0591b9123b79a1f0f6a14a4f9 Mon Sep 17 00:00:00 2001 From: David Karnok <akarnokd@gmail.com> Date: Tue, 2 Mar 2021 13:01:19 +0100 Subject: [PATCH 417/417] Update README.md --- README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 21e4679a44..1cd82b7f63 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,13 @@ # RxJava: Reactive Extensions for the JVM +## End-of-Life notice + +As of February 28, 2021, The RxJava 2.x branch and version is end-of-life (EOL). No further development, bugfixes, documentation changes, PRs, releases or maintenance will be performed by the project on the 2.x line. + +Users are encouraged to migrate to [3.x](https://github.com/ReactiveX/RxJava) which is currently the only official RxJava version being managed. + +---- + <a href='https://travis-ci.org/ReactiveX/RxJava/builds'><img src='https://travis-ci.org/ReactiveX/RxJava.svg?branch=2.x'></a> [![codecov.io](http://codecov.io/github/ReactiveX/RxJava/coverage.svg?branch=2.x)](https://codecov.io/gh/ReactiveX/RxJava/branch/2.x) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.reactivex.rxjava2/rxjava/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.reactivex.rxjava2/rxjava) @@ -8,8 +16,6 @@ RxJava is a Java VM implementation of [Reactive Extensions](http://reactivex.io) It extends the [observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) to support sequences of data/events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety and concurrent data structures. -:warning: The 2.x version is now in **maintenance mode** and will be supported only through bugfixes until **February 28, 2021**. No new features, behavior changes or documentation adjustments will be accepted or applied to 2.x. It is recommended to migrate to [3.x](https://github.com/ReactiveX/RxJava/tree/3.x) within this time period. - #### Version 2.x ([Javadoc](http://reactivex.io/RxJava/2.x/javadoc/)) - single dependency: [Reactive Streams](https://github.com/reactive-streams/reactive-streams-jvm)